instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I've been working on an app based on the MEAN Framework. I have got the app working but I just wasnt sure whether my coding structure and standard was good enough, meaning does it adhere to the programming standards in terms of structure, security etc. So I'll explain my app: A very simple app, it consists of a MongoDB...
stackexchange/codereview
I had a task to reduce my Lisp Interpreter from 400 lines to 120 lines. I was able to bring it down to 255 lines without including newline after every function. I'm not able to figure out where I can reduce the lines of code. I wanted a different perspective to my code probably a repeating pattern which i'm not able to...
stackexchange/codereview
Search in a 2D array to check if there is a column or a row in the 2D Array thats contains all the word “error”, if yes return the index of that row or column else return 0; Exception: if the row index equals the column index then it does not matter if contains the word "error" or not. FYI, n is the size of 2D array (...
stackexchange/codereview
I've created a program for my job that unlocks spreadsheet files quickly and efficiently. What we use to have to do before this program is we'd have to go into the system, search for the file, kill the users process containing the file, unlock the file, then the user can finally get back into their spreadsheet. With my...
stackexchange/codereview
After watching Stroustrup's presentation on performance comparison between vectors and linked lists (https://youtu.be/YQs6IC-vgmo?si=9r5wXqnwkmN29xqn), I've decided it would be a good problem to get a hang of C. To that end, I've profiled how long gthe removal of all elements from the lists by sampling random indices t...
stackexchange/codereview
I'm writing method that takes a pandas iterator and then computes something based on that. The problem is that some of these computations require iterating twice over the data. For example the normalized variance needs to first iterate over the data to compute the mean, and then iterate again to compute the (normalized...
stackexchange/codereview
I'm working on getting switch and if statements down and I came up with this. It works well and I don't have any problems with it running properly. I was wondering if I could get some feedback on how I put it together. If there are things I am doing wrong or could do better, I'm very open to suggestions! public stat...
stackexchange/codereview
In my company, I've inherited some Java library that I'm now writing tests to, refactoring and fixing Sonar issues. One particular point that Sonar is complaining about is a big chaining of if/else if/else statements, that is used in a class responsible for parsing values that come from the DB to the corresponding valu...
stackexchange/codereview
Today's code is a filtering streambuf (and associated stream type) to automate word-wrapped output in C++: #include <iostream> #include <streambuf> #include <iomanip> class widthbuf: public std::streambuf { public: widthbuf(int w, std::streambuf* s) : indent_width(0), def_width(w), width(...
stackexchange/codereview
This is a ReactJS component that accepts a date and displays how long ago this date was (5 seconds ago, 3 minutes ago, 5 hours ago, ...) + it uses a setTimeout to automatically update itself when the state.displayDate changes. What's going on: On ComponentWillMount: set state.date from props Update the state.display...
stackexchange/codereview
I'm going through the eBook Intro to App Development with Swift by Apple and I am making the Rock, Paper, Scissors app in lesson 20. This is the assignment that I got: [...] Name the enum Sign. Add a calculated property to give the emoji that represents the Sign. [...] You need to be able to compare two Sign instances...
stackexchange/codereview
Since I have little to no knowledge about native languages, I tried once more to write a simple application in C++, this time with a Brainfuck parser. It works, kind of, verified with the Hello World and Cat examples given in the Esolang wiki. So...what did I just break? #include <iostream> #include <fstream> using na...
stackexchange/codereview
I am also pretty new to Python so I want to show my code for a very small currency converter with an Tkinter GUI. The code does what I want, but now I want to optimize it and find new "next level" topics for me to learn. So I would be happy if some of you could take a look on my code and please give me constructive cri...
stackexchange/codereview
Kindly provide your review comments: //SmartPtr.h class RefCount { public: void AddRef() { ++(this->_count); } int Release() { return --(this->_count); } private: int _count; }; template <class T> class SmartPtr { public: // constructor SmartPtr(); SmartPtr(T* iObject)...
stackexchange/codereview
I wonder which is better practice when I need to return the primary key value of a newly inserted record from a SQL stored procedure. Consider the following implementations: As Return Value CREATE PROCEDURE [CreateRecord] ( @value NVARCHAR(128) ) AS BEGIN INSERT [Records] ( [Value] ) VALUES ( @value ); RETURN S...
stackexchange/codereview
Someone says that my PHP code is vulnerable to XSS. I asked them what I should do to fix it, but now they don't want to help. $action=$_REQUEST['action']; /* send the submitted data */ { $name=$_REQUEST['name']; $email=$_REQUEST['email']; $message=$_REQUEST['message']; if (($name==""...
stackexchange/codereview
The problem I have a program that takes a file of DNA sequences as input and writes each entry to one of two output files: one file for sequences containing only canonical characters (A, C, G, and T), and another file for sequences containing non-canonical (or ambiguous) characters. The data DNA sequencing machines pro...
stackexchange/codereview
My Windows desktop is messy with many files of different types here and there, therefore I thought of writing a program to organize it, and other directories too, for me. Here is my code: import os import shutil class File: """Represents a computer file. attributes: path, name, extension """ def __in...
stackexchange/codereview
I use the following method to scan and index video files and pass data to an array. I get video file duration, file name, files size. Is there any better method, or do I need to improve? public static void load_Directory_Files(File directory) { File[] fileList = directory.listFiles(); if(fileList != null && fil...
stackexchange/codereview
I wanted to practice my programming skill and I started solving exercises from kata-logs site. The exercise: The game consists of 10 frames. In each frame the player has two rolls to knock down 10 pins. The score for the frame is the total number of pins knocked down, plus bonuses for strikes and spares. A spare i...
stackexchange/codereview
I've created a neural network that attempts to detect when a DDOS attack is happening but it only gets to 89.6% accuracy before plateauing. My code: import os import arff import numpy as np from matplotlib import pyplot as plt from keras.layers import Dense, Dropout from keras.models import Sequential from keras.call...
stackexchange/codereview
I use Python for various computational reactor modeling activities. While there are many components to the models I develop, the basic structure of the project folder tends to be similar to the following: pyreactor/ ├── gas_properties.py ├── geometry.py ├── main.py ├── parameters.py ├── results │   ├── fig1.pdf │   └──...
stackexchange/codereview
I am currently setting over a hundred global variables by performing individual checks against the URL string. var Query_MenuTiles = getParameterByName("menutiles") var Query_Link = getParameterByName("link") var Query_Speed = getParameterByName("speed") Unless it would slow things down, I assume that setting keys and...
stackexchange/codereview
I am a beginner (with zero Python experience) working through the book Automate the boring stuff with Python. At the end of Chapter 4, the author provides a review problem. I was supposed to write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space,...
stackexchange/codereview
I have written the following Javascript class function InScroll( container, options ) { "use strict"; var isRunning = false; // utilities var noop = function() {}; var inter = null; if(!container) { alert('container element not provided'); return; } if(!options.interva...
stackexchange/codereview
from typing import List import itertools my_string = "Atunci când citești un text trebuie să fii capabil să identifici ideea principală a textului și să o poți formula în propriile tale cuvinte" my_list : List[str] = my_string.split(' ') my_list2 : List[str| int] = [item for lis in list((len(word), word) if len(word)...
stackexchange/codereview
Using LaTeX creates a bunch of auxiliary files like foo.aux, foo.log, etc. Sometimes, I want to create a clean run of my document. I usually manually execute this in the terminal as $ ls foo* foo.tex foo.aux foo.log foo.bbl foo-blx.bib $ rm foo{.aux,.log,.bbl,-blx.bib} This works fine. However, it is error-prone and I...
stackexchange/codereview
I have implemented as follows, a class applying singleton pattern to get a global single access to database. I intend to provide a thread-safe implementation. using System.Data.SqlClient; public sealed class Database { private static volatile SqlConnection instance; private static object syncRoot =...
stackexchange/codereview
I created a customised GUI application in Python, which is a calculator that does some basic functions for my company. I would like to ask you for overall suggestions for code improvement. # -*- coding: utf-8 -*- """ Created on Tue Mar 20 17:18:39 2018 @author: Dimitar Dimov """ import PIL import Tkinter import Tkint...
stackexchange/codereview
Inspired by another question here on Code Review, I decided to try implementing a Fraction type in Rust. Requirements: Able to be added, subtracted, multiplied, divided Able to be compared (equality and ordering) Able to be converted to the floating point representation of the fraction When printed to screen, automati...
stackexchange/codereview
Input The first line of input contains a string s: the word misspelled by your partner. Assume that your partner did not add or remove any letters; they only replaced letters with incorrect ones. The next line contains a single positive integer n indicating the number of possible valid words that your partner could ha...
stackexchange/codereview
I need to get a selection of dates from the given to the current, breaking the range of dates into equal parts of 3 months. My code works, but it's clearly not perfect. Give advice on code refactoring. from datetime import datetime from dateutil.relativedelta import relativedelta start_date = "2021-03-30" def get_da...
stackexchange/codereview
This is my project(beta) after studying for 3 weeks. It took me more or less 30 hours of writing and researching. I would appreciate a review based on my beginner level. I'm very proud of it, it was hard work for me. Learned... Files management, control if for while loops, integers and strings, lists dictionaries and t...
stackexchange/codereview
I implemented a card game using pygame, the game is a game of war and using png files that I made in Microsoft paint. I tried to keep the object classes as separated from the pygame module as possible. The idea of this is so I can use the CardClasses module with other graphical interfaces, and to reuse it on different ...
stackexchange/codereview
User specification "var_dump($GLOBALS) is ugly as ... without wamp" General specification Produce a PHP function to display the contents of $GLOABLS in a user-friendly manner Must produce properly indented HTML Must include appropriate CSS classes for customisability So far, this is what I've got: function __printR...
stackexchange/codereview
I am avery beginner at SPring MVC, Mongodb and java. I am trying to make a sample application so that the user can serach, create, update and delete a customer: My CustomerDAO class: package com.example; import com.mongodb.BasicDBObject; import com.mongodb.DBCursor; import com.mongodb.MongoClient; import com.mongodb.cl...
stackexchange/codereview
This is an mqtt driven, interactive, and asynchronous remote shell daemon written in bash. I call it "MqSH" or simply "mq". It works with bash, the busybox ash shell, and perhaps other Bourne-like shells. It's designed for embedded devices with low system resource, so I wrote to be friendly to busybox-based systems. It...
stackexchange/codereview
I have an imperative programming background and I've decided to study functional programming by applying it to problems found on sites such as Project Euler and Rosalind. My language of choice is Scheme (I use CHICKEN). As can be seen, I'm only starting out. This is about the 3rd problem found on Rosalind, that goes li...
stackexchange/codereview
JavaScript beginner here! I have written a Tic Tac Toe game is JS that seems to be unbeatable (Title says 'almost' because I'm not sure if it's really unbeatable or just I can't beat it :) ). I really appreciate any help to improve my code and learn from my mistakes. Project's CodePen = https://codepen.io/MiladM1715/...
stackexchange/codereview
(This post has part II/II.) Intro This time, I have this GitHub repository. The idea is that if the graph node expansion is slow (for example, in the case where you ask a web server to return some data), it make sense to have multiple threads to do the graph crawling. Benchmark output Random seed = 1710824771814. Sourc...
stackexchange/codereview
I'm intern and work on a project where I develop DRF API that need to interact with mobile app written by my colleague with Ionic framework. We are creating new user. My view method is following: class NewUser(generics.CreateAPIView): model = User permission_classes = [permissions.AllowAny] serializer_clas...
stackexchange/codereview
I got this question from the interviewbit site test. There are n horses and you are the kth person in the line to ride on the horse. All the persons in the queue will go with the lowest numbered horse available i.e if horse no.1 and horse no.2 are present , the person will choose horse no.1 .All the horses have their o...
stackexchange/codereview
Curious what people think about this implementation of Conway's Game of Life in Haskell. {-# LANGUAGE QuasiQuotes #-} module Test.Conway ( conwayCalculateAge, conwayStep, conwayMakeRandom, conwayMakeRandomIO, conwayMakeEmpty ) where import Data.Array.Repa import Data.Array.Repa.Stencil...
stackexchange/codereview
I had the idea to have a static method on an activity which creates intents that it can use. For example if I have an activity with a webview that can load html from a resource or a URL I would have 2 methods in the activity like so. public static Intent createURLIntent(Context context, int titleId, String URL) { I...
stackexchange/codereview
I wrote a class that generates combinatorial necklaces with fixed content as per Sawada: A fast algorithm to generate necklaces with fixed content. The class is instantiated with an input list that states the occurrence of each value that is to appear in the necklace. The execute method is called to run either Sawada's...
stackexchange/codereview
I want to limit the request rate in a spray/akka-http route. I'm not an expert with both scala and spray/akka but learning. So I came up with the following custom directive: trait RequestRateLimiter[T] { def check(ctx: RequestContext, realIp: Option[RemoteAddress], proxiedIp: Option[RemoteAddress]) : RequestRateR...
stackexchange/codereview
Is there a simpler way to implement this function? function has_duplicates(arr) { var myObject = {}; for (var key in arr) { if (myObject[arr[key]]) return true; else myObject[arr[key]] = true; } return false; } console.log(has_duplicates(["foo", "bar", "baz", "quux", "foo"]));
stackexchange/codereview
I have to implement a relatively basic order system in Java for part of the process of a job interview. At the moment I have working code that allows for the creation, and updating of orders for an imaginary company that manufactures bricks. Before I submit the codebase to the company I am interviewing for I want my co...
stackexchange/codereview
This is a continuation of the last thread. I wanted to add a thread-safety and I was considering AwaitableCriticalSection and Task+Mutex. I ended up with mutex; it can be a bit slower but it would allow different files to be stored independently. public static async Task<T> ReadJson<T>(String fileName) { if (Strin...
stackexchange/codereview
My implementation of a binary-to-bits converting function: #include <stdio.h> #include <limits.h> unsigned char *return_byte (unsigned char source) { static unsigned char byte[CHAR_BIT]; unsigned char *p = byte, i; for(i = 0; i < CHAR_BIT; i++) p[i] = '0' + ((source & (1 << i)) > 0); return p...
stackexchange/codereview
I'm working on my first Windows Forms tool for a project; this is my first time using C# extensively. Right now, my only objective is to be able to open an XML file and have the resulting XML in hand. I know this works, but I want to know if there's a better, or proper, way to do it. There is also the issue that when I...
stackexchange/codereview
I am trying to build a neural network classifier. I have created a neural network with 1 hidden layer (25 neurons) and 1 output layer (1 neuron/binary classification). The dataset I am using has the following dimensions: size(X_Train): 125973 x 122 size(Y_Train): 125973 x 1 size(X_Test): 22543 x 122 size(Y_test): 22543...
stackexchange/codereview
For a very simple databaseless website, I'm using an associative array to store logins like this: $logins = array( 'user' => 'password', 'user2' => 'password2', ); I check login attemps using this code: $user = strtolower($_POST['username']); $pass = $_POST['password']; if(!isset($logins[$user]) or $logins[$user] != $...
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
I am creating an API for a version control system. This is my first time creating an API (and a web project in general) and I wanted to get some feedback. I plan to connect this API to a frontend to create website. I choose to share this part of the code because the rest of the code follows this structure. For referenc...
stackexchange/codereview
A friend posed to me a question to see if I could solve it. He says I solved it appropriately. I was hoping someone here could give me a review of the program I wrote to answer it. I figured it would be a good exercise in trying to do things as well as possible and try to follow conventions. The problem Aaron and Alexa...
stackexchange/codereview
i have the following json object const file = [ { "seatNumber": "1A", "price": "£19.99", "available": true, "disabilityAccessible": true }, { "seatNumber": "2A", "price": "£19.99", "available": false, "disabilityAccessible": false }, { "seatNumber": "3A", "price": "...
stackexchange/codereview
This is a continuation of my earlier question. I have a plain text file with the content of a dictionary (Webster's Unabridged Dictionary) in this format: A A (named a in the English, and most commonly ä in other languages). Defn: The first letter of the English and of many other alphabets. The capital A of the alpha...
stackexchange/codereview
I have a very simple helper class to validate credentials. Sometimes the domain has a value, sometimes not. Depending on this, a different constructor for PrincipalContext must be used. PrincipalContext is disposable, so I am using using. It looks ugly, and recommendations? public class LDAPManager : ILDAPManager { ...
stackexchange/codereview
I am new to functional programming. Just now I solved my first "real world" task using Haskell and now I'm wondering whether I got it "right" and what can be improved. The problem arises from tensor calculations (I am a theoretical physicist), where I have the tensor product of \$\frac{n}{2}\$ identical symmetric tenso...
stackexchange/codereview
I have sample graphs like the following (un-directed un-weighted cyclic graphs). My goal is to find the shortest path between a given source and destination. I have found this implementation on web and have made some modifications only. How can the code be improved? Are there any gotchas that I need to take care of? fi...
stackexchange/codereview
I'm just here for suggestions and code optimisations, what i could've done better, are there any better coding practices... There's github repo link if you're interested in the code with a form too https://github.com/throtz/Operators You basically have 2 textboxes in which you enter numbers and choose with a combobox w...
stackexchange/codereview
I am working on a program that is meant to fold a large input line into smaller ones. Basic flow of the program would be as follows: User calls the program with a long string as input Program prints tokens generated in separate lines I haven't seen handling file input yet, so keep that in mind. I haven't seen reading...
stackexchange/codereview
I have written an API for a dating service. This part is related to user authentification, authorization, login and etc. It uses FastAPI, which in turn is based on starlette web server. You may wonder what is fastapi.Depends.... It's internally calling a passed function when the endpoint is requested to satisfy its dep...
stackexchange/codereview
I know that this program is not very outstanding, but I'm learning "Python" and decided to publish this code in order to get some advice and parting words and overall evaluation of the program. This is a simple timer with the ability to enter the desired number of minutes, start and reset functions. As a beginner, it i...
stackexchange/codereview
The data I'm using is summoning rates from a gacha game, One Piece Treasure Cruise. The game provides the probability of getting a certain character in percents rounded to the nearest thousandth. However, the data does not sum to 100%, so I want to find the original fractions used to calculate those decimals. I've pro...
stackexchange/codereview
I have written a program that makes it possible to write as cool as the cool kids. All you have to do is enter the boring, normal text, which is then transformed into an exciting, stylish text. Is there a possibilty to make the code more performant without decreasing it's readability? Example Output: I H@Ve wRITTen @ ...
stackexchange/codereview
My code looks like "spaghetti code". I have yet to use OOP in PHP but I am really interested in how a good programmer would handle this many if statements. It looks like a mess. <?php session_start(); include './functions.php'; if(empty($_FILES['browseMovie']) || empty($_FILES['browseThumbnail']) || empty(...
stackexchange/codereview
Is this the best way of doing this? I wanted to make sure the grammar is correct when the array is output. 1 car, 2 cars. The output is correct but is there an easier way generally? I just want to make sure I am doing this in a proper way. I don't have the benefit of the experience of the majority of you guys so I am a...
stackexchange/codereview
$(document).on('dblclick', '#li', function () { oriVal = $(this).text(); $(this).text(""); input = $("<input type='text'>"); input.appendTo('#li').focus(); }); $(document).on('focusout', 'input', function () { if (input.val() != "") { newInput = input.val(); $(this).hide(); ...
stackexchange/codereview
I use a lot of lambda expressions in C#, so I've decided to create some similar functionality in JavaScript. Since jQuery is included in my projects, I'm using $.grep() instead of Array.prototype.filter() to support older browsers without including shims. The two examples below corresponds to Where() and FirstOrDefault...
stackexchange/codereview
I've written a function which should generate an ISO 8601 duration string, given two Dates as input. import { differenceInYears, differenceInMonths, differenceInWeeks, differenceInDays, getDaysInYear, eachYearOfInterval, } from 'date-fns/esm'; // v2.11.0 /** * Given a start Date and an end Date, returns a...
stackexchange/codereview
I have a complex directory structure on my web server that includes .tar files for download; I'm trying to create a report on the size distribution of these files (e.g. 10 are less than 1MB, two are 1-2MB, three are 2-3MB...) Is there a better way to organize this code? I started it as a console application, writing d...
stackexchange/codereview
(See also the Algorithms part.) Post details The program I am putting for being reviewed does not fit entirely in a single post, so I have to resort to the equation by Niklaus Wirth: Algorithms + Data Structures = Programs This part is about data structures: a set of classes that do not do anything fancy. Of course, ...
stackexchange/codereview
#! python3 # `regexSearch`: Finds all lines matching a given regex in each file in a given folder. # Usage: # The directory to search and regex to be searched for are provided as a command line arguments. # The 1st and 2nd command line arguments are the directory and regex pattern respectively. # ...
stackexchange/codereview
I am trying to implement the code described this post about how Reddit identifies duplicate user names (I do believe it is called binary search). Just to clarify, this is mainly for me figuring out how these things work; thanks @Graipher for pointing to bisect). The way I understand it, the steps are: You have a new u...
stackexchange/codereview
How can I simplify this functioning JQuery validation process: class UserEdit { addUser(uobj) { if(uobj.adduser == "" && uobj.addfullname == "" && uobj.addemail == "" && uobj.addlevel == "") { $('#adduserError').show(); $('#addfullnameError').show(); $('#addemailError').show(); ...
stackexchange/codereview
My function is a solution to the Knight's Travails problem. It receives start and end point coordinates on a chess board, and must return the shortest path from start to end. class Node{ constructor(coordinates){ this.value=coordinates this.possibleMoves=[] } } class Tree{ constructor(star...
stackexchange/codereview
So I've attempted this project from hyperskills where you're asked to make a calculator script that can calculate annuity and differentiated payments given that 3 of 4 values are known. I think i went with a real hardcoding way of doing this, as such I would like some advice on making my code more compact and efficient...
stackexchange/codereview
I'm keen to get some feedback on how I have utilized the Revealing Module pattern here. This code is part of a web application that is used by the public. The purpose of this code is to encapsulate all logic concerned with sending events to Google Analytics within a module...called GAU, which is short for googleAnalyti...
stackexchange/codereview
I wrote a Risk battle simulator that returned the odds of every possible outcome and put it up to be reviewed here. I used the comments to improve it, and am wondering if it can be optimized further. #include <iostream> #include <iomanip> #include <cmath> #include <vector> using namespace std; class battle { publ...
stackexchange/codereview
From SICP Exercise 1.3: Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers. Square is: (define (square x) (* x x)) I know the code could be written using language features like lambda or let, but first to remain true to the exercise, I wouldn't use ...
stackexchange/codereview
I am a Java programmer who has C this semester. Needless to say, my writing style is heavily influenced by Java, which is probably not a great thing. I'd be grateful for a few nudges in the right direction. Here's the code: #include <stdio.h> #include <stdlib.h> #include <string.h> #define LEN 100 #define WID 80 void ...
stackexchange/codereview
I'm trying to learn and write best practice unittests and practice test driven design. Can you give me some tips and review my code? using System.Threading.Tasks; using Moq; using Xunit; namespace Blockchain.Unittests { public class AccountShould { private static string _webUrl = "https://test.test/tes...
stackexchange/codereview
I have a class that I am using to generate 10 character alphanumeric 'tokens' (Strings) and writing them to a txt file. I would like to be able to generate as many as possible as quickly as possible without producing any duplicates. This is what I have so far: import java.io.BufferedWriter; import java.io.File; import...
stackexchange/codereview
I want to make a general alert dialog to use across the whole app. I created a class called AlertDialogManager and just one method to show AlertDialog. Is there a way to refine my code or this code? import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; public class Ale...
stackexchange/codereview
The code is working perfectly. I'm little bit sure this is a packet what I am sending from client to server in streams. Is this packet? Am I sending in a right way? Another thing is that I am sending ACK from server to client. Is this right way to send ACK and NACK? Moreover, I am parsing on client side the ACK and che...
stackexchange/codereview
I am working on a script that recursively searches a directory to find files which matches a regex 5 or more times. Using the script I can search for files which look like https://github.com/nicolargo/glances/issues/1087 https://askubuntu.com/questions/758696/cannot-login-into-locked-ubuntu-14-04-session-unity https://...
stackexchange/codereview
I use this node.js script to migrate MongoDB collection to a schema to another. It does work if the collection is <20k documents, but slows down to a crawl and sometime throw a FATAL ERROR: JS Allocation failed - process out of memory Is it because of a memory leak? Or the intensive call to process.nextTick() (once p...
stackexchange/codereview
I am modeling a linear process at a number of equally spaced time steps. I have a large list (~70k elements) which corresponds to a location at each time step, timerange = np.linspace(0, time, iterations, False) * speed. For each element in this list, I want to compare its value (location) to two other lists and see if...
stackexchange/codereview
Can you improve? rc = [] for i, j in zip(A_response, B_response): rc.append(i) rc.append(j) I use zip and append, but could this be better using list comprehension?
stackexchange/codereview
Reversi Game: The image from the Reversi game: I have my algorithm to find all legal moves in Reversi game. Here's the code with comments: """ -1 => no disc 0/1 => player's disc """ for row_idx, row in enumerate(board): for column_idx, column in enumerate(board): if board[row_idx][column_idx] == -1: ...
stackexchange/codereview
I've been trying to write a really basic function to determine the difference (in days) between two dates. I am very new to C++ so as you can imagine I am very happy with my work. This function is part of a much larger code so I have missed off my includes, but the function does compile without warnings. Just looking f...
stackexchange/codereview
I want to design an elevator system, which has functionality for pressing button from outside of the elevator (Not selecting a direction - Only calls the passenger’s existing floor). And also select floor functionality needed to select a floor for target. Inside controls have priority over outside controls. While trave...
stackexchange/codereview
I'm doing freeCodeCamp's Coding Interview Prep to improve my JavaScript skills. This challenge is called "Word Frequency", and is based on the Rosetta Code's entry of the same name. The version I'm solving says: Given a text string and an integer n, return the n most common words in the file (and the number of their o...
stackexchange/codereview
This function represents an integral type and represents it in a base. #include <type_traits> #include <limits> #include <array> #include <iterator> namespace detail { template <class Integral> char n_to_digit(Integral n) { static const char * digits = "0123456789abcdefghijklmnopqrstuvwxyz"; return digits[n];...
stackexchange/codereview
I'm writing a bash script to manage multiple JDKs, the script is very simple, you have to choose a directory when you store all the jdk's, and the script maintain a symlink to the current jdk'. TheJAVA_HOMEis always pointing to thesymlink`. In order to use the script you have to source the jdk-manager.bash in .bash_pr...
stackexchange/codereview
I wrote a small program which downloads song or video from the given youtube link. I used pytube library https://github.com/nficano/pytube and for GUI (Tkinter). from pytube import YouTube import tkinter as tk from tkinter import ttk from tkinter import filedialog import re import threading """Program downloads song o...
stackexchange/codereview
This code works fine, but I'm still learning, and feel like there is a more Railsy way to write this. Is there a good rails ActiveRecord method I should learn more about? Please let me know if you know a shorter, more direct way to run this same code. Scenario: A user can have many languages, and level is an attribute ...
stackexchange/codereview
I'm new to programming (1.5 years experience at university), and I'm working on my first computer vision related project! My goal is to take a file which might have CSV (comma separated) or txt format with XYZ coordinates and process the data. I want to round the X and Y coordinates into integers and leave the Z coordi...
stackexchange/codereview