instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
Its my first attempt to unit-test in Js. Not yet TDD. What I can change? EventsPersistancyService.js: var Q = require('q'); var EventsPersistancyService = { accept: function acceptService(msg) { var worker_id = WorkerCacheService.get('some login'); var app_category = AppCategoryService.get('some'); var...
stackexchange/codereview
Table Structure ApprovalOrder int EntityCode varchar CostCentre varchar DelegationCode varchar ProjectCode varchar RoleGroup varchar Position varchar DelegationText varchar DelegationAmount money Active bit Query / Explanation The purpose is to pull all records for a delegation chain and add a new...
stackexchange/codereview
Am trying to create a minesweeper game, I have the following code which has to many nested ifs, I want to change the code to take out the nested ifs and make it better to read. But I am stuck on how to change the nested ifs. Any help would be great. thanks /*method to check cells around a cell and set its value.*/ ...
stackexchange/codereview
Some fellow code reviewers (hi @Janos!) have been inquiring about a SEDE query to allow to check progress of the Red Shirt "hat" progression. Try it here! Background Red Shirt cast 5 downvotes on posts that are later deleted or closed Limitations There are certain Stack Exchange limitations which make querying th...
stackexchange/codereview
I have an assignment to create a GUI with a keyboard and text area. Conceptually, the user would type on the physical keyboard and the respective key would change background on screen to reflect that key press. Pressing the onscreen keys yields no behaviour so I don't need to implement keyTyped(...) (I think). For brev...
stackexchange/codereview
This class can be used to access the Google Translate web interface and get translation result for large text (split up into sentences). The Signal class is copied from here. #!/usr/bin/env python3 import urllib.request import urllib.parse import re import traceback from multiprocessing.dummy import Pool from bs4 impo...
stackexchange/codereview
Intro I wrote this code to solve sudoku as part of an assignment (closed now) for an AI course. The program works correctly and I am quite happy with the code. Please let me know if I am rightfully pleased or if the implementation could be so much better. This is a pure code review question so don't hold back on anyth...
stackexchange/codereview
C++ code version (description copied from it) gameKeys id is authentication function of an MMO game server. When someone wants to play with friends, he sends request to server, server calls generateId, then gameKeys id and returns it as JSON using encodeJSON to player via API. When a friend establishes connection, he s...
stackexchange/codereview
I'm working through CLRS, and I'm hoping to get some pointers (ha!) on my C++ coding style and the way I've implemented recursive matrix multiplication. The code right now seems a bit complex for something that should be rather simple, but I'm avoiding using too many built in tools so I can strengthen my baseline C++ s...
stackexchange/codereview
Task: "Implement a method 'gruppiere', in a way that it can be invoked on all enumerable objects (Enumerable). The method receives a block and returns a hash. The items of the enumerable a grouped within the hash according to the return-value of the block." What they like to have is an own implementation of Ruby's "#gr...
stackexchange/codereview
I am trying to create a function that I want to use in my real data. Is there any way to optimize the following function? This is a function I created to filter the data. filter <- function(x, m, delt) { series <- x series_filtered <- rep(0,length(series)) delta_t <- delt # time step between data points (hours) ...
stackexchange/codereview
I'm writing unit-tests with pytest for sqlite database and reporting functions and I need to arrange them by inserting minimal dummy data into required columns. In order to avoid repeating the names of the columns I generate the query and the parameters from the function's signature and inject them into that function a...
stackexchange/codereview
I am making a game event messenger based on the observer pattern and I'd really appreciate some feedback on this please. The intent behind it is that I am sending in a function pointer so that it can work for the broadcasting. Also using the subscribers memory address as a way of detecting it for unsubscribe. Thank you...
stackexchange/codereview
I implemented K-Nearest Neighbours algorithm, but my experience using MATLAB is lacking. I need you to check the small portion of code and tell me what can be improved or modified. I hope it is a correct implementation of the algorithm. function test_data = knn(test_data, tr_data,k) numoftestdata = size(test_data,1);...
stackexchange/codereview
I am a beginner with regards to C; I'm used to using high-level languages (Java, Python, JS, etc) and this is my first project in a lower-level language. I wrote a simple Brainfuck interpreter, given that my Python implementation was super slow. Here's the code: #include <stdlib.h> #include <stdio.h> #include <stdbool....
stackexchange/codereview
I am new to Python and recently started exploring web crawling. The code below parses the S&P 500 List Wikipedia page and writes the data of a specific table into a database. While this script is hardcoded and I would certainly be interested in some thoughts on performing the same task in a slightly more generic way (p...
stackexchange/codereview
I wrote my first unit testing code on a service class using Mockito. The code looks like this: // Test Class public class TestVideoService { private VideoService videoService; @Mock private VideoRepository videoRepository; @Rule public MockitoRule mRule = MockitoJUnit.rule(); @Before public void se...
stackexchange/codereview
I am creating a drawing-app. I want to have a toolbar populated with tools. Each tool is defined in a separate js file. Right now i have defined each tool as an object that contains functions and variables that dictate it's behavior, for example i have 'setDragBehaviour()' and setDrawBehaviour()'. All these functions i...
stackexchange/codereview
I am new to Python and am trying to see if there is a cleaner way to write my code. The following code take iterables as parameter it produces the first value from the first parameter, then the first value from the the second parameter, ..., then the first value from the last parameter; then the second value from the f...
stackexchange/codereview
Write a function that takes in two sorted lists and outputs a sorted list that is their union Could anyone help me to improve this code and make it more user-friendly? We are not supposed to use any built-in Python functions, but rather develop our own efficient algorithms. def answer(list1, list2): len1 = len...
stackexchange/codereview
This is the first time I am working on OOJS code and I am a beginner in JS. I think I have pretty much messed it up. I am planning to modularize my code, but with the inclusion of rest calls, I got confused and have messed up my structure. The trouble I am facing is that my success function of Ajax call keeps growing w...
stackexchange/codereview
This is my account table: CREATE TABLE mwUser ( username varchar2(20) primary key not null, salt varchar2(64) unique not null, hashedpw varchar2(64) not null, email varchar2(320) unique not null ); When I register a new user with my java webservice I automatically generate a random salt and store in the dat...
stackexchange/codereview
I have stored in a XML file some Travel packages, each package has a code( the codes are stored in an array = $code). I am using the below code to pull the requested data from the XML based on the given code. At this time I have copy/paste the code for each given code, but I have lots more and I dont want to copy paste...
stackexchange/codereview
The code is completely functional but I'd rather not call two functions when I know it can be done more efficiently. My goal is to store EditText values in SharedPrefs using a single addTextChangedListener. Any advice is much appreciated! fun preserveText() { val sharedPref: SharedPreferences = PreferenceManag...
stackexchange/codereview
I wrote a script that moves files older than two days over to a network share (via scheduled task). Windows Task Scheduler doesn't seem to like the script so much, but it works well by itself. Is there a faster way than what I have? Is there a way to programmatically make it a scheduled task or service of some type? ...
stackexchange/codereview
I need to get this program reviewed. It is counting the lines of code in all files in the given directory. I'm new to python and need some advice on pretty much everything. #!/usr/bin/python import os import sys def CountFile(f): counter = 0 f = open(f, "r") for line in f.read().split('\n'): coun...
stackexchange/codereview
I was hoping for someone to review my current project, which was created in Swift and uses a PHP web service. I'm not worried about UI elements, as this is just a 'test' project, but I'm concerned about two things: using the best practices and security. I'm concerned that the SQL query is not safe, among other things. ...
stackexchange/codereview
I am fairly new to the Groovy arena. I recently modified some code to add the following block. This code is added to remove dates we were supposed to remove from the total counts. This data goes on reports that a bug was noticed, that we weren't removing the queue entry dates. result.processed.each{ def queueEntry...
stackexchange/codereview
I want to make the creation of the pack Uri for WPF resources more verbose so they are easier to read and less error-prone and I thought I implement it using the builder pattern. The base class for each builder (there are four of them) is the PackUriBuilder. It implements the UriKind logic, checks the path and requrie...
stackexchange/codereview
I have implemented a little Flappy Bird clone with swing. I'm pretty new to Java, especially in graphic programming, so I'm really glad if someone an give me a feedback to my Code and maybe to movement of the bird, because it's not really smooth. The bird is represented as a red square and the pipes are green rectangl...
stackexchange/codereview
I am implementing my own double-indirecting shared-ownership smart-pointer because I needed a way to replace the managed object a group of smart-pointers is pointing to with a new object (it's the method reset_all in the code below). I tried to keep this as close as I could to the std::shared_ptr's interface, while avo...
stackexchange/codereview
I'm trying to display data from Keen.io we're collecting from an iOS app where we report what devices of ours the app is used to communicate with. In particular I'm trying to find where there are more than one of our device. An entry from the Keen collection looks like: { "iOS_OpenUDID": "hexadecimal", "iOS_Country...
stackexchange/codereview
This is my RubyWarrior solution. I think RubyWarrior is well known to Ruby coders. I am starting to learn Ruby and I would appreciate some help from you to improve the organization or the mistakes that I could have. I don't need another example as the Internet is full of them, but what I need is some advice that I can...
stackexchange/codereview
After my Brainfuck Interpreter written in x86 Assembly I decided that it was time to get to the next step, writing a Brainfuck Compiler in Java that generates x86 Assembly and compiles that to an executable. Currently it only supports Windows and it still uses NASM and GCC as dependencies to transform the x86 Assembly ...
stackexchange/codereview
I'm currently trying to make the code of an app I'm developing a bit more efficient and easier to read. Basically what this does is after the user taps with two fingers (gesture) it retrieves a previously saved array from NSUserDefaults of player names, and fills in the 6 text boxes (tagged 6-11) on a table view with t...
stackexchange/codereview
This is a naive implementation - I know that there are algorithms like KMP However I was trying to implement it as best as I can. string test = "giladdarmonwhatareyoudoing"; int index = StrStr(test, "are"); //Returns an index to the first occurrence of str2 in str1, //or a -1 pointer if str2 is not part of str1. pub...
stackexchange/codereview
My first program using C. I would appreciate pointers on how to improve the code. I exit just before turns reach 9 and the grid is filled because it causes all sorts of bugs. The computer is random. #include <stdio.h> #include <stdlib.h> #include <time.h> // Struct with all game state variables. struct game_data { ...
stackexchange/codereview
A simple set of functions which solves the sliding pyramid problem. In summary, the task is to find the path from top to bottom of a triangular grid of numbers that has the smallest sum. The program uses the file input.txt as input. from time import time def build_tree(): with open("input.txt", "r") as file: ...
stackexchange/codereview
This is a very simple implementation of dragging elements in html/js. I'm working on a web application that could have thousands of draggable elements on screen at any given time. Currently, this code works perfectly as shown below (with only one draggable element), however if I copy and paste that element (<span class...
stackexchange/codereview
I am working on a project in which I am using vue js 2 and electron , to manage the state I use vuex , I have at least 20 actions to call methods: { ...mapActions('Store1', ['FETCH_AB',...]), ...mapActions('Store2', ['FETCH_DS',...]), ...mapActions('Store3', ['FETCH_SD']), ...mapAction...
stackexchange/codereview
This is my code, I like to put a console log so I know when stuff is rendering. const SignUpStepTwoPrivate = ({ route, navigation }) => { console.log( " %%%%%%%%%%%%%%%%%%%%%%% Sign Up Step Two rendered! %%%%%%%%%%%%%%%%%%%%%%" ); //TODO the watch(password) is re-rendering every input. const { width } = use...
stackexchange/codereview
I'm working on a primality test and have written a recursive function that returns the value of the function \$b^{q-1} \bmod q\$ where \$3<= q <= 32000\$ Is there any way to speed up my function? It works, but takes a while to return the answer as \$q\$ approaches 32000. Variables: pow = \$q-1\$ mod = \$q\$ b is ...
stackexchange/codereview
This is my draft implementation of Huffman encoding & decoding. I'd appreciate any feedback, but have a couple specific questions: I wrote the code assuming vector represents each bool with a single bit. Is there a standard way to check whether the STL used by the compiler actually does that? With concepts would be be...
stackexchange/codereview
I have a specific method that I like because it lets me decide whether or not I want to use the default. If I want anything different I enter in :option => value otherwise I get the default. Here's a concrete example that works, but is a little ugly. How can I accomplish the same thing in a more elegant manner? def con...
stackexchange/codereview
Given a fraction p/q, I want to count the number of unit fraction solutions $$\frac{p}{q} = \frac{1}{u} + \frac{1}{v}$$ with some contraints $$lower \le u \le upper$$ By manipulating the first equation and completing a square you arrive at a formula $$(pu - q)(pv - q) = q^2$$ So the number of solutions is related to th...
stackexchange/codereview
I have a DataTable with id, parent, label columns and want to populate a TreeView with it. I'm new to c# and as far as I understand, there is no ready solution for it, unlike some other languages. So I sorted the data hierarchically at DataTable level and wrote not a very pretty recursive method. Is this a good solutio...
stackexchange/codereview
Given a directed connected graphs, find all paths from source to destination. Looking for code review, optimizations and best practices. Also need help figuring out complexity, which in my best attempt is O(E!), where E is the number of edges. class GraphFindAllPaths<T> implements Iterable<T> { /* A map from node...
stackexchange/codereview
I've been working on my Rust a bit and want to know how idiomatic my rust code is for the following Project Euler problem: What is the largest prime factor of the number 600851475143 ? I'm not looking for ways to improve efficiency or how to improve the strategy, but purely what I can improve with my Rust technique. Th...
stackexchange/codereview
its a practice project from "Automate the Boring stuff with Python" book. i am an intermediate level Python programmer and i tried to solve this problem with less code as possible. This code will not take any wrong date into consideration eg: 29-02-2002 will not be selected because 2002 is not a leap year and only leap...
stackexchange/codereview
This is used on an Excel order form to calculate quantities in a userform for variables based on various criteria on the worksheet. It's too much code for a single Sub, but I'm not sure how I can make it any smaller or break it up. Private Sub UserForm_Activate() Dim LastRow As Integer LastRow = ActiveSheet.Cells(Rows....
stackexchange/codereview
I was looking for a way to markup parts of my app as restricted to only certain roles, on an element basis. This works quite well, using an attribute directive, where I specify the allowed roles and disable/hide the corresponding element; e.g. <input require-role="admin" /> In order to make the app more maintainable ...
stackexchange/codereview
I need your opinion about my practice. I want to improve it. The requirements are the following: RESTFUL + OWIN (SelfHosted) Endpoint - Upload a file asynchronously Make a request to the endpoint from Postman Well, This is what I got For the OWIN selfhosted I followed the Microsoft Documentation OWIN Self-host Endpo...
stackexchange/codereview
We have a "Committee" class and I need to ensure that any new committee has start and end dates (don't know why they're CharFields instead of Dates or even Ints, but that's not my call) that are after any existing instances. This works, but I would appreciate any general review as well as specifically on my solution t...
stackexchange/codereview
I've written what I think is a constant time implementation of a uniqueness check. I've seen many algorithms online, which run in linear time, but was wondering whether my conclusion that this runs in constant time was correct. I've seen many linear versions of this algorithm, but I haven't seen any that run in O(1). A...
stackexchange/codereview
The code below is an implementation of purely recursive solution to find a powerset of any given set. The input set is a string, and the output - array of strings. Both of them are wrapped into a structure for convenience. The underlying algorithm is pretty common one. The recursive function executes exactly 2^n - 1 t...
stackexchange/codereview
This here is a templated singly linked list that I have been working on for the past couple of days in C++. I am not a programmer or computer scientist by training; finishing up my undergrad in physics this fall but trying to add more skills to my toolkit, so to speak. I have been working my way through implementing th...
stackexchange/codereview
I have a vote and a comment table. Now I want to display all comments and order them by votes-sum. Sum because some votes can have a higher value than others. Therefore I want to display if the user has voted already on a comment. So I need to get that value too. This is my actual query: SELECT *, SUM(v.`value`) as vot...
stackexchange/codereview
Here is my word break problem in c# static void breakSentenceIntoWords(string input,List<string> validWords) { if (String.IsNullOrEmpty(input)) throw new Exception("String cannot be empty"); int indicator = 0; StringBuilder builder = new StringBuilder(); for (int i = 0; ...
stackexchange/codereview
Swift's SequenceType is a useful means of generating a sequence of values, and it makes it particularly useful iterate over these values. I don't really have much experience with these SequenceType types, so I wanted to implement my own for some practice and learning. What better sequence to take a look at than a Fizz...
stackexchange/codereview
I'm reasonably new to D3, and I've put together a class based React component which outputs a genomic alignment visually. The result looks like this: The component is as follows: import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import * as d3 from 'd3'; const Sty...
stackexchange/codereview
I started off with a simple dispatch class, but it's grown and I'm sure it could be simplified in the very least. In fact, I'm doing way too much in the __construct() method It it being called as such: $router = new router($_SERVER['REQUEST_URI'], $database); $router->dispatch(); Yep, I'm pushing my database object i...
stackexchange/codereview
I'm looking for advice / best practice to avoid doing a deeply nested set of IF/THEN statements in Rails. The intention is to seed a database. Short version - without specific examples My basic pattern is 1 .. n IF(1st_object_exists) THEN 2nd_object = 1st_object.relationship.create!(args) IF (2nd_object) THEN 3r...
stackexchange/codereview
I wrote a thread pool where the user can submit jobs through ThreadTask objects. These objects bundle the job priority, the task as a function, and some arbitrary number of function parameters. After much frustration I ended up with something like this: struct ThreadTask { template <typename Func, typename... Args>...
stackexchange/codereview
We are given an array of intervals we need to merge all overlapping intervals and sort the resulting non-overlapping intervals. When they "touch" in a single point, intervals are also considered to be overlapping . class Span { public uint Start { get; } public uint End { get; } private Span(uint start, ui...
stackexchange/codereview
I have this Python program for calculating Leibniz of 'pi'. I am not able to shorten it more. Can anyone here optimise/shorten it? s,a,b=0,[],[] for i in range(int(input())):a.append(input()) for x in a: for j in range(int(x)):s+=pow(-1,int(j))/((2*int(j))+1) b.append(s) s=0 for i in b:print("{0:.15f}".form...
stackexchange/codereview
This is my first time building anything remotely like a robust database. I'm midway through designing it and I would be grateful if you have suggestions or have found any logical errors. Goal: allow authenticated users to enter data for multiple hospitals. My database has three tables: User, Hospital, and Data. A User ...
stackexchange/codereview
Introduction to the problem You are free to implement any mechanism for feeding input into your solution. You should provide sufficient evidence with unit tests that your solution is complete. As a minimum, please use the provided test data to indicate that the solution works correctly. Any programming language can b...
stackexchange/codereview
export function addition(a: number, b: number) { return a + b; } export function subtraction(a: number, b: number) { return a - b; } The code is the same except the operator. Is it possible to avoid code duplication in such cases?
stackexchange/codereview
I am studying graphs and I am trying to make a library in C# for myself and anyone else interested, that is didactic and simple, so I can remember how to solve common problems. I would like to improve it. How can I improve, for example, the DFS, complete the Prim's algorithm and implement the Kruskal's and Dijkstra's a...
stackexchange/codereview
I'm experimenting with ways to reuse code throughout a Rails web app. I'm interested in feedback concerning one such approach! Context A user's request may be scoped to a physical location so that the view shows location-relevant information. In most cases, the location is stored in a cookie. It's possible for location...
stackexchange/codereview
I am new to Java and learning about Strings in Java. So I wrote a program which counts the number of times a character repeats in a String and also identifies unique characters(chars not repeated more than once) in a String. Is this an efficient way to do this? public static String uniqueValues(String str){ char[] arr...
stackexchange/codereview
I am fairly new at writing jQuery plugins. Moreover, I am a huge fan of best practice. I have written a plugin which centers an element inside its parent. I would love some feedback on how I could have written it better. (function( $ ){ $.fn.verticalCenter = function(options) { var settings = $.extend({ ...
stackexchange/codereview
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. I could not find an out-of-the-box solution online so I created my own with what I could find. Out of curiosity and a willingness to learn, as well as to maybe serve the needs of others try...
stackexchange/codereview
Update: there is a new version of this code: v4 is posted here Goal: implement traits that for anything callable return its arity, return type and the argument types. Since pointers to data members are also callable, those should be handled (and be considered 0-arity). Code below, try here. This is v3 (v2 here), incor...
stackexchange/codereview
This is a follow-up to the previous question: Implementation of the linked list data structure in C++ I've tried to improve the design of the previous code by fixing some indexes that could go out of range and cause the dereferencing of a nullptr, and minor changes for compactness and elegance. However, I'm not sure ab...
stackexchange/codereview
I have written the following Tampermonkey/Greasemonkey script. I am trying to obtain a list of all CSS rules for a page; across all stylesheets. As of now, I am just iterating over everything. Is there a faster way to obtain the rules? Also, I feel that there is a more efficient way of converting the CSS text to an obj...
stackexchange/codereview
here it is my simple cash register app. It lacks some functionality ( class Payments should have more options like daily statements etc, class TillSettings needs more settings as well) but it does the job. Simple Cash Register and Stock Manager allows to add items to stock and then sell it and register total value of s...
stackexchange/codereview
I posted a couple of weeks ago with a double linked list. It was recommended that I rewrite the code as a singlely linked list and replace the recursive parts with loops. I've gone ahead and made several edits and was hoping to get another critique of the code. #include <stdio.h> #include <stdlib.h> #include <stdbool....
stackexchange/codereview
I have written a double linked list in Scala. The list should be fixed in size and items are always added to the head. if the list reaches max size then the tail is dropped. This is my code. I want to review this for brevity and functional approach. sealed trait List { var prev : List var next : List } case ob...
stackexchange/codereview
I'm trying to figure out a way to make my code more readable and maintainable. While rewriting some ugly spaghetti code, I stumbled across this: if($header !== null && $fieldValue === null) { $errorMessage = $message . ': row ' . $row . ', header "' . $header . "\"\n"; } elseif($header === null && $fieldValue !== ...
stackexchange/codereview
I have implemented a binary search algorithm in C#. Can anyone give me suggestions on improving its effectiveness? using System; namespace bs2 { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int[] arr = new int[n]; ...
stackexchange/codereview
(I created a GitHub repository; there are few improvements as suggested by other users in the comments) As we know, C99 has no garbage collector. To address the problem of manually deallocate objects I wrote a little framework for reference counting. I would like to have comments about the style and clarity of the code...
stackexchange/codereview
I wrote two microservices in Springboot and tried to follow the best practices. I would appreciate any suggestions about any improvement that I can make on the whole codebase. What are the parts of the code that I can improve on the whole project? Project Link: https://github.com/forhadmethun/mbank Technology used: Jav...
stackexchange/codereview
I'm looking to learn how to write efficient Haskell code. This snippet works, but the run time is slow. How can I write faster Haskell code? Input: maxPrice = 7 Input: vendorsDelivery = [5, 4, 2, 3] Input: vendorsProducts = [[1, 1, 1],[3, -1, 3],[-1, 2, 2],[5, -1, -1]] Output: [1,2] (fastest delivery time for a given ...
stackexchange/codereview
So I am a newbie obviously, This was part of a small assignment I had to do for Uni, and it works alright. It just reads a number from the console and then outputs the Greek letter Φ (sort of). Sure it could use some outofbound exceptions etc, but my question is this: My code overall (not just in this example) seems a ...
stackexchange/codereview
I currently have a dictionary (Duplicate_combos) that has a unique identifying number for the key value and the value is a list with two elements, a company code and then either a yes or no (both of these values are currently stored as strings). I am essentially just trying to see where the company code is equal and th...
stackexchange/codereview
I've done it in C# before but thought that a functional language would be a good fit for this kind of thing. From this ascending list of integers: [100,103,106,112,118,121] I had to calculate the difference between two consecutive numbers and group them while the result doesn't change. The final output must be a str...
stackexchange/codereview
In the beginning, everything is defined to be of value 10, but I have to change them to suit them for different possible values, hence those are changing. I'm a (Im)mature C coder, hence there might be trivial mistakes. I would like to get feedback on how to improve it. #include <stdio.h> #include <stdlib.h> #define...
stackexchange/codereview
Lately I've been working on a practice project using JS ES6 to understand it better, therefore I've read a lot about JS design patterns and JS coding strategy. My question is about splitting the functionality of the project so I have to briefly explain to what I'm trying to do in this project. I have an input that gets...
stackexchange/codereview
I implemented the tee command from linux. The program implements the -a option Reads standard input until end-of-file, write a copy of the input to standard output and to the file named in argv[1]. This is another implementation of the tee command. I posted another code trying to implement the command, but I think I fo...
stackexchange/codereview
I am brand new to writing hooks and I am having a little trouble getting my head wrapped around it. Initially, I wanted to write this with one event listener that passed the event and a separate param to distinguish itself from the other incoming arguments. With hooks, I was confused as to how I should pass a separate...
stackexchange/codereview
I have a service which receives many requests and I am trying to optimize it by aggregating requests in batches and then processing batch which is much quicker than processing requests one by one. That worked better than expected and I decided to try and make this batch processor generic. Here is code for BatchCollecti...
stackexchange/codereview
To test the queue I perfected from one of my CR questions, I've developed a maze program that receives an input maze, starting and end positions, and solves it. I have separate software that handles the maze execution and file parsing. I'm curious as to whether my implementation is optimal (fully expecting it to not be...
stackexchange/codereview
I am trying to implement a singleton builder that would be shared across multiple builder threads for Coordinate objects. Here is the simplified target class Coordinate with only two Integer fields. public class Coordinate { private final Integer x; private final Integer y; private Coordinate(CoordinateBui...
stackexchange/codereview
Was asked this today in an interview. Didn't see it before, and spent quite a lot of time getting it to work (tricky with all the recursion). The goal was to find all possible combinations of choosing k elements from a n-sized array (basically the Binomial coefficient) and return them. Unlike this code - here I don't ...
stackexchange/codereview
I've implemented the well known Luhn Algorithm in Python. It's a simple one, so it's good for beginners. import random from math import ceil def Luhn(digits): if digits >= 2: num = random.randrange(10**(digits-2),10**(digits-1)) num_digits = list(str(num)) for i in range(0,digits-1): ...
stackexchange/codereview
Selection Sort The selection sort algorithm sorts a list (array) by finding the minimum element from the right (unsorted part) of the list and putting it at the left (sorted part) of the list. The algorithm maintains two sub-lists in a given input list. The already sorted sub-list The remaining unsorted sub-list Bubb...
stackexchange/codereview
I start with an hourly table that has around 40 of items (example: bread, barley, bagels, beef, chicken). The purpose of my code is to aggregate this hourly table's numbers to daily numbers but broken out by a sublocation or "type". My only way to allocate to type is to use a table that shows the % breakdown of type to...
stackexchange/codereview
I have just written a PHP router, but I have some security concerns about this function. I am trying to serve all the content of a folder using this function. I am trying to prevent harmful URLs. public static function set_up($reletive_path = true) { self::$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); ...
stackexchange/codereview
I wrote a very simple implementation of cycle detection in an undirected graph; I'm not interested in applying it to any real-life case: it's just for explaining the basic idea behind cycle detection in a CS lesson. I went for recursive DFS, and unlike other implementations I found on the internet, I used just one set ...
stackexchange/codereview