instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
When the page loads, it checks to see if the user is trying to update an existing book or create a new book. Something about my code just doesn't seem right. It feels cumbersome and not very logical. Could someone put me out of my misery and let me know that I wrote this bit ok? Public Property modID As Int32 Protect...
stackexchange/codereview
I wrote a matrix library to replace my old matrix library. I was using my old matrix library to do basic operations for 3D rendering but that library grew old and now I'm seeking to replace it. I'm mostly looking for comfort while writing code and I want to know what you think about the coding style and the simplicity ...
stackexchange/codereview
I'm a beginner in PHP. Here my script $url1 = $chemin.'include/aaa/url1.php?param='.$param.'&page='.$p; $url2 = $chemin.'include/aaa/url1.php?param='.$param.'&page='.$total_pages; //url2.php $url3 = $chemin.'include/aaa/url2.php?page='.$p; $url4 = $chemin.'include/aaa/url2.php?page='.$total_pages; //url3.php $url5 ...
stackexchange/codereview
Here is my code to create a definition text from 3 arguments. Is there any way to make it work with better performance and look nicer? private const string IllegalCharacters = "\\" + "\"" + "'#,.[]{}" + " "; public static string CreateDefText(string mainId, string secondaryId, string extraText) { ...
stackexchange/codereview
I have a CSV containing ~600k part numbers to be uploaded to my website's inventory. However, this CSV only contains limited information. We're missing pricing and other related information. To get this information I'm required to make requests to the provider's API, and add it into the CSV. At the moment, I've been sp...
stackexchange/codereview
I have 2 dictionaries that I have to compare, if an element of one dictionary exists in the other dictionary, then add the element to an array but only one time... here the working code const getFavouriteShows = (graphql, favouriteShows) => { const arraya = []; //iterate trough favouriteShows for (let item...
stackexchange/codereview
The Problem I am trying to determine numerically how many possible ways a number of books can be arranged on a shelf. Specifically, there are x3 categories "physics", "sci-fi", and "travel". Each contains N_phys, N_scifi, and N_travel numbers of books respectively. Within their category, the books can be placed in any ...
stackexchange/codereview
This is an object exposed to the view and is being used on directives within the same view. The directives need to track changes on the ctrl.filters.applied object. It's a simple part of a project at my work and I'd like to know if I'm doing it right. Other properties and methods are just being used on the view itself....
stackexchange/codereview
I know a lot about Java, PHP and stuff, but I'm fairly new to ruby. I've written this script to look into the current working directory, get two parameters from the command line and then resize and rename all jpegs it can find. To all rubyists, what could I have done better to make things ruby-ish? require "rmagick" re...
stackexchange/codereview
I am creating a simple bot that collects coins in-game. The code runs under a game-loop so there are 60 ticks p/s Here is the function that I use to check for the nearest coin (Game object) to be collected: public GameObject getNearest(ID objectID) { LinkedList<GameObject> object = new LinkedList<GameObject>(); ...
stackexchange/codereview
I made a simple script to implement basic mathematics operations by using variadic functions. I would like to know if my implementation is correct. The code only works for Visual C++ compiler Nov 2013 CTP (CTP_Nov2013). #include <iostream> #include <string> #include <exception> using namespace std; template <typename ...
stackexchange/codereview
This cache is like a list where new elements are inserted in the middle, cache hits are put to head of the list and replaced elements are taken from the end. Would I just use a list the lookup would take O(n). With a dictionary it is O(log(n)) but I lose the order of elements, so I use both. .Net but only has Concurren...
stackexchange/codereview
I came up with this question. Let A and B be two N bit numbers. You are given initial values for A and B, and you should write a program which processes three kinds of queries: set_a idx x: Set A[idx] to x, where 0 <= idx < N (where A[idx] is idx'th least significant bit of A.) set_b idx x: Set B[idx] to x, where ...
stackexchange/codereview
In the codebase I support, I found the following code. I am interested in your opinion about its expediency and especially the expediency of redefining the operator(). template <typename KEY, typename VALUE> class MyUnorderedMap { std::unordered_map<KEY, VALUE> map; public: template <typename T> auto...
stackexchange/codereview
Context I am building an algorithm that automatically assigns a planning to drivers. However there is a lot of pre-processing and reused outputs. I try to structure it in a maintainable way. Questions I created a class Availability that represents the number of hours each driver has each day. There is a base planning, ...
stackexchange/codereview
The following algorithm works correctly for the purposes that I need, which is to set the top side of an image with a transparent gradient blend. Any tips to optimize it for speed? void ImageUtil::sectionAlphaGradient(uint32_t* pixelBuffer, const int width, const int gradientHeight) { unsigned int pixelOffsetY, pix...
stackexchange/codereview
Hi everyone I'm trying to reduce the complexity of some of my Python code. The function below aims to compute the validation and test loss for a variety of PyTorch time series forecasting models. I won't go into all the intricacies but needs to support models that return multiple targets, an output distribution + std (...
stackexchange/codereview
With the festive season mood and the new year coming, I thought I would make my first question this year, a tree implementation. Blame me because it doesn't have anything to do about Christmas. public interface ITreeITem { object Key { get; } object ParentKey { get; set; } } public class Tree<T> : IEnumerable...
stackexchange/codereview
I was thinking of adding a very high-level implementation of the event/observer pattern to my project. The implementation would manage adding and removing observers as "needed". You can use an almost DLS-like API to define when an observer should be added or removed. Here is an example of the API in use. We want to tra...
stackexchange/codereview
Is this OK? (.Net 4.5) try { StreamReader sr = = new StreamReader(ValidFilePathName); line = file.ReadLine(); While (line != null) { line = file.ReadLine(); } sr.Close(); } catch { // blah Do nothing } I feel like there is something wrong with my pattern here. My concern is that whe...
stackexchange/codereview
I have a small Person Domain Model as follows: public class Person { public Person() { FirstName = "John"; LastName = "Doe"; BirthDate = DateTime.Now.AddYears(-18); } [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid PersonId { get; set; } [Max...
stackexchange/codereview
Within a function, I want to grab a set of parameters from a named array. What is the most efficient way of testing if the parameter exists in the array, and if it does, use it as a variable? I came up with a few alternatives. target = $('#page_links') if ( functionobject.target ) { target = functionobject.target }...
stackexchange/codereview
I recently create a function to combine some arrays of associative arrays in a single array in response to a stackoverflow question, where you can found more details about this. The function works as expected, but I think their description is very obscure. In addition, i choose constant T_OBJECT_CAST as option to conve...
stackexchange/codereview
i have solved this problem https://leetcode.com/problems/find-eventual-safe-states/submissions/ import scala.collection.mutable object Solution { def eventualSafeNodes(graph: Array[Array[Int]]): List[Int] = { val seen = mutable.HashSet[Int]() val safeNodes = mutable.ArrayBuffer[Int]() val color_of = ...
stackexchange/codereview
So I'm creating a unity3D game with infinite terrain and it's going great! However, I'm struggling with a specific but important part of the 'infinite' terrain. Make the terrain actually infinite. I got it working but it's very slow and I've looked through the code and at the profiler that unity has built in and came t...
stackexchange/codereview
I am experimenting with ES6 using BabelJS in a codepen project you can find here. I am confused as to why my code breaks when I decide to use let instead of var in the following function: function getUnits(country) { const imperialCountries = ['US', 'BS', 'BZ', 'KY', 'PW']; if (imperialCountries.indexOf(country) === -...
stackexchange/codereview
Example: If a linkedlist list contains 10->20->30->40, and 2nd node has to be deleted then the output should be 10->30->40 This question is attributed to Geeksforgeeks. Looking for code-review, optimizations and best-practices. class Nodde<T> { Nodde<T> next; T item; Nodde(T item) { ...
stackexchange/codereview
I am currently writing my bachelor's thesis about on-line handwriting recognition. This is not OCR, because I have the information how a symbol is written as a list of pen trajectory coordinates (x, y). I call this hwrt - handwriting recognition toolkit. It has a documentation and a friend of mine got the "first steps"...
stackexchange/codereview
Given an html page with heading tags such h1, h2 through h6 and p tags construct a hierarchical structure. A super problem of this problem is explained in Heading Based Sectional Hierarchy Identification for HTML Documents. I've written the following code, how can I improve it: (use-modules (ice-9 match)) (define-syn...
stackexchange/codereview
I am building my first OOP program, Tic Tac Toe. I want to conquer it in chunks, but the first part for me is the intialization of the program and the creation of the two players. I want to get some feedback about how I structured this before I move on to build the board and the actual gameplay logic. For instance,...
stackexchange/codereview
I'm currently working on a Scala HTTP library, fetch, mostly because I have yet to find one that suits all my needs. As part of this library, I need a generic key / value store, which I intend to use both for request / response headers and URL query parameters. This store uses type classes for value parsing and formatt...
stackexchange/codereview
I'm really new to coding so I'm looking for a bit of feedback on this twin prime finder. She works pretty decent but I know it could be better. import math primes = [] def get_primes(lower, upper): for num in range(lower, upper): for i in range(2, num): if num % i == 0: break else: pri...
stackexchange/codereview
I took some time to create a function, which can validate which keys you input on an element. So far it has two uses: You call .validate() on the object, but make sure it has a data-match attribute with the regex in it You call .validate("REGEX") on the object, but replace REGEX with your actual regular expression He...
stackexchange/codereview
What I try to achieve I need to create a administration-panel for a website. Therefore, I need a possibility to protect the content of the panel via a password. The functionality doesn't have to be very advanced. I neither need a password-reset functionality nor the possibility to add more than one user. I also don't n...
stackexchange/codereview
I've written the following code for computing the powerset of a list (we consider the list has all distinct elements, although it doesn't really matter). Can this function be further optimized? def powerset(A): if A == []: return [[]] a = A[0] incomplete_pset = powerset(A[1:]) rest = [] for ...
stackexchange/codereview
I have a function returns a random integer number. This function only accepts these three numbers 1,2 and 3(there's another function in my code which is make sure of this otherwise that function will raise ValueError and re-prompt the user again). If the function gets 1 it should generate a random number between 0-9. I...
stackexchange/codereview
I want to rewrite if else statements with something nicer or refactor the code i have to something neat using javascript. below is the code, const title = () => { if (result) { //here checking if the title field is not undefined or null and title field //has no empty string "" if (result?.t...
stackexchange/codereview
I have this code which I use to iterate through every permutation of every subset in an array witch holds integers. One big problem is the efficiency of course, another problem is the fact that if I have some similar values it holds only one of them (Ex. [100,5,3,5] is held as [100,5,3]). Any help in improving this is ...
stackexchange/codereview
I am new to the whole Data Structures thing and I want to get better at writing efficient code. So, I have been practicing some problem sets. The questions is - Replace characters in a string using iteration and recursion approach. I am still learning the whole recursion approach. But I tried to design an algorithm usi...
stackexchange/codereview
This code has several functions and procedures for the program to generate cards like '5 of diamond'. I would like to shorten the code. def random(one,two): import random number = random.randint(one,two) return number def suit(): suitnumber = random(1,4) if suitnumber == 1: suitb = 'Spade' ...
stackexchange/codereview
For practice I wrote a function to generate a list of numbers from a start to an end by a step. I couldn't make it- like the built-in range- default start to 0, because all optional parameters must come after required ones, so def range(start=0, end, step=1) won't work. Here's my script: def Range(start, end, step=1): ...
stackexchange/codereview
I'm writing a laser connection game. This is my first game on Windows Phone, and I've never used C# and XNA before. The part of my code that could be improved is Update() (where I make my sprites move). public void Update(GameTime gameTime) { TouchPanelCapabilities touchCap = TouchPanel.GetCapabilities(); if (t...
stackexchange/codereview
Our database has several tables that have a value that can be one of 4 things, so we made these columns instead have an id column with a foreign key to an enum table with an id and a value column to hold those 4 values. When interfacing this through an ORM, I came up with the following enum-like class to manage keeping...
stackexchange/codereview
Given an arbitrary \$N \times N\$ matrix, find the maximum sum submatrix. This particular approach uses the Kadane's algorithm. What could be improved both in terms of algorithm and code style? def read_matrix_from_input(): return [[int(s) for s in input().split(" ")] for row in range(int(input()))] def max_subar...
stackexchange/codereview
This is my first test, I think it's testing what I need it to test but wanted to get some feedback. I wanted to test to make sure the controller action returns a view with a certain ViewModel. The code that it will be testing: Controller: public class UserController : Controller { private readonly ILogger<UserContr...
stackexchange/codereview
A Minesweeper library in C#. To be included with any GUI stack. Did some breakpoint tests and unit testing, seems to work fine. I'm asking if the code makes sense to everyone, and if there can be improvements. Three classes: Tile, Board and Game. Tile public enum TileStatus { Revealed, Flagged, Hidden } p...
stackexchange/codereview
Is there a way to write this code block cleaner and more readable? var shareNavigate = function () { scope.sharingActions.shareOnFacebook().done(function () { app.router.navigateToStories(); }); }, sharePublishNavigate = function () { scope.sharingActions.shareOnFacebook().don...
stackexchange/codereview
I am trying to fight my way trough self learning Django (as this is a beast on its own) and Python (just for coding <3) in combination with nginx, PostgreSQL and gunicorn - I have some limited experience with PHP. After a short struggle I managed to get everything up and running (enough tutorials for that around). Basi...
stackexchange/codereview
Please review the implementation of Kruskal algorithm. Points on which I have doubt: My Graph doesn't have any ID for nodes. Nodes are accessed based on their data. Is there any general approach in that? Should nodes be referenced by an ID as that will also make these algo somewhat easier to implement by using id as ...
stackexchange/codereview
Given a text file containing a list of links, I wrote some code to download them, one by one, from YouTube, using either YoutubeMP3 or Convert2mp3 logging any songs that failed to download. The code with Youtube-mp3 is significantly faster than Convert2mp3 but less accurate (some songs fail for unknown reasons, even ma...
stackexchange/codereview
I am learning about the binary tree data structure and implemented some basic functionality. It was working great with module level functions until I realized that I need to keep track of the root for operations like checking height. The simplest solution that I could possibly think was of creating a container class to...
stackexchange/codereview
I started learning Lua yesterday and wanted to write a quick program as a practice. It queries an external service for the IP address and country code, and naively check for the existence of network interface names used by VPNs (like Nordvpn or other). It then prints a colored output containing the country flag emoji a...
stackexchange/codereview
I have the following form that creates a new "activity": For which I want to enforce the following requirements: Name => minimum # of chars: 1; maximum # of chars: 50 Description => maximum # of chars: 200 I have written the following code: // ActivityDetailViewController.swift import UIKit private struct Constant...
stackexchange/codereview
I implemented an O(N^2) algorithmic solution but not sure it is better than my previous implementation Find Triangle Triplets from a list of given numbers in case of performance. I adapted almost all suggestions from answer except a structure to keep the triangle triplets.The reasons to ignore the suggestion are foll...
stackexchange/codereview
I have some legacy classes written without thread safety in mind. Instances of these classes are now being accessed in a multithreaded context in a thread-un-safe manner. Cue chaos. To fix this I make a wrapper class that enforces the user to take a transaction lock to serialize access to the instance. #include <memor...
stackexchange/codereview
i am currently learning to do things with vanilla Javascript. No plugins, libraries or code snippets. I want to do things on my own, so that I understand 100% of what is happening. I wrote a little script which checks, if a section of the page is in view. Now, the script works as expected, but I was wondering, if I had...
stackexchange/codereview
I had a task to create a VBA macros which will take a matrix data set with products in rows and persons as a columns (on intersection we have an ordered qty for each material for each person) and convert it into a CSV file for Advantix to load. As I'm new to VBA, I spent a couple of days investigating the forums and se...
stackexchange/codereview
I implemented Kosaraju's algorithm on a graph with 800k vertices and 5100k edges. The time taken by various operations are: building graph took 11.84 seconds ordering took 2.54 seconds finding SCCs took 2.63 seconds My computer has an i7 with 4GB RAM. I would like to know if my code can be made more efficie...
stackexchange/codereview
Project description I'm making a website listing products. The listing goes as following (See here): Product name Shop name Price in that shop If the product appears multiple times in the table for the same user (Which means he/she selected it in multiple stores. Merge them and just show multiple shop names) Exampl...
stackexchange/codereview
Due to the fact that nobody's ever posted this before (sarcasm) I've made a brainfuck interpreter in java. The interpreter fits in a single method, and is designed to be readable, fast, and concise, so please review on those things. I have tested it to confirm that it works. /** * Interpret program as a brainfuck prog...
stackexchange/codereview
The following code was my first attempt at creating and manipulating socket variables. I compiled and ran the code through cmd. What are the most common ways to organize methods in both a server and client program? Client program: import java.util.Scanner; import java.io.InputStreamReader; import java.io.BufferedWriter...
stackexchange/codereview
I have to say without sounding arrogant, because I am only a novice coder, yet after looking at other's solutions, my solution is definitely not the shortest and most lightweight one and probably not even close to one of the most optimized ones. But! I think I have made a very readable solution and I think that it is t...
stackexchange/codereview
I want to process a file chunk by chunk to prevent memory exhaustion. I need to consume the file using a read stream. When trying it, this implementation seems to work fine. I am asking your expert eyes: have I overlooked anything or did I forget some case? have I made a mistake somewhere and it's going to bite me in ...
stackexchange/codereview
I am self-taught and trying to improve my programming skills. My project is a point-of-sale application, with lots of buttons. I am curious how improve this section of code, as I seem to be going against the DRY principle. I have a Customer object named cust, and each customer has an ID that is set to one of 8 differe...
stackexchange/codereview
Somewhat experienced with JavaFX, but this is my first potentially large JavaFX project that I recently started and wanted some feedback on anything that could be done better or more efficiently thus far, before continuing. Note: I am aware that there are a few functions not in use, I'm just leaving them in for future...
stackexchange/codereview
I made this really simple "attribute container" class that allows you to store arbitrary data to an object at will, sorta like in python how you can just assign attributes to arbitrary objects, but in C#. My gut is telling me it's a terrible idea, but I just want to get a group opinion. public class AttributeContainer ...
stackexchange/codereview
Out of fun, I solved "Nice Angles" challenge on CodeEval in C# 4.0: CHALLENGE DESCRIPTION: Write a program that outputs the value of angle, reducing its fractional part to minutes and seconds. INPUT SAMPLE: The first argument is a path to a file that contains the values of angles with their decimal fractions: 330...
stackexchange/codereview
val y: Seq[Either[String, Int]] case class Response(value: String) val notFound = Response("Not Found") val found = Response("Found") val response: Response = y.lastOption .map(_.fold(_ => notFound, _ => found)) .getOrElse(notFound) I am getting a list of Eithers. I want to get the last Either in the lis...
stackexchange/codereview
I tried following the official solution of LC975 (https://leetcode.com/problems/odd-even-jump/), using a monotonic stack - i.e., I reimplemented their solution (Approach 1) from python in C++. TLDR Problem statement: Given an array of ints A, "good index" is an index from which the last element of A can be reached, thr...
stackexchange/codereview
I have this piece of Ruby code: HTTPCLIENT = HTTPClient.new def read_page(url) HTTPCLIENT.get(url).body end The HTTPClient object is being created and declared as a constant, and thus it can be accessible by methods. I would do this by declaring it as a global variable ($) or as a class variable (@), but I'm not su...
stackexchange/codereview
I'm trying to create a simple triplet class, but the more I look at the implementation of std::pair the more I feel like I'm missing important details. What I have feels "too simple". I am aware of std::tuple and other options, but the use case is to be able to use uniform initialization -- so we can make certain ass...
stackexchange/codereview
I have created a ViewModel for a Product Edit page because it has specific related entities I need to load - the class currently looks like this: public class ProductEditView { public ProductEditView(Product product) { this.ID = product.ID; this.Code = product.Code; this.ProductLanguage ...
stackexchange/codereview
I have implemented a splash screen which is the main activity of my Android app. This splash screen shows an image, and after 1000ms there is an animation to show another activity's layout. The code I've written is the following: public class SplashScreen extends AppCompatActivity { @Override protected void on...
stackexchange/codereview
I have the library that I have found to be very useful when creating dynamic content rich web applications. I call it DO.js. It allows me to create entire DOM structures inside of Javascript in a similar manner that HTML markup should look. Additionally, it does it all without writing any HTML strings. It uses a hierar...
stackexchange/codereview
So I have written a Makefile that has a release function that can be run like: make release bump=patch and I want it to be fully executable in the Makefile. The only issue with my current implementation is that there is a lot of redundancy and long lines of commands, which I think can be simplified a lot, although I ha...
stackexchange/codereview
I'm writing this simple program for school, and using NumberFormat on all the variables seems very repetitive (Note that we were asked to use the NumberFormat method). Is there any way to clean this code so it doesn't look so cluttered? import java.util.Scanner; import java.text.NumberFormat; public class CarPrice { ...
stackexchange/codereview
I heard/read that writers of texts can be recognized by counting their used words and compare these to previous works. As a code kata I experimented with this a bit and found some disturbing facts. 'Romeo and Juliet' was written by one of the Bronte sisters. Shakespeare plagiarized it from the future. My program is n...
stackexchange/codereview
Class class Player { std::string name; int score; int id; }; I thought about how to write a code to sort and search vector of these classes by three criteria: name, id, and score. The search what I want is to output the previous value and next value of the found element. The cod...
stackexchange/codereview
A list of objects needs to be grouped. The list is iterated and checked with other objects in the same list except itself. The method People.isAttributeEqual() checks if two objects can be grouped. The list returns a list of two unique objects with the same attributes. I am trying to optimize the method People.groupSi...
stackexchange/codereview
I recently had a programming interview, where I had to create an Api Gateway. The description is as follows: You need to create a gateway in which it only allows certain number of callers to call api and rest of them will be blocked within the given timeframe. For eg : If the time window is 1 minute. You need to allow...
stackexchange/codereview
For my game engine that I'm trying to write without using STL I implemented dynamic array class(some kind of std::vector). I would like to know whether this code suits best practices. I'm also not enough knowledged about move semantics and all that stuff, so please tell if I should add them somewhere in my code. My eng...
stackexchange/codereview
Task: convert this array of hashes: animals = [ {"cats" => 3}, {"dogs" => 5 } ] to this hash: { "cats" => 3, "dogs" => 5 } This is my solution, any feedback is appreciated :-) animals.reduce({}) {|m,e| e.each{|k,v| m[k] = v}; m }
stackexchange/codereview
I am working on my Python skills and would like some feedback on this problem I have tried to solve. I would like to return a boolean if two knights at their current position can attack each other using standard chess notation example (4,'A') from itertools import product class ChessPosition: def __init__(self, nu...
stackexchange/codereview
Introduction/Disclaimer This is a project for educational purposes. I'm not intending to replace the "award-winning" Collections Framework in java.util. I'm just looking for constructive criticism. For obvious reasons, I'm tagging it as reinventing-the-wheel. I'd like to see someone break my code. Preferably in a multi...
stackexchange/codereview
Recently I have been developing a library for Java which provides utility functions for arrays, strings, etc.. While researching string similarity algorithms, I managed to write one of my own. I am curious as to if anyone has come across a similar approach or if it is a commonly known one. The code is sampled below. pu...
stackexchange/codereview
I'm an active contributing member of Wiktionary and an active member of an active Wiktionary Discord server. Some time ago, several users proposed a bot which would make linking to Wiktionary in Discord much easier (originally one would have had to go to Wiktionary, search their entry, copy the link, and then navigate ...
stackexchange/codereview
I recreated the game Hangman and I'm decently happy with it, but like always it would be preferable if anyone knew how to improve my code: main.cpp #ifndef UNICODE #define UNICODE #endif #include <iostream> #include <conio.h> #include <Windows.h> #include <ctime> #include "gameInfo.h" // Function declares std::wstri...
stackexchange/codereview
Here is code I wrote to dynamically choose between three country options (United States, Canada, Other). After the user selects a country it will show the related select option or an empty input (when "Other" country is chosen). Then I pass the previous value into an input called spr(state/province/region). The end res...
stackexchange/codereview
How can I improve/secure my login script and how to check for any possible injection? PS. the script must run on multiple platforms, so I need empty arrays for cases such as the Android ones. user_table: CREATE TABLE `user_table` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `user_type` varchar(255) NOT NULL, PRIMARY K...
stackexchange/codereview
I would like to use Haskell to do some image processing so I have been writing small programs to test performance. I wrote a program to batch convert PNG images from color to greyscale. I compared the performance of the program below with a Python script using PIL. I found when compiled with -threaded -O2, the Haskell ...
stackexchange/codereview
Description: Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. Leetcode Code: class Solution { public int minDepth(TreeNode root) { if (root == null) return ...
stackexchange/codereview
Update at the end Is it possible to implement IDisposable pattern correctly while using object composition principle to promote code-reuse, reduce code duplication and hide verbose "official" implementation? Rational Composition over inheritance is a good principle Implementing IDisposable correctly and thoroughly i...
stackexchange/codereview
I'm working on this problem, Problem statement, Given a Binary Tree, find vertical sum of the nodes that are in same vertical line. Print all sums through different vertical lines. Examples: 1 / \ 2 3 / \ / \ 4 5 6 7 The tree has 5 vertical lines Vertical-Line-1 has only one node 4 => vert...
stackexchange/codereview
Exercise 2-3 in Think Complexity: Complexity Science and Computational Modeling by Allen B. Downey asks us to implement a method for a class of undirected graphs: Write a method named add_regular_edges that starts with an edgeless graph and adds edges so that every vertex has the same degree. The degree of a node is t...
stackexchange/codereview
As part of a first year university course in computer architecture some time ago we were tasked with learning 8086 ASM. The final course work required creating a small animation of shapes moving around the screen changing colours and the like. As I would not expect anyone to review 720 lines of assembler I'm just goin...
stackexchange/codereview
This is, kind of, my first programming project. It's a small project to complete first year's university programming course. The program allows the user to record his mouse/keyboard/cursor activities and then replay it. It's a mini-bot. I am unsure whether I will continue developing this project, or abandon C and go l...
stackexchange/codereview
I have two classes: country country_name Country.java public class Country { private Integer ID; private String ISO; public Integer getID() { return ID; } public void setID(Integer ID) { this.ID = ID; } public String getISO() { return ISO; } public void...
stackexchange/codereview
In order to reduce time complexity, instead of loading (and then dumping to use it for later) the whole file into an array (It would be O(n) with n=number of lines), I have saved it as array into a PHP file and included it index.php <?php include "english.php"; $test = new English("false_friend.php"); ?> english.php <...
stackexchange/codereview
I have the following Node.JS (runtime v6.10) executing on AWS Lambda: exports.handler = (event, context) => { send(event); }; var flota = ['CZWF64', 'DRZY65', 'DRZY66', 'FPBS85', 'FPBS86', 'FPBS87']; function send(json) { var ppu = json.vehiculo.patente.replace(/[^a-z0-9]/gi, ''); if (flota.indexOf(ppu)...
stackexchange/codereview
I have this Javascript which call the web api to see the available folder and then the available files. Any comment or code review on my code? var divFolder = document.getElementById("rootFolder"); var divFiles = document.getElementById("files"); function createFolderElement(data) { var li = docu...
stackexchange/codereview