instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I have this code which creates a team using the github API and returns the team-id(success) or -1(failure). My problem is with the error handling. When the request responses with an error status code I try to deal with a few different types of failure. It looks like a mess! Is there any way to make it more readable/e...
stackexchange/codereview
I wrote this little program to... I don't know. But it connects to IRC servers using OpenSSL and can login via SASL. The code needs refactoring, of that I'm certain, but I need some advice in that regard, so please roast my code. tallis.h: #ifndef TALLIS_H #define TALLIS_H #include <openssl/ssl.h> #include <openssl/bio...
stackexchange/codereview
I'm trying to create a lost password function on my site. When a user enter their email it updates 2 columns in the users table with that email called: new_password_key and new_password_requested (int, using PHP time()), I then send them a link with that password key to a page where they may change their password. It s...
stackexchange/codereview
This code gets a state from a query string hash part, converts the hash part to a JavaScript object and then tries to get a view, dashboard or a mode value. If those keys are not present in object, it returns $.pulse.qs.views.home. Does this JavaScript code with ternary operator follow common best practices? It looks l...
stackexchange/codereview
Suppose want to calculate the shortest path from one node to all other nodes, with the restriction of intermediate nodes cannot be more than a given number. My major idea is, following how Dijkstra's algorithm works, with only the exception that when updating shortest path, if I see shortest path intermediate nodes exc...
stackexchange/codereview
Is there too much logic in this controller (should I migrate them to the model)? How else can it be refactored? class StatsController < ActionController::Base def create @stats = Stat.receive_stats(STATS_SOURCE) sport_type = @stats["sportsID"] Stat.categories.each do |category| ...
stackexchange/codereview
The following routine is the block-allocation procedure in a fixed-size allocator being written for library use. It is designed to be accessed from C++ (the un-mangled symbol name is void * Superblock::alloc_block()). The performance of this routine is the critical to the library; and I, with almost no prior experience...
stackexchange/codereview
For the following question, does my JS Solution seem correct? I'm looking for some peer review. Q: Given a string s containing only a and b, find longest substring of s such that s does not contain more than two contiguous occurrences of a and b. Examples: "aabbaaaaabb" => "aabbaa" "aabbaabbaabbaa" => "aabbaabbaabb...
stackexchange/codereview
Please provide general and any specific criticism of the following which is intended to provide a map of SF transit cars. The code can be viewed in the working version and also in a group of gists. If this isn't the appropriate place or way to request a review please let me know. Feedback received so far indicates the ...
stackexchange/codereview
if __name__ == '__main__': url='http://pokemondb.net/pokedex/all' #Create a handle, page, to handle the contents of the website page = requests.get(url) #Store the contents of the website under doc doc = lh.fromstring(page.content) #Parse data that are stored between <tr>..</tr> of HTML tr_e...
stackexchange/codereview
I wanted to write a template matching algorithm from scratch. The key area's I'm interesting in are readability, maintainability, DRY, and if the program performance/efficiency could be improved in any way. Image scanning class: import sys from itertools import izip class ScanImage: def __init__(self, image, templa...
stackexchange/codereview
I have the following code to loop through a directory of folders and print all folders names with their paths in a worksheet. This is a follow up question to this one: Excel VBA - Get Folder Names Looking for code optimization for faster and better performance. Sub PrintFolders() Dim wb As Workbook Dim ws As W...
stackexchange/codereview
After a conversation with my math teacher about a base algebra (base 43 using all the algebra symbols) and finding it more than the 30 min of work I was looking for, I decided to make this instead. import math letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T...
stackexchange/codereview
I use this function in browser automation. It pings the document in the browser to check if an element we are looking for is available (useful when there is JavaScript generated async content). If it's not available, it will retry after a given interval or times out eventually. Example usage: function clickContinue() {...
stackexchange/codereview
I'm pretty new to C, started learning it less than a month ago, the only language I had previous experience was Javascript. Anyways, I wrote a library for dealing with CLI flags. It's not a serious project by any means, I wrote it for practice and fun. It's composed of a source file and a header file (with declarations...
stackexchange/codereview
I'm working on a singleton object to manage size changes in the viewport, I wanted it to be a singleton because there may be different unrelated objects that need to be notified when a change in viewport dimensions has occurred. So I came up with this solution based on the singleton design pattern found in here. var C...
stackexchange/codereview
Can anyone please review the following .htaccess file and let me if it is correctly put together? What I think it does: So it direct to a custom 404 page Remove the extensions from the end of the urls (example .php) Remove /index I don't really understand what the final rule does, can anyone please explain it if could...
stackexchange/codereview
Is this an efficient way to implement the Roman Numeral Converter ? So first, I put all the digits of the parameter number into an array. Then I loop through this array, and multiply a 10 power based number to the current digit. I use the resulted number in multiple statements, to compare it with special cases or numbe...
stackexchange/codereview
I am writing a function which on update of any attribute of model sets the status of variable is_kyc_verified to false. Here is the code of the User model and the method which changes the status: class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :time...
stackexchange/codereview
Aside: This code assumes a class Option that can be Some or None to represent the presence (Some) or absence (None) of the value it contains. Haskell calls it Maybe. Here is my first pass at wrapping Iterator in a thread-safe way: public synchronized Option<T> nextBlocking() { return iter.hasNext() ? Option.of(ite...
stackexchange/codereview
The repetition is super obvious here. How can I rewrite this code? I need one base method in which I pass a Django model, to call objects.filter, but I can't figure out how to do it. from profiles.models import BasicInfo, BillingInfo, DocumentInfo __author__ = 'vol' class BasicInfoService: def __init__(self): ...
stackexchange/codereview
Consider my simple business requirement as follows: There is a list of talks and they need to be scheduled in tracks. Each track has a morning session starting at 9am and an afternoon session starting at 1pm ending by 4pm and a lunch break from 12pm to 1pm. Given: A list of talks - Talk.txt Python session 90min Java s...
stackexchange/codereview
Because std doesn't provide an overloaded version of std::abs for std::size_t, I built a version to calculate distance between unsigned numbers. It subtracts the smaller one from the larger one, to prevent a negative result, since in unsigned integer it would wrap around. std::size_t size_type_abs(std::size_t a, std::s...
stackexchange/codereview
I recently wrote a piece of code to convert between two bases of X, (Where 26 > X > 0). I was mighty proud that I did this. And then I started wondering, am I using modern coding conventions/practices? The code can be found here. And some sample outputs are shown: // syntax: convertBase(input, inputBase, outputBase) co...
stackexchange/codereview
Over the past couple of days I have been working on a super-basic text editor with Tkinter. It can: Open new files Open files (general) Save files Obviously you can edit any file you open or make. This is very similar to this question, though I did not see that until I checked for duplicates of this question. I did n...
stackexchange/codereview
I received the following question in a technical interview today (for a devops/SRE position): Write a function which returns true if the two rectangles passed to it as arguments would overlap if drawn on a Cartesian plane. The rectangles are guaranteed to be aligned with the axes, not arbitrarily rotated. I pr...
stackexchange/codereview
Here's Some Context So I was messing around in Minecraft and decided to make some code that basically makes you god. While making the code and testing it I noticed there were some problems that I didn't know how to fix, and came here to see if there were at least a semi-professional coder that could review my code for ...
stackexchange/codereview
I wrote up a script a while back to let me play around with fractals. The idea was to have direct access to the script that creates the fractal. None of that close, edit, then run hassle; just edit then run. renderscript.py contains the GUI: import tkinter as tk from tkinter.filedialog import askopenfilename, asksaveas...
stackexchange/codereview
I was looking for long time around to have a portable robust solution for multiprocessing synchronization. Who touche this things know that good solution are boost::iterprocess named sync objects. When your process have a named_mutex locked and your process die (there are many normal situations when process die, not ju...
stackexchange/codereview
I am learning about stacks, queues, lists & hash tables from the book Data Structures using C and C++ by Tanenbaum. I am also spending time to take in OOPs essentials, to ensure they sink in well, so that I don't learn by osmosis/need-be basis in the future, and there are no knowledge gaps. The author of the book sugge...
stackexchange/codereview
Sometimes I have the need to call an async function from a non-async function and get the result back synchronously. Therefore I wrote the following helper function to be able to do this in one line. public static T RunSync<T>(Func<Task<T>> taskConstructor) { var signal = new ManualResetEventSlim(); T result; ...
stackexchange/codereview
I have written this program to remove the duplicates from an unsorted array. Please review and give me your input on how I can improve it a little more. public static void main(String[] args) { int[] arr = {4, 3, 4, 2, 6, 1, 1, 7, 6, 8, 9, 9, 1, 1}; // perform quick sort for o(n log n) time. quickSort(arr...
stackexchange/codereview
Problem Validate if a given string can be interpreted as a decimal or scientific number. Some examples: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true " -90e3 " => true " 1e" => false "e3" => false " 6e-1" => true " 99e2.5 " => false "53.5e93" => true " --6 " => false "-+3" => false "95a54e5...
stackexchange/codereview
I've been trying to teach myself Rust, and I decided that a simple console calculator would be a good project to learn from. use std::io; extern crate regex; #[macro_use] extern crate lazy_static; use regex::Regex; fn main() { loop { println!("Enter input:"); let mut input = String::new(); ...
stackexchange/codereview
Is this a good approach of designing a class or is there some other way that I am not aware of? Student.h specification file #ifndef STUDENT_H #define STUDENT_H #include <string> using namespace std; class Student { private: int ID; string name; double GPA; char gender; public...
stackexchange/codereview
I'm having a bit of trouble setting up a basic bank account in Java. I'm trying to create a transfer method that I can call to transfer funds from one account to another. The problem is that the method I have created has an unnecessary step where I have to declare the name of the object twice. To execute the transfer m...
stackexchange/codereview
I am trying to time radix sort on 128 bit unsigned integers for different base sizes (that I call bitwidth). My code has at least the following problems: The radix sort itself may run slower than it would otherwise as the bit width, number of passes etc are not constants that the compiler can understand and also mayb...
stackexchange/codereview
This code can woocommerce order change status. But as you can see, this code is hard to read. How can I make it cleaner? <?php $tarih = explode('T', $order->get_date_completed()); $now = date("Y-m-d"); $origin = date_create($tarih[0]); $target = date_create($now); $interval = date_diff($origin, $target); $iade_hakki=$...
stackexchange/codereview
hackerrank.com Task: Given a base-10 integer, n, convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1's in n's binary representation. This question has already been answered but it was in Ruby and I couldn't quite understand the concept, I am just startin...
stackexchange/codereview
I have an image upload form with which I call multiple functions before uploading the file such as checking the size and dimensions, and that it is in a valid image. The code works, but calling the functions and dealing with the results seems quite cumbersome and complex. Is there a tidier way of structuring the code? ...
stackexchange/codereview
I recently wrote a mathematical expression parser in C++. The software can read valid mathematical expressions and evaluate them. An example of an expression the code can parse is (sin(pi)*e^(-3)). I would love to receive constructive feedback if possible for the code. Such as compiler optimizations, memory optimizatio...
stackexchange/codereview
The idea here is to implement a configuration system using INI files for a pathfinding library nammed Kraken. This library is in java and I am helping implementing it in C++. The goal is to make it cross platform and to specificaly aim embedded systems. For now the INI parser uses inih for simplicity, but should be abl...
stackexchange/codereview
Description In a time where thin clients, web browsers, web services and micro services are prevalent, we tend to forget we still have to deal with thick and smart clients. Many applications in B2B still use the latter. It is common in such clients that the user can perform a set of actions on the client before synchro...
stackexchange/codereview
I've done my best to contrive an example of the problem I'm trying to simplify. I have a pool of workers, and each worker can do several tasks at a time. Each task takes an unspecified amount of time. The goal is to drain the task queue by keeping each each worker as busy as possible. In order to accomplish this, once ...
stackexchange/codereview
I'd like this code to be improved Input string: codereview is awesome Output string: awesome is codereview My approach: Reverse the entire string Reverse each word in a string package com.arun.reversewords; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Re...
stackexchange/codereview
I have been updating my build tools to optionally use autotools (autoconfig/automake/libtool etc.). As part of this change I have written a couple of M4 macros. This not being something I have done before, any input is appreciated on style or if things can be done better. This macro checks to see if the YAML libraries ...
stackexchange/codereview
Recently I needed to expand the exports in a file to all methods in order to allow for Jest tests to cover more of the code (without using Rewire). Beforehand, only the functions used by other production files were exported, meaning unit tests only covered the exposed methods and not the non-exported ones. I'm wonderi...
stackexchange/codereview
I am new to programming and I have made a program to make all repeating numbers in an array 0 and put those all 0s in left side: import java.util.*; class ArrayWork { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int arr[],n,i,j,nr[]= new int[5]; System.ou...
stackexchange/codereview
At the documentation for QGraphicsScene, there is a simple example that does not work as written. I've written a fix that does work, and am curious if it could be improved. From the docs (does not work as is): scene = QGraphicsScene() scene.addText("Hello, world!") view = QGraphicsView(&scene) view.show() Fixed vers...
stackexchange/codereview
I am developing a CUDA program and I want to enhance my performance. I have a kernel function which is consuming more than 70% of execution time. The kernel calculates the distance between several spatial points and based on whether they are neighbors or not, it fills a boolean vector. Any ideas on how to get more spee...
stackexchange/codereview
The time has come in the development of the initialization process of my OS to get details about memory. I could have done this a lot simpler as both systems I use, have 4 gigs, but on every system that I'll use my software, I want detailed reporting. This code is somewhat fashioned after the example detecting memory a...
stackexchange/codereview
Purpose: After you've submitted a resume and cover letter for a job position, you haven't heard anything back, so you decided to send a follow up email. The script generates the follow up e-mail based on this template. """ followupemail.py A script to generate a follow up e-mail after a job application submis...
stackexchange/codereview
I wanted to split a list into 2 parts, as per the chosen size, first the size and then the list. Example: (split 3'(1 3 5 7 9)) (defun split (list count) (values (subseq list 0 count) (subseq list count)))
stackexchange/codereview
I have datalayer code as below which is implementing an interface as: Note: I have hand written this code on Notepad so it may contain some typo errors, which you can gracefully ignore. I am searching for an approach here. public interface ISimpleInterface{ void DosSomething(long someValue); } public class Concr...
stackexchange/codereview
I am writing a small oauth2 library for Play! 2.1 scala. As I am still learning I got stuck trying to TDD and ended up writing the code first, then refactoring for testability. By testability I mean two things: make the code testable by me as the author make it easy for users (since I will be a user) to stub/mock it o...
stackexchange/codereview
I've got my own website! Woo! It's got HTML and everything! But after struggling for a while with HTML and keeping my navbar consistent across pages, I gave up and wrote a program which: Searches for every markdown file in the given root directory or below. Parses it into HTML with mistune, which thankfully only needs...
stackexchange/codereview
I decided to do a bit more in C# by writing two methods that find duplicates, one being a naive approach, and the other one utilizing the LINQ capabilities of C# as a form of learning and training. Below is my code, and I would appreciate any critiques of it in terms of style, design, and if there are more succinct way...
stackexchange/codereview
I completed a coding challenge recently in which my function was to be given two parameters: N, the number of counters to be used (numbered 1 through N) - and A, an array of integers. Iterating through the array A, when the index of a counter occurs, that counter is incremented by 1. When an index of N+1 occurs, all of...
stackexchange/codereview
I would like to make my code "prettier" and also speed up the runtime of my implementation. Nodeinfo is literally just an object that holds its "parent node"(the node it came from) and its distance. i try to traverse the graph by finding the distance of the node i want to move to then adding it to a priority queue base...
stackexchange/codereview
Problem: User inputs a word or phrase as command-line argument and a new word is printed with some vowels replaced by numbers. Question: How do I improve my code design and style? Is it possible to not have to repeat x[i] == '…' in my if statement? #include <cs50.h> #include <stdio.h> #include <string.h> string replac...
stackexchange/codereview
Is there a better way of writing this? I feel like there's a lot of lines for such a small thing. Can it be optimized? $j('#hideShowBtn').toggle(function() { $j('.playlist-bar-tray').slideUp(); $j(this).attr("title","Show Playlist"); $j(this).children("div").html('Show Playlist'); $j(this)...
stackexchange/codereview
Given the JSON response below: const result = { 'potential': { A: 514, B: 3127, C: 2970, D: 282, E: 41, F: 1, undefined: 48, }, 'current': { A: 2, B: 961, C: 2897, D: 2568, E: 455, F: 47, G: 5, undefined: 48, }, }; I need to transform it to: const tem...
stackexchange/codereview
(See the next iteration.) I have this pathfinding algorithm: DirectedGraph.hpp #ifndef COM_GITHUB_CODERODDE_DIRECTED_GRAPH_HPP #define COM_GITHUB_CODERODDE_DIRECTED_GRAPH_HPP #include <cstddef> // for std::size_t #include <sstream> #include <stdexcept> #include <unordered_map> #include <unordered_set> namespace com::...
stackexchange/codereview
Here is a class which I have written to create a simple Stack data structure which can be shared across multiple threads. It's a simple LIFO which has 2 operations: one to push onto the top of the stack and the other one to pop from the top of the stack. Please help me to find any issues with it. package com.thread.te...
stackexchange/codereview
Thanks for taking the time to read this first off. I want to say that I have always been very interested in generating random terrain and since I'm new to any sort of graphical programming, I decided to start as simple as I could get. I am trying to implement the midpoint displacement algorithm to make fractal type mou...
stackexchange/codereview
While answering this question on SO I came up with a very simple solution and I wanted to know if there were improvements that could be made to it. The function takes an array of participants as inputs, generates a list of pairs using the array of participants with an associated score (to be generated by a function com...
stackexchange/codereview
I have a pivot table of approximately 2 millions lines coming from a dataframe with the same structure as below: raw = pd.DataFrame([[123456,datetime(2020,7,1),'A',10 ], [123456,datetime(2020,7,1),'B',25 ], [123456,datetime(2020,7,1),'C',0 ], [123456,datetime(202...
stackexchange/codereview
I'm trying to implement a left leaning red black tree as described here. This is their snippet for insert private Node insert(Node h, Key key, Value value) { if (h == null) return new Node(key, value); if (isRed(h.left) && isRed(h.right)) colorFlip(h); int cmp = key.compareTo(h.key); if (cmp == 0) h.v...
stackexchange/codereview
I have created a linked list in C++, I suspect there is a good chance I have made some larger errors in this code as I am working with a few concepts new to me. Please be very hard on me as I want to eventually be good at this. #include <iostream> // basic linked list implimentation in C++ using templates template <...
stackexchange/codereview
I wrote a simple linear/polynomial regressor based on my previous matrix project (https://github.com/frozenca/Ndim-Matrix). #include <Matrix.h> #include <algorithm> #include <concepts> #include <cctype> #include <functional> #include <stdexcept> #include <numeric> #include <ranges> #include <string> #include <vector> ...
stackexchange/codereview
Here is an article on password hashing, along with an implementation. Is this code secure with number of iterations 10000, key length 256 and salt bytes 32? Is there a rule-of-thumb for key length vs. salt bytes? Regarding key.destroy() and pbeKeySpec.clearPassword(), is it necessary to "manually" destroy the ke...
stackexchange/codereview
I have a sniffer tool which populates my DB with data found after parsing the packets and filling them in. Since each row in my table deals with one packet, I had to make a procedure that provides the correlation between packets. I fill that using the stream_index column. +--------------+------------------+------+-----...
stackexchange/codereview
There are lots of shell programs that have /bin/sh as interpreter, yet use some features that are specific to bash or other popular shells. I have written a little program that detects these unportable features. It is not meant to compete with ShellCheck, its purpose is only to catch a few common mistakes. Since the pr...
stackexchange/codereview
In this python program, I built a ticketing system with functionality such as keeping track of tickets sold and error handling in case there are any invalid inputs. I need advice on my code in terms of (architecture, risks, opportunities, design) so that I can learn how I can code better & grow my skills. TICKET_PRICE ...
stackexchange/codereview
The program interacts between cards and four players among whom cards are to be distributed. The Program do the following function Creates a deck of cards. Shuffle the deck. Shows the deck. Deal cards equally among four players. Show the cards of each Player. Please suggest some better ways of doing this program. A...
stackexchange/codereview
This script is designed to create an Excel spreadsheet from each HTML table from auto-generated index.html file. It needs to be very robust but unfortunately I don't have many example files to test it against. Any feedback on style, possible points of failure, or vulnerabilities would be very appreciated. Powershell f...
stackexchange/codereview
I am trying to reduce the total execution time of my code. I have a GPS system which calculates routes between two points, and returns all points in between them. I did a simple profile and the calculation of the route takes on average 30 ms while, from main thread input to main thread output, it takes almost 700ms to ...
stackexchange/codereview
I've written a small function for solving simple quadratic equations: class EquationSolver def solve(x, *args) args.reverse.map.with_index { |coefficient, index| coefficient * x ** index }.reduce { |result, element| result + element } end end To calculate f(3) for f(x)=3x3−2x2−x+5, one would write: puts Equat...
stackexchange/codereview
Can you review the code? #include <stdio.h> #include <pthread.h> #include <windows.h> #include "bin/include/pthread.h" #include "bin/include/sched.h" #include "bin/include/semaphore.h" #define TCOUNT 10 #define WATCH_COUNT 12 int count = 0; pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cou...
stackexchange/codereview
I have been learning c++ for a few weeks now and I attempted this problem on Hackerrank Delete a node. I am aware of a similar post Delete a linked list node but the code seems more of a C structure than a C++ structure. Please feel free to suggest areas of Improvement and shorter way of writing this if any exists. Her...
stackexchange/codereview
I reinvented a c++ smart pointer, shared_ptr to be precise. It is meant for practice purpose and does not attempt to replace the standard implementation. To the best of my knowledge, the code works as expected. I decided to skip the custom deleter because I want to keep things simple for now. I would love feedbacks and...
stackexchange/codereview
I developed the following Python functions when solving a few Project Euler problems, and since I'm not that familiar with Python, I'm curious at how I could improve them. The code consists of a data holder class, and a few functions. Option class: This object stores data for a combination option. It has two data membe...
stackexchange/codereview
I am looking for advice on my input component. There is no real problem with it yet, but I am just getting started on everything and want to know if there is any obvious problems with it, plus I was looking for advice on a design question of it. The design question refers to whether or not I should treat alt, ctrl, an...
stackexchange/codereview
I've written this Python script to make regular backups of a Linux server. It works pretty well except that the script sometimes backups files more than one time, which is pretty strange and I don't know why that happens. But that's not the key point of my posting here (just someone may see a little error I've made whi...
stackexchange/codereview
I am new to C. I tried to make a bank management console application. I want some one to review it for advice to enhance and develop my coding skills. This is what the program does with the inputs: 1 add an account 2 search for a specific account 3 modify a specific account 4 delete a specific account #include <st...
stackexchange/codereview
I have a MySQL query which runs very slowly. I've rewritten it many times but no improvements yet. My current query for advanced search takes about 60 secs to complete. Any suggestions for improving this? Database: MySQL Webserver: Apache - PHP (PDO) Current code structure: SELECT B.title, COUNT(*) AS NUM FROM libr...
stackexchange/codereview
Is this a performant strategy to implement a stack in Kotlin to compare and delete values? Expect Create a stack in order to compare an array of asteroids (ASTs) and handle collisions (deletions), returning the final array of ASTs after collisions. Each AST moves at the same speed Negative numbers move left, positive ...
stackexchange/codereview
Here is my attempt at solving Project Euler problem 3. It works for test numbers up to 9 digits long, but overflows when I input the real 12-digit behemoth. I've looked at other methods of solution, but I wanted to challenge myself to code one that doesn't search with unnecessary numbers - only primes - and never any o...
stackexchange/codereview
Amongst the lesser-known unstable sorting algorithms is the QuickXsort family of algorithms, as described in QuickXsort: Efficient Sorting with n log n - 1.399n +o(n) Comparisons on Average by Stefan Edelkamp and Armin Weiß. This family of sorting algorithms tries to exploit the technique of internal buffering that we ...
stackexchange/codereview
How do I better calculate the definite integral? I am using a function to integrate and another to find the factorial recursively. I'l like to better the algorithm or the efficiency or even the accuracy for that matter. public static double testStatistic(double meanTreatmentSumOfSquares, double meanErrorSumOfSquare...
stackexchange/codereview
I've written a code reading csv file using fold expressions. The only thing that should be defined is columns types and file name: template <typename ...T, std::size_t... Is> void parseLineToTuple(std::tuple<T...>& empty, const std::string& line, std::index_sequence<Is...>) { std::stringstream ss(line); (ss >> ...
stackexchange/codereview
In the ZF2 model mapper, mappings are quite often duplicated in the original mapping class & other mapping classes. I am using a static mapping methods (mapToInternal, mapToExternal) to remove this duplication. Could this be done any better? <?php //... /** * Class ItemTable * * @package Job\Model\Mapper\Item */...
stackexchange/codereview
Problem Problem is Maximum sum path from https://firecode.io Given a binary tree, \$T\$, whose nodes have positive values find the value of a maximal path. A path is a simple path from a node to another node. The value of a path \$P\$ is $$val(P) = \sum\limits_{u \in P} val(u)$$ that is, the sum of the values of the no...
stackexchange/codereview
Background I'm building a lisp-like toy language in Haskell with the following (stripped down) AST: type Lisp = ExceptT Error (StateT Env IO) type PrimOp = [Value] -> Lisp Value data Value -- | any identifier, e.g. "x", "lambda" = VName Name -- | s-expression, e.g. "(x y z)" | VExpr (NonEmpty Value) -- | curr...
stackexchange/codereview
I have implemented Binary_Search in python (I think), and my own method for range objects. I want to know if there is any way to improve this code, here it is: def findAmountString(string, char): amount = 0 for n in range(len(string)): if string[n] == char: amount += 1 return amount def findrange(rangeToFind)...
stackexchange/codereview
For a school assignment we had to implement IPC between two processes using File Maps with some specific requirements. The relevant requirements are: ComLib will send a null-terminated (C-style) string (contrary to most other circular buffers I've found online that deal only with fixed-size elements). If a message doe...
stackexchange/codereview
I'm getting more and more into programming js in a functional manner which makes heavy use of multiple returns via tuples (especially useful with recursion). Also, a pattern that I use often is creating simple temporary values for projections _.chain(arr) .filter(...) .map(function(x){ return [x.foo, get...
stackexchange/codereview
I've created an SDL input manager for my 3D OpenGL applications. It's not finished yet, but I would like to know if I'm doing it the right way. I really tried to optimise and compact my code, as it is for an OpenGL library. InputHandler.h #pragma once #include <SDL2/SDL.h> #include <vector> #include <glm/glm.hpp> #incl...
stackexchange/codereview
Feature-based authorization It seems to me that if you rely on roles to authorize a web application it makes it very difficult to render UI or code based on a set of features. This means that each role would have be checked against for each feature. if(User.IsInRole("SomeRole") || User.IsInRole("OtherRole")) { // Do ...
stackexchange/codereview
First, the script checks to see if it is installing two kernel module packages or removing them by looking at the first parameter. If no parameter is provided it complains and exits. If installing, it checks if each of the packages even needs to be installed by looking at the version of the existing module. If they do ...
stackexchange/codereview