instruction
stringlengths
71
71.9k
Basically, what this program does is that this generates a random number, and asks the user to guess it with multiple chances. So, if the user is close, it says that the user is close, and if the user is not close, then it says that the user is too high/low and if the user guesses it right, it congratulates the user. S...
Here is the culprit; headers omitted for brevity, and also, see notes afterwards: /** * A GUI-neutral background task executor * * <p>A very common scenario when programming with GUI toolkits is the need to * perform operations in the background without blocking the "UI thread" (this * would be the infamous EDT, o...
This is a simple Area Calculator coded in Java. What this does is that it prompts the user to select a shape, and asks for the details needed to calculate the area of that specific shape. Main.java: package com.AreaCalculator; import java.util.Scanner; public class Main { public static void main(String[] args) {...
I am practicing some simple Java coding problems in an attempt to learn while doing them. I would like to know if my code is redundant/is there an easier way to accomplish the same thing? Question: Which Alien? "A person who witnessed the appearance of the alien has come forward to describe the alien's appearance." ...
I am trying to build a websocket server to run on the Raspberry Pi. The websocket server has to push periodic realtime update to a browser. Here is a sample code that I am planning to use. The example code here sends the current time instead of sensor data. Most of the code is built form an example. However, what I nee...
While looking for Naruto posts (= overlooked accepted answers well worthy of upvotes), I noticed some odd false positives, selfie answers, where the user who asked the question accepted his own answer under suspicious circumstances. I'd call suspicious circumstance the case when other answers exist with positive votes,...
I've been working on a live form validation project, initially I intended on finding a way to solely use CSS for said validation but it quickly became apparent I would require some jQuery to get it to function properly. That said, I'd like another set of eyes on my jQuery to see if anyone has improvements or tips to st...
I'm looking for an algorithm to make my code faster and better for big strings. Problem link Let the simple prettiness of a string be the count of vowels (I, E, A, O, U, Y) divided by the length of the string. Find the sum of the simple prettiness of all substrings of a given string (with precision within 1 part per m...
Any suggestions are welcome. package je3.io; import java.io.*; import java.nio.charset.Charset; /** * Created by IDEA on 30/01/15. */ public class CountCharsWordsLines { public static long[] count(String filename) throws IOException { long[] counts = new long[3]; try(InputStream in = new FileInp...
This is what I've done; import Control.Applicative import Control.Monad import qualified System.Directory as SD main = do files <- SD.getDirectoryContents =<< SD.getCurrentDirectory exes <- filterM (liftA SD.executable <$> SD.getPermissions) files print exes This works fine, but I can't help feeling that t...
I am new to object-oriented concepts. The following is my attempt at creating a basic calculator using class and operator overloading concepts. Please review it for improvements. Also, how do I make it more intuitive? I want to display: +,-,*,/ as options and use switch on them. #include <iostream> #include <conio.h> ...
I develop Windows Phone App with Prism framework (MVVM). I use data caching. To get data I use proxy service. Proxy service creates two tasks: the first task is receiving data from a web service and update data in local database (SqLite). the second task is receiving data from the local database. The ViewModel laun...
I'm currently working on a kind of PHP Quiz about mathematical calculations. We show a mathematical equation, and user need to input his answer. Currently, this is what I have written: echo '<div class="table-title">Super Quizz</div>'; echo '<div class="row text-center quizz">'; function addition($x, $y) { return $x...
As part of my C++ training, I wanted to create a basic complex number class for basic complex number calculations. The class should have the following: constructor (non explicit, for implicit conversions) << and >> operators to stream with cout and cin ==, != operators to compare complex numbers +, +=, -, -=, *, *=, ...
Around June of last year, I made my very first GUI 'app.' Wish I knew of this amazing site then, I thought for posterity's sake it would be great to get it reviewed. It's a simple I/O window just to keep track of the quantity of X exercise that was done, and if I used these two other workout apps. I'd like to evaluate:...
I've got a rather long function that will take the size of a triangle print it with stars and give the user the option of whether or not they want stars printed inside the triangle, and the orientation (point up or down). I was hoping for some general refactoring methodologies I could apply. Every permutation is possi...
A Person has coordinates and an Item has coordinates as well, and hence both are derived from Entity, which has the coordinates data member. If a person holding an item moves, the coordinates of the item must change to whatever the person's new coordinates are. And if he drops the item, this is no longer true. So I ...
Any suggestions are welcome. package je3.io; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Created by IDEA on 31/01/15. */ public class DirWalker { private List<File> recursiveList = new ArrayList<File>(); public void walkDir(String pathname) { File d = new File(path...
I have a project in embedded systems and I have to write the code in C, and make it simple. This is my first time, and it's only a simulation of how it should work. #include<iostream.h> #include<stdio.h> void manualMode(); void defaultMode(); int temp, timeToWash, operation; int main() { int mode =0, part=3, w...
I've come up with the following code to handle drag and drop operation. It's composed of a constructor function that returns an objects with methods to attach to event handlers. Notes about this solution: It's client responsibility to attach methods to event handlers; specific CSS classes should be added to DOM elemen...
Inspired by this question, I decided to implement a Disjoint-set data structure in Python 3. I mainly followed this description for understanding the algorithm (but did not do the optimizations for path compression, union by rank etc. -- so mine is a "naive" implementation). Here is the Wikipedia article for reference....
In my app, I have an ObservableCollection of MenuItems: public ObservableCollection<MenuItem> ItemList { get; set; } When an item in it is selected (either programatically or by the user), this method is run: public void SelectionChangedWS() { if (!NavButtonUsed) { Back.Insert(0, CurrentItem); } if (Forward.C...
I am experimenting with ECS design and I am looking for a solid way to implement a message bus for use between the different systems. Here is a stripped-down version of my current implementation: #include <iostream> #include <cstdlib> #include <functional> #include <vector> struct BaseEvent { static size_t type_co...
I wrote a record which encapsulates conversion of colors between TColor, RGB values, CMYK values, and HSV/HSB values. It seems to work (at least for the purpose I made it), but I'm not too confident about the rest. Specifically the conversion between RGB and HSV. This record supports implicit conversion with TColor. I ...
public function insert($table, $fields = array(), $values = array()) { $fields = '`' . implode ( '`,`', $fields ) . '`'; $values = "'" . implode ( "','", $values ) . "'"; $sql = "INSERT INTO {$table} ($fields) VALUES($values)"; if ($this->_pdo->prepare ( $sql )) { if ($this->_pdo->exec ( $sql )...
I'm super new to this so please be nice. I tried solving Chris Pine's challenge to print the entire lyrics to 99 bottles of beer on the wall. This seems to work, but is there a better/more efficient way to do it? Just want to learn how to improve it if I can. var1 = 99 loop do puts (var1.to_s) + ' bottles of beer o...
I'm new to JavaScript and was hoping there was a cleaner way to write this. It's a block of code that looks at a group of documents in a collection (called Messages), and makes a call to the GitHub API for each one. If any of the API calls finds a certain string in the response, the function returns true via callback. ...
The previous and initial iteration at Kruskal's algorithm in Java Now what I did is remove the fields and let the actual Kruskal-routine create the required data structures in the local scope, which leads to thread safety. The only file that changed is KruskalMSTFinder.java: package net.coderodde.graph.mst.support; im...
When I last did a lot of Java programming, I'd do this: All classes in a package would be default (package) visibility. Each package would have a public PackageNamePack factory class, e.g. BusinessPack. And the package would have a number of interfaces. The package factory would have methods like newBusiness(...) whi...
The program is displaying given number (right now it is only signed int) converted to different numeral system (binary,octal and hexadecimal for now). Number can be input in the text box and the display updates automatically in the ConvrterDisplay UserControl. Form has a possibility to enable autoincrement provied by ...
The code I wrote to do this effect stays "fixed" on top or on bottom. I did it the manual hard-coded way and wanted some advice on the best way to write something like this. jsFiddle <script type="text/javascript"> function toggle_visibility(id) { if (id == 'firstDivHeader') { document.getElementById('firstDivResults...
I had come up with the following code: hello_worlds 0 = putStr "" hello_worlds x = do putStrLn "Hello World" hello_worlds (x-1) main = do n <- readLn :: IO Int hello_worlds n I am aware that it is making one extra call to putStr. Is there any better way of doing this? If so, please give some...
I'm trying to implement an algorithm for a resource-constrained project scheduling problem. I have several resources, resource constraints and all of this is in integer time domain. With my class ResourceUtilization I want to assure that resource constraints are not violated in all time. Key element of my class is arra...
Input: An array of integers. Output: That same array, but with the even numbers at the front and the uneven numbers at the back of the array. I wrote three different solutions, depending on the needs of the client. First solution: // linear time not stable and not in-place private static void partition1(int[] a){ /...
The problem is: Define a procedure that takes 3 number arguments and returns the sum of the squares of the 2 largest numbers. I am a CS graduate and I am revising my university notes. This is my code so far: (define (square n) (* n n)) (define (square_of_larger_numbs a b c) (cond ((and (> a b) (> a c)) (c...
I'm starting with make, and I made my first makefile to build my project. I don't know if it's the best way to do it or not, so I share with you my makefile to get your opinion on it: Directory structure: ├── LICENSE ├── Makefile ├── objs │   └── parser.o ├── out │   ├── libsip.a │   └── parser.h ├── README.md ├── src...
URL: http://jsfiddle.net/rabbit_aaron/ve7deecw/ This is again, a JUST FOR FUN project. In this attempt, I use a closure instead of validating caller to ensure only member methods can access private methods. Pros: Easy to implement Works in strict mode All class instances has the same private methods Yes, real private,...
This is a simple class for a label with a score that animates counting up or down. When someone in the game scores points, the numbers count up or down to the new total. Here is an example of what it looks like: I ran into a few problems when building this class. It was important to prevent the building of further ...
I have the following piece of code in my project, and that a few times: $this->uniqueSessionKey = $settings->get('uniqueSessionKey') ? $settings->get('uniqueSessionKey') : $_SERVER['HTTP_USER_AGENT'] . time(); I was wondering if there's a better way of writing this, especially the part where it checks if $settings->ge...
I am taking Stanford's Introduction to Databases Self-Paced online course. I have gone through the videos in the SQL mini-course, and I am having trouble completing the exercises. The following is the question from the SQL Movie-Rating Query Exercises, Question 7: For each movie that has at least one rating, find the...
Input: Real number y and Integer number x Output: x^y Constraint: Must be done in O(log(y)) time. Notice that O(log(y)) is O(length-of(y)). public static double expon(double x, int y){ double result = 1.0; double part = x; for (int i = 0; i < 32; i++){ if (((y >> i) & 1) == 1){ resul...
I implemented the Simple Factory Pattern with some unit tests, but I'm with a feeling that I did something wrong and that I can improve it. Tell me what you think about the code (source and tests). PizzaFactoryTest.php: <?php namespace Pattern\SimpleFactory; use PHPUnit_Framework_TestCase; class PizzaFactoryTest exte...
I am learning Python (3) and Django (1.7) after a while in PHP (not POO). I am rebuilding my own website that has public members. My members have a user account, a public profile and a private profile. When a member signs in, an email is sent to the admins to say that a new member has joined the team and a new email is...
I'm quite new to Scala and was surprised that there doesn't seem to be anything like Java's try-with-resources block. So of course I wrote my own little construct. Is there anything I could improve? import scala.util.control.NonFatal import scala.util.Try import scala.util.Failure import scala.util.Success object TryW...
I'm working on a script that will be able to press the login button on any site for an app I'm working on. I have it working (still a few edge cases to work out such as multiple submit buttons and iFrames and I'm going to rewrite it to make it prettier once I figure them out). Can you think of any ways I could improve ...
Recently, I perform re-factor on one of my frequent used custom enum, by removing its getter. My rational for doing so it. The enum's custom fields are immutable Only use getters when it is necessary. Less typing. Reduce verbosity. This is a very stable class, with only 17 commits, since 2008. Its getters behavior ha...
This is a header file for my bezier curve utility and several of BezierCurve2D's methods return newly created arrays of Point2D objects. Should I create (using new) and delete objects in the same scopes? Should I have these methods receive a pre-allocated space of Point2Ds? #ifndef BEZIER_UTILITY_H #define BEZIER_UTILI...
Here is my simple chat program. I'm wondering whether it has an acceptable design (both object oriented design and network design). If you want to run it, I can provide the solution folder. Server public class Server { private TcpListener _tcpListener; private readonly int _packetSize = 64; private int _cl...
pwgen is a nice password generator utility. When you run it, it fills the terminal with a bunch of random passwords, giving you many options to choose from and pick something you like, for example: lvk3U7cKJYkl pLBJ007977Qx b9xhj8NWPfWQ pMgUJBUuXwpG OAAqf6Y9TXqc fJOyxoGYCRSQ bpbwp6f2MxEH fUYTJUqg0ZMB GjVVEQxuer0k oqT...
As nobody has provided input, I have updated the question. (The next one is coming soon) Coding to this interface: namespace ThorsAnvil { namespace Serialization { class ParserInterface { public: enum class ParserToken {Error, DocStart, DocEnd, MapStart, MapEnd, ArrayStart, ArrayEnd, Key, Value}; ...
In Json strings characters can be escaped with \\. Here is an iterator that can read such strings and convert the escaped characters to UTF-8 #ifndef THORSANVIL_SERIALIZATION_UNICODE_ITERATOR_H #define THORSANVIL_SERIALIZATION_UNICODE_ITERATOR_H #include <iterator> namespace ThorsAnvil { namespace Serialization ...
Today, a solution written in Python was posted to this challenge, and since I was inspired by it, I made a version in EcmaScript 6. I tried to explore some new language constructs: arrow functions template Strings let for..of generators The code: function* bottlesOfBeer(howMany=99){ let pluralizeBottles = count => ...
I'm trying to implement function downpairs which takes monad of pairs and transform it into pair of monad My current implementation is import Control.Monad import Control.Arrow import Data.Maybe downpair :: (Monad m) => m (a, b) -> (m a, m b) downpair = ((return . fst =<<) &&& (return . snd =<<)) main = do prin...
I'm doing a project in ms sql and I have to fill table with random records. Here is a definition of table: create table invoice( id_invoice INT PRIMARY KEY IDENTITY(1,1), id_employee INT FOREIGN KEY REFERENCES Employee(id_employee), id_client INT FOREIGN KEY REFERENCES Client(id_client), id_service INT ...
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...
It's been a while since I last wrote some lolcode, so I felt like tackling Project Euler #1. If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. This is the code/script I wrote to solv...
For one of my [WIP] project, I extended the dictionary class a lot with specific handlers, as such I determined that I wanted KeyError and TypeError exceptions to be specific to my project's parser. I extended the exception class like this: Github Permalink """Exception classes """ class ValveException(Exception): ...
I just finished working through Exercise 16 of Learn Python The Hard Way. To further study, I wanted to create a script that will read and display a file's contents on screen, and then have the user re-write the file with three lines. Can my code be written in a much cleaner, pythonic way? from sys import argv script,...
First LOLCODE program, run here. This program inputs a Fibonacci number from the user, then determines and prints whether the number is in the Fibonacci series. What do you think? HAI 1.2 HOW IZ I GetNum VISIBLE "Entr yr numbr: " I HAS A WatzNum GIMMEH WatzNum FOUND YR WatzNum ...
Is there a neater way to write this code? var table, field, dbFieldEntries; var s = 'one.two'; // The DB field is always the first parameter dbFieldEntries = s.split( '.' ); if( dbFieldEntries.length === 1 ){ field = dbEntryEntries[ 0 ]; } else { table = dbEntryEntries[ 0 ]; fi...
def smoothen(heightProfile, travelTime): newHeightProfile = [] # Berechne einen gleitenden Mittelwert smoothingInterval = 30 * travelTime for i in xrange(smoothingInterval): heightProfile.append(heightProfile[-1]) for i in xrange(len(heightProfile) - smoothingInterval): mean = 0 ...
As a programming exercise, I've attempted a Tic-Tac-Toe solver which takes a finished board and determines a winner. On top of checks for malformed input/ambiguous games (e.g. both players with winning positions), what else can I do to improve this? In particular, is the coding style acceptable and are there better w...
The Edmonds-Karp algorithm relies on breadth-first search in order to find an augmenting path in the residual flow network. This version of the algorithm uses bidirectional breadth-first search in order to speed up the entire algorithm. My profiling reports consistently speed ups of at least 3. The files DirectedGraphN...
Very useful operation that hasn't been merged into a function.. until now. This is supposed to insert a substring into a previously d.allocated source string. void strapp (char *source_offset, int position, char *appendage) { size_t appendage_size = strlen(appendage) + 1; char copy[strlen(source_offset)]; ...
I am building a PHP framework and would like to get some feedback on a few different sections of the project. I consider myself still a neophyte in PHP so I would like to ask if I'm going about completing these different tasks in an efficient and or correct way. I have create two classes, initializer and Loader. The i...
I wrote a minimalistic thread pool using some C++11 features. I've used it on two projects so far and it has worked fine, but when I ran the code on my laptop, I believe that my thread pool might be entering some kind of dead-locked state -- occasionally the CPU activity drops to almost nothing, and the program hangs. ...
This is more of a 'model' of TicTacToe, as you'll see it's not "gameified" in the sense that it will allow for inputs and outputs nor will it record any "active" state of the game but those things are trivial to implement. I'm cheating a little bit on the functional paradigm in my function to rotate the grid, but this ...
I'm visiting some code that I wrote for one of my finals projects and wanted to know whether there were a more optimal, more elegant way to do this so it does not look so "hard-coded". The problem was that I needed to calculate the Determinant of a matrix, and, at the time (some of it was rushed) I did not know of a be...
I'm using jquery and cookie.jquery to remember the scroll position. Is there anything I can do to improve my code? Thanks! $(document).ready(function() { // convert cokkie variable for easy access var prev_scroll_position = $.cookie('prev_scroll_position'); // scroll to position $(window).scrollTop(pr...
I'm just starting to learn JavaScript. I implemented the Diamond kata, and I would appreciate if anybody could give me some feedback. I'm particularly concerned about learning the most 'idiomatic' way to do things in JavaScript, style conventions, etc. The diamond kata consists of the following problem statement: Give...
This may be a bit overwhelming, but me and a friend of mine have written a Database class with methods for our queries. All of these queries should be generic so we can use them in multiple ways. We make use of PDO. These are the thing bothering me; We need a session class to handle all the sessions within our classes...
For the problem given: Douglas Hofstadter’s Pulitzer-prize-winning book, Gödel, Escher, Bach, poses the following mathematical puzzle. Pick a positive integer \$n\$ as the start. If \$n\$ is even, divide it by 2. If \$n\$ is odd, multiply it by 3 and add 1. Continue this process until \$n\$ is 1. The thesis is...
I am creating a shopping cart application to learn Spring MVC. I want to display a list of all categories and subcategories in more than one page. i.e; Home Page, Products page, and Category page. In the Home Page controller I am retrieving the list of categories, subcategories and featured products and passing them to...
I've got a problem where I need to parse a line in a parameter file of the form PotentialName [... variable number of parameters] I've got code which works however it seems like it will be horrendous to maintain when I add more than a few options here. What would be the best design pattern to avoid the long chain of e...
Are there any ways I can clean this code up to make it more user-friendly? import random #Random Function import os print("What is your name?") #Asking User Name name = input().title() #.title() capitilises the first letter in each word, so when the name is printed in later code the first letter will always be capitil...
I have several routes, and I need Facebook authentication only in the routes that start with /admin: app.get('/admin/dashboard', passport.ensureAuthenticated, .....); app.get('/admin/dashboard/new/email', passport.ensureAuthenticated, ....); app.get('/admin/dashboard/new/question', passport.ensureAuthenticated, ....); ...
Haven't any experience writing recursive functions.(Generally tend to avoid them - not sure if that's a negative). What do you think about the following? This is also my first time using JUnit, I'd appreciate input if I'm doing something wrong there. Challenge: Create a digital Root Function. Specifications: A digital...
Original question: Average interval between dates with random blanks I have a spreadsheet with order date data: I need to find the average interval in days between each order date. I have to both find a way to get past the blank cells in the row, and also take into account that some clients have 5-10 orders and some ...
I'm doing a bunch of work with echonest audio objects (as returned by the echonest API) in the Python CLI and rather than having to recreate them each time, they can be saved. This bit of code reloads them all, referenced via a dict: def get_saved(directory = 'audio/', extension = 'en'): return glob.glob(directory ...
I am implementing a search bar here. I have finished basic UI. I have been recently developed a taste for scalable and robust HTML/CSS. Therefore I am closely following things like BEM and OOCSS Am I on the right path? Also, how can I make the UI responsive? index.html <div id="container"> <form class="search-box"> ...
I came across it as a problem to solve. What kind of limitations are there? public long parseLong(String number) { long n=0; if(number==null || number.isEmpty()) { System.out.println("Number is null or empty"); return n; } boolean isNegative = false; if(number.charAt(0)=='-') ...
I writing a hash table with double hashing. This code works ONLY with ASCII text files and finding the number of occurrences of each word in input file! Please point out mistakes and shortcomings. #include <stdio.h> #include <stdlib.h> #include <math.h> #define STRINGSIZE 50 #define EXP 2 #define TABLESIZE 100 str...
My approach to solving the problem of selecting the best match on a bejeweled board is a fully object oriented approach. Some of the other relevant code can be found in my previous questions regarding bejeweled, but this question will only be about the DMMatchFinder class and associated classes. I should note that I o...
In my project, I have a type BalanceByBucket that is an immutable type and has a bunch of methods. I have another class called a FundBalance which is basically just a BalanceByBucket that has an extra int FundID property applied to it. I want this FundBalance to also have access to all the same methods as BalanceByBuck...
I have a function that accepts a \$255\times1024\$ array and remaps it to another array in order to account for some hardware related distortion (lines that should be straight are curved by the lens). At the moment it does exactly what I want, but slowly (roughly 30 second runtime). Specifically, I'm looking at the ne...
I am trying to optimize an object filter function. Given an array of keys, I need to filter an object. I feel that creating a new object each time may degrade performance. Is there a way to mock the Array.prototype.filter function for objects? function main() { var Types = { INTEGER: { value: 'int' }...
This bit of code is a small game to see how long you play a game of FizzBuzz without messing up. Code: The top of the code: #include <stdio.h> #include <string.h> #include <stdlib.h> typedef enum {false, true} boolean; typedef enum {FIZZ, BUZZ, FIZZBUZZ} FB; int n = 0; // the number that is being incremented char inp...
I've been learning Common Lisp lately and I've implemented ANFIS network based on Sugeno model I. Network layout and details can be read in these slides by Adriano Oliveira Cruz. I use sigmoid as the fuzzy set membership function of each input (in layer 1) \$ \mu(x) = \sigma(x) = \frac{1}{(1 + e^{b * (x - a)})} \$ T-no...
I am just testing out a few small functions for learning purposes: def peaks(iterable): # returns a list of int for those values in the iterable that are bigger # than the value preceding and following them. itr = iter(iterable) peak =[] curr = next(itr) last = next(itr) try: while T...
I'm trying to implement generic queries and handlers so that I can make requests with simple syntax, like this: var query = new HelloQuery("hi"); var result = processor.Process(query); This post explains a brilliant technique for accomplishing this, but it uses reflection and dynamic to resolve handlers for queries. ...
In the code below, $rows is the result of database query. In the view that consumes this, I need to break the results into a separate table for each vendor. The below creates a structure that allows this in the template, but it seems like a clunky way of doing it. Advice on how to improve it? $byVendor = []; i...
Making an Android app involves making a lot of images of various sizes: The app's launcher icon, in high/low/medium resolution Buttons, menu buttons, if any, in high/low/medium resolution Images for listing on Google Play: main icon, feature graphics To simplify this, I use high-resolution source images + ImageMagick...
I have array contents with some date ranges, fetched from the database: $calendar = array ( array ( 'check_in' => '2015-01-02', 'check_out' => '2015-02-28' ), array ( 'check_in' => '2...
I am just testing out a couple of small classes for learning purposes. Here is my current working code: class Permutation: '''An int list a permutation if starting at any index, one can reach every other index by repeated index accesses. The list [4, 0, 3, 1, 2] is a permutation: for example index 0 stor...
You are being watched Code Review has an open system A machine that spies on you on every hour of every day I know because I built it. I designed the machine to detect suggestions to post on Code Review but it sees everything Horrible comments involving ordinary users Users like you Comments that Stack E...
Please have a look at this little coroutines library ccoro: http://sam.nipl.net/code/ccoro I'd appreciate a general code and style review, and your kind comments! ccoro.h /* * ccoro - Coroutines in C * Sam Watkins, 2009 * this code is public domain * * ccoro uses setjmp and longjmp to achieve coroutines in plain ...
The goal of this code is to take dollar or cents input from the user and give out minimum number of coins needed to pay that between quarters, dimes, nickels and pennies. If this code can be shortened, how would one do it? #include <stdio.h> #include <cs50.h> #include <ctype.h> #include <math.h> int main(void) { float...
I'm making a 2048 clone and my method to move and merge tiles is really long. I've heard of helper methods but I'm a little lost as to how I should use them. I feel like my code is a little too long and can be made shorter but I don't know how. What can I do to make it shorter and cleaner? I'll also take any constructi...
This is a small personal project where most non-sensitive data is distributed to some globally hosted CDN servers, which store the JSON. Now one problem we've seen during testing is a few deadlocks during spike loading of Ajax resources at the precise time that the cache is being distributed to the cache servers. So I ...
I have such method where: primary_images is dict, additional is dict, get_uri_text is some decorating method, marker is telling how to parse two dicts. How can I simplify this method? @staticmethod def decorate_sort_images(primary_images, additional_images, get_uri_text, marker=False): srt_keys = ...