instruction stringlengths 71 95.1k |
|---|
Everything you need to do OOP in one neat little package without having to do all the work by hand. Almost like C++.
Here is how you would use it:
var A = Object.extend("A",
{"static" :
{"counter_start" : 5 // all static propertiers and methods should
// be initialized
... |
This challenge took me awhile to figure out, and it's characterized as "easy," so I'm sorta wondering what I missed.
Problem Statement
You are given a list of N people who are attending ACM-ICPC World Finals. Each of them are either well versed in a topic or they are not. Find out the maximum number of topics a 2-pers... |
I have created a Tetris AI which can play Tetris on its own given a set of rules. It places the next piece in every possible way on the board, and calculates which position that gives the fewest "holes" on the playfield.
The playfield is represented by an int[] array, where every bit represents a position in a row, an... |
I'm learning Angular and I don't like my current approach. The current controller uses first Geolocation service and when getLocation() is resolved, then the Pagination service is invoked with the location param. Is it any better solution to provide one service that query server with location? Can I integrate the Pagin... |
The code contains an AI function, that searches breadth-first all possible moves and get the score of their grids, a depth of 6 is used which makes at most \$4+4^2+...+4^6\$ computed grids. The highest scores (and their associated moves) are kept for each level of depth, the most redundant one is chosen.
This function ... |
I recently have been working on a project to simulate segmentation in memory. I wanted to create everything from scratch; not use pre-built data structures.
I create a memory object that allows for "segment" nodes and "hole" nodes.
A segment is: Any location in the memory object that is occupied by data.
A hole is: Any... |
I have the following functions:
function getExample($id, $otherid) {
global $db;
$query = 'SELECT * FROM examples WHERE id = :id AND otherid= :otherid';
try {
$statement = $db->prepare($query);
$statement->bindValue(':id', $id);
$stat... |
Use case: We have a simple two tables plus a link table setup using some modern RDBMS.
For example:
Hospital table (id, name, ...)
Physician table (id, name, ...)
Visiting_Privilege table (hospital_id, physician_id, ...)
Our goal is to find records that are "missing" (absent) from the link table.
Using our example: L... |
I have written a SQL query against the Stack Exchange Data Explorer that identifies answered questions with a positive score for which all the answers have a negative score (this was an answer to this Meta Stack Exchange post, though the code in that post is different from what I've posted below).
It's a fairly straig... |
I wrote up a quick API to help me save time while writing applications that require either a delay or frame rate. It should require me to implement a void run() method, which may or may not be annotated with the @Loop I created. If it doesn't contain the annotation, it will simply call the run() method once. If it is a... |
I have here a class which represents a directed acyclic graph (Graph) and a vertex in the graph (Vertex). The vertices are stored in an adjacency list. It has the ability to find a vertex's indegree, and to find a topological sort order. The graph does not own the vertices.
I'm particularly interested in comments regar... |
I'm using JQVMap, and I have my code to where depending on what state you click, it'll reveal info about that state within a single div below the map. However, I feel there's a simplified, more efficient way to set up this code so there's not a lot of repeat, especially once I start adding more states. Is there?
switch... |
This is the first coding class I've taken and I'm not getting much feedback from the instructor. The function of this program is to take two roman numeral inputs, convert them to arabic, add them together, then convert the sum to roman numerals. I wanted to see if any of you code ninjas could give me some feedback on t... |
Here's Problem 5 - Smallest multiple
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?
How can I improve this code? How to make it faster? Is there a better/faste... |
Please check if this date filtering function is inefficient code. It seems so to me, but I can't figure out the other way around it.
function makeTime () {
/////////////////////////////////
//Create a filtered Time/////////
var timesStamp = new Date();
var time = timesStamp.toLocaleTimeString();
var... |
I have a function to handle image uploads. Originally, it contained a goto:
restartA:
$name = $this->random_name() . $ext;
if(file_exists($this->img_path . $name)){
unset($name);
goto restartA;
}
It seems pretty clear to me what the code does, and I think anyone who reads it would immediately understand what... |
I've just started delving into JavaFX, and the following is essentially my "Hello World". Although it's simple, I question the code formatting and wonder if I'm breaking any conventions, especially if explicitly concerning the library.
I also find myself concerned with what best promotes readability. Unfamiliarity brou... |
I have an app that user submit the log in form , when it sent the data to server app create a connection for its account.
In this connection i have an integer field named as state.
the state value is : 1 for connecting, 2 for connected and 0 for failed.
I show a dialog to user display Connecting ... and then check the... |
I am currently writing a TcpListener class where it begins a new socket and adds a new Session. I have classes called Session and SessionManager.
Session is where I establish a new SESSION, a new instance of the class. I have a new session for each player entering and connecting to a socket
SessionManager is where I ke... |
Control like if..else and while
If \$f\$ is a numerical function and \$n\$ is a positive integer, then we can form the \$n\$th repeated application of \$f\$, which is defined to be the function whose value at \$x\$ is \$f(f(...(f(x))...))\$. For example, if \$f\$ adds 1 to its argument, then the \$n\$th repeated appli... |
Having contributed to this Community Wiki on StackOverflow regarding validating user input, I thought I'd finally sit down and write something more robust to do these kinds of tasks. I wanted something that would allow detailed configuration of the acceptable inputs, but without a huge list of arguments or spaghetti of... |
My code is for a 10-faced dice-rolling game. There are 2 players who start off with 50 points, then they both roll a dice and get a random score between 1-10. The player with the highest roll gets the difference between the rolls deducted from their score (50 points), but the loser gets the difference between the rolls... |
I have made this small text-based RPG in C++ which is based around one quest. I did this to practice what I have learnt so far. How could I improve it? Be as picky as you'd like.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void riverstead();
void aragornHouse();
void stage1();
void ... |
The purpose of this code is to track player development on a Multi-User Dungeon I play. It allows saving multiple characters to the same database. It allows for updates on level, hour, tier, morts, months, years, weeks, and days.
Are there any improvements that could be made? Assume that any "missing" functions are fun... |
what could I do to make this code more beautiful?
exports.index = function (req, res, next) {
Booking.aggregate(
[{
'$group': {
'_id': '$booking.date',
'name': {
'$first': '$booking.name'
},
'participants': {
... |
I am trying to implement a Trie class in Java which just supports insertion and searching operation up until now. I think it works perfectly on the several examples I have tried but I am not able to come up with a tricky test case to check if it functions perfectly or not. Can you take a look at my implementation and s... |
I am writing an encryption program that will encrypt the message "STOP POLLUTION" with the encryption function f(p) = (3p + 7) mod 26 where p is given letter.
Here is my code for doing so (tested it works):
static final int SPACE = -33;
static int[] convert(String s) {
char[] array = s.toCharArray();
... |
I wrote a RomanNumeral class in C#. Please pull it to pieces:
class RomanNumeral
{
public RomanNumeral(string num)
{
AsRoman = num;
AsArabic = RomanNumeralToArabic(num);
if (AsArabic == -1)
{
throw new ArgumentException();
}
}
public RomanNumeral(in... |
Is this correct MYSQLI implementation?
IS it safe from injection?
IS the object cleanup done properly?
<?php
include_once '../../securelogin/db_connect.php';
include_once '../../securelogin/functions.php';
sec_session_start();
if (login_check($mysqli) == true)
{
$con = new mysqli("localhost", "username", "passwo... |
I recently started learning Java for a class and my teacher gave us an assignment in which we had to write up code which would print out the Pascal's triangle to an amount of rows decided by the user, and use recursion to do so. I believe that I'm done with the assignment, but wanted to know, for myself, as to how I co... |
I haven't done anything similar so I got nothing to go on. The point was to load everything from the file and I thought a struct would be a good choice to be the handler to store the information.
The loading part is, however, not really something that is to my satisfaction as I find it very primitive and illusive. I tr... |
I wrote this function that recursively traverses a given directory resolves
the relative file-names to absolute file-names and yields the resolved file-name if it matches a given pattern. You can specify a callback function as well.
The first issue I have with this function is that it is a bit hard to comprehend, I thi... |
I have a vote and a comment table. Now I want to display all comments and order them by votes-sum. Sum because some votes can have a higher value than others.
Therefore I want to display if the user has voted already on a comment. So I need to get that value too.
This is my actual query:
SELECT *, SUM(v.`value`) as vot... |
I'm wondering what can be done to optimize the following. I've tried to note the points at which most of the overhead is occurring. The main two points I see are
The call to DiffDays from within the LINQ query.
The ordering by DateTime LastOnline before putting results in memory.
Right now, with only 2000 rows, I'... |
With the ANTLR-powered parser, I was able to reimplement all code inspections from the last release build, and the rest of the inspections on the road map are now implementable.
Code inspections and quick-fixes are nice, but we want our Rubberduck even smarter than that. So I wrote one of the coolest things I've ever ... |
I need to parse the following input string into a hash table with the following format:
Input:
'1001=23;1001B=5;1002=0;1003=5;'
Output:
=> {'1001'=>23,'1001B'=>5,'1002'=>0,'1003'=>5}
My solution:
def parser input
output = {}
input.split(';').map {|ar| ar.split('=')}.each {|id, c| output[id]=c.to_i}
output
end
p... |
I need to create a database which stores details products, Manufactures,Suppliers. So initially I divided Products into categories and subcategories.
These are the tables I created.
Manufacturer, Category, Sub_Category, Products,
ProductSpecs, ProductAvailability, Supplier
Manufacturer table contains Brand Details (... |
def line_to(x: 0, y: 0, rect: nil)
unless rect.nil?
x, y, width, height = rect.x, rect.y, rect.width, rect.height
end
`#{@context}.lineTo(#{x}, #{y})`
end
def fill_rect(x: 0, y: 0, width: 0, height: 0, rect: nil)
unless rect.nil?
x, y, width, height = rect.x, rect.y, rect.width, rect.height
end
`... |
I want to find the lowest hop count from source to destination.
The challenge, in summary:
The first line contains the number of test cases T, 1 ≤ T ≤ 100000.
The next T lines each contains three integers A, B, and M. 1 ≤ A ≤ B ≤ 1012. 1 ≤ M ≤ 1012.
For each test case, print the number of multiples of M that are i... |
I've got an Excel file from which I have to read out data to an object to serialize. So far I came up with this solution, and I'm curious if there are any clearer solutions.
public myClassFromXsd excelToMyClassFromXsd(String excelFile)
{
Excel.Application excelApp = new Excel.Application(); ... |
I've decided to learn some more Haskell writing a Sudoku validator, the function checkSudoku outputs True if the Sudoku is valid and False if it is not. I did not write the checkSquares function because it would have been too hard. I am looking for any tip about Haskell and functional programming.
Some specific questi... |
Take a look at the following function:
std::vector<double> get_data(
std::vector<double> const &data,
double const t,
double const x)
{
std::vector<double> result(data.size(), 0.0);
double const
A = func(t, x),
B = func2(t, x);
std::transform(std::begin(data) + 1, std::end(data... |
I'm wondering how this code could be improved. I especially don't like the use of mutable Buffer but not sure what the best way to get it out cleanly.
def find(service: Service): Traversable[Long] = {
def loop(lastId: Option[Long])
(acc: mutable.Buffer[Long])
(quota: Int): Traversable[... |
I'm currently developing a new version of ExpressGenGen Using TDD. While I'm rewriting the new version of my Code Generator Generator.
I'm using its old version to generate code to be used by the new version.
This is how I'm creating new classes: when a new class is created,
it will generate a .cpp and .h file and the... |
I'm busy rewriting some from my spaghetti code into OOP classes. I'm still learning OOP and very new to the concept. From help from this answer from @EliasVanOotegemto on a previous question I've asked I have written the following class which sets up conditionals according to 4 values passed to it by a user and checkin... |
I'm currently enjoying this exercise I'm working on for fun: I wish to write optimized code for the searching of particular strings per line in a (very large) file, counting how many exist, and producing a text file with a count of said strings.
The data format is actually very consistent, so when I do my indexof() o... |
Challenge:
Print set intersections.
Specifications:
Your program should accept as its first argument a path to a filename.
Each line in the file is a test case.
Each test case contain two semicolon delimited sorted lists of numbers in ascending order, whose numbers are separated by a comma.
Print out the ascen... |
After a few pages reading Learning Python Hard Way, I've decided to try to make a simple cm-to-inch calculator. I am very excited about this achievement, and I want someone to check my code. It works well, but i just need someone to confirm everything is written well.
# cm to inch calculator
inch = 2.54 #centimeters
c... |
This is my first test at making a key event dispatcher. Some of the code is unnecessary if one is interested in separating lower and upper cases, however I want to treat them as the same. Hence my wonderfully named method keyToLowerCaseIfUpperCase(char c). I also want to lock the key if it has been pressed untill it is... |
I've started a little challenge on a website, and the first one was about counting different DNA letters. I've done it, but I found my method very brutal. I have a little experience, and I know that hard-coded information is not good. Any way to improve this code?
chaine = "AAAACCCGGT"
nA = 0
nT = 0
nG = 0
nC = 0
for... |
This produces recursive directory listings(it's intended to do other things, so there will be something else instead of echo, but it isn't important), yet it isn't very intuitive. How can I improve it?
#! /bin/bash
deploy ()
{
for file in $(ls $1); do
if [ ! -d "$2$file" ]; then
echo ${2}${file}... |
I'm not sure if anyone else has ever heard of Factman, or even where the name comes from, but my AP Computer Science teacher calls this project Factman, so that's what I'm going with.
Naming aside, the game is simple. Players take turns choosing from a list of numbers. They get the number added to their score, but th... |
One of the inspections we wanted to implement in Rubberduck for the next release, is one that finds all unassigned variables in a VBA project.
Implementing this inspection has been ...complicated (it's the most complex inspection in the Rubberduck code base so far). Here's the code:
public class VariableNotAssignedIns... |
I want to amalgamate these two functions into one, Any ideas?
function toggleVisibility() {
document.getElementById('regStart').style.visibility = 'hidden';
document.getElementById('regPage').style.visibility = 'visible';
document.getElementById('facebook').src = "/images/js project/Faceboo... |
This is a sequel to my previous question: Sieve of Sundaram for Project Euler 7: Python implementation slower than C++ and R
I am trying to implement the Sieve of Sundaram in various languages to solve Project Euler Problem #7.
I have written a solution in Haskell (to which I am still very new, but eager to learn) base... |
For my second project in CS2, I was given the following assignment:
Implement a new ADT called a bag with receipts.
The specification for the class of bag with receipts differs from a
typical bag in the text in the following ways:
The add() operation will return a unique integer receipt for each object inserted ... |
What could I improve in the following code? The goal is to test a function againts a table of input parameters and compare to some expected results with some tolerance (as there are random variables involved in the computations).
This is how I am doing it right now. Note that I cannot use any C++11 features.
void test(... |
I'm building an application that implements the A* algorithm to calculate a route between two rooms. I am trying to create a graph which the algorithm can operate on and I am not sure if this is the right way to do it.
Here's what I've done so far:
Vect2.java:
package myalgorithm;
public class Vect2 {
private int... |
Given a Dialogue Script for SDT (NSFW! Google at own risk), parse said dialogue script for validation with checkers. A dialogue script consists of a set of lines.
There's a special line, initial_settings, formatted like such:
initial_settings:{"variable1":numericvalue,"variable2":"stringvalue"}
The rest of the lines f... |
I have a model with a hierarchical structure like this:
Batch (root)
Groups (List of groups owned by the Batch)
Groupnames (Nameing of the Group in different Languages)
Tags (List of Tags owned by the Group)
Tagnames (Nameing of the Tag in different Languages)
Logs (List of L... |
I'm attempting to create a replacement shell for /bin/bash, that only permits commands defined by a read only config file. These commands will be run by absolute paths, and take no arguments. I'm not an experienced C programmer, so I kindly ask for your comments and feedback. I'm especially concerned with buffer overfl... |
In general, in Prestashop there are no functions to really have the final category (i.e. the one with highest level_depth) of a product based on id_product, so I extended the Product class and added this simple static method:
public static function get_product_category($id_product, $id_lang = null){
$lang = (!isset... |
I have only been coding C# for a short time and I can't say I'm an expert but I am rather enjoying it. I wondered if you could see any way I could improve my code.
using System;
using System.Net;
using System.Net.Sockets;
namespace Reality.Network
{
/// <summary>
/// Callback to be invoked upon accepting a new... |
I have this very simple method:
private boolean isTheParticipantTalking(ParticipantID participantId){
if(mCurrentParticipant != null) {
return participantId.equals(mCurrentParticipant.getId());
}
return false; // no one is talking
}
I receive a warning stating that I can simplify the code in the fo... |
This program takes an arbitrary array of strings and group anagrams into arrays and return them in a array. Any string without any anagrams is still put in an array.
This code works perfectly and I would appreciate any comments on making this more efficient in terms of computation time.
import java.util.Arrays;
import ... |
This one is, or rather, should be, fairly simple. I have a list of tuples of XY positions, and am trying to pull out angles relative to the origin from it. However, unlike atan2 / friends, I want it to be continuous, in other words not wrapping. I know (and am assuming) that the differences between successive XY coordi... |
Can someone review my timer class that runs some code every second, please? The void it's calling (runCode) is just a void with some code in it.
using Reality.Game.Sessions;
using System;
using System.Threading;
namespace Reality.Game.Misc
{
public static class UserTimer
{
public static void Initialize... |
I am trying to get familiar with OOP JavaScript, in particular working with the prototype pattern and would love some pointers/suggestions on how to improve my code.
I think I have understood the basics well, and have been able create class instances successfully.
I am however, a little unsure on how to work with event... |
Does this make sense? How would you achieve the same thing, with cleaner code?
function retrieveBatch(offset){
var opts = {}
opts.limit = 100
if(offset) opts.offset = offset
return new Promise(function(resolve, reject) {
chargebee.subscription
.list(opts)
.request(function(err, value){
if(err)... |
I have a private function in PHP that takes a given URL string and just leave the Alpha or numeric and certain punctuation left. I need the stripping of string due to having it match against ElasticSearch and ElasticSearch doesn't take it too kindly for special characters when it comes to exact match.
The following fun... |
I have a simple web page where the user enters the name and rank of a soldier and hits submit. If the input is invalid, an appropriate error message gets displayed. Otherwise, it adds the soldier to a database and adds it to a list of current Soldiers via AJAX request.
//Find elements on page
var rankField = $("input[n... |
I am learning C++ and SFML so I want to know if I am laying my code out neatly and if my code is efficient. I know this is not a full game yet but I want to know if I am on the right tracks.
#include <SFML/Graphics.hpp>
#include "ResourcePath.hpp"
#include <iostream>
class Paddel {
int speed = 3;
sf::Vector2f... |
I am writing this smart pointer as a learning exercise. Any feedback would be most appreciated.
Any flaws? Have I missed any test cases?
smart_pointer.hpp:
#ifndef SMARTPOINTER_HPP_
#define SMARTPOINTER_HPP_
#include <iostream>
template<typename T>
class sp {
public:
sp(T* ptr) : ptr_(ptr), ref_cnt_(new unsigned(... |
The following code is for a calculator made in ruby, I find that this way saves much time than having to build this calculator from scratch, especially that I want it to support BEMDAS operations. However, I'm feeling that it is inefficient because I'm using eval, and I think this could be dangerous.
Is it a good idea ... |
I'm a senior Comp. Sci. major working on a senior design project for our faculty. The name of this project is "Gradebook", and it is responsible for allowing instructors to record grades for students and for students to check their grades in a class. This project is written in Ruby on Rails, and this feature set is int... |
I recently got a Scala developer position, so I'd like to get more comfortable with Scala on my own. Here is a maze solver that I wrote (previously in other languages) that I translated to Scala. Any tips or suggestions on coding style is greatly appreciated.
Ideone
import scala.collection.immutable.Queue
object MazeS... |
Trabb Pardo and Knuth devised this simple procedure as a way to explore the functionality of various languages. The wiki page describes it as:
The Trabb Pardo–Knuth algorithm is a program introduced by Donald Knuth and Luis Trabb Pardo to illustrate the evolution of computer programming languages.
The algorithm is si... |
We were discussing Standard Deviations in chat, so I decided to write a standard deviation calculator:
static double PopulationStandardDeviation(List<double> numberSet)
{
double mean = numberSet.Average();
return Math.Sqrt(numberSet.Sum(x => Math.Pow(x - mean, 2)) / numberSet.Count);
}
static double SampleSta... |
I needed a simple way to add this test to certain click events:
if isUser then fireClickEvent else openSignInModal
So I made this directive:
angular.module 'openLETS.core.lib.guestLock', []
.directive 'authGuestLock', ($compile, $state, olString, Auth) ->
######### Private #########
restrict = 'A'
priority = 1
... |
Here's an implementation of Hangman that I've written that uses a basic GUI. As I am new to Java, please let me know of any improvements I can make to my coding style. Thanks for your help.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
... |
When I run this function for outputting an inverted index to a text file in Debug Configuration, it takes nearly two minutes (96 seconds) with a comparatively tiny dataset, 1252 records with the longest being 76 entries.
std::ostream& operator<<(std::ostream& out_stream, const InvertedIndex& rhs) {
std::ostringstre... |
This is a bit tricky to explain. I'm trying to model a cyclic iterator that would return the next available DataSource(SQL). So infinite calls would just pick the next source nicely. The new twist comes with the idea that one DataSource might be 'busy' or somewhat. That is abstracted as a 'waiting' datasource. This des... |
I'm just looking for some feedback on my User class. The class is designed to handle users being able to register, login, and logout of the site. I'll be using it in conjunction with a forum I'm also working on.
I'm mostly curious how I've handled validation of input, MySQLi interactivity, and whether my code is redund... |
I'm in the process of a complete re-write of a stagnant and ill-conceived project. I would like some feedback on the following Python 2.7-3.4 code, before I go any deeper into it.
I would hope it is self-explanatory, but that is always the illusion when you stare at something long enough. The other dilemma is glossing ... |
I'm new to PDO and haven't been coding in a while. Is the following custom session handler industry-acceptable?
class Session {
protected $sdb;
function __construct() {
session_set_save_handler(array($this, '_open'), array($this, '_close'), array($this, '_read'), array($this, '_write'), array($this, '_... |
This is a script that utilizes lazy exception throwing. What I do is decorate a function that might throw an exception to throw an exception with a formatted string.
from functools import wraps
def on_fail(message):
def on_fail_dec(func):
@wraps(func)
def on_fail_wrapper(*args, **kw):
... |
I've been fiddling with Unity, trying to make nice walking/running animations. So, i found the Stealth tutorial and I used pretty much the same animator as the AI, only I only use Speed and AngularSpeed and, of course, added a control script. The controls work as intended but the whole script is laggy. I know, my Updat... |
Given a limit \$n\$, find all the pairs of values less than, or equal to n, which have the the property:
pair(a,b)
where a = sum of divisors of b
and b = sum of divisors of a
I need to speed up my double for-loop but I don't see how to do it in this case.
def diviseurs_propres(n):
t = [1]
for i in range(2... |
I'm working on website with a parallax effect. The jQuery code is working, but I wonder if there could be made any improvements made to the code. At the moment it works totally smooth in Firefox, but in other browsers it seems to be a little bit jumpy. Also, the effect is not working in IE 9.
(function($) {
var $con... |
The following is code on "prime factors of a number". Any suggestions to optimize the code? It runs for a pretty long time for inputs like 35068499. I also want the code to take 10 digit numbers as input.
#include<stdio.h>
void pf(long);
void main()
{
printf("Enter a number: ");
scanf("%ld",&n);
pf(n);
}
vo... |
This code works, as far as I can tell, but there's something that just feels wrong about it. The intended flow is like this:
If no dialog is showing
Show dialog, return result
else
Move dialog into view, return no result
It sounds easy enough, but because there's a possiblity of multiple threads I have to use loc... |
I want to map values of a enum to some other values. For instance, here I map Color to Group:
enum class Color {
Red, Green, Blue, Cyan, Magenta, Yellow, White, Black
};
enum class Group {
Primary, Secondary, Neutral
};
One particular interesting case is to map enum to a string (serialize), but I'm interested in t... |
I wrote a Perl script to implement a simple menu where you can call subroutines for each menu option. I created a Menu class that can be used to create new menus and a print method that will start the menu.
Is there any way I could simplify this?
# Menu.pm
#!/usr/bin/perl
package Menu;
use strict;
use warnings;
# ... |
I have recently started using browserify and have created a custom module to toggle two menus based on the ID clicked and apply a transparent overlay effect behind the menu. I have got it working but just wanted to get some feedback on weather it can improved performance or coding wise as I am wanting to improve my JS ... |
I need to be able to accept some options from either the command-line or a config-file.
This code is a snippet of the class that I am working on, I cannot post the entire class here. This code works, but I am wondering if it can be made better. I will need to have a class here, there is a lot more work that goes on in ... |
As a Java programmer who's trying his hand at C++, I thought I'd start building a library for working with matrices as my first C++ project. I've got very little C++ experience and it's been a long time since I've even so much as dabbled in it.
So far I've only implemented an addition function, but I think this should ... |
I'm new to Python and wondering what can be improved with the following super novice program - in terms of the solution and code style etc.
test_fizzbuzz.py
import unittest
import fizzbuzz
class TestFizzbuzzFunctions(unittest.TestCase):
def test_it_converts_multiples_of_three_to_fizz(self):
self.assertEq... |
I was looking for a way to perform additional tests before waiting for an event:
if everything_is_alright():
event.wait()
But this is not thread-safe. A correct version would be:
with lock:
wait = everything_is_alright() and not even.is_set()
if wait:
event.wait()
The problem is that the lock have to be a... |
This is not the latest question in iterative code review of this program. You can find the latest answer here.
Here's my solution to Project Euler #54. Click the link for the full project description (abbreviated here):
The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the fi... |
There are many ways to shuffle lists; for example, Racket's built-in shuffle assigns each list element with a random number as a sort key, then sorts the list, which provides an O(n log n) runtime. However, I'd like something that's O(n), and that's where Fisher-Yates comes in.
Fisher-Yates is designed for use with ran... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.