instruction_seed stringlengths 71 95.1k | _source stringclasses 1
value |
|---|---|
I am computing Nth element of the the sequence:
\$a_n=-2a_{n-1}+a_{n-2}+2a_{n-3}\$
Initial values are
\$a_1=-2\$
\$a_2=6\$
\$a_3=-8\$
Code
#include <iostream>
//#define NDEBUG
#include <cassert>
using namespace std;
struct Matrix
{
int n, m;
int* elements;
int getElement(int r, int c) const
{
... | stackexchange/codereview |
I just started watching some regex tutorials on Plural Sight just to learn how to write a proper regex expression. So far so good, it's been alright and I decided to test my knowledge on Hackerrank. Although, the tutorial explains how to use PCRE (Perl Compatible Regular Expressions) and ECMAScript engines but I'm comf... | stackexchange/codereview |
This code simply receives a very basic 'password' (numbers, letters, nothing fancy). After you press enter, it will display it back. The only special key I'm handling is backspace (code 8 in ASCII).
uses crt;
var
pass: string;
key: char;
len: integer;
begin
clrscr;
key := chr(0);
pass := chr(0);
write(... | stackexchange/codereview |
This is my first Go program. I would like to know what could be improved, what is done wrong, and anything else that I should know. The CSV contains 10 questions with the 10 answers separated by a comma. For example:
10+10,20
4+5,32
If you want the full context this is from gophercises which are some exercises to prac... | stackexchange/codereview |
I have an n-tier solution which consist of DAL,BL and a ASP.net WebAPI project. I'm new with Asynchronous Pattern and I'm trying to add it to my Framework. Am I using the asynchronous pattern correctly? I'm not convinced with my implementation of it. Could you give me a recommendation on how to use it correctly or any ... | stackexchange/codereview |
Is this an acceptable approach to update WPF MainWindow from an async task, using events thrown from a public static class?
In MainWindow.cs, I subscribe to UI.TaskCompleted event
In UI.cs, I subscribe to AsyncTaskActions.TaskCompleted event
Using this pattern, AsyncTaskActions.TaskCompleted is raised when an async ... | stackexchange/codereview |
I am doing a php project with the codeigniter framework. In my controller, I have a function that does the following.
Uploads an image to the server
Add a row to the database. The data would be retrieved from the form that calls the controller.
The best approach might be to put these two things in separate functions,... | stackexchange/codereview |
Roadmap
I'm trying to follow usual compiler design:
Lexical analysis (1, 2)
Syntactical analysis <---- you're here
Semantic analysis
User input
Code generation + execution
Background
I think I understood the first golden rule of newbie in compiler creation:
When in doubt, create gigantic if-else/switch chain.
and ... | stackexchange/codereview |
I'm writing a pixel library to do an AJAX request so I'm not allowed to use any helper.
function ajax(options) {
var xhr = new XMLHttpRequest();
var opts = Object.assign({
withCredentials: false,
method: 'GET'
}, options);
xhr.withCredentials = options.withCredentials;
xhr.open(opts.method, opts.url... | stackexchange/codereview |
In my Backbone.Collection I need to parse the response before to render it in Backbone.View. The following code works, but it will be great to have some suggestions:
// response is array of object
// [{id:1, prop: null },{id:2, prop: "bar" }]
// the output parsed_response can be
//[{id:1, prop: null, isProp: true }... | stackexchange/codereview |
I'm a beginner in python and my code looks a little cluttered and a lot of lines are being duplicated, so I was wondering if I could get some suggestions on how to declutter and improve?
import time, random
def start():
global user
global character
global shadow
user = {'gold': 0, 'HPP':1, 'EPP': 1}
... | stackexchange/codereview |
In an application there is a table for one-time-passwords (OTP) which will be sent to users via SMS. These OTPs are needed for a maximum of two hours in order to detect abusing behaviours.
A simple DB cleaner will delete these rows (DeleteAsync is from this library):
public class DbCleaner : BackgroundService
{
pri... | stackexchange/codereview |
This is part of the project I started just now. It is a function that returns the offset address of a first occurrence of a string match into a given range of memory blocks.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct
{
unsigned long offset;
unsigned long terminal;
} Range;
unsig... | stackexchange/codereview |
I have a library function that returns a pair of two numbers like this
def library_function(x0, x1):
return x0**2 + x1**2, 10*x0*x1 + 1
(Actually, it is a function that returns predicted probabilities of two classes for some object, but it doesn't matter, so I created an artificial one.) I want to draw contours wh... | stackexchange/codereview |
I got this program that I am working on and in it, I got a section that has a try statement and two error except statements.
try:
...
if ...: raise SyntaxError
except SyntaxError:
...
except ValueError:
...
The thing is that the SyntaxErrors are technically ValueErrors, but the errors occur for differ... | stackexchange/codereview |
Which of these names is better: time.getHours() or time.hours()? And why?
public class Time implements Serializable {
private final int hours;
private final int minutes;
public static Time from(Calendar calendar) {
int hoursIn24HourFormat = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = ... | stackexchange/codereview |
This code takes a list and a integer and duplicates every element in the list the specified number of times.
(define (super-duper source count)
(define (next-super source left)
(if (zero? left)
(super-duper (cdr source) count)
(cons (super-duper (c... | stackexchange/codereview |
Reason for script:
dir="auto" is an attribute value from the HTML 5 spec with current poor support in IE and Opera browsers. The project I am working on only cares about IE, Firefox and Safari browsers and handles text in both left to right LTR and right to left RTL languages. For cases where the directionality of th... | stackexchange/codereview |
I saw this UI for a mobile app, but I reverse engineered it for the web. This is how it looks in my CodePen
This would be either a favorites or featured list locations to travel to. I decided to go with a <ul> with class of "locations"
HTML
<ul class="locations">
<li>
<a href="#"> <!-- url would be generated-->... | stackexchange/codereview |
I implemented date range picker logic using the jQUery UI datepicker component:
var onDocumentReady = function () {
var datepickerConfiguration = {
dateFormat: "dd/mm/yy"
};
var startDatepickerHandler = function () {
var selectedDate = $(this).val();
var newC... | stackexchange/codereview |
I am very new programming and am trying to develop a small tycoon game as a hobby project in Unity. This algorithm executes beautifully but if 100+ agents are getting new paths simultaneously there is a significant drop in frame rate. Where should I start with optimizing?
I use 4 classes for my pathfinding. The PathFin... | stackexchange/codereview |
One fun feature that was added (fairly) recently in .NET is the [CallerLineNumber] attribute, which, in conjunction with [CallerFilePath] and [CallerMemberName] can allow for some very nice logging methods.
I was thinking today, though, that they might be used for another interesting purpose. Consider the case where y... | stackexchange/codereview |
I wrote this script to backup some important files. It backs up the files to a local folder as well as to an external hard drive. It creates a new subdirectory which has its name constructed with the current date and time. Works perfectly, but I'm just wondering if there are any Python best-practices I'm missing or ... | stackexchange/codereview |
Is the complexity of this code \$O(n^3)$? How can I improve the efficiency and reduce the complexity?
A = [3,2,4,2,4,2,4,5,3]
n= len(A)
def ALG2 (A,i,j): #to check whether all entries between A[i] and A[j] are the same
if i==j:
return True
for k in range (i,j-1):
if A[k] != A[k+1]:
... | stackexchange/codereview |
Here is my Implementation. It is I think almost like algorithm.
public static uint[] CountingSort(uint[] A ,uint max)
{
uint[] B = new uint[A.Length];
int[] c = new int[max +1 ];
for (int j = 0; j < A.Length; j++)
c[A[j]]++;
for (int i = 1; i < ma... | stackexchange/codereview |
I have a database class that in __construct() initialize a PDO connection and insert the instance into a $db private var.
Now i'm working on a method that can be used to query in this way:
$db = new db;
$db->query(array(
'select' => 1,
'from' => 'table',
'where' => array('id' => 1, 'name' => 'charlie'),
'limit' => ... | stackexchange/codereview |
I'm new to Java and am following a series of lectures on Stanford's YouTube. I know that the code works, but I'd like to know if it can be improved upon.
/*
* File: PythagoreanTheorem.java
* Name: Will
* Section Leader: N/A, I'm freeloading the class off Youtube.
* -----------------------------
* This file is the ... | stackexchange/codereview |
I've made a python script to properly organise D&D monster stats in a directory. The script brings up the stats as instance variables of a Monster (class) instance.
For those unfamiliar with the game, keeping track of monsters (to me at least) is cumbersome and prone to many dead trees. You have to flip through the Mon... | stackexchange/codereview |
There are two functions, sportsRunning and sportsWalking, that will render different text. For this, I am using an if condition at the bottom to display corresponding div:
{sportsDescription.sportsDate && sportsDescription.sportsDate.length > 0 && sportsDescription.sportsDate !== '2199-01-01' ?
this.spo... | stackexchange/codereview |
from inspect import signature, Parameter
def check_can_take_positional_arg(fun, arg_ix):
params = signature(fun).parameters.values()
return len(params) >= arg_ix + 1 or any(
param.kind == Parameter.VAR_POSITIONAL for param in params
)
def check_can_take_keyword_arg(fun, arg_key):
params = si... | stackexchange/codereview |
Here's my second try at pairwise summation in Haskell:
pairwiseSum :: (Num a) => [a] -> a
pairwiseSum [] = 0
pairwiseSum [x] = x
pairwiseSum x = pairwiseSum (sumPairs x)
sumPairs :: (Num a) => [a] -> [a]
sumPairs [] = []
sumPairs [x] = [x]
sumPairs (x:y:xs) = ((x + y) : sumPairs xs)
I ran both versions on pairwiseSum... | stackexchange/codereview |
I have a script that checks if the specified set of $_POST variables are supplied and not empty and returns an error string that is human readable.
Here's my code:
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Local variables initialization
$missing = [];
$checkVariables = [
'name', 'address', 'c... | stackexchange/codereview |
I wanted to use <select multiple> but was annoyed by the poor design on desktops which is why I created a version with dropdown:
convertSelect("001", "Options");
function convertSelect(el_id, name) {
let el = document.getElementById(el_id),
opts = Array.from(el.options);
let input_el = document.crea... | stackexchange/codereview |
Update: further succinct versions below (inspired by Haskell)
Quick sort in JS assuming an immutable array:
const reorder = (arr, pivot) => {
let larger = []
let smaller = []
let equals = []
for (let i = 0; i < arr.length; i++) {
if (arr[i] < arr[pivot]) {
smaller.push(arr[... | stackexchange/codereview |
I got annoyed having to do things like string.IsNullOrEmpty(myString) when it seemed as if myString.IsNullOrEmpty() would perfectly suffice. Therefore, I wrote a small, simple library to wrap the static methods of primitives in extension methods.
I don't suppose there is much to critique about the code itself, as most ... | stackexchange/codereview |
This is my first attempt at scripting with bash. I am running Ubuntu server, so I don't get to use all the gui back ups out there. Besides, tar works fine for personal use. Please let me know of any improvements and why.
#!/bin/bash
# PURPOSE:
# TO BACK UP ALL FILES AND FOLDERS FROM A GIVEN DIRECTORY
# Directory to ba... | stackexchange/codereview |
I've written a simple C# class to use as a dll for simple math calculations: addition, subtraction, division, and multiplication.
How can I improve this code, specifically for addition and multiplication? I've tested it with a C# GUI and a VB.NET GUI. I've tried it with VS 2005, 2008, 2010, 2012, and the Community Edit... | stackexchange/codereview |
Problem: Given an even number (greater than 2), return two prime
numbers whose sum will be equal to given number.
NOTE 1: A solution will always exist. (Goldbach's conjecture)
Note 2: If there are more than one solutions possible, return the
lexicographically smaller solution.
This solution becomes slower for hi... | stackexchange/codereview |
Is this implementation correct? Do you find any threading problem? Also, what parts of the code can be changed to be more C++11-ish?
#include <iostream>
#include <vector>
#include <thread>
#include <random>
#include <condition_variable>
namespace {
int sleep_for_random_time() {
std::random_device rd;
... | stackexchange/codereview |
I am working on a pseudo graphical interface for a Chess engine I wrote. I want to draw a colored Chess board with ASCII pieces. To abstract the pure std::cout << std::endl; I wrote this little class to organize an ASCII-character "framebuffer":
#include <iostream>
#include <sys/ioctl.h>
#include <unistd.h>
#include <v... | stackexchange/codereview |
I'm learning concurrency and asynchronous programming in C#. For a better grasp on the matter I'm trying to create an OLX Crawler. My issue here is the performance: It takes roughly 159 minutes to crawl 17.901 links.
The method which crawls each item is this:
public async Task FetchItemsData()
{
var itemsTa... | stackexchange/codereview |
I have a method that parses XML into an array of hashes.
Here is the original XML:
<rowset name="skillqueue" key="queuePosition" columns="queuePosition,typeID,level,startSP,endSP,startTime,endTime">
<row queuePosition="0" typeID="20495" level="3" startSP="2829" endSP="16000" startTime="2013-03-04 16:25:50" endTime="2... | stackexchange/codereview |
There are the following class:
class ConsoleForegroundColor : IDisposable
{
public ConsoleForegroundColor(ConsoleColor color)
{
OriginalColor = Console.ForegroundColor;
Console.ForegroundColor = color;
}
public ConsoleColor OriginalColor { get; set; }
public void Dispose()
{
... | stackexchange/codereview |
I am learning Python online on Stepik platform, and unfortunately I don't have any opportunity to get reviews from the tutor. The platform only checks the correctness of the answer that my program gives. So I decided to share the code here. Comments and corrections would be much appreciated.
Write a program that print... | stackexchange/codereview |
I am parsing an XML file and trying to get the guid of a node where it has an attribute "name" and a value of "Name" like so:
<property name="Name" guid="7eca00b3-38e0-f0e8-9b72-2b822b21de6b" />
string propertyGuid = propertyList.Where(x => x.name == "Name").FirstOrDefault()?.ToString();
if (propertyGuid == (object)nu... | stackexchange/codereview |
This program calculates common factor for given numbers. The original use case is to find a possible resolution for pixel games that scale well with new screen resolutions (that's why I don't have any check and optimizations for big numbers and use simple brute force).
(define (fun1 l d)
(if (apply = (map (lambda (... | stackexchange/codereview |
I am looking for a review of my code that implements a MyQueue class which implements a queue using two stacks.
public class MyQueue<T> {
Stack<T> stackNewest, stackOldest;
public MyQueue() {
stackNewest = new Stack<T>();
stackOldest = new Stack<T>();
}
public int size() {
return stackNewest.size... | stackexchange/codereview |
I've asked a question receiving excessive (in a good sense) feedback. After I've incorporated it into the code, it changed substantially and I felt that I'd need opinion on the new version. Posting revised code is against the rules, so I'm asking a new, follow-up question.
Choice of exception names. Are those informat... | stackexchange/codereview |
I'm sure this game gets put up here all the time but I'd appreciate it if you could have a look over my code and give me some suggestions on how to improve it.
Here is a live example so you can play the game and here is the code on GitHub if you want to fork it and tinker with it.
(function(){
/*
* Rock, paper, sciss... | stackexchange/codereview |
I'm currently looking to try learn CSS properly and I'm looking to recreate the following image using CSS:
Now I've managed to recreate the image (sort of) what I am looking to know though is based on my code what am I doing wrong/what would be the best practice. Many solutions fix a problem I want to know if my solut... | stackexchange/codereview |
I'm wondering if you see anything terribly wrong with this code, or if you see any areas for improvement. My objective is to make sure its simple enough for someone else taking over my job to be able to pick up fairly quickly.
My basic question has to do with the fact that in my model, I'm trying to distinguish betwee... | stackexchange/codereview |
A friend sent me this question, and I'd love somebody to review this and give his opinion.
Write an algorithm that counts the number of ways you can paint a
fence with N posts using K colors such that no more than 2 adjacent
fence posts are painted with the same color"
Is this algorithm accurate? Could it be impl... | stackexchange/codereview |
I am new to coding. Given int arrays A and B, I would like to find the maximum GCD (Greatest Common divisor) any element of A and any element of B. I am doing the following
Sorting both arrays, then
Comparing every value of array A to array B to find GCD
Using a temp number I am checking if the GCD found is bigger tha... | stackexchange/codereview |
I consider myself a beginner at writing in Java. I have never had a programming class, nor had my code reviewed. I have come to Code Review for some pointers. (Tips that is, not data references.). I have written a simple server/client set, where the server behaves as a textual message relay, receiving and forwarding te... | stackexchange/codereview |
I am supposed to make a basic RSA encryption/decryption code, where I am only given e.
I wrote this code to randomly generate two primes and then find their totient. But the totient is supposed to not be co-prime with e which is given as 65537. So this code would technically return a good value eventually, but in rea... | stackexchange/codereview |
To practice learning x64 AT&T Assembly (GAS), I implemented three solutions for Project Euler Problem 1 (find the sum of all the multiples of 3 or 5 below 1000).
The codes and a rough pseudocode sketch of each are shown below. I'd like some open-ended feedback (some more specific questions are at the bottom). To clarif... | stackexchange/codereview |
I just completed level 2 of The Python Challenge on pythonchallenge.com and I am in the process of learning python so please bear with me and any silly mistakes I may have made.
I am looking for some feedback about what I could have done better in my code. Two areas specifically:
How could I have more easily identifie... | stackexchange/codereview |
I have an assignment to solve this problem. I’m not too sure how permutate works by tracing, just tried on inspiration and it works. This code runs on all provided test cases, but I’m just trying to look for ways of improvement in terms of time efficiency, space efficiency and styling.
Question Description
Bob the Dog... | stackexchange/codereview |
I've the following tables
Candidates
Id Name PicId
1 Tom NULL
2 James 1
3 Bob NULL
4 Manny 2
Attachments
Id Name
1 One.jpg
2 Two.doc
3 Three.rtf
The join table AttachmentCandidate
CandidateId AttachmentId
3 1
3 2
4 3
So from the above tables it sh... | stackexchange/codereview |
I want to implement code for inserting a new Node in a binary search tree in java so please check if my code is correct ,,, Here is my method :
public class BinarySearchTree {
…
public boolean add(int value) {
if (root == null) {
root = new BSTNode(value);
r... | stackexchange/codereview |
This is my first time using Boost and templates in general, so I'm mostly looking for a style critique on my C++. In particular, I'd like feedback on:
state_type, is there a good way to do this such that consumers of the library and the private members of the class can use this type? Other than making two separate typ... | stackexchange/codereview |
I'm trying to build a Web API using best practices, based on a simple proof-of-concept using students.
My goal is to build the system using:
Onion Architecture to seperate concerns.
Service-Repository for interaction between BLL and DAL.
Autofac for IoC, to control injected dependencies.
NPoco for micro-ORM.
Moq for m... | stackexchange/codereview |
This is a follow-up question for A recursive_transform Template Function Implementation with std::invocable concept in C++ and A recursive_transform Template Function Implementation with recursive_invoke_result_t and std::ranges::transform in C++. Besides the version using std::invocable, I am attempting to implement a... | stackexchange/codereview |
My program....
Downloads a file
Connects to a server
If one of these operations were to fail, the program stalls for a minute and goes back to step one.
So, I would avoid recursion and the use of global variables. I think I did the first one right, but I need help to avoid the second one. What would I do if I need to... | stackexchange/codereview |
I'm a mechanical engineer/amateur programmer trying to learn modern C++. I'm working on a personal project where I'm building a library that uses PortAudio to abstract some basic audio processing, specifically pitch and volume extraction from microphone input as a way to facilitate that learning. I'm as interested in... | stackexchange/codereview |
I'm building an angular application using AngularJS and AngularFire. As this is the second part of this "series" it might be a good idea to also check out part 1 to gain an even better overview of the register/login process.
I have a few concerns here:
It feels like I shouldn't need to have a $scope.loggedIn variable ... | stackexchange/codereview |
I created a quick program to test the precision of randomness generated by the .rand method. The primary question is whether I can use the .times method in place of the while code blocks to increase efficiency and:
Whether such a practice would reduce the amount of processing required/if this would be at all signific... | stackexchange/codereview |
I have a specific method that I like because it lets me decide whether or not I want to use the default. If I want anything different I enter in :option => value otherwise I get the default. Here's a concrete example that works, but is a little ugly.
How can I accomplish the same thing in a more elegant manner?
def con... | stackexchange/codereview |
I have the following tables in my database:
people: phones:
+----+------+ +-----------+------------+-------------+
| id | name | | person_id | number | description |
+----+------+ +-----------+------------+-------------+
| 1 | Jade | | 1 | 1234567890 | home |
| 2 | Ben | | ... | stackexchange/codereview |
I have used the factory pattern for one of my projects.
I want to know if this is a good design or if my code can be improved to make it as fast as possible.
I am not an expert in C#.
This is what I came up with after 2 days of research, with lots of rewrites.
What I want to ask is:
Is this the right approach?
Can I im... | stackexchange/codereview |
CATS, willing to get a hold of all the bases, asked Dijkstra to give him a hand designing the most powerful algorithm to reach all bases with the least distance travelled.
I tried to implement the Dijkstra's algorithm using TDD. This algorithm is designed to find the fastest route to reach all nodes of a graph. Right... | stackexchange/codereview |
I am doing some math - combining, reusing, extending different analyses methods over the same original data set. It would be reasonable to use C# extension methods in my case instead of defining everything in one class. The same time there are too much stuff to be constantly recalculated in this extension methods - I d... | stackexchange/codereview |
I got bored and decided to make a merge sort from scratch. I like everything, except for my "merging" of the two arrays into a sorted array inside the for loop. I had several bugs that I had to iron out, which were along the lines of if subArray1 or subArray2 ran out of elements, checking them caused ArrayOutOfBounds... | stackexchange/codereview |
Given two int values, print whichever value is larger. However if the two values have the same remainder when divided by 5, then the print the smaller value. However, in all cases, if the two values are the same, print 0.
This is what I have so far:
public static void main(String[] args)
{
Scanner scan = new Scanne... | stackexchange/codereview |
I am gaining a lot of interest in Game development.
I created Chrome Dinosaur game in C++.
I have not paid much attention to UI/UX, just trying to see if i can apply some OOPs in game programming.
As I'm a beginner, I'm not sure whether I'm using good code design and logic.
I could use some code review and tips. Before... | stackexchange/codereview |
class InvitationConfirmationValidator < ActiveModel::Validator
def validate(record)
invitation = Invitation.find_by_url_suffix(record.id)
if invitation
if invitation.materialized?
record.erros.clear
record.errors[:base] << "Invitation already materialized"
end
else
record... | stackexchange/codereview |
I wrote an API including a CLI program and a daemon to set the brightness of a display under Linux.
The API is mainly represented by the class Backlight() and is the basis for both, the CLI program and the daemon and is intended to be reused in other programs.
The CLI program can read and write the screen backlight bri... | stackexchange/codereview |
This code creates a problem for the user to solve (very simple problem) it will then check if the user has got it right and will say so.
import random
import time
def mathsquestion():
attempts=2
bananas1 = random.randrange(1,40)
bananas2 = random.randrange(30,70)
print('lucy has', bananas1,' bananas an... | stackexchange/codereview |
I've just started programming and read a book called Head First Java.
I thought it would be fun to make a training project that I can put all the stuff I learn into. Is the code I've written here just really bad or good code written for a beginner?
I've got 4 classes:
Main class:
public class Main {
Player p = new... | stackexchange/codereview |
I'm using an HTML editor to insert code into a website. When you embed media like an iframe element, it deletes the code.
It's apparently a bug with TINYMce and grappelli, so as a workaround, I insert non-media content into the HTML editor:
<div id=”youtube1”><p>width="854" height="480" src="https://www.youtube.com/emb... | stackexchange/codereview |
I want to make sure that the code I have for encrypting and decrypting a serializable object makes sense and is proper. Does it look right too?
Here's what I have so far:
public static void encrypt(Serializable object, String path) throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, Inva... | stackexchange/codereview |
I've written my own prime number sieve in JavaScript. It loops through numbers 1-100 and puts them in one of two arrays, depending on if it is composite or prime.
I was wondering if there are any inefficient or unnecessary parts of my code that might be slowing down the program. Is there anything I can do so it will wo... | stackexchange/codereview |
Service Class
# services/search.rb
class Search
include Rails.application.routes.url_helpers
include ActionView::Helpers::TagHelper
def initialize(term, app_ids)
@term = term
@app_ids = app_ids
end
def results
term = @term
app_ids = @app_ids
multi_search = Tire.multi_search do
no... | stackexchange/codereview |
The following makefile builds my classwork for my various college classes and builds pdfs to hold the notes I took during class. I would like feedback on my directory structure and any optimizations that can be thought of to help improve it. I've been using and updating it for the past 18 months. I know that I should p... | stackexchange/codereview |
My final version is a direct translation from Python. Thanks to build-in support for generator, its speed is almost the same as Python. As I quite like using generator and list comprehension in Python, I am not sure I get the right way in Racket.
Moreover, I've only found explicit support for generator in Racket these ... | stackexchange/codereview |
How do you guys think I can improve the code for collision detection on my website asteroidfield.eu5.org? The current code is
var dx = Math.abs(c1.getcx() - c2.getcx());
var dy = Math.abs(c1.getcy() - c2.getcy());
var dist = Math.sqrt((dx * dx) + (dy * dy));
if (dist - (c1.getR() + c2.getR()) <= 0) {
if (done === fa... | stackexchange/codereview |
I am working on a project where users have to log in then if it is correct it creates a cookie to process requests. I would like to find a way to auto-renew sessions every day without affecting the user or requiring the user to log in again.
I would like to also know if I overlooked any security flaws such as SQL injec... | stackexchange/codereview |
I'm working with ACF in WP which provides a get_field() function. The function can return an array of values, null or false. When the result of the function doesn't contain an array of values I want to default to an empty array.
This is how I do it at the moment but would like to know if there's a neater way to accompl... | stackexchange/codereview |
I currently have a logging setup that looks like this:
require 'active_support'
require 'singleton'
class Worker
def initialize(logger)
@logger = logger
end
def perform
@logger.with_context(["tag1"], "Started work")
Provider.say_hello
end
end
class Vlogger
include Singleton
attr_accessor :logg... | stackexchange/codereview |
This is probably my final submission to Code Review regarding this making a report from payroll details series. Basically, working in the human services sector, the funding agency requires A) Weekly documentation of services provided and B) Monthly documentation of general progress for each of 60+ developmentally disab... | stackexchange/codereview |
My code works, but the aesthetic of the code seems to need some real work. The logic is simple enough:
Create three lists of words that will be used throughout the conversion
Create three functions:
One for sub-1000 conversion
Another for 1000-and-up conversion
Another function for splitting and storing into a list... | stackexchange/codereview |
After referencing http://csharpexamples.com/tag/unsafe-bitmap-access/
I tried to put together one for 1 bit per pixel bitmaps.
If you can review this, it would help me greatly in verifying this is the correct way to do it.
This takes a Format1bppIndexed bitmap and locks it in memory, and directly parses the memory bit... | stackexchange/codereview |
My teacher wants me to find all the perfect numbers between 2 and 1000 and must use:
for loops
% operator to determine if a number is a divisor
static final variables for 2 and 1000
A static method to return a boolean value by finding and adding the divisors of the integer parameter and comparing the sum to the parame... | stackexchange/codereview |
I recently started out with C++ and I am working on an application that can watermark entire directories of images at once.
Currently you can call the program with an argument of the target directory where the images are stored and an argument for the path of which watermark image to use.
It works so far but I think my... | stackexchange/codereview |
I solved the following problem:
Consider the range 0 to 10. The primes in this range are: 2, 3, 5, 7, and thus the prime pairs are: (2,2), (2,3), (2,5), (2,7), (3,3), (3,5), (3,7),(5,5), (5,7), (7,7).
Let's take one pair (2,7) as an example and get the product, then sum the digits of the result as follows: 2 * 7 = 14, ... | stackexchange/codereview |
I've been doing project euler problems in Haskell, and often I've found the need to get the value that gives the maximum of a function.
For example,
answer = argmaximum $ map collatzLength [1..10^6]
Where collatzLength is a previously defined function.
I came up with this code, which is heavily influenced by learning ... | stackexchange/codereview |
Based on the excellent answers provided for my previous question, I've thoroughly revised my attempt at "deep" versions of all, any, etc. It uses the recommended encapsulated flattening function, and streamlines some unnecessary stuff.
def flatten(*sequence, preserve=False):
for item in sequence:
try:
... | stackexchange/codereview |
Old code:
Login system security
This is an update on the code and suggestions I received from generous users on the old thread.
So same rules apply, just check it out, tell me what you think. Is it better or worse? is the security getting better and if so what else can I do to make it better? Are the sessions correctl... | stackexchange/codereview |
Here is my iterative implementation of the Counting change example in SICP. Please note that I'm a beginner, which means I only know the basic syntax for the time being.
Requirement:
How many different ways can we make change of $ 1.00, given
half-dollars, quarters, dimes, nickels, and pennies? More generally,
can... | stackexchange/codereview |
I'm having this part of code which I want to make smaller, more readable and easy to manage. Any thoughts? I tried linq but got lost.
foreach (var o in state.s)
{
TimeSpan timeDiff = (DateTime.Now - o.time);
if (timeDiff.TotalSeconds < 300)
{
richTextBox.Appe... | stackexchange/codereview |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.