instruction stringlengths 71 95.1k |
|---|
I have a question about lock upgrading.Specifically what bothers me is between readlock.unlock() and following writelock.lock()...
I am providing a nearly complete implementation for a sample cache.I just omitted actual loading of cached data from database.
I appreciate if you can review the code and share your thoug... |
I'm working on my way to write most efficient, reusable and robust code, and this is why I'd like to receive some support. I've written a datetimepicker script that allows datetime chosing, and a shortcut button that will subtract from higher date (the right input) a variable number of minutes:
Is there a way to simpli... |
I am trying to compose an illustrative example which shows how to implement move semantics on an object that will be stored in a vector.
Please consider the following code, which is my illustrative example so far. It is designed to be a canonical, pedantically correct implementation of an object that implements move se... |
I took a base from here and built on it. You call the function with onkeypress (hence live changing).
The function gives output like this for domestic numbers:
(123) 456–7890
When the numbers pass the above character limit (13), the function outputs international numbers like this:
+12 (345) 678-9012
It doesn't han... |
Recently me and colleague had a discussion about the following piece of code (simple bool function that checks if string is a number, +1000 not allowed, -1000, 1234 ... allowed).
He felt that it was hackish, while I thought it was nice, clean and elegant (since it uses STL, not hand made loops).
So is this a judgemen... |
I am new to MVC and Zend, so I have little idea what I am doing at the moment, but here is my question.
The following code is my get method for an API I am attempting to build in order to learn both. It works as is, but given the sparsity of code I have seen in example methods, and the fact that Zend seems to do a lot ... |
I have a working script that I wrote in Python which for e-mail messages that consist only of a plain text part + an HTML part, discards the HTML and keeps only the plain text part.
The script is not exactly elegant and, as can be seen from the code, it smells like it is C (in particular, I simulate the use of bitmasks... |
For reasons unknown I've recently taken up generating word squares, or more accurately double word squares. Below you can see my implementation in Python, in about 40 lines. The code uses this word list. It takes around 10ms for dim=2 (2x2 word squares) and around 13 seconds for dim=3 (3x3 squares). For dim=4 it explod... |
After becoming interested in various bits of functional programming provided by non-functional languages, I've recently decided to start learning Haskell. As I'm fairly experienced with conventional imperative programming languages, I decided to make my "hello world" something a little more complex - an implementatio... |
I think I have correctly implemented Powerset in Clojure.
(use '(clojure set))
(defn powerset [input result]
(if (nil? (first input))
(concat result #{})
(set (reduce concat
(for [x input]
(let [set-of-x #{x}
input-no-x (set (remove set-of-x input))
... |
I'm training a bit with C, and I'm trying to build a bit array. I would like to have some comments about my code, because I'm not sure that it's the best way to do it.
// BAL.c
#include <assert.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include "BAL.h"
#define BAL_Mask(n) (1 << ((n) % CHAR_BI... |
How can I improve my remove function? Could someone also give me a solid explanation of the free() function?
Here is my remove function:
void removeData(void *data, struct accList *theList)
{
if(theList->head == NULL) //nothing can be deleted
return;
else if(theList->head == theList->tail) ... |
I've seen plenty of examples and questions on how to do this, but the issue is that they all rely on a massive database on the server-side. I figured I could try to move that to the client-side. Here's what I have:
(function() {
var data, pos, read, write, fcnt, tcnt, i, forums, threads, l, fid, id, t, allunread, post;... |
I wanted a timer, rather like the Visual Basic object, and I wanted it with no cumulative error. And I wanted it flexible, so I wouldn't have to write another one. I'm very lazy BTW, so lazy that I will go to great lengths to avoid having to write something a second time. Actually, this fits quite well with the "write ... |
I am very new to Java and programming theory and am desperately trying to improve my knowledge. This is the first program I've made without help and really would appreciate some feedback. I know there must be 1,000,000 better ways to do what I did.
Notes:
I want to move away from main() programming. How could I achiev... |
So this is my code and I would like to add subtraction, multiplication and division. If you have any suggestions on algorithms to use I would be very happy to see it. I do not wish to copy the code, I just want an outline of how to simply, and efficiently create a calculator. I want to make a calculator for KIDS with a... |
I've created a simple Javascript library to be able to create "classes" and extend them defining instance and static methods and variables.
It consists in a simple function Class with two methods: create and extend.
var Class = function(){};
Class.extend = function(obj){
var Extended = function(){};
for(var ... |
For the following C linked list implementation, please give me some suggestions for improved efficiency, style and design. This implementation is not 100% complete, please give some suggestions for additional features. Notice the data type for the list is void*, I want it to be as generic as possible.
accList.h:
#ifnde... |
Everything in this code is completely working, but I still feel that this code needs to be refactored. any suggestions?
<?php
class Db_CheckUsername{
protected $_conn;
protected $_username;
protected $_minimumChars = 8;
protected $_errors = array();
public function __constr... |
My code here is completely working, but I feel like I destroyed or didn't follow the DRY rule, what suggestions can you give to me for this code??
<?php require_once("./includes/Utilities.php") ;?>
<?php require_once("./includes/Db_Resources/db_connection.php");?>
<?php require_once("./includes/Db/DatabaseUtilities.php... |
I created an XML wrapper to easily access XML data.
Please tell me what do you think about it.
Performance
Scalability
Anything else...
This is how you use it:
var xml = new Xml(dataString);
xml.load("UserEmail");
alert(xml.length + ", " + xml.getValueAt(0)); // Out: 2, jchen@contoso.com
XML source file:
<Users>
... |
I wanted to learn how to work with file I/O properly and found an assignment in my college papers and decided to write it:
//Write a C program which reads data about books and inputs them into a file named books.txt, like this:
//
//book_name#author_name#page_num#code#is_lent#
//
//book_name is an array of a maximum of... |
I'm a little frustrated with the state of url parsing in python, although I sympathize with the challenges. Today I just needed a tool to join path parts and normalize slashes without accidentally losing other parts of the URL, so I wrote this:
from urlparse import urlsplit, urlunsplit
def url_path_join(*parts):
"... |
In the world of casinos, there are different types of games and jackpots. In this example, there are normal jackpots, multi-casino jackpots. I have a separate model for each of these. I need to display these in-line with each other. For instance, I'm grabbing the top 10 Caribbean Stud jackpots (Model: Jackpot), then di... |
Here's something I tried putting together as I'm learning. Critiques on anything are welcome. There's also a logic bug in the Plane module I can't identify.
The long and the short are that it takes the URI "some float/some float/some float/some float", and makes the first 2 (x,y) coord where something is, and the sec... |
My CSS feels dirty and I have no idea how to improve it.
Suggestions are greatly appreciated!
html, body { border:0; margin:0; padding:0; }
body { font: normal 12px helvetica,sans-serif; }
.header {
background-color:#242424;
height:40px; }
.header h1, h2 { text-transform:uppercase; }
.header h1 {
color:#F... |
The code works, but I guess it could be much better.
/*
DESCRIPTION
The strncpy() function is similar, except that at most n bytes of src
are copied. Warning: If there is no null byte among the first n bytes
of src, the string placed in dest will not be null-terminated.
NOTE
If the length of src is less than n, strncpy... |
I've been given the following PHP code:
if(empty($search)){
$_SESSION['keyword_exists'] = "no";
}else{
if(isset($_SESSION['old_keyword']) && $_SESSION['old_keyword'] != $search){
$_SESSION['keyword_exists'] = "no";
}
}
if(isset($_REQUEST['limitstart']) && $_REQUEST['limit... |
I've written a general purpose repeat function which allows you to repeat a callback function X times separated by I intervals with the option to start immediately or after the interval. It can also default to just looping infinitely, which is what setInterval does. Is there a better approach, or any improvements peopl... |
If you look at the condition of If calculated Then in the code below, this is what slowing down the code. While the code provided seem fast with Const initBit = 4 try it with something over 12. I want to be able to use this code (with calculated param as true) with initBit of 20 or more.
Beware that 20 or more might r... |
I thought to spent my free time by solving a puzzle: Best Before Spotify Puzzle.
I coded in Java, and yeah I did not clean up my code (just a rough work) and I have yet to optimize... so I did check for possible test cases (including leap year) and could not find any of these cases failing, but I got a reply from the b... |
This works, but nvl AND case seem redundant.
Basically, if null then 'N' else 'Y.
CHICKEN_HATCH_DATE is a DATE data type.
select stricken_chicken_id,
case nvl(to_char(chicken_hatch_date),'N')
when 'N' then 'N'
else 'Y'
end chicken_hatch_date
from stricken_c... |
I am creating a database class in PHP but I feel that there's something wrong with my code. Is there any suggestion to refactor this? I feel like there's something wrong and missing in this code.
<?php
require_once("db_constants.inc.php");
Class MySqli_Database
{
public $db;
public funct... |
I'm looking to see if my current evolution of ETL logic is getting in the ball park of "how it's done in the real world".
Specifically, do I use the metaphors correctly (Extract, Transform, Load)?
Is this code reasonably clear for another developer's consumption?
Is the OO nature clean or should it be decomposed mor... |
What I am trying to accomplish is to create an efficient thread-safe singleton base class (as stated in the title).
So this is my singleton class, which is used via inheritance (see below).
#pragma once
#ifndef SINGLETON_HEADER_INCLUDED
#define SINGLETON_HEADER_INCLUDED
#include <memory>
template <class T>
class singl... |
Could someone review my linked list code? Specificially, is the design to separate Node and actions to create linked list appropriate?
template <typename T>
class Node {
public:
Node() : next(0) { }
Node(T value) : val(value), next(0) { }
T val;
Node* next;
private:
Node(const Node& nd) { }
... |
I'm not used with perl but had the need to add a couple of features, I wish I can adopt a more perl-ish coding.
Any help is welcome.
This is to add style classes to paragraphs if strarting with !, ? and a clear: both with %
Original:
foreach (@grafs) {
unless (defined( $g_html_blocks{$_} )) {
$_ = _RunSpan... |
I'm trying to develop a base for a blog using some of the new tags introduced in HTML5 and I want to not only make sure I'm using them correctly, but my code is also semantic.
Here is just the 'sample' document.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title>pa... |
Is there a more elegant way of doing this? I really think this looks ugly.
private static string InsertMethodNameHere( bool hasCondition1, bool hasCondition, bool hasCondition3)
{
if (!hasCondition1 && !hasCondition2 && !hasCondition3)
return "0";
if (hasCondition1 &... |
I'm learning F# and have a couple of routines much of whose functionality looks common so I am looking to refactor them together.
Here are the routines (which for the record I lifted from elsewhere:
let Prices time ID (polling:float) =
let sync = System.Threading.SynchronizationContext.Current
let obs = new Event<... |
I have a form written in the usual way. After submitting, if there are errors in the form, the form page itself is the target of the redirect, with a query string appended. The query string contains the error messages, but also the values submitted with the form. The query string and its format are provided by a 3rd-pa... |
I just recently learned about Project Euler and have started doing the problems on there. I cleared problem 1 and 2, had no idea how to do 3 and 4, and started to do 5. I've seen the post regarding the quick mathematic solution, but I'd like to know if there are better ways to do it programmatically.
For those that don... |
Currently my below code takes an average 9.27300 every time I run it. This is an iOS application and I can't expect the user to sit there for roughly 10 seconds.
This code takes an array (originalData) of placeObjects and calculates the distance from the selected location (CLLocation* searched). It does by [searched di... |
I have been reading this thread on Stack Overflow about simulating enums in PHP and it seems that the most common approach is to use class constants. My problem with that is I can't use it for type hints, so I have added a static function that checks if a value is defined as one of the constants.
class DataType
{
c... |
I am looking to refactor the three lines of code in the else part of the conditional, you'll see where I have it commented.
You'll notice a naming convention for the id's: id, id-div, as seen in the first line: club-community-service, club-community-service-id
I want to shorten that up. I thought maybe storing all name... |
This function combines a Twitter feed and an Instagram feed and sorts the items by date. I just want to write better, more efficient code, so any tips on how to transform this into more of a "pro" JavaScript function would be much appreciated! Would it work to combine all these functions into one namespace?
The result ... |
I'm quite new to JavaScript, and I'm trying to understand the idea behind inheritance in JavaScript. I've read a bit about it, and I don't want to mess with prototypes (which I don't yet fully understand) so, I wrote this code using the xtend module for node.js.
var xtend = require("xtend");
// Human constructor.
// H... |
What are some advantages and disadvantages of providing default implementations for dependencies. I have chosen to do this because it allows the objects to be easily used in the application but also allows me to mock for unit testing.
public class RoleProvider : RoleProviderBase
{
private IRoleDataProvider _roleDat... |
This is continuation and implementation of feedback found in this post: Basic user registration code
I just began to use the PDO object, I'm not sure if i'm using it efficiently. Are there any security issues? Is the myEncrypt function suitable enough or still a bit lacking?
initialise.php:
try {
$db = new PDO("mys... |
So this question is prompted by two things.
I found some code in our source control doing this sort of things.
These SO questions:
https://stackoverflow.com/questions/297213/translate-an-index-into-an-excel-column-name
https://stackoverflow.com/questions/837155/fastest-function-to-generate-excel-column-letters-in-c... |
I wrote a script to scroll pages when menu buttons are clicked, similar effect like: http://css-tricks.com/examples/SmoothPageScroll
var m1 = document.getElementById('m1'),
m2 = document.getElementById('m2'),
m3 = document.getElementById('m3'),
m4 = document.getElementById('m4'),
m5 = document.getElemen... |
I am pretty new to Rails and in fact this is the first thing I have made. This is a todo list type app. My JS and Rails is a big mess. I have just kinda hacked it up to work. Please suggest better ways to do things. Styling suggestions are welcome too.
class UsersController < ApplicationController
def index
... |
Here is my progress calculator class. It is used for downloads/uploads. It takes bytes in and calculates the percentage(to the nearest 5%) that should show on a progress bar. Please let me know how I could improve it. Thanks a lot!!
public class ProgressCalculator {
private int totalAmount;
private int progres... |
I seem to have this tendency to write custom methods, i.e. code that isn't reusable. The following seems to be one example of trying to do too much in a single method.
But the point I'm not sure about is, in order to split it up, I'd have to redo the for loop each time. Is that acceptable?
Any general pointers on how ... |
I'm wondering about the difference between these two linq statements
bool overlap = GetMyListA().Intersect(GetMyListB()).Any(); // 1.
vs
bool overlap = GetMyListA().Any(i => GetMyListB().Contains(i)); // 2.
Will statement 2. call GetMyListB() for each item in ListA?
Which is more readable?
|
I want to simplify this C code into different functions:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
// Declare functions
void parseSystemProperties(char *xmlFileName);
void parseSystemModules(xmlDocPtr doc, xmlNodePtr cur);
void parseSystemConfig... |
I find my self often doing things like this in Ruby on Rails:
@count = 0
LineItem.all.each do |item|
if (item.cart_id == @cart.id)
@count += item.quantity
end
end
So many things look wrong with this, but I want to initialize my variable (@count) before the loop, and then be able to use it after I'm o... |
Any suggestions to improve the performance of the following code? This code is exceeding the time limit for the last four cases. This is a solution to the problem https://www.interviewstreet.com/challenges/dashboard/#problem/4fcf919f11817
def main():
N = int(raw_input())
if(0<=N<=100000):
x = []
... |
Is this an acceptable use of typedef in the class, Inventory?
Inventory.h
#ifndef INVENTORY_H
#define INVENTORY_H
#include "Item.h"
#include <unordered_map>
class Inventory
{
public:
typedef std::unordered_map<Item, int> ItemTable; ///< Items and their quantities
const ItemTable& items() const;
void add_... |
In C++ (and C++11), classes defining a + and += operators often define a - and -= operators that do nearly the same thing (except + is replaced with - in the function).
What is the best way to avoid duplicated code here (and still achieve good performance)? I am sure there is a good way to do it with functors:
Here's ... |
i had made a small code snippet for multiple inheritance in js. this code is working for me but actually i like to get the review, that its good and if any problem; provide the solution. etc. the code snippet is below.
/**
* WebbaseUtility provide the bundle of utilities used for support the webbase
* functionalities... |
I had code that violated the Single Responsibility Principle in a question on Stack Overflow.
In order to overcome that problem, I changed the code as follows.
Is this a good practice in order to overcome the problem?
Is this a pattern?
Is there a better way?
Does it satisfy the Unit Of Work pattern using LINQ-to-SQL... |
I have written an algorithm in C#. It is recursive, but it is not optimal. Maybe you have suggestions for improvement? (I already posted this question on stackoverflow but the question was closed there).
This is the exercise (I made it up myself). There are 3 or more buckets and there are 4 or more balls. The goal is t... |
I wrote the following code for printing all the paths to the leaf nodes in a tree (NOT a binary tree ) without using recursion. I have used a stack and performed dfs on the tree. Whenever I reach a leaf node I pop all the elements in the stack right till the root so that the function starts over again from the root and... |
This was for an assignment. I had to write a function to compare two roman numerals. This had to return true only if the second number was larger than the first and had to be done without converting the letters into integers. Also prefix subtraction didn't apply so all the letters came in descending order.
Here is what... |
I'm looking to bullet-proof this method. Specifically, I never want an item to be left without calling the following:
MailMethods.UpdateMessageState(item.Mail_ID, 2, ex.Message);
The Method
private static void SendMail(MailItemViewModel item)
{
var r = new MailItemRepository(); // Repository
var ... |
Can someone critique this Java code?
package javaapplication;
import java.util.Date;
import java.lang.Long;
interface infix_operator {
public int apply(int x, int y);
}
class f implements infix_operator {
public int apply(int x, int y) {
return x + (2 * y);
}
}
class g implements infix_operato... |
In my project, I have this kind of code to test my controllers:
#encoding=utf-8
require 'spec_helper'
describe ProjectsController do
let!(:project) { build_stubbed(:project, user: user) }
let(:user) { build_stubbed(:user) }
before(:each) { sign_in user }
describe "GET 'index'" do
it "render index templat... |
I'm working code sample here.
Note: Above only tested in Firefox 13.0.1, iPad (non-retina) and Chrome 20.0.x.
Here's the relevant code:
var $outside = $(document)
.add($('html'))
.add($(':not[' + data.target + ']'));
$outside.on('focusin.goober click.goober', function(e) {
if ($(e.target).closest(data.tar... |
I've previously posted this on Stack Overflow, and am considering submitting it to Boost for wider distribution, but thought perhaps it would be best to put it up here for peer review first, and see whether there are clear improvements that can be made first.
// infix_iterator.h
//
#if !defined(INFIX_ITERATOR_H_)
#def... |
I am refactoring my controllers, trying to improve the way common data is loaded for the actions. Initially, I was using before_filter methods to do this but read that helper methods were preferred.
class CategoriesController < ApplicationController
before_filter :authenticate_user!
helper_method :category, :categ... |
The following search script creates a JSON response for an autocomplete field. The tables and fields search from are flexible to allow using the same script for different type of searches - the idea is to search from each database field separately and see how often a term appears and sort them in descending order.
The ... |
I was solving problem 18 and 67 on Project Euler and came up with an algorithm that actually goes through almost all the possibilities to find the answer in O(n) time. However, ProjecEuler claims that a Brute force solution will take too long.
Many have implemented this problem using trees, dp and what not.
Is my app... |
I recently got serious about learning Haskell and upon finishing chapter 4 in Real World Haskell, I decided to try out my accumulated knowledge on a project of my own.
This code hosted on github is a Kalaha solver. It's just one file of code and I've included information about the game and the rules in the README.
Whil... |
As with my other question this is regarding my Kalaha solver.
Currently the way I find out the optimal progression of moves is with a command like this:
snd $ head $ reverse $ sortByMostInStore $ pickAllPaths $ generatePotList 4
The snd is there to just get the list of moves from the ([Pot], [Int]) pair and the revers... |
Assume I have an article list, each with the following format:
Article
In the header I'm placing: the article's title, the author and the image,
the paragraph belongs to the section, in the footer all the bottom elements (share, read more).
This is my html5 article code:
<h1>HTML5 Website</h1>
<div id="content">
<a... |
So I have a customers site I am remaking into an mvc3 app and they have an existing JavaScript pricing calculator. Is this safe and efficient? I am no JavaScript guy, but it looks pretty solid to me.
<script type="text/javascript">
window.onload = function () {
//Carpet
var ppf = .25; //price ... |
I just started to program Python. As my first application I implemented an interactive console which automatically python modules before a new code block is evaluated. Here is the code:
### module "module_reloading_console.py"
import sys
import code
import imp
import readline
import os
class ModuleReloadingConsole(cod... |
The below sections of code are part of a list administration project I am working on to teach myself C#. This is from a tab that is used for list administration. There is a drop down box that allows selection of list administrators, which populates a dropdown box with available lists.
Once a list is selected, it popula... |
I'm using this PHP to modify A elements in a DOM fragment (a vBulletin $post['message'] if that matters) so that links to external sites always open new tabs. This is actually the default in vBulletin but it's not always reliable. Anyway, the code works, but looking at the loop makes me think it could be done better. A... |
I am trying to solve a puzzle. I came up with a few classes to represent results. They looked similar, so I defined a common Result class. But what if I need to define different results according to different functions?
In other words, do I need TypeOneResult and TypeTwoResult or only CommonResult?
If I get rid of the... |
Is this the best way of doing this.
The sample code is a simple lookup of postnr (read zipcode).
I'm trying to encapsulate all the client side logic inside one "class".
Is this the way of doing callbacks? The this/that stuff sort of creeps me out a little
Should the constructor just be a place where you declare variab... |
I have to display all the numbers between 200 and 600 (both numbers inclusive) that are divisible by 8:
for($i=200;$i<=600;$i++)
{
if($i%8==0)
echo $i.',';
}
It reaches maximum execution time.
|
I am trying to learn to format XSL more efficiently. I can tell by the definition of duplicate variables and nearly identical templates that I did not create this efficiently at all. How could I have formed this better?
Here is my XSL: you can see all of it at http://wwwstage.samford.edu/calendar/ADCCancel.xsl
<?xml ... |
I have used the following code for a stack implementation. The top keeps track of the topmost node of the stack. Now since top is a data member of the node function, each node created will have a top member, which ideally we wouldn't want.
Is this good approach to coding?
Will making top as static make it a better cod... |
I'd like to know how to optimize this by shadowing symbols 'lo and 'hi inside nested function f. I guess CPS conversion would solve this but how?
;; chess engine - early development
;; Alist: (cons 'piece xy-coordinates)
(define whites) (define blacks)
(begin
(define setup
(let ([lo `(p0 p1 p2 p3 p4 p5 p6 p7)]
... |
Please review the two code snippets below and let me know if the second snippet is better than the first one.
In code snippet 2 I have added an inline function. According to my peers, using inline functions can help improve performance, since context switch will occur less often.
But I am not able to verify this claim... |
I am quite new to ASP.net and am currently trying to implement my data access layers of my application. I have so far implemented a generic repository pattern as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Entity;
using PayPlate.Models;
using System.L... |
I'm curious what people think about this little bit of logging code. It seems to work ok. Is there anything I'm missing?
public static class Logger
{
private static readonly object Locker = new object();
private static readonly StreamWriter Writer =
new StreamWriter("c:\\temp\\logtest... |
I thought about the best way to implement localisation with runtime in Swing.
I currently solve the problem like that:
JMenu menuData = new JMenu("Data");
menuData.setName("mainframe.menu.data"); // property key
localeChangedListener.add(menuData);
The LocaleChangedListener:
public class SwingLocaleChangedLis... |
I am new to PHP so this is largely compiled from examples around the web. It seems to work fine. Are there any ways in which it can be improved upon? Is it secure?
<?php
mysql_connect("localhost", "myusername", "mypassword");
mysql_select_db("companyDB");
function user_login($username, $password)
{
ob... |
I have read about it at a few places and tried to write my own version. I would like to get it reviewed.
class Node {
private int value;
private Node left;
private Node right
// getters and setters
}
public class DeleteNodeBST {
Node parent = null;
boolean deleteNodeBST(Node node, int va... |
There is a function with bunch of a redundant lets and ←s inside a list monad.
example ∷ (Int, Int, Int, Int, Int)
example = head $ do
let list1 = [0,1]
e1 ← list1
let list2 = φ list1 e1
e2 ← list2
let list3 = φ list2 e2
e3 ← list3
let list4 = φ list3 e3
e4 ← list4
let list5 = φ list4 e4
e5 ← list5... |
Is this JavaScript code robust? It is for an interactive book about a card game. When the reader clicks on the checkbox, an answer is revealed and related text is highlighted. I need to get this right before I write more chapters.
JSBin
<!DOCTYPE html>
<html>
<head> <title>Quiz</title>
<script>
function hl... |
Below are the bunch of functions which I wrote to determine paths between give coordinates of a square tile-based game. It permits paths between tiles in 4 directions (i.e. not 8 directions/diagonal paths).
It can be pretty resource-intensive when the path is long, especially if the target is unreachable (on large maps... |
I'm a few months into learning C++ programming and I want to know if I'm moving generally in the right direction or not with the following code. This is the most advanced thing I've created so far, but it doesn't contain any pointers or references so I'm worried I'm not doing things properly on the memory level. I espe... |
This code was posted as answer to Async file writer in .Net 3.5.
How would it be done better using Tasks or new features in .Net 4.5?
public sealed class Logger : IDisposable
{
private delegate void WriteMessage(string message);
private static readonly Logger Instance = new Logger();
private static object L... |
I'm building a typo correction program. This is the function, which compute the levenshtein distance between two words (a dictionnary word and an input word). I will call this function many times, so it should be fast. I'm looking for therefore some optimizations. I've seen some faster algorithms, but I don't know how ... |
This is my first go at genetic algorithms, using PyGame for the visual representation. Is there a way to improve the speed of the code? Click to place a point, press ↑ to start looking for the shortest route, or press c to clear all.
import pygame, time, random
#Size of next generation, change number at the end if ne... |
Doing graphics in Java, I find myself writing lines like these regularly:
Vector3f b = mid.add( a.mult(yOffset + length / 2) ).add( up.cross(a).mult(xOffset) );
It gets even worse when I'm reusing objects.
Vector3f vTemp = VarPool.getVector3f();
Vector3f b = VarPool.getVector3f();
b.set(mid).addMutable( a.multAndStor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.