instruction stringlengths 71 39k |
|---|
I have been playing around with tables and random colors to generate some mosaic.
As I find it rather slow, tell me how it can be improved in terms of speed.
function generate_mosaic(cols, rows) {
var i, ncol, trans, colspan, style, html;
html += "<table>";
for (i = 0; i < rows; i += 1) {
html += "... |
In our hg workflow we use default as testing branch and stable as the one that contains stable code. All changes are made in feature-branches that are started from latest stable. This hook checks if there is a "direct" commit to default or stable (they are denied, only merges may change contents of default and stable) ... |
There can be some errors in the script, if u find them thanks, but the main thing is to get useful suggestions about how can I do this better and secure.
ini_set('session.use_only_cookies', true);
session_start();
//Create a random salt value
$salt = 'Hjkhkjh9089&j98098';
$tokenstr = (str) date('W') . $salt;
//Create... |
I currently have this encoding function which simply subtracts one from each character code:
String.fromCharCode.apply(null, text.split("").map(function(v) {
return v.charCodeAt() - 1;
}));
E.g. test becomes sdrs.
I know that this function is silly because it isn't a strong encoding algorithm, but that's not my po... |
I came up with the following class that I can use as an XNA service to manage rendering to things other than the screen as I didn't want to be passing Games/GraphicsDevices around all over the place for testing reasons. I can't see anything wrong with it, but I'm curious what other people think about the design/etc. of... |
I hope this is not a really bad question for a first time here beginner.
This piece of code selects from the left table and will list the content in the right hand table. This is a working code but I would like to see how a professional would protect and make it faster.
Any suggestion (with some code) would be appreci... |
I'm attempting to implement a simple long-polling/comet/reverse AJAX solution, and came across the concept of delegates, specifically with the BeginInvoke and EndInvoke methods. I've built a Web Service that uses these concepts, but, having never used these, they make me a little nervous, and I have my doubts as to whe... |
I've been working on implementing a fast Huffman decoder for video decoding. With some help from you, I have been able to produce a decent implementation. However I am still not satisfied with the results. I have done some research both on Stack Overflow and some research papers, however I haven't found anything to fur... |
I am trying to create a new website, and i am using a class that has many functions on it.
First i want to say that my class has about 5000 rows , is this a problem ?
The main function i have used on my class is this one :
function f3($id = '') {
$id = mysql_real_escape_string ($id);
$sql = 'SELECT id,post_... |
I have written this PHP function which will flip an image (horizontally, like looking in a mirror). It reads the file, flips it, and writes it to a new filed called filename"_flipped".ext. I would like to refactor this to the smallest possible size, but maintaining human readability.
Here is the function:
function ... |
I have this code:
private void numWidth_ValueChanged(object sender, EventArgs e)
{
if (ignoreChange) return; // Sometimes I only want to change the value without the event firing (like when undo-ing)
PushUndoStack();
int width = (int)numWidth.Value;
foreach (Layer layer in doc.TileLayers)
lay... |
Example code:
<?php
class MyClass {
public $bar = array('a', 'b', 'c');
public function getBar() {return $this->bar;}
public function execute(array $fooArray) {
foreach ($fooArray as $foo) {
echo $foo.":".$this->checkBar($foo, $this->getBar())." ";// PASSED IN//
//echo $foo.... |
BudgetCode is in the format 'xxxx-yyyyy-zzzzz'. This splits it correctly but I think that there has to be a more efficient way.
Select
substring(pc.BudgetCode,1, CHARINDEX('-',pc.BudgetCode)-1) as Cost_Center,
substring(Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)),1, CHARIND... |
I have recently become annoyed enough with something about the linux command line experience to take action.
I welcome all comments, but specific things I'd like input on are:
Is there something already available that does this?
How would you do the same thing in Perl or Python?
How would you go about reducing code du... |
The following code is a quick implementation since I only needed 3 random images sorted by category (a random eyes image, a random nose image and a random mouth image and then combine them):
fileinfos = FileInfo.all().filter("category =", "eyes")
fileinfo = fileinfos[random.randint(0, fileinfos.count()-1)]
... |
I have been working on a maze generator in C++ in an effort to learn the language and brush up on some long lost knowledge. I want to ensure that I am using best practices, and really doing things the way that they should be done.
My code is safely tucked into a GitHub repository. I would like to have two specific cla... |
Often I find myself setting various fields in a Javabean and then passing that Javabean to some method.
customerEntity.setName("Foo");
customerEntity.setAge(45);
customerEntity.setAddress(address);
em.merge(customerEntity);
Or
requestPayload.setCustomerId(2343);
requestPayload.setCustomerPreference("green");
//lots ... |
I've written a linked-list version of something like shared_ptr, which gets destroyed when the last copy of a pointer is destroyed.
Aside from the thread-unsafety, is it a fine implementation? Anything I could improve?
Also, what's the best way to extend it to make it work with HANDLEs, etc., without repeating (or limi... |
I am trying to get a row if it has the desired specific value, otherwise get the first or default:
dr =
(from avTable in DAL.DataStore.DSet.Tables["Values1"].AsEnumerable()
join pavTable in DAL.DataStore.DSet.Tables["Values2"].AsEnumerable()
on avTable.Field<int>("PK") equals pavTable.Field<int>("FK_Valu... |
I have been making this FSM today. However, as this is probably the biggest practical program I have ever written in CL, I don't know if there are some things that could be improved, or if using a closure is the best thing here.
Any feedback is appreciated.
;;; States: -- EnterMineAndDigForNugget
;;; -- Quench... |
I am trying to learn graphs and implement in code. Can you please review my code and give me feedback?
Source code
#include <iostream>
using namespace std;
#include <list>
#include <queue>
#include <map>
Class Edge
class Edge
{
public:
int dest;
int weight;
Edge(int dest) : dest(dest), weight(0) {}
};
Class ... |
I'm drawing rectangular ROI region by darkening the area outside of it as in this image:
But image.MakeTransparent takes too much time. What is the best way to increase drawing speed?
void DrawRoi(Bitmap Image, RectangleF rect)
{
Rectangle roi = new Rectangle();
roi.X = (int)((float)Image.Width * rect... |
I started implementing a graph drawing application in javascript and < canvas > element, and i just wanted to hear your thought on the progress so far. I'm very open to suggestions and i'm very interested to hear what you have to say.
So you can see the progress so far in the present code, if you have any questions abo... |
I'm learning to implement linked list. I've implemented sorting with merge sort, reversing etc...
LinkedList.cpp
#include <iostream>
template <class T>
struct Node
{
T data;
Node * next;
};
template <class T>
class LinkedList
{
public:
LinkedList() : head(NULL), size(0) {};
~LinkedList() { destroyList(); };
... |
I have been solving a set of online Clojure problems. One of them involves the look and say sequence.
(defn look-and-say [s]
(let [las (loop [item (first s) coll s counts [] count 0]
(cond
(nil? (seq coll)) (conj counts count item)
(= item (first coll)) (recur item (rest coll) counts (inc co... |
I've written this small class in Python that wraps bound methods but does not prevent the deletion of self.
Do you have any thoughts on my code?
Do you think I handle errors appropriately?
Is it missing anything?
What should be done to make it more robust?
Is the documentation clear enough?
import weakref
class Wea... |
Implemented
Bubble Sort, Insertion Sort, Selection Sort,
Quick Sort, Merge Sort and
Radix Sort
https://code.google.com/p/medicine-cpp/source/browse/trunk/cpp/sorting/SortingAlgorithms.cpp
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void swap(std::vector<int> & data, int i, int j)
{
... |
I'm processing about 3.5gb/15minutes, and I was wondering if I could get this down to a better time...
Note that this is for a very specific CSV file, so I am not concerned about generality - only speed of implementation and optimization.
int main(int argc, char *argv[]) {
std::string filename;
std::cout << "P... |
I have to use a C++ member function in pthread_create. Also, the member function needs to be able to get the argument.
So, I have implemented a launcher function, which with help of a launcher object which stores the member function's address and the argument, will be able to do the desired.
Is there a better/elegant w... |
Are there any issues with below implementation?
Input: from STDIN, a list of strings
Output: serialize to a file called "out.txt" and then unserialize into a list of strings, and output to STDOUT
Goal is not here too much about code organization, but I would like to know if this code can fail for certain types of inp... |
I wrote a language in C, dubbed gecho. The code can be found here.
I'm writing this for a purely educational reason (not for school at all) and I just hope to make it Turing complete, and to improve the structure. The basic syntax is in the README. Let me know if you happen to do anything super cool with a gecho progra... |
I'm a beginning Scala programmer with a strong background in functional programming (ML, Haskell, Scheme) and I've just written my first Scala program. It is an implementation of a FSA (finite state automaton). Below is a simplified version that has 3 events/actions/labels (E0, E1, E2) and four states (S0, S1, S2, S3).... |
I'm trying to get a list of all artists on an iPhone / iPod touch music library. The best way I've found has been to group by artists (the convenience constructor on MPMediaQuery) and to iterate over the collections, being one for each artist. That way I've optimized out having to use an NSSet to ensure uniqueness in t... |
So I have some Javascript code that resembles the following:
var mylibrary = new (function ()
{
this._getLibraryObj = function ()
{
var newLibraryObj = {};
var libraryData = window.specifiedLibraryData;
// Add head librarian details
// open library
// etc. etc. turn into... |
For a site I wrote this JS contact parser. It simply reads contacts and parses links if a known service is identified. Could this be made more compact? How about robustness? (it cannot handle exceptions where the url does not begin with http for instance). What other services should I consider to add?
Here is jsfiddle.... |
I have an array of objects eg.
[
array(
'id' => 1,
'name' => "simon"
),
...
]
and I need to get an array of IDs eg.
[1,2,3,4,5];
Currently I'm doing this:
$entities = $this->works_order_model->get_assigned_entities($id);
$employee_ids = array();
foreach ($entities as $entity) {
array_pus... |
After I made a change to the html structure for a project, I found myself having to change many jquery selectors in many places. To avoid this problem in the future I decided to make a simple function where I pass an element indicating where I am and a string indicating where I want to go. This function should apply ... |
Is the code below safe from SQL injection?
<?
mysql_connect ("localhost", "db","pass") or die (mysql_error());
mysql_select_db ("db");
$term = mysql_real_escape_string($_POST['term']);
$sql = mysql_query("select * from tblListings where category like '%$term%' or title like '%$term%' or postcode like '%$term%' or i... |
I'm creating a dispatcher class - which is itself a long running task which can be cancelled at anytime by the user. This Task will poll the database to see if there is any work that needs to be done, and run up to X [5] # of child tasks.
As far as I can tell - it's working great, but I have a few questions/concerns a... |
I am developing a class library for processing credit cards. There is a thought in management in the short-term future to look for a new credit card processor. So I want to write once and use everywhere (I should be anyway, right?).
We are currently using First Data's Global Gateway Web Service API. I need a separate w... |
I was told that I might get some feed back about the code below. I'm learning and need some criticism.
My initial question was how to save users answers and tally them up to display number correct/wrong.
import random
import os
if __name__=='__main__':
books=['Genesis', 'Exodus', 'Leviticus', 'Numbers', 'Deuteron... |
I wanted to give Haskell a try, and I started with a simple exercise I found here.
Write isPrime :: Integer -> Bool, which determines whether a given
integer is prime.
Define primes :: [Integer], the list of all primes.
Revise isPrime so that it only tests divisibility by prime factors.
My answer to Q1
isPrime ::... |
Please review this:
#include <iostream>
using namespace std;
template <class T>
struct Node
{
T data;
Node * next;
Node(T data) : data(data), next(NULL) {}
};
template <class T>
class CircularLinkedList
{
public:
CircularLinkedList() : head(NULL) {}
~CircularLinkedList();
void addNode(T data);
void dele... |
Please, review the code:
#include <iostream>
using namespace std;
template <class T>
struct Node
{
Node(T data) : data(data), next(NULL), prev(NULL) {}
T data;
Node * next;
Node * prev;
};
template <class T>
class DoublyLinkedList
{
public:
DoublyLinkedList() : head(NULL), tail(NULL) {}
DoublyLinkedList(c... |
Please review this:
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
template <class T>
class Stack
{
public:
Stack() {}
void push(T x);
void pop();
T & top();
size_t size();
bool empty();
private:
std::vector<T> elems;
};
template <class T>
void Stack<T>::push(T x)
{
elem... |
There is a 1-to-many relationship between the posts table and the votes table, and they join on posts.id = votes.postid. I would like to know how many posts have 1, 2, 3, 5, etc. votes.
Thanks to Waffles' most controversial posts query, it was trivial to write this:
declare @VoteStats table (PostId int, up int)
set n... |
I'm volunteering some time to work on an open-data project, which I've started a repo out here for:
https://github.com/0xdeadcafe/Open-Hamilton/blob/master/whereare.js
The general idea is you'll paste in script tags the same way Google maps does to any third-party site to call the JavaScript.
I'm trying to prevent glob... |
I am trying to send mail via the mail() method, but I am doing it on my localhost, which does not appear to have a SMTP server running.
I think the code is fine, and the mail method itself is returning true, but could someone tell me if there is anything wrong with the use of the function before I put it onto my produ... |
I've written a class that makes writing singletons easy. The class is meant to be used as a decorator (example below). I'd like to see your thoughts about the code, the documentation, and everything else that you feel is worth noting.
class Singleton:
"""
Helper class meant to ease the creation of singletons. T... |
I have a lot of repeatable blocks of code and want to optimize/simplify them:
function animationInit() {
content = $('#content')
.bind('show',function(event, f) {
$(this).animate({right:0}, lag + 200, function() {
if (f) f();
});
})
.bind('hide',fu... |
I'm doing something quite strange. I'm trying to create a tiny system for creating templates inline in PHP, so that I can refactor by creating multiple templates in the original script, and eventually move the templates to separate scripts.
Here's the silly/basic template library that just calls an anonymous function ... |
I have a table that contains the UserAgent string and a Count of how many times its seen. The T-SQL below is used to give a breakdown of what browsers are seen and how often then are seen.
I'm looking for comments (good or bad) and suggestions (good only).
SELECT
Browser,
LEFT(Version, CHARINDEX('.', Version + '.', CH... |
I have a bit of code that came from Egg Head Cafe a long while ago and it's been working great. But I ran the entire site through Redgate's Profiler. and it came up as the biggest hot spot in my code. (Honestly it ran so hot the rest of my site hardly spiked.) The point of it is to capture traffic into my site and filt... |
My code keeps some int value about the date range, and there is a method to check if all of it is zero. Is there a better way to do it than doing this?
public bool IsAllDayZero
{
get
{
return
Today == 0 &&
Days1_2 == 0 &&
Days3_6 == 0 &&
Days7_10 == 0 &&
... |
Is this an efficient way to do this?
the code is designed to find the nearest friday, without passing Sunday. If it is already past Friday, the start date should equal now.
function get_weekend(){
$start = time();
$day = date('w',$now);
//find friday, without going past Sunday
while ($d... |
Any ideas?
public override string ToString() {
string returnValue;
if (!string.IsNullOrWhiteSpace(Country))
returnValue = string.Format("{0}", Country);
else
return returnValue;
if (!string.IsNullOrWhiteSpace(City))
returnValue += string.Format(", city {0}", City);
else
... |
I have the following code, which replaces " " <-- Spaces with "-" <-- Dash.
Because some of the title text will be returned with more spaces, it converts it into 3 dashes.
Examples of Possible Titles:
"Hello World From Jquery" <--- Notice 2 Spaces between the words, not 1
"Main Title - Sub-Title or description h... |
Even in the presence of <fstream>, there may be reason for using the <cstdio> file interface. I was wondering if wrapping a FILE* into a shared_ptr would be a useful construction, or if it has any dangerous pitfalls:
#include <cstdio>
#include <memory>
std::shared_ptr<std::FILE> make_file(const char * filename, const ... |
I have the following function:
from collections import Counter
import itertools
def combinationsWithMaximumCombinedIntervals(data, windowWidth, maximumCombinedIntervals):
for indices in itertools.combinations(range(len(data)),windowWidth):
previous = indices[0]
combinedIntervals = 0
for i... |
I've created a custom timer to satisfy the following requirements:
Millisecond accuracy
I want the tick event handler to only be called once the current tick handler has completed (much like the winforms timer)
I want exceptions on the main UI thread not to be swallowed up by the thread timer so this requires Invoke/S... |
Please provide positive and not-so-positive feedback on style, clarity, or any other additional feedback you would like to provide.
#ifndef MATRIX_H_
#define MATRIX_H_
#include <string>
struct Matrix_error
{
Matrix_error(std::string error)
{
m_error = error;
}
std::string m_error;
};
class Ma... |
$.fn.linkNestedCheckboxes = function () {
var childCheckboxes = $(this).find('input[type=checkbox] ~ ul li input[type=checkbox]');
childCheckboxes.change(function () {
var checked = $(this).attr('checked');
checked = checked || ($(this).closest('li').siblings('li').find('input:checked').length >... |
How can I rework the code up that ema(x, 5) returns the data now in emaout? I'm trying to enclose everything in one def.
Right now its in a for loop and a def.
x = [32.47, 32.70, 32.77, 33.11, 33.25, 33.23, 33.23, 33.0, 33.04, 33.21]
def ema(series, period, prevma):
smoothing = 2.0 / (period + 1.0) ... |
All colors can be represented by an int, and often you want to get the individual red, green and blue values from that int.
I have a method int2rgb (and another called rgb2int) that does this. Is this a clear/good name?
public static int[] int2rgb(final int color) {
return new int[] { (color >> 16) & 0xFF, (color >... |
i will give a list of urls, and want to make multi processes to fetch certain url's web content, and quit if all the urls are all fetched.
here is my implementation, and not sure if it's the right way to do the stuff:
#coding=utf8
import multiprocessing
from multiprocessing import JoinableQueue
import urllib2
import l... |
I've been looking for a solution to the ABA problem for a lock-free stack. Searching the Web revealed patented and complicated hazard pointers and tagged pointers using double compare-and-swap (DCAS, CAS2). I would settle for the DCAS, but it's not available on some older AMD CPUs. So I came up with this helper class:
... |
I am writing a wrapper around the GeUserArea class of Cinema 4D's Python API to enable creating user interfaces using an object orientated interface.
I've already written 2 prototypes, but I am not satisfied with my class-design.
They do work very well, but I decided to start over to make it even more efficient, more c... |
I know this is a lot of code, but I'm not looking for any kind of detailed review of the code. I'm just hoping some nice Javascript guru can give it a once over and offer any needed advice for using OOP in Javascript better than I am.
Here are a few areas of concern that I have, that don't quite seem like they're ide... |
This is a plugin for inserting content, which is for fallback for CSS generated content for IE
Please review and suggest optimization tips and or improvement of code. See the TODO in code and offer advice.
//jQuery plugin for generating content
(function( $ ){
$.fn.genContent = function($$options) {
//;;;_debug(this)... |
The encryption script:
import random
splitArray = []
def takeInput():
rawText = raw_input("Type something to be encrypted: \n")
password = raw_input("Please type a numerical password: \n")
encrypt(rawText, int(password))
def encrypt(rawText, password):
for c in rawText:
divide(c, password)
... |
How can I improve this?
#include "stdafx.h"
#include <iostream>
/*A program that accepts input of an employees' base salaries and years of service.
Then it also calculates their bonus based on the years of service.
- 20 or more years of service, bonus = salary * 0.1
- 10 or more years of service, bonus = salary * 0.... |
Can anyone check this code of mine for improvements? This was coded using Java with OOP concepts.
Game Class
import java.util.Random;
public class Game {
Player player = new Player();
Banker banker = new Banker();
private int a = 0;
private int b = 6;
private double myAmount = 0;
private... |
I wrote a search script, now I want a more efficient way of finding the keywords used for the search and make them bold. I used this code but it I feel it could be greatly improved on. Thanks for any suggestion.
// I use this code to select the lines to display
$lines = explode('.', trim($search_result));
// Break up ... |
I have classes representing gates (OR, XOR, AND etc) with the following method that is called whenever a property changes.
Here is the XORGate code:
public void computeOutput() {
if (this.input1 != null && this.input0 != null) {
if (this.input0.getValue() || this.input1.getValue()) {
... |
I have a small class of 2D drawing utilities, Draw2D which is the global entry point for anything related to drawing. Currently, the class looks like this:
struct Draw2D
{
std::shared_ptr<D2Label> CreateLabel (...);
std::shared_ptr<D2Plot> CreatePlot (...);
void Draw (D2Element& e);
std::vector<std::w... |
I recently wrote my first webapp and here is the code. I want to make it better, but I'm not exactly sure how. I believe the first place I should start is with the structure of it. Is this spaghetti code? If yes, how do I change that? You can view it at http://shiftfrog.com
I created a class called 'doer' that basical... |
I need to draw a lot of multi-line text to the screen so I first used DrawText but it was getting a bit slow... So I've been looking at a few alternatives: save the drawn text in memory DC's, use Direct3D/Direct2D, write my own function. I don't want my program to be a memory hog so using memory DC's wasn't too great. ... |
I'm developing a publishing engine and trying to find better ways to optimize the code. The end result is to have an open-source alternative to publish content on mobile devices.
For now, though, I have a touch-scroll-slide system I have created from a modified scroll system found elsewhere. There is a peculiar hesitat... |
As a personal habit I generally prefer to use string replace and format methods, along with string "patterns", in lieu of string concatenation and other methods in most languages I use (typically C# and Javascript).
For example, if I want to generate a URL with parameters (C#), I use:
string url = "page.aspx?id={id}&re... |
Well I just finished my first go at my own form validation (I always used validate plugin) for simple front end. It's definitely small potatoes as it's only meant for a form with 4 fields; 3 required text and one required e-mail.
I'm new to Jquery so I am doing little exercises like these to help me learn and I was h... |
The idea is to apply some function on each element in each list, then compare two lists by the value returned by the function.
My current solution works but is not fast enough. running "python -m cProfile" gives sth. like:
ncalls tottime percall cumtime percall filename:lineno(function)
2412505 13.335 0.0... |
I want to fill a DataSet with 20,0000 records using a SqlDataAdapter by using this code:
adapter.Fill(dataset);
If I fill a DataSet this way it takes a long time. Is there anything wrong with this?
This is my code:
connection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
connection.Open()... |
I've got a form, for which the "Send" button should only be available, upon each form field being validated. For most of my check, I call a function checkFormValue() which is a function gathering all the simple checks, give warning where check failed, and if at least one of the check fail, disable the button. The call ... |
I've implemented a polling function with a timer in C, that every 10s checks a given condition (I've just replaced it for a log to stdout for testing purposes only) but I would like to know your opinion on this code, namely if there is a simpler way to achieve the same result, what issues may arise concerning performan... |
I have these MySQL tables:
-- Create product table
CREATE TABLE `product` (
`product_id` int NOT NULL auto_increment,
`price` decimal(10,2) NOT NULL default '0.00',
`discounted_price` decimal(10,2) NOT NULL default '0.00',
`avail` enum('Y','N') NOT NULL default 'Y',
`... |
I used to mostly do this:
class Person
constructor : (@parent, @data)->
@index = @parent.length
class People
constructor : ->
people = []
for data in database.people
people.push new Person(people, data)
Lately I have been trying the following:
class Person
constructor : (@data)->
pushTo : ... |
package xml.impl;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
public class XMLCreator {
private String parent;
private String child;
private Integer ctr = 0;
private HashMap<Integer, String> xml;
private String root;
private HashMap<Integer, String> roots;
private StringBuild... |
This is a simple login script. Thought I'm not sure when it's appropriate to use includes over just embedding the code. I'm also not sure if I should make cookies, but I guess I don't really need to right now. Also looking at my code would it be easy to create a 'Remember Me' function?
<?php
$validUser;
$validPass;
$w... |
I'm using Winforms C# .NET 3.5. I'm getting frames, and this is how I handle them:
delegate void videoStream_NewFrameDelegate(object sender, NewFrameEventArgs eventArgs);
public void videoStream_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
if (ready)
{
if (this.InvokeRe... |
I have simple code that just has to check if a checkbox is checked and if so enable some fields that, by default, should be disabled.
I have written the next code which I know can be severely improved. Could anyone tell me how? I tried getting the siblings of the checkbox also but that just caused some trouble.
$(funct... |
How could I improve this algorithm? The goal is to organize matches between sport teams such that:
Each team affront each other
A minimum number of team should start a match after just finishing one
The interesting part is here:
myPerm [] _ = [[]]
myPerm xs threshold = [x:ys | x <- xs,
ys <- take ... |
This game is explained here.
Could this code be more efficient?
The Game Class
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
public class Game {
private Case[] cases = new Case[26];
private Player player = new Player();
private Banker banker = new Banker();
private int ... |
I need to read records from a flat file, where each 128 bytes constitutes a logical record. The calling module of this below reader does just the following.
while(iterator.hasNext()){
iterator.next();
//do Something
}
Means there will be a next() call after every hasNext() invocation.
Now here goes the read... |
I recently implemented a cache for a pet project of mine. The main objectives behind this implementation were:
Support move-only types for values: C++11 is here, and some of the objects that will be used with this template are movable but not copyable. Keys are fine with a copyable requirement because move-only keys m... |
I am making an Address Book like application .
I have a contactType enum.
public enum ContactType
{
//just a cut down version
MOBILE,PHONE,FAX,EMAIL;
}
Then I have a Contact class
public class Contact
{
private ContactType contactType;
private String value;//e.g phone number or email
private String are... |
Here is my standard .htaccess file, any suggestions on how I can improve it with regards to page load speed? Would gZip instead of DEFLATE make any sort of difference?
ExpiresActive On
RewriteEngine on
RewriteBase /
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterBy... |
I am trying to create a function similar to Excel's EOMONTH function in C#. I have written the following, however, I am not entirely sure if the it achieves the equivalent functionality. Is my equivalent of Excel's "Eomonth" function correct and are my tests sufficient?
public static DateTime EOMonth(this DateTime date... |
I have two text boxes and one combobox. I am retrieving the data based upon the text entered into the text boxes and combobox selection, by using the following method:
private void textboxfillnames()
{
if (txtlastname.Text != "")
{
var totalmembers = from tsgentity in eclipse.member... |
I am writing a JavaScript feature where by I need to make a call to a third-party library (pre-1.10 DataTables) depending upon whether or not the user provides an integer as an input to the function during initialization. I am pasting here the snippet. As you can see it has duplicate code in the if/else clauses, the on... |
I'm still fairly new with JavaScript, and wrote something to generate some social media links on my page. The idea was to have that script grab the necessary URL info and feed it to the social media APIs.
<script type="text/javascript">
// print links
titleElement = urlencode(document.title);
linkElement ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.