instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
Please review my class. It uses iconv() (it's probably not the best solution however I haven't found any better alternative to change unknown characters). <?php /** * Class NiceUrl * * Creates friendly url from given name */ class NiceUrl { /** * Whether convert to lower * * @var bool|null ...
stackexchange/codereview
I have an Access macro that runs AfterUpdate of a form. It opens an Excel workbook and edits a few cells. I have It working the way I want, but the problem is that the code takes about 25 seconds to run. This is way too long for the users of this database to have to wait. After adding some timing messages, I found that...
stackexchange/codereview
A week or so ago, I wrote a binary expression calculator with the hope of better understanding how interpreters and compilers work. In the same vein, I've tried to write a lisp like language interpreter in C#. So far, I've only written code to represent the abstract syntax tree, and haven't written code to parse string...
stackexchange/codereview
I have a lot of code (probably about 1/2 of all of my 891 lines) dedicated to just making players and teams. Here's the code that makes the players and teams: private void makeTeams() { toPlay = maps.get(random.nextInt(maps.size())); // I have a method that I shortened to make maps pName = toPlay.islands().get...
stackexchange/codereview
I am working on a project where I need to consume lot of records and then I am sending these records to some other system which uses zeromq. Here is the flow: Store all the incoming records in a CHM from multiple threads. Records will come at a very high speed. From a background thread which runs every 30 seconds, sen...
stackexchange/codereview
I would love to get some feedback on this Sleeping barber implementation in C. the entire project can be found here: https://github.com/T0iS/sleeping-barber How to run. 1. make 2. start the server on a selected port ( ./server XXXX) 3. start the client on localhost and connect to the previously specified port (./...
stackexchange/codereview
My task is to run a subprocess using asyncio.create_subprocess_shell and yield the lines of output. I am using asyncio to avoid creating threads just to pump the streams. It is necessary to separate stdout lines from stderr lines. Both outputs need to be read simultaneously, it is not possible to read all of stdout or...
stackexchange/codereview
I am to compute recurrently (not necessarily recursively) the y, where $$y = {x}^{2n} + {x}^{2(n-1)} + ... + {x}^{4} + {x}^{2} + x$$ Here is what I am doing: #include <iostream> using namespace std; double polynom(unsigned, double); int main(void) { cout << polynom(2, 3) << endl; return 0; } double polynom(u...
stackexchange/codereview
Although this question has been asked a lot of times, I was hoping for a feedback on my approach. Tax Calculator Basic sales tax is applicable at a rate of 10% on all goods, except books, food, and medical products that are exempt. Import duty is an additional sales tax applicable on all imported goods at a rate...
stackexchange/codereview
I have been programming for about ~2 years, and mostly wrote OOP and structural code. Recently, I have decided to pick up a functional programming language, and Haskell being too alien for me, looked to Racket (since it is high time I learned a LISP anyways) and am loving it. Since this is a new area of programming for...
stackexchange/codereview
I have the code such as this for opposite conditions. For Each iCell In Range("A2:A6").Cells If iCell.EntireRow.Range("H1").Value = "" Then BOM = InputBox("The current BoM Code is...", "BoM Calculator v1.1", (iCell.Value)) scrUpdt = Application.ScreenUpdating Application.ScreenUpdating = Fal...
stackexchange/codereview
I currently have a utility that will display details about a list of specified users. In its current state I don't use any functions, which I've noticed make it a little more repetitive than I would like. I'm specifically interested in how to make this more functional, but I'd be interested in any suggestions for how t...
stackexchange/codereview
I've read so much arguing about "sort by value maps". Well, I wrote the following log(n) sort by value Map . And, by the way, a real Map , does not allow duplicate keys. Many of the maps I googled ignore that annoying problem. I assume this map is still log(n)...: public static void sortByValue_logN() { class MyCo...
stackexchange/codereview
Original question Reimplemented solution following JS1's answer. Changed bit string hack to bitwise operations to get the corresponding base64 index values. #include <stdio.h> #include <assert.h> void get_b64_quads(char *hex, char *b64quads, int pad) { char *dec_2_base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnop...
stackexchange/codereview
The following program is an updated version of this question, an implementation of the Vigenere cipher in C. It has been updated to take input from stdin and pipes, amongst other suggestions made by users answering the previous question, as well as having been significantly cleaned up. The program has been through seve...
stackexchange/codereview
There are three scenarios only for when the sign up validations fail, so is there a better way of representing them rather than having 4 scenarios? I don't want to create a model folder so please don't suggest that. Is there a better way of representing this RSpec code on Rails using Capybara? feature 'Login' do befo...
stackexchange/codereview
I'm creating a C# application that produces unique lines of data. The main purpose of the application is for me to learn C#. The secondary purpose is to have available lines of (dummy) data when testing database development. For this particular question I'm concerned with the most efficient algorithm for incrementing c...
stackexchange/codereview
I've made a simple drawer using CSS3 and jQuery that works with hover and click. It seems to be working fine but surely there's a simpler way of writing the code. Fiddle: http://jsfiddle.net/73MpU/ $("#bottom-page").click(function () { $("#top-page").addClass("push"); }); $("#bottom-page").mouseover(function () { ...
stackexchange/codereview
Employee hierarchy in an Organization is classic example of modeling Composite design pattern. Following are the details that are to be modeled: There are two type of employees; Manager, and Developer. A Manager manages a team that can comprise managers, and developer. A Developer has fixed salary at given point of t...
stackexchange/codereview
Suppose there is a huge bitmap, huge_bitmap, in the drawable-nodpi folder. I want to create a custom view with huge_bitmap as its background: public class CustomView extends View { private Bitmap mBackground; public CustomView(Context context) { super(context); } public CustomView(Context con...
stackexchange/codereview
Alright guys, I know this isn't the proper way of problem solving, But I need some guidance here. Since I am just starting in programming, the code is not really readable. The Winforms program (essentially a glorified Excel sheet) I created is made up from different textboxes (as shown in designer picture below). The t...
stackexchange/codereview
While trying to discover a way to calculate the digits of Pi faster with the Leibniz formula for Pi, I noticed that, if I took two consecuent numbers in the series, and calculate their average, I would get a number incredibly closer to Pi compared to these other two numbers, and furthermore, if I took another consecuen...
stackexchange/codereview
This is a simple speed hack I created for Call of Duty World at War. It uses a pointer, SPEED_ADDRESS with an offset, SPEED_OFFSET1 to find the address I intend to write to. I'm not very well versed in using offsets. The code I provided does work, but I feel there's probably a better way of dealing with offsets. For in...
stackexchange/codereview
I had me a code challenge and I was thinking: is there a way to make this more efficient and short? The challenge requires me to scan a string and ... In the first line, print True if it has any alphanumeric characters. Otherwise, print False. In the second line, print True if it has any alphabetical characters. Oth...
stackexchange/codereview
I reverse engineered the API from adac.de and wrote a client to query it for traffic news (constructions sites, traffic jams etc.). Here 's what I came up with: #! /usr/bin/env python3 """ADAC traffic news API Client.""" from argparse import ArgumentParser, Namespace from functools import cache from hashlib import md5...
stackexchange/codereview
I observe the same pattern in a number of my classes but can't extract/abstract it due the tight coupling inside each particular implementation. Having the class accepting an optional number of dependencies onto its constructor: public Repository(IBuilder, IFormatter, ILoader, ISelector) With the single method passing...
stackexchange/codereview
The following bash code is meant to check every second the amount of NEW (relative to the last second) network socket files. at the end of the run it summarizes every 60 entries (should be 60 seconds) and output a file called verdict.csv that tells me how many new network sockets were opened in that minute (I run under...
stackexchange/codereview
This is a very simple ball game in which we have to avoid projectiles falling from the sky. This is my second project and first game. Please review and tell where I can improve. import time import random import pygame pygame.init() #colors black=(0,0,0) white=(255,255,255) red=(255,0,0) green=(0,255,0) blue=(0,0,255) ...
stackexchange/codereview
I need to get length of the longest sequence of numbers with the same sign. Assumes that zero is positive. For example: {10, 1, 4, 0, -7, 2, -8, 4, -2, 0} → 4 {0, 1, 2, 3, -2, -4, 0} → 4 {1, -2, 0, -1} → 1 I wrote a function: unsigned getLongestSameSignSequenceLength(std::vector<int> const& a) { unsigned maxlen =...
stackexchange/codereview
Summary: Is my server handling every error and corner case possible? If not, what did I miss? Details I'm trying to write the most basic socket server I can, so I can learn TCP and the pitfalls of parsing network data. I'm also worried about security (DDOS mitigation) and making sure the server never panics (unless it ...
stackexchange/codereview
I'm planning to use Tarjan's algorithm for a program in which I would be processing a file, converting the processed data to a dictionary, doing a topological sort on that dictionary (using this implementation), and then finding the longest path. Is there any optimization that can be made to the below code, or can be ...
stackexchange/codereview
Thus code uses a mergesort-like algorithm to perform an outer join (in the database sense) on two sequences. (It's derived from the ActiveState recipe mentioned in the docstring.) The actual algorithm is completely obscured by the extra code required to handle the possibility that either of the main iterators might th...
stackexchange/codereview
I have been working on a toggle script, but I find myself repeating my code. Is there a way of combining it all? jQuery(document).ready(function($) { var topContainer = $("#alles"); var topButton = $(".abutton"); topButton.click(function() { topContainer.slideToggle(1200, 'easeInOutQuart'); ...
stackexchange/codereview
This is small piece of bigger puzzle, but usable by its own. It an attempt to have a nonblocking queue with "unlimited" (besides memory size) buffer length. Got unit-tests 100% statement coverage, it looks that it's ok, but I'm very new to Go and concurrency so I might miss something. import "sync" // Message and Mess...
stackexchange/codereview
This is the problem statement for Insertion Sort - Part 2. In Insertion Sort Part 1, you sorted one element into an array. Using the same approach repeatedly, can you sort an entire unsorted array? Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted array, o...
stackexchange/codereview
I am new to C++ and Data structures, so I have started writing a custom vector as a practice. Please provide critique and advice. I know it is quite long, so thank you very much in advance. I just want to get better and not to get used to bad practices. #pragma once #include <iostream> #include <util...
stackexchange/codereview
I have a video which I read in a loop frame by frame. For every frame, I want to do temporal kernel filtering, the coefficients of which come from the input variable model (a dictionary). The temporal kernel is an array that has size of 15. So, basically, for every frame we apply this function. The variables scale, cli...
stackexchange/codereview
I have been reading this thread on Stack Overflow about simulating enums in PHP and it seems that the most common approach is to use class constants. My problem with that is I can't use it for type hints, so I have added a static function that checks if a value is defined as one of the constants. class DataType { c...
stackexchange/codereview
I have the following ReactJS unordered list which is generated from answers: <ul className="mt-2 col-md-12">{this.state.answers.map((v,i) => <li className="list-group-item" style={{"width": "220px"}} key={i}> {v} </li>) } </ul> I get answers the following way: handleSubmit(event) { const url = "api/" + t...
stackexchange/codereview
I'm a student and this is my first application/project that I made and finished today in C++ using OOP and I want to hear your opinions and suggestions, what I did wrong, what I did good, what should I improve, what should I exclude, about comments, anything that can help me getting better and improve my code. To test ...
stackexchange/codereview
I think the running time of this should be \$O(log_{2}(n))\$: def count_bits(num): assert num >= 0 count = 0 while (num != 0): num >>= 1 count += 1 return count print count_bits(0) #0 print count_bits(2) #2 print count_bits(pow(10, 2)) #7 print count_bits(pow(10, 9)) #30
stackexchange/codereview
I've followed several guides on how to implement MVC in Java, and so far I've come up with the classes shown below. From my understanding, MVC follows these guidelines. The Model should be independent and unaware of the View and Controller. The View should wait for interaction from the user and inform the Controller. ...
stackexchange/codereview
I want to show you my implementation of the array list in C. Is there something I can improve or fix? Header #ifndef ARRAY_LIST_H #define ARRAY_LIST_H #include <stdlib.h> static const int AL_INITIAL_CAPACITY = 16; struct array_list { int *array; size_t capacity; size_t count; }; struct array_list *al_ne...
stackexchange/codereview
Here's a pretty rookie attempt at creating a shell script to squeeze videos into Twitter's 140s limitation: for f in "$@" do /Applications/ffmpeg -i $f -filter_complex "[0:v]setpts=140 / \ $(/Applications/ffprobe -i $f -show_entries format=duration -v quiet -of csv="p=0") \ * PTS[v];[0:a]atempo= \ $(/Applic...
stackexchange/codereview
I read quick sort algorhitm and implemented in like this: public List<Integer> sort(List<Integer> list) { if (list.size() <= 1) { return list; } int pivotalValue = list.get(list.size() / 2); List<Integer> left = new ArrayList<>(); List<Integer> pivotalValues = new ArrayList<>(); List<I...
stackexchange/codereview
I often end up working with systems where the data is delivered with some Id property and possibly a parentId prop, but never do anyone tempt to actually give me a nice recursive object to play with. Now, the code below is merely a suggestion in how to solve these kind of "problems", I've created the FlatObject to simu...
stackexchange/codereview
I have written a program for the SPOJ PALIN problem: A positive integer is called a palindrome if its[decimal representation is the same]from left to right and from right to left. For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. … My p...
stackexchange/codereview
I recently made this game for rock, paper, scissors in Python 3. Everything works as intended, but I am sure this is not an optimal way of accomplishing this task. Wondering if there is any beginner friendly advice on how to improve upon this. Thank you! def main(): import random game_active = True options ...
stackexchange/codereview
I am trying to use decorator pattern to decode and encode packet layers in my application. I've supposed my packet has three layers: Header, Level2, Level3. So far I've come up with the following code. For the sake of simplicity, I've supposed that the data of each layer is the first 10 bytes of the input packet. I've ...
stackexchange/codereview
I am new to learning Repository Pattern. I am developing a site in MVC 4 (I'm new to it as well). The way I am using Repository pattern as follows: I created IRepository<T> interface as follows: public interface IRepository<T> { void Insert(T entity); void Delete(T entity); IQueryable<T> Search...
stackexchange/codereview
As I am new to bash scripting, and want to use apt-get in my university. I know that many people have issues when trying to do so. My focus is simplicity and ease of use, but still need to be somewhat robust. #!/bin/bash string="install" errormsg="\n\tInvalid input\n You should run this script with the following st...
stackexchange/codereview
First of all, I am here to explore unsafe features of Rust, if you are the kind of guy who likes "safe" Rust and will start nagging about using safe features of Rust I will still happily read your comment and learn about the safe alternatives. That said, I am looking to enhance my knowledge about unsafe Rust. The docum...
stackexchange/codereview
From SICP Exercise 1.11: A function \$f\$ is defined by the rule that: \$f(n) = n\$ if \$n < 3\$, and \$f(n) = f(n-1)+2f(n-2)+3f(n-3)\$ if \$n >= 3\$. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process. Please review my code. I thi...
stackexchange/codereview
There are solutions e.g. list.OrderBy(item => Math.Abs(number - item)).First() or list.Aggregate((x,y) => Math.Abs(x-number) < Math.Abs(y-number) ? x : y); which are O(N) at best. The solution bellow should be faster than a sequential scan on a large list. It is more performant to sort the list first (O(NlogN)) and t...
stackexchange/codereview
Task is basically: "Write a function which takes two number as the first two parameter. The third parameter is one of the arithmetic operators (+ , - , * , /). Execute the arithmetic operation (number1 operator number2) and return the result of it." Here's the first idea I've had: function calculate(num1, num2, oper...
stackexchange/codereview
The code below takes a String and encrypts it using AES/CBC/PKCS5PADDING as transformation. I am learning as I go and I have a few questions about my code. Is SecureRandom ok for generating my KEY and my IV? What's up with all these exceptions? Is my code creating any vulnerabilities in the encryption process? (mista...
stackexchange/codereview
I am a beginner in Python and am currently learning about making beautiful code. I've started with a small program. Can you please review my code? def inputAndRes(): try: a = raw_input("Enter no. :- ") n = int(a) except Exception: print "-----------------------------------" ...
stackexchange/codereview
I am working on a calendar widget for a project. For any given date, I need to build a 2D array representing the "Month" that the date falls in, where the rows represent weeks in the month and the cells in those rows are individual days. The weeks must start on Monday, and if the month does not start on a Monday, it mu...
stackexchange/codereview
I'm trying to dynamically create a table of input fields (two per field) that I will then send off to a Python script. Here's the expected behaviour: User chooses "manual entry," specifies rows, columns, of table, clicks button. Table is printed with two input fields per cell (e.g.: A(i,j), B(i,j)), user fills in all ...
stackexchange/codereview
I have (for example) the following license plate image: And I want to segment the characters. The code I have so far consists of me using cv2.MSER to detect regions in the image. Afterwards I create bounding rectangles for each of the contours and create a dictionary according to height of the bounding boxes (characte...
stackexchange/codereview
I was writing simple String class implementation (and it is quite ordinary), but I had found out that constructors, destructors and operator = are the most sensitive areas. So I wonder, if my implementation good in the sense of C++11/14 standard and are they efficient enough? String::String() { m_characters = new c...
stackexchange/codereview
I am new to the concept of prepared statement and i am trying to adjust my "user login" function to be a prepared statement. The part i am really struggling with is the fact i have multiple SQL queries in the one function and the biggest hurdle right now is fetching from a prepared statement. Here is the code i have wr...
stackexchange/codereview
Mod note: This question is being discussed on meta I tried to create a method, that given 3 int numbers and a bool returns true if they are in strict increasing order (by the same amount) like (1, 2, 3), (3, 7, 11) or (0, 4, 8). Except if equalOk is set to true, then equality of two adjacent elements is allowed, such...
stackexchange/codereview
The program is simulate a situation where my goal is to lose money in Corresponding exchange, however I will win max_lose times with min_amount_per_lot amount in Corresponding exchange and lose the same amount in Bybit, using martingale strategy in Bybit will lead to magnify the capital needed in Bybit each time losing...
stackexchange/codereview
To learn about classes, I chose to create a little something that checks if you have included the following: @ sign Provider (e.g. 'hotmail') Domain extension (e.g. '.com') It also checks if you entered spaces in the address and gave the option to keep them or get rid of them. I would really like some feedback on wha...
stackexchange/codereview
How should I deal with ViewModels that are "fat"? Or should I just accept it sometimes. Example - one of my ViewModels (editing image page, almost 300 lines of code) which has a lot of UI commands like cropping, quick image filters (like contrast, brightness), undo, redo etc. public class ImageEditViewModelWinRt : Shar...
stackexchange/codereview
I'm using PHP, MySQL, Smarty, jQuery, etc. for my website. I'm using an MVC architecture to develop the website. Now in one of the functionality I'm fetching a large amount of data and perform some processing on it. Then I'm returning the finally processed data from model to the controller and assigning it to the Smart...
stackexchange/codereview
This is my solution for problem 2 of Project Euler using Python: a, b = 1, 1 total = 0 while a <= 4000000: if a % 2 == 0: total += a a, b = b, a+b # the real formula for Fibonacci sequence print (total) I put the codes in the function IsEven: def IsEven(n): if n % 2 == 0: return True ...
stackexchange/codereview
I've made a little mechanism for creating 2-D vectors in Lua. Vectors have two components i and j, and support addition, dot product, magnitude, and conversion to strings. Vector = { new = function (i, j) return setmetatable({i = i, j = j}, { __index = Vector, __add = function (self, v) return...
stackexchange/codereview
I have to check an uploaded file for anti-virus and if there is an exception, I have to give a message according to the exception to the users. e.g. if its a timeout, I would ask the user to try againg in a while. My first class, fileUpload is: public class FileUpload { //Message when no virus found. pri...
stackexchange/codereview
The script downloads images and videos from a user's profile page on Instagram. It works fine, but I'd like to know if there are ways to improve it. All ideas and suggestions are welcome. import sys import os import requests import urllib.request import time import json from colorama import init, deinit from termcolor ...
stackexchange/codereview
First of all, this code will ask for a number (first) on how many test the user would like to have. Then the user will input the strings depending on how the number entered. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim input As String = txtInput.Text Dim inputArr As Stri...
stackexchange/codereview
The following is my first try at this classical interview question. It is quiet different from the solutions Gayle Laakmann provides in her book, and in another question on stackoverflow, someone initially mentioned there are better ways to do it. I think my solution should run in O(n) time and use O(n) space. Would b...
stackexchange/codereview
I'm looking for feedback or tips to maybe make my code more readable or faster or just general tips to help get myself started with app making with Python. import sys # check for valid input if len(sys.argv) == 2: try: int(sys.argv[1]) if(len(str(sys.argv[1])) == 16): pass else:...
stackexchange/codereview
Here is my attempt to implement the Ukkonen algorithm for the Finding a Shared Motif problem on rosalind.info. The code works, it produces a correct answer. It does so in 11 seconds. I am hoping to optimize it so that it runs faster. # http://rosalind.info/problems/lcsm/ from sys import stdin # A suffix tree is a tre...
stackexchange/codereview
Here is my code. It works fine but I need to make the code more efficient. def o(s): l=len(s) return len(set([a+b+c for a in s for b in s for c in s]) )==l*(l+1)*(l+2)//6 M=int(input()) N=3**M i=1 s=M*[i] while i: if s[i]-N: s[i]=s[i]+1 if o(s[:i+1]): ...
stackexchange/codereview
I am trying to write something that will copy the current <input>s value and enter it into any <input> that start with the same name. <input> names will follow this pattern: price-0, price-1, price-2, upc-0, upc-1, upc-2. So if a user enters a value in <input name="price-0"> and hits copy the value should be transferre...
stackexchange/codereview
Currently I check whether a string contains all words from an array like this: function contains($string, array $array) { $count = 0; foreach($array as $value) { if (false !== stripos($string,$value)) { ++$count; }; } return $count == count($array); } Example call: $string =...
stackexchange/codereview
Write a function strend(s, t) which returns 1 if the string t occurs at the end of s, and 0 otherwise. Here is my solution: unsigned int strend(char *source, char *pattern) { char *saver = pattern; while(*source) source++; while(*saver) saver++; while(saver >= pattern) if(*...
stackexchange/codereview
I've taken this class and made it my own but I'm curious to know what other think of it? Are there things I'm missing? Anything you can recommend? class Database { private $host = ''; private $user = ''; private $pass = ''; private $dbname = ''; private $dbh; private $error; private $stmt; ...
stackexchange/codereview
I have written two different codes for merging (merging with costs) and I want to know if I can make optimizations to run faster. merge1: private static long merge(List<Integer> array, int[] res, int start, int mid, int end) { int i = start; // index of left subarray int j = mid; // index of right sub...
stackexchange/codereview
I have created a cumulative profiler, meaning it runs a function several times in a row and prints the cumulative profiler results. it's python >= 3.6 specific, but you can remove nonlocal and the type hints for it work on older versions. import cProfile, pstats from typing import Union, List, Callable, Optional, Tuple...
stackexchange/codereview
I've created a method which is useful for executing multiple queries, and it works perfectly. Is this a good way to handle this? public function foo($rQuery) { try { $this->done->beginTransaction(); foreach($rQuery as $val) { $rSql = $this->done->prepare($val); $rSql->execu...
stackexchange/codereview
I need to create matrices that follow a specific format: the matrix is a square NxN matrix and the off-diagonals all have the same value (param) and the diagonals have values such that the rows sum to zero (in other words, they are equal to 0 - param * (N-1). The output is a numpy array Here is my code. Is there any wa...
stackexchange/codereview
I am getting products using given parameters (name of real entity and columns changed for illustration purposes), public IQueryable<Product> GetProductsByPara(string price, string weight, string dimensions, string trend) { var result = dbContext.Products.Where(a => a.Price.ToLower().Equals(p...
stackexchange/codereview
I've implemented a simple binary search tree for practice purposes: #ifndef BST_H #define BST_H template <typename T> class treeNode { public: treeNode *left; treeNode *right; T key; treeNode(T key) : key(key) , left(nullptr) , right(nullptr) { } }; template <typename T> cla...
stackexchange/codereview
ES6 syntax helps to write code in a declarative style, which is exactly what I am trying to achieve here. Any advice to make my code "more declarative" (and easier to read) is welcomed. const middleIndex = xs => Math.floor(xs.length / 2); const split = xs => { return { fst: xs.slice(0, middleIndex(xs)), ...
stackexchange/codereview
The goal of my program is take some headers and fields and display a nicely formatted table like this: +----------+----------+----------+ |First name|Last name |Middle | | | |initial | +----------+----------+----------+ |This is a |This is a |This is an| |line. |longer |even | | ...
stackexchange/codereview
This is a follow-up question for std::array and std::vector Type Arbitrary Nested Iterable Generator Functions Implementation in C++ and std::deque and std::list Type Arbitrary Nested Iterable Generator Functions Implementation in C++. The only thing different in the previous implemented n_dim_vector_generator, n_dim_a...
stackexchange/codereview
I am trying to create a validation class that can be used to validate many forms of my webpage in general. It makes use of the database as well to verify records. The problem with it is that it looks bad and somewhat inefficient. I couldn't find any alternatives and I have used too many if-else if statements. And also...
stackexchange/codereview
I'm wondering about the difference between these two linq statements bool overlap = GetMyListA().Intersect(GetMyListB()).Any(); // 1. vs bool overlap = GetMyListA().Any(i => GetMyListB().Contains(i)); // 2. Will statement 2. call GetMyListB() for each item in ListA? Which is more readable?
stackexchange/codereview
I am dealing with a system which sends any unexpected errors back to me in a string, for example: Error Type - Database Error Message - Error Executing Database Something is wrong. Error Detail - [Macromedia][SQLServer JDBC Driver][SQLServer]Incorrect syntax near '1'. Now to create a better UI I am expected to deal wi...
stackexchange/codereview
I have an instance method which calculates the position of an element, depending on the tariff of its seller. If the seller is of a level3 tariff, it gets to top 100, the probability of 40%. If the tariff is level2, then 30%, etc. TARIFFS = {level3: 0...40, level2: 40...70, level1: 70...90, ...
stackexchange/codereview
I have a function which contains two switches, which check for Command Code and Response Code after that updating UI elements. The code is working fine. How I can reduce or improve those switch cases? private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { byte[] buffer = ne...
stackexchange/codereview
I have a component that I want to render with certain styling based upon the props that it will receive. I'm currently defaulting the prop types, and then creating the styling at render as such: getDefaultProps: function(){ return{ size: "small", shape: "rounded" }; }, statics : { function getShape(shap...
stackexchange/codereview
I wrote a function to find a specific fibonacci number, which runs in O(lg n). Then I modified it with a template. Though it works, I'm new to template and want to know if I used template correctly. Moreover, I wonder whether someone who has a BigNumber class can use my function without modify my source code. #include ...
stackexchange/codereview
This is a follow up to: Lvl 1 upgradeable attributes From before: I've built the groundwork for an attributes (as in Strength, Intelligence, not as in DebuggerHidden, TestMethod) framework for my game. Each attribute can be upgraded and downgraded individually as well as part of a bulk change (such as for upgr...
stackexchange/codereview
I'm a beginner working through an exercise on ruby arrays. Given a two-dimensional array with 0's and/or 1's, it should return an array with the non-diagonal surrounding elements of 1 changed to 1 if they are 0. That is a = [[1,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,1,0]] should return [[1,1,0,0], [1,0,0,0...
stackexchange/codereview
My alghoritm works and produces good result, but it takes too much time(6 s for 300 input items that is too much for branch and bound alghoritm), so I have maken a mistake somewhere, but really can't find it :( It is supposed to be depth-first branch and bound. Any help would be appreciated! public void knapsack2(Item[...
stackexchange/codereview
I'm trying to calculate perfect powers to solve this code wars challenge: https://www.codewars.com/kata/55f4e56315a375c1ed000159/haskell The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not consid...
stackexchange/codereview