instruction
stringlengths
71
71.9k
I have been working for about a week on a calculator in Tkinter, and the result is a very ugly, but functional calculator. Is it possible to clean up the code, and make it more readable? from Tkinter import * import tkMessageBox import sys import os import math main = Tk() string = [] x = 'add' def exit(): sys....
I recently wrote a chat bot for a chat room here at Code Review. The chatroom is meant to be a place where people can come and pimp a post. That chat bot is meant to handle a list of subscribed people and a list of pimped IDs. People on the subscribed list can pimp posts and will get notified when someone else pimps ...
I have just finished up making an object Depth Management system that I will be using for drawing and explicitly drawing. Because we all know that the order in which things are drawn heavily effects the way the game will look. My system has a very simple and easy to follow code, and the only problems I have found are t...
I have a very simple view that handles touch events and draws accordingly. It's nothing significant, but it does use a bit more CPU than I would like (35%). Again, it is the bare minimum (<90 lines), but I can't really think of a simpler way to draw using user input. What would you change? import UIKit class DrawView:...
I have an array with the following structure Array ( [0] => Array ( [area] => Area ABC [activity] => Array ( [0] => Activity 1 [1] => Activity 2 ) ) ) I'm trying to render this array in the fol...
I've been working on this for the last few days. Any improvement ideas? (Notes are very simple, making this for school and notes have to be for complete novices to Python). import random # Allows the computer to generate random numbers, vital for the program to function correctly. import sys # Al...
In preparation for the end of Code Review's 2015 election, I've built a simple bot to get the election votes, run OpenSTV on them, and post the result to a chatroom. I'm using this Python implementation of STV and ManishEarth's ChatExchange. import getpass import logging import os import time import urllib import sys f...
I am currently working on an implementation of SoundCloud for a 3rd party iOS app, and as there is no SDK anymore I am doing all my calls via Alamofire. This is what SC expects you to send in your body params: { "playlist": {"tracks":[ {"id":"__"}, {"id":"__"}, {"id":"__"}] } } I han...
I know this type of question has been asked before. However, my reason for asking it is gaining insight into what is expected in a 45 min interview when asked to implement graph algorithms. I have never had to give an interview, but have been asked in several interviews, questions pertaining to graphs. Specifically adj...
This code works as intended, however, I am sure that there is a way to condense the xmldataLoad method. If someone could maybe explain a better approach than what I have done with the method, I would be extremely grateful. Essentially, what I am saying is I am rather new to using LINQ and don't fully understand the var...
Mac doesn't have the Unix clock_gettime so I am trying to create something that's really portable and only dependent on C. So far I've come across this function: static void current_utc_time(struct timespec *ts) { #ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time clock_serv_t cclock; mach_...
I've implement a custom dropdown, that help to find users from data. Each item have a userpic, first name and last name. And my task is create a dropdown with settings like use picture or not. I coded it in create function, in a loop with if-statement: if (is_use_picture) { /* ... */ }. It would be great if I could get...
This is the HackerRank problem Algorithmic Crush: You are given a list of size N, initialized with zeroes. You have to perform M operations on the list and output the maximum of final values of all the N elements in the list. For every operation, you are given three integers a, b and k. The value k needs to be added t...
I wrote a little function that monitors some directories. If a file gets created, it will check in the extension list for a match. Can you please tell me if I could make my function better in any way? private void sysWatcher_Created(object sender, FileSystemEventArgs e) { try { if (File.Exists(e.FullPath)...
I am new to PHP and was just wondering if there is a better way to write the following OR if it would make any difference to use elseif here instead of multiple if statements - especially if the options in questions might be more than in the example here (the current code is working). Note: I cannot use switch here si...
I'm completely new to Groovy, but have many years of Java experience, and recently I have started working on a Grails application, currently it contains the following: User and Person domain classes UserService service class UserController controller class to offer a REST API This application is written using Groovy ...
I have the following code blocks that generate apparently random numbers by using thread timing variations. I am looking for a general code review, and a specific focus on whether the results are "true random numbers". For computers with more than two CPUs #include<chrono> #include<iostream> #include<thread> using name...
I wanted to create a simple and easy to use permissions system. The ones I've found on the Internet would need to attach every permission to a route manually (e.g. Entrust). My idea is to build a permission name out of the current action, so for example method 'store' in 'TestController' becomes 'test.store' permission...
I need to concatenate 3 input fields into a string which is formatted as a date dd-mm-yyyy, using type="date" or new Date() will not work in my scenario because Firebase doesn't allow it for some reason. I came up with a rather ugly solution, but I'm not quite sure how to improve it. delete is bad for performance, but ...
I've made the following python script to to append the contents of the latest Stackage nightly build to the global cabal config file (instead of going to the site, copying the page and appending it manually...). I would appreciate your feedback: """ Appends the latest stackage nightly sources from Stackage(http://www.s...
I have built an RC car and attached a Raspberry Pi to it - in order to control it, I wrote some Java code to listen to commands over the network and make the car move accordingly. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class...
Instructions: Write a Java program the displays the State bird and flower. You should use your IDE for this exercise. The program should prompt the user to enter a state and print both the state bird and flower. The user should be able to enter a State without worrying about case. (e.g. Users could enter Maryland, mar...
I've been inspired by @SirPython's SirAlfred JavaScript chat bot, so I went and made my own. This one is slightly different though, in the fact that it can accept input in a more lenient way. For example, here's a "conversation" with the bot: sudo make me a sandwich bot BOT: It will be done master. sudo make me a sand...
In JavaScript, I wrote a class that can be optionally instantiated with the new keyword, but can also be called statically as well. What is the best way to demonstrate this behavior in comment syntax? I was thinking something like this: // localize constant var PI = Math.PI; /** * Complex constructor * optionally in...
Most of what I'm writing is pretty quick and dirty as I'm crashing through a lot of stuff to learn. My variable/function/class names are most likely not efficient and I still need to get a lot of the PEP8 formatting down. That said, I put a quick Tic Tac Toe game together in Python. I'm going to add some decision logic...
The following C++ code is a lightweight implementation of in-close algorithm. Full details of the project can be found here. I was trying to translate the C++ code to C# but it's very difficult to manage. That new version simply doesn't work due to pointer implementation. In fact, I need to keep using pointers because ...
I'd like to have some feedback on this sieve of erasthotones that I've wrote. It outputs all prime numbers up to n correctly (I've tested with the first 10k prime numbers). Is this well written? Does it look good for python programmers? I've made the math up to the sqrt of n + 1, which improved the performance a lot. i...
I am preparing for interviews, and have implemented a solution to this problem from Geeks for Geeks: Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. I don't fully have my head wrapped around the dynamic programming approach. If I pro...
I have been through a few SQLite tutorials and wrote this code on my own to reinforce the principles. The tutorials I went through varied widely in a few areas so this is what I came up with as a combination of everything. Other than the two classes I have listed below, all I have is one activity that adds, remove, in...
I'm pretty new to C# and was just wondering if there is a better way I can write this calculator that I made: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnthonyCalculator { ...
This is a simple example of script to run the test write/read performance of third party software of the drive in Windows environment. Please let me know if you find any place can be better improved, thanks. #! /usr/bin/env python import sys, os import PCMark import PCMTest from decimal import Decimal import re impor...
After the advise from this code review I have come up with the following changes. I'll go in the same order as my previous post. This post is mainly for an updated version so that others can see the previous posts suggestions. If I have made any mistakes please let me know. ObjectPoolManager.cs: public class ObjectPool...
I implemented a Sudoku validation program. Can this be optimized even further in terms of performance? public class ValidSudoku { public boolean verifySudoku(int arr[][], int num, int i, int j, int row, int col) { return (verifyRow(arr, num, i, j, col) && verifyCol(arr, num, i, j, row) ...
Whenever using ArrayList, the method containsAll(collection) runs in time \$\mathcal{O}(mn)\$, where \$n\$ is the size of ArrayList and \$m\$ is the length of collection. However, it relies only on equals(Object)-method. I have this subclass of ArrayList that does the same in time \$\mathcal{O}(n)\$, but relies on hash...
I am making a small 2D game with the use of Allegro 5 library. I am making use of inheritance e.g. sprite class as the base class and player class as the child class, but I want to know if it's a good idea to approach it in this way and other ways that are better to do this, if there are any. Main.cpp #include "Allegro...
The following script draws 6 numbers at random. I input another 6 numbers and compare with random numbers generated, if they're the same, you win. <html> <body> <form align="center" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post"> Numele jucatorului <input type="text" name="nume" min=...
I've recently coded an event manager with performance as the main factor. I'd like to know what you think of it and what could be made better. public class EventManager { public static EventManager mouseRightClick = new EventManager(EventType.mouseRightClick), mouseLeftClick = new EventManager(EventType.mouseLeftC...
I have a written some code which helps me to get OAuth Access Code from Reddit. Reddit uses standard OAuth2, so like any other OAuther server, here's are the steps to perform: The client/app sends app key, app secret and redirect URL to browser. User authorizes it and gives permission. Reddit sends request back, with ...
For a puzzle I had to brute force a password. I've never used goroutines before, and I don't have much experience in concurrency. This is the cksum function, which takes an array of the ASCII code for each letter in a string (a is 97, b is 98...etc): func cksum(bytes []int) int{ a := 0 b := 0 for i := 0; i ...
The program sorts the array from lowest to highest and outputs the index of the searched value: public static void main(String[] args) { Integer[] random = {6, -4, 12, 0, -10}; List<Integer> list = new ArrayList<Integer>(Arrays.asList(random)); Collections.sort(list); Integer[] array = list.toArray(new...
I programmed a Tic Tac Toe game using JavaFX, and I'm looking for a code review of it to improve my skills and practices in Java. It would highly be appreciated if you reviewers emphasize on these points specifically: Bad practices which I am following Inefficiencies and how would I rectify them TicTacToe.java: packa...
I'm building a spiking neural net (recurrent, integrate and fire), and I'm curious about how to reduce the warp divergence (and other problems) I may have. Here's an example with a few hand-placed neurons and synapses for a better apprehension. I upload the whole code on a Git repo for faster access, make tui then ./cu...
I'm just starting to learn Java and I have written this simple Tic Tac Toe game. Please review it and give me some feedback, advice, guidance etc. Main method: import java.util.Scanner; public class Main { public static void main(String[] args) { char player='o'; int row,column; Scanne...
I'm kinda new to PHP and I'm trying to make a script to validate a HTML form only with PHP (I know there are options to do so with JS, but I guess it's better to have a "cover" with a server-side script). Project folder structure: project/ classes/ #contains classes to validate and process the HTML form DB...
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...
I have been trying my hand at Python lately. I have been able to look at code examples and create a custom application that queries a Microsoft SQL Server, pulls out two columns (date, balance) and charts them using pyplot embedded in tkinter for future development. Because of the "chop and change" nature in which I wr...
language-tags is my first crate, it is hosted on GitHub and I uploaded it to Crates.io. It parses language tags like en-US into useful parts, like language and region for example. These tags then can be compared or printed out again. To create language tags it provides the langtag! macro. Is it good code, where can I i...
Below is my implementation of Word Morph solver in Python. The challenge consists of transforming one word into another word by changing one letter at a time. Each word in the chain should be an English word (part of a dictionary). One should output all such chains of the minimal possible length. Examples: 'tree' to '...
Function: char **strsplit (char source[]) { char **strings = calloc(1, sizeof(char *)); int nStrings = 0, nChars = 0; strings[0] = calloc(2, sizeof(char)); while('\0' != *source) { if(*source == ' ') { nStrings++; nChars = 0; strings = realloc(st...
Problem: Write a method that takes in a string. Your method should return the most common letter in the array, and a count of how many times it appears. Note: I solved it with Ruby, but the solution will be almost the same with other OOP language which have arrays and hashes. Solution: Split the string into an a...
I am developing a Python script that will process large amounts of data from an experiment. Files are read in, calculations are made, images are plotted and saved as .pngs, and calculated parameters are outputted to a .txt file. When I save a file, the user is prompted if they want to overwrite any existing files. If ...
This code takes a list of ints and sums their pairs, storing the summed pairs in an array sumPairs, then returning that array. If the supplied array toSum has an odd number of elements, it returns the sumPairs with the last element of the toSum as the last element of sumPairs. Any suggestions for improving my code, or ...
Just looking for an initial steer on my AngularJS implementation. Background Started work on a clients new site which uses a popular CMS as the backend and AngularJS has been chosen as the client side framework. Functionality Build a simple control that will manage alerts generated from the CMS. If the alert has bee...
My assignment was to write a method that is capable of visiting each edge in a graph in each direction exactly once. With it, I included a basic Graph class to test it with. What I'd like a review of: This is like my 1000th attempt after trying everything I could think of. This is the first version that I've had that ...
I wrote some code to solve this question and I was wondering if it was efficient or not. I just started learning code last week and I would like to get some input so I can get in the habit of writing the most efficient code possible. #include <iostream> using namespace std; // What is the largest prime factor of the ...
I have written an n-body simulator, implementing the Barnes-Hut algorithm. Please comment on anything you can see wrong with this. Wikipedia Barnes-Hut page This is a screen shot of the simulation 20 hours in. All the particles spawn in a uniform disk, given an initial velocity in order to "orbit" the "Galactic center...
I am attempting to build a compiler for a stack-based (or concatenative) programming language in Haskell. I've done fine getting the lexer and parser up and running, but now that I'm into the meat of the semantic analyzer, implementing the algorithms idiomatically is getting trickier. I finally had to force myself to l...
Problems: Wanting to check all checkboxes when the checkbox w/id=checkall is checked. Wanting to uncheck the "checkall" box when any other checkbox is unchecked. Solution: $(document).ready(function () { $('#checkall').on('click', function () { if ($(this).is(':checked')) { $('input[type="checkbox"]').each(functi...
I've created a short piece of code to determine whether or not various 2D shapes (circles/lines/rectangles) intersect. It was a job interview question, but now it's just about self-improvement. I'd like any suggestions for how best (in terms of code cleanliness and scalability) to handle the fact that in implementation...
I wrote up a small script to calculate the answer to Project Euler Problem 5: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? I'm wondering if this algorithm...
It is very messy and I lack the experience to make it eloquent so I wanted some help with it. The process time is also very slow. Currently it goes into the first page and goes through the links in the index looking for the word "symptoms." If its not found it will look for a link inside that link named "faqs" and go t...
I'm working with an existing code base here and while I don't have the time/budget to re-do the entire thing (ultimate solution), I do get a bit of leeway to enhance the code base, as well as maintaining it. We're using EntityFramework and the SynchronizedBindingList is essentially just that; it keeps all the data in m...
Few months ago I posted my code Getting a single value from the DB. I implemented suggested changes and this is how it looks like right now: public class DataBase : Page { protected static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); protected static...
I intend to populate some fields in a form based on some presets values. The user choose the presets from a list. The following code is working, but as I'm a newbie, I would like to know if I done it the proper way and if it can be improved. Preset obj: var obj = { "preset_a":{ "input":{ "field_...
My algorithm generates combinations of elements. For example, having [A, B, C ] creates the following combinations [ A ], [ B ], [ C ], [ AB ], [ AC ], [ B, C ], [ ABC ]. Unfortunately for items too large too long and too much memory space, I get java.lang.OutOfMemory thrown. How can I fix? public void combine() { ...
I am developing a server for a web-client. Basically it's just a simple CMS to modify some data. My problem is that I never had a project like this where I have to take care about the server and the client and of course everything that happens between those two. I've started to implement a database with Hibernate which...
I am trying to create a PHP / MySQLi wrapper class that uses prepared statements, the goal of the class is to create a connection to the Database, then INSERT / SELECT / UPDATE information from the database. The class should hopefully be general enough to be able to use in multiple applications with other wrapper class...
I am writing a macro to move data from a CSV to an excel template. Currently, I have the code set to search for a keyword in column A of the CSV, and extract data from specified columns in the keywords row. I would like to know if there is something I can do to simplify the code. Public Sub MoveData() '**defines ...
The code works well but before I added sections (13) and (14), it ran in 6 minutes and now runs in 16 minutes. If there is a way to streamline this to cut down the runtime, that would be extraordinary. Main part of code grabs values from under the header 'CUTTING TOOL' in various opening files in a designated folder. T...
I'm reading serial data in binary format from a stream, and I'm not happy with how I extract the data because it takes so much operations to extract the binary data from a simple line of binary data. Each line starts with a character indicating the type of data, and afterwards follow a few 16 bit integers (big endian),...
I am creating a custom Exception class and trying to log the CallerFilePath, CallerMemberName and CallerLineNumber in the error log file along with the error message which is my main motive. I am just wondering if it is a good way of doing this task or if there is a much better/cleaner way to raise/handle and note down...
I found myself in need of a Readers-Writer mutex. With C++17 TR2 support not yet available in our compiler, I set out to implement std::shared_mutex so that we have an easy upgrade path to the STL implementation once we get C++17 support, rather than rolling my own API. I put all classes intended to implement or suppl...
I wrote a basic Python script that consolidates and customizes several popular adblocking hosts files. I was interested in making it more efficient if possible, and I'd like to improve my style and best practices. import urllib.request import re import os os.chdir('C:/Windows/System32/drivers/etc') # This contains a...
On my quest to become a master programmer I have created a simple game of Hangman, and so I thought I would upload it here and see how it could be refined. One question I had was my use of exception handling. I tried to utilise it here, but I get the sense it might have been overkill. Should I only be using try/except ...
I'm trying to create a caching solution used in various parts of a clients' application. The resulting code will be open source. For example, it will be used for caching API queries like "get all users" or "get all projects", whatever "all" may mean to the consumer (the constructor accepts a lambda as a "getter functio...
This is my sound system that allows for the following functionality: One master volume that controls every sound. A function to stop/pause every playing sound A function to control every instance of a sounds volume(@creation) A function to stop/pause every instance of the same sound Sounds that are playing are kept i...
For school we have to develop a product manager. The basic task is to add new products. A product has a name and a price. I know the one or other class is currently pretty empty but its planned to add more methods. The code is developed in MVC-format and comments plus texts are in German. I would like to know what's go...
For the community challenge, I wrote ultimatoe. For me, the most interesting part is clearly the AI, but what I did so far is just a stupid Monte Carlo tree search, which isn't ready for a review yet (but may come soon). Before reviewing, please have a look at the README. The text is much shorter than the code. I'd lik...
I answered a question yesterday on SO based on this riddle, but the code was so hard to read/follow to actually understand what was going on it was easier to write my own code to test the scenario and debug the program. I wrote it pretty fast, but I want to make sure the program I wrote is easy to follow and adheres t...
I have the following task: Create a simple treasure hunt game. Create a two-dimensional array of integers 10 by 10. In a random position in the array store the number 1. repeat Get the user to enter coordinates where they think the treasure is. If there is a 1 at this position display ‘success’. Until they...
I am learning OOP. I feel I have a grasp of basic dependency injection in that as a rule of thumb, you pass an object to a method rather than the parameters to create an object. As such, never create an object within a method, but use a factory. Right? The code below is for connecting to a REST API. However, I feel am ...
I created a standalone Java application that acts as a consumer that retrieves/listens for messages inside an ActiveMQ queue. Planning to run two instances of these on different machines for high availability purposes. What bothers me is the usage of Connection, Session, MessageConsumer, and Transaction (Hibernate). I ...
I've written some code to: Parse an XML file. Extract some strings. Make copies of the original XML whose names are suffixed with the extracted strings. Please review this. from lxml import etree as ET import re def create_paramsuffix_copies(xmlfile): NSMAP = {"c": "http://www.copasi.org/static/schema"} pa...
I have been working on a file parser that takes a very specific file format and parses it into a list that is arranged into node data and the neighbors that it relates to. I am new to Python (this is my very first program in this language), so I am not familiar with more advanced methods of solving the problem using Py...
I need criticisms and refactoring advice for my controller code: class ItemsController < ApplicationController def new end def create params = items_params if not titles_and_urls_are_same_length(params) render :new end collection = false if params[:tit...
I have started learning XML parsing in Java (currently reading Java & XML by Brett McLaughlin). Here is my first program to parse XML using SAX parser. Please review the code and let me know if that is correct way of parsing books.xml and storing into to a List<Book> (The code is working fine. I just want to ensure I'm...
This is the first code I've written. It's for an intro to Java course. Could you look over it and let me know of things I could improve before handing it in? For reference, I've also provided what I'm being graded on at the bottom. import java.util.Scanner; public class LB01Smith { public static void main(String[...
Link to previous question: Barnes-Hut N-body simulator It still has issues I'm sure. Node.h #pragma once #include <vector> struct Body { double posX, posY; //position x and y double velX, velY; //velocity x and y double AccelX, AccelY; //force acting on object since last frame f...
Could somebody help me out with trying to clean up this big list of if / else if statements please? I've found that switch statements won't work because it won't handle a TextBox as the parameter. I've seen many answers involving the Dictionary, but those won't work either in my case. private void SelectNextTextBox...
I'm trying to implement Dijkstra's algorithm in Python, but the issue is that Python doesn't have support for key-based heaps out of the box, so applying relaxation step of the classical algorithm presented in CLRS becomes cumbersome. My idea is to keep maintaining current total distance and then pushing frontier nodes...
First of all, I would like to know if there is any difference (execution-time) in C between: GET request made by using cURL GET request make by using sockets (BSD sockets) Second, I've done a C program which parses a XML file (without using any xml-specific library) and makes a GET request with the parsed info as it...
I was writing class Player with private fields and getters and setters. But the number of methods started to grow, I used lists and maps so additionally I had to create methods to get size of them and every item by index, key and etc. I got tired and decided to use public fields instead of getters and setters. Addition...
There are quite some questions and answers about how to make enum really type-safe and I didn't find a solution that ensures both type safety and valid values. So I took some ideas and extended it to my own generic solution, somehow resembling to enum classes used in some other languages. My solution adds the overhead ...
I am developing an application based on Repository design pattern. What should be the return type from the Repository? This is my UserRepository class: public class UserRepository : Repository<UserMaster>, IUserRepository { public UserRepository(DbContext context) : base(context) { } public Us...
Please review my custom ArrayList class I constructed from scratch and add any suggestions or constructive criticisms. The point of this template class is give the user a lightweight ArrayList with optimal control over how it operates. It is automatically created on the heap with an optional seed value which determines...
I would like the following code reviewed: I am trying to create a local server which listens indefinitely and provides the latest information. The server runs another while loop which fetches the latest info every one hour. I have tried multi-threading approach, in which one thread is a socket server (runs ind...
The code is working but slow. Is there a way to speed it up or make it more compact but still easy to read? There are 35 different jobs to be done. They are made in a worksheet with merged cells to enter, who did the job, when, how long, workorder, nr, etc. Next to the layout is a command button, and when you click on ...
I made a slide show using array values, it works, but I strongly believe that the way I did is too long. There should be an easier or more compact way to achieve this. $(document).ready(function () { var num = 0; var myArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"]; var batch = 1;...
I am using the following code to try and only allow letters, numbers, backspace, space, dashes, slashes, and ampersands. I also want all other keys including the function keys (F1, F2, etc) to be disallowed. I feel like this code can be optimized to make it more streamlined. This function is part of a live search featu...
I have some code to handle integer, double, Boolean, and string settings. Right now, each setting variant extends an abstract class, where the setting value is stored as an object. Is there any way to avoid this? What I'd like to do is have IntSetting objects return their Value as an integer, DoubleSetting objects ret...