instruction stringlengths 71 71.9k |
|---|
As part of my project, a game, I have progress bars with countdown timers. These are updated every 250ms, to keep a relatively smooth animation if the countdown time is short.
Here's my function:
var time_format = function(time) {
var elms, names, ret, i, n;
elms = [
time / 29030400,
time / 2419... |
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
fib = (x) ->
return 0 if x == 0
return 1 if x == 1
return fib(x-1) + fib(x-2)
i = 2
fib_sum = 0
while (fib i) < 4000000
n = fib i
if n % 2 is 0 then fib_sum += fib i
i++
a... |
I am running through a file and inserting elements one by one. The counties all contain specific county codes which are duplicated many times throughout the file. I am looking for a way to assign these codes to a specific county while ignoring duplicate county codes.
I have two versions I wrote below with runtimes:
get... |
Goal:
Write a character creator program for a role-playing game. The player
should be given a pool of 30 points to spend on four attributes:
strength, health, wisdom, and dexterity. The player should be able to
spend points from the pool on any attribute and should also be able to
take points from an attribute... |
I'm generating a table to use on jQuery visualize plugin and generate a chart. The code is pretty good, but maybe there is a way to improve it. Maybe do more work on the LINQ query and less stuff on the rest of the code.
The idea is get every content and the launch date of them for each region. Separate all dates and t... |
I wrote a method that gathers data from an Oracle server, formats and encrypts the data then inserts it into a MS SQL server. The method moves about 60000 records and takes a bit long and is a little sloppy. Can anyone see places to clean it up and make it faster?
Two of the areas that I see might need improvements are... |
The model looks like this, with no attributes:
public class PersonalModel : Validatable
{
public string Name { get; set; }
public string Email { get; set; }
public override void Validate(dynamic item)
{
if (this.ValidatesPresenceOf(item.Name, "Name is required"))
{
if (((... |
Goal: Create a simple battleship game to test what I've learned so far.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void buff_clr(void)
{
char junk;
do{
junk=getchar();
}while(junk!='\n');
}
struct coord
{
int y;
int x;
}coords;
int randgen(int **ships_ptr,int n)
{
int i,... |
I was wondering if it's normal/efficient to have this many static collections in my state based game?
I started doing it for ease of access but it looks sloppy to me and I was just wondering what conventions other people use to maintain references to game objects?
public class DungeonDigger extends StateBasedGame {
... |
Model:
public class UserBean {
@JsonProperty
private String userId;
@JsonProperty
private int limit;
@JsonProperty
private int page;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
... |
Does this look right to you? What are its shortcomings? Strengths?
import Control.Monad
import Control.Monad.Trans.Class
import Control.Pipe.Common
import Data.Conduit
c2p :: (Resource m, Monad m) => Conduit a m b -> Pipe a b m ()
c2p = do
PreparedConduit push close <- lift $ runResourceT $ prepareConduit c
loop p... |
I am trying to solve a problem at Codechef. As I am new to programming, I am not familiar with dynamic programming. However, I do know the basics of recursion and memoization. Hence I implemented a solution to the above mentioned problem. The problem with my solution is that it exceeds the time limit given. As far as I... |
In this new project I'm working on I need to create objects on runtime by data from the DB, right now I have two groups of classes, each group implementing a different interface.
I started working on a factory class, which will map id to a type, an abstract one so I can extend with a factory for each group.
The constru... |
I want to write a regular expression to determine whether a given string is uppercase and sorted in non-descending order.
^A*B*C*D*E*F*G*H*I*J*K*L*M*N*O*P*Q*R*S*T*U*V*Q*X*Y*Z*$
I was just wondering if it is possible to improve the above regex.
Examples of correct strings:
AEHIIEFKLZ
Examples of wrong strings:
AbCDE... |
I'm running into an issue while playing around with some models in a Rails app. Namely issues of the polymorphic variety. I think I may have solved it, more or less looking for an approval.
I have the following models in my app:
class Issue < ActiveRecord::Base
belongs_to :creator, class_name: 'User', foreign_key: 'c... |
Puzzle Description:
A number is called lucky if the sum of its digits, as well as the sum
of the squares of its digits is a prime number. How many numbers
between A and B are lucky?
How can I improve performance of the following code?
import java.util.Scanner;
public class lucky_num {
public static void mai... |
I have written this piece of code to help the development of FileMaker developers having to use the dog-awful PHP API.
<?php
require_once ( 'fm_api/FileMaker.php' );
require_once ( 'config/config.php' );
/**
* Interface between the FileMaker API and PHP - Written by RichardC
*/
class FMDB {
/**
* Setting u... |
Deleting folders programmatically is extremely dangerous. It is enough for somebody else to change a configuration file or constant variable including the target folder's name to, say C:\, and that's it: the workstation is paralyzed!
The following suggested methods are to prevent such a situation. Their aim is to wrap ... |
The following method is designed to return true if it passes all of the rules for a password. Does anyone see a way to improve it? Performance improvements are welcome for sake of education.
I already know password rules beside length are counter-productive. It's not my choice. Also, I know that performance is absolu... |
I just finished chasing a Heisenbug that was entirely my fault. I'd like to avoid it happening again.
I have a function which formats a date to a certain preset format. Turns out I was not allocating enough space:
char* FormatDate(DT dateTime)
{
char* formattedDate;
formattedDate = (char*)malloc(
6 //That... |
This is my first attempt at a jQuery plugin. If someone could help me make sure that the code is clean, efficient, and formated correctly I would really appreciate it.
Background
So the reason I wrote this plugin is because I cannot find an easy to use code that has already been written. Plus, many people who work with... |
I was finding myself frequently calling getApplication() and casting it as MyApplication so that I could call a method in MyApplication. I decided to declare the static variable Current in MyApplication and set it in the constructor. Now I don't have to do the casting.
Are there any pitfalls to taking this approach?
... |
I'm fairly new to Python and currently building a small application to record loans of access cards to people in a company. I'm using wxPython for the GUI and SQLAlchemy for the CRUD. I'm loosely following Mike Driscoll's tutorial for a similar application but I want to add some extra things that he hasn't implemented ... |
I am relatively inexperienced with MySQL and have a query, which to my eyes appears relatively complex:
SELECT SQL_CALC_FOUND_ROWS
songsID, song_name, artist_band_name, author, song_artwork, song_file,
genre, song_description, uploaded_time, emotion, tempo,
user, happiness, instruments, similar_artists, pl... |
I been working on getting the SocketAsyncEventArgs to work the way I want it to work. Now I was wondering: is this going to work how it should work?
/// <summary>
/// The settings to use with this ServerSocket.
/// </summary>
ServerSocketSettings Settings;
/// <summary>
/// The buffer manager for allocation a buffer b... |
This is my first forray into Java Swing and it's not exactly pretty. I have quite a few methods, and a lot of stuff going on (XML parsing, data conversion, etc) and I'm just wondering what kind of general improvements / redundancies I can eliminate from my code.
test.xml:
<weeks>
<week>
<date>2012/01/23 00:... |
Here is my solution for Project Euler 35. (Find the number of circular primes below 1,000,000. Circular meaning all rotations of the digits are prime, i.e. 197, 719, 971.) The code takes about 30 minutes to run. Can you help me identify which parts of the algorithm are hogging up computation time?
I know there are many... |
It's simple. Person is a superclass. Student and Instructor are its subclasses. The program suppose to allow user create a student or an instructor.
Run
package com.exercise.inheritance1;
import java.util.Scanner;
import org.joda.time.LocalDate;
public class Run {
public static void main(String args[])
{
... |
I have the following code that gets the difference in time between now and when an alarm is supposed to go off (i.e. "alarm goes off in 23 minutes, 56 seconds").
def time_to_alarm_in_words
#AN EMPTY STRING WE WILL BE ADDING TO
time_in_words = ''
#THE TIME TO THE ALARM IN SECONDS
total_seconds = (time - Time.no... |
I've implemented CommonJS Modules 1.1.1 as a simple bash script with a bit of help from M4.
I'm interested in comments on the shell scripting and the javascript output.
Some specific questions on bash scripting:
How are backquotes different from $( ... ) as far as evaluating stuff in strings?
Are there places where I... |
I know there is probably a better way to have coded this. Can anyone be of help? I am not an expert JavaScript coder.
$(function() {
$('#clientLoginText').hover(function() {
$('#clientLoginBox').stop().animate({ "height" : '80px'}, 700);
}, function() {
//$('#clientLoginBox').stop().delay(500).a... |
I want to do binary search and if the target is not there get the index of where it should have been.
This is the code I came up with. It seems correct. Is there any problem? Can it be improved?
private int binarySearch(String[] sortedArray, String target, int start, int end) {
if(start <= end){
int mid = (... |
I have the following routine that I would like to simplify:
public void SetUniform(RenderContext ctx, string uName, object value)
{
if (ctx == null)
throw new ArgumentNullException("ctx");
if (value == null)
throw new ArgumentNullException("value");
if (value is int)
SetUniform(ctx,... |
I'm studying C on K&R and I solved exercise 2.08:
Write a function rightrot(x,n) that returns the value of the integer x rotated to the right by n positions
I've tested my code with some bit patterns and it seems to work, but I'm not sure that this solution covers all possible cases.
What do you think about this code... |
For quite a long, I have been using a pattern to make my life a bit easier. please help me evaluate how good or bad my approach is and how can I improve it.
I have a static class for just returning values:
class ReturnValue {
const STATUS_SUCCESS = "SUCCESS";
const STATUS_FAIL = "FAILED";
... |
I'd want an advise about the following idea that I have for organizing JavaScript when it comes to creating an HTML page. My group will be starting a new project and the approach that I'm trying to come up with will be large scale because every HTML page will be using it. Below I'll show a sample code and I'd like it t... |
I'm trying to solve the Spotify bestbefore programming challenge found here http://www.spotify.com/us/jobs/tech/best-before/
I have written the code in Python but when I send it in, it says "Wrong Answer". I have checked my code for bugs many times but unable to find out what is wrong. I know the answers to other's peo... |
I'm creating a factory design for math problems. The purpose of the factory is:
The problems must be generated with a certain difficulty (or level). To do this, I've got an abstract method called ConfigureLevels.
I set an abstract method called Generate, this one must be implemented in a concrete class.
This is the f... |
I have written a simple python program which takes a number from the user and checks whether that number is divisible by 2:
# Asks the user for a number that is divisible by 2
# Keep asking until the user provides a number that is divisible by 2.
print 'Question 4. \n'
... |
I wrote a little utility to check stdin for correct UTF-8, reporting any errors encountered, but I am concerned about its simplicity and performance. Could anyone take a look and suggest some improvements please?
#include <stdio.h>
#include <stdint.h>
int in, msz_byte, state = 0, cpbytes = 0;
uint8_t byte;
uint32_t cp... |
I have a very big class Foo that should be divided into FooBar, FooUtility, FooBench, FooBranch. Each of this "subclasses" should have different methods. So that if Foo has:
public function methodA();
public function methodB();
public function methodC();
public function methodZ();
Then I should be able to divide them ... |
I just wanted to share this script I wrote in that hopes that someone might find it useful and can hopefully simplify it(?).
I'm very new to writing anything with jQuery, so this script is probably bulkier than it needs to be, but it does work.
Here's the full HTML page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Tr... |
I have a collision detection for terrain setup (non-terrain is handled with a quadtree I implemented apart from this) and I was wondering how others have done it compared to mine and what I could learn from people's critiques here.
My map is stored in a 2D array of "GameSquare"s
public class GameSquare extends GameObje... |
I have a multiview to insert and edit users. Users are listed in a gridview. In selectedindexchanged event of gridview I've placed this code:
protected void GrvList_SelectedIndexChanged(object sender, EventArgs e)
{
// EditView
FrmaddEditUsers.ActiveViewIndex = 1;
// Get Username
UserName.Text = GrvList... |
I recently tried my hand at CodeSprint2 through Interview Street. Having not coded in quite some time, I wasn't surprised that I had difficulty writing optimized code, but on one problem in particular I can't find where I've gone wrong. I've compared my code to successful algorithms used by other programmers, and I d... |
I'm trying to refactor some code for unit testing and was hoping you could critique it.
This is the original method:
public class MyNonRefactoredClass
{
public List<MyClass> DoSomething()
{
List<MyClass> data = GetData();
if (data.Count == 0)
return new List<MyClass>();
data = GetFormat... |
I have just started reading through Learn you a Haskell I got up to list comprehension and started to play around in GHCi, my aim was to make a times table function that takes a number n and an upper limit upperLimit and return a nested list of all the 'tables' up to n for example
> timesTable 2 12
[[1,2..12],[2,4..24]... |
I have been following this question on SO, copied below. I put together a solution, but which is \$O(n^2)\$. In order to get a more efficient \$O(n \log n)\$ or \$O(\log n)\$ solution, I tried to sort that array, but could not get it solved hence would like to ask here how to optimize this solution to get it in less t... |
I had to replace all instances of scientific notation with fixed point, and wrote a Python script to help out. Here it is:
#!/usr/bin/python2
# Originally written by Anton Golov on 29 Jan 2012.
# Feedback can be sent to <email> .
"""Provide functions for converting scientific notation to fixed point.
When imported,... |
I wrote this program that recursively prints all the files and directories starting at the current directory:
import Data.Tree (Tree (..))
import System.Directory (doesDirectoryExist, getCurrentDirectory, getDirectoryContents)
main :: IO ()
main = do
currentDirectory <- getCurrentDirectory
tree <- tree currentDire... |
I'm writing a JavaScript/PHP file uploader and I want to start this project off on the right track. I've started with this, a JavaScript Uploader object which will handle Ajax calls, display progress, show error messages, etc. I'm just hoping to get some feedback on the way I'm setting up my scripts.
function Uploader(... |
Is there a very short way to do this same thing in a pure LINQ based way? It seems like I should not have to do all of this below to get to the OrderBy.
Dictionary<DataColumn, DateTime> columns = new Dictionary<DataColumn, DateTime>();
int startIndex;
int endIndex;
for (int i = 0; i < table.Columns.Count; ++i)
{ ... |
I am creating a Minecraft like terrain engine in XNA, and am having problems when I render water, sayings that the "numVertices" passed should be greater then zero - which they should always be. The terrain is seperated into regions 32x32x32 in size and the vertex buffers are set as dirty when a block is added, but whe... |
We have a setup script for setting up a development environment, and setting up the image libraries is getting a bit messy:
# this is to get PNG and JPEG support working in PIL on Ubuntu
if [ -d /usr/lib/x86_64-linux-gnu ] ; then # 64 bit ubuntu
sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib/
sudo... |
I'd like to check the following process relating to the uploading of data by FTP, after the data is read from a database.
I have a stored procedure that returns data in the following pipe delimited format in a single column. It typically returns around 300 rows, each row has about 300 bytes.
1234|||||PROPERTY|||MARKE... |
I'm trying to symmetrically encrypt some data using C#, and there seems to be a lot of misleading or incorrect information out there on the subject.
I created a project on GitHub to act as some sort of standard for encrypting and decrypting data in C#: Encryptamajig on Github
It would be great if you guys could review ... |
I'd like to make this SQL scalar function more efficient. How can I do that?
CREATE FUNCTION [dbo].[fnFilterBySampleType]
(
@context VARCHAR(10),
@contextId INT,
@sampleTypeId INT
)
RETURNS BIT
AS
BEGIN
IF (
@context = 'batch' AND @sampleTypeId = 247
AND EXISTS(
SELECT *
... |
I wrote this, which essentially acts as a single library for all possible REST services.
Here is the main file, as of alpha version 1:
import requests, json
class RestConsumer(object):
def __init__(self,base_url,append_json=False,**kwargs):
self.base_url = base_url
self.uriparts = []
self.... |
I'm doing a site at the moment (first Rails site, learning as I code) and I'm concerned that I'm over complicating the routes.
My associations boil down to:
class Recipe < ActiveRecord::Base
has_and_belongs_to_many :categories
belongs_to :book
end
class Category < ActiveRecord::Base
belongs_to :category_ty... |
This code is for handling addition of two binary numbers, which can be as long as 100,000 bits... and up to 500,000 queries are performed.
High-level pseudocode:
First input N: number of bits in binary number A and B.
Second input Q: number of queries to be performed.
Next N inputs: 0/1s ... bits for A
Next N inputs: ... |
I'm new to Java. I'm trying to build a simple hierarchy of classes.
abstract class Vegetable
{
public Vegetable(double weight)
{
this.weight = weight;
...
}
...
}
class Tomato extends Vegetable
{
public Tomato(double weight)
{
super(weight);
...
}
... |
Is there a better or easier way of doing this?
if array[1] and array[2] and array[3] and array[4] and array[5] == false then
--somthing
end
I have a lot of arrays to check and was wondering if there is a way to work with arrays where you can do something like array[1-6] or [1,6] or something. Can't seem to find ... |
I have a custom validator that checks the min and max score of different sporting leagues -- e.g., MLB, NBA, NFL, NCAAB, etc.
Here's short version of what it looks like:
class ScoreValidator < ActiveModel::Validator
def validate(event)
if event.league_is_mlb?
if event.total_score < 1
event.errors.... |
I am looking for best practice on how I may write this function more efficiently.
var d = new Date(),
time = d.getHours(),
day = d.getDay();
if (day > 0 || day < 7){
if (time > 18 || time < 8){
// execute code
}
}
|
(defmacro with-condition-retries(retries expected-errors fail-function &body body)
"Attempts to execute `body` `retries` times, watching for
`expected-errors`. Optionally, if `fail-function` is set, each time a
failure occurs, prior to retrying, `fail-function` is executed.
Other conditions beside `expected-errors`... |
I need to determine a meeting date which convenes on the second Thursday of every month.
I've written the following code to do this:
//Determine next monthly meeting (occurs on 2nd thursday of each month)
define('MAX_POSSIBLE_SECOND_THURS', 14);
define('JANUARY', 1);
define('DECEMBER', 12);
define('THURSDAY', 4);
$cur... |
I'm seeing a lot of code like this at my new site
try
{
Task.Factory.StartNew(() =>
{
...
});
}
catch (AggregateException ex)
{
ex.Handle((x) =>
{
Log.Write(x);
return true;
... |
I've written this class for two purposes (I think only this fact shows that this code violates SRP): convert weight from one unit to another and to represent them accurate or not accurate. So class methods can be used for calculation and the present method rounds the value for presentation. I don't like this code - can... |
How can I code this in a better way, in one file? Output must be more than one (if there is more that one status_update with the given word "online or performancedegradation"), like:
#online
System is operating at peak performance.
#directonly
Traffic is bypassing Smart CDN system, and going directly to websites.
<... |
I need some second or third eyes to look over this, since right now, the necessary actions to make this work sound just bad and I suppose I am missing something due to a lack of C# experience.
I am currently working on a winforms c# application. More specifically, I am reworking a highly convoluted control flow between... |
How can I script this in a better way?
// Tweets
$twitter_username_string = "aasampat OR ashwinsampat OR somemore";
$twitter_number_of_tweets = 1;
$twitter_hashtags = "ashwinsampat+OR+franq2+OR+franq2.net";
// Instantiate a Twitter object which will scan Twitter depending on the parameters
$twitter = new Twitter($twi... |
This does the job, and it's pretty much all the functionality I need at the moment. However, I feel like it could be optimized a bit. Namely, is there a way I can do this without the div#boundary? Also, the drop down re-fires if I go back up into the menu, which not a big deal, but it would be nice to prevent this beha... |
Background
I'm converting Unicode text to TeX for typesetting. In the input, I'm allowing simple fractions like ½ and ⅔ using single Unicode characters and complex fractions like ¹²³/₄₅₆ using superscripted and subscripted numerals. First I convert the simple fractions (½ becomes \frac{1}{2}) and superscripted and su... |
I'm new to Rails/Ruby and I would like to get feedback on my little ApplicationController which is able to detect the visitor's language. I'm especially interested in optimizations on the control structure in the set_locale method (2 nested if statements and 3 assignments to one variable). I'm using the http_accept_lan... |
More readable way to do this?
renderHtmlTable(function(tableItems) {
var tableArray,_i,item,_len;
tableArray = ['<table id = sampleTable ><thead><tr>' +
'<th>Header 1</th>' +
'<th>Header 2</th>' +
'<th>Header 3</th>' +
... |
Today, I do not have a coding question, but just a general question about a piece of code that I have written.
As you guys can see, I run the following JavaScript code every ten seconds. I tried to run it every second, but it started eating up the CPU of my hosting company like crazy. With it running every ten second... |
I want to do insert sort in a linked list without using dummy nodes.
This is my code. How can this be improved? Any input is appreciated.
public static Node insertSort(Node node){
Node sortedList = null;
while(node != null){
Node current = node;
node = node.next;
Node x;
Node previous = null;... |
Is there a more succinct way to write code like this that has a lot of sharing between branches of the case statement?
(This is the main part of my solution to one of the Round 1 problems of the Facebook Hacker Cup 2012. The round is over.)
type Memoizable a = a -> a
recoveries :: Int -> Memoizable (String -> Int)
rec... |
Migrating to using prepared statements and would like some feedback on CRUD modules, concerned with syntax (usage and DRY) and speed:
START:
<?php
// This page is for deleting a user record.
// This page is accessed through view_users.php.
$page_title = 'Delete a User';
include ('includes/header.html');
echo '<h1>De... |
I'm not the greatest at writing tests yet and I'm starting a new OSS project for learning and as part of it I want to tackle being more effective at writing tests, more specifically quality tests. I think I write a lot of tests that don't bring much value except maintenance pain sometimes.
Can I improve these tests?
us... |
I've got this all working, but it seems to be quite long-winded, and I thought I'd post here and see if I'm doing it wrong...
I have a M:M relationship between an Installer and a MasterInstance. The classes (code-first) look like:
public class MasterInstance
{
.. rest of fields here ..
public virtual ICollectio... |
When I want to make some quick tests for my UITableViewControllers, I usually create an NSArray that holds some dummy data. I would like to know if I'm doing anything wrong here:
First in MasterViewController.h:
#import <UIKit/UIKit.h>
@class DetailViewController;
@interface MasterViewController : UITableViewControll... |
I'm putting together some classes as a model for some information (that I'm currently pulling from a website).
The classes are implemented in C# - because in the current version of F# there are no autoimplemented properties. The logic to fill these classes from the website is going to be writen in F#. (Because I like F... |
What is the best practices to pass data from presentation to application layer?
Currently I have something like this:
in presentation layer:
the controller:
public class ProductController : Controller
{
private readonly IProductService _productService;
public ProductController(IProductService productService)
... |
I use the following code to populate my HTML with JSON. The problem is that I'm afraid this code will be inefficient if the number of records that I get from the service call are large (200 or more).
Are there ways I can change my code to make sure this won't be an issue? Or is my code fine as it stands?
<html>
<head>... |
I have existing code that handles a tarball and would like to use that to process a directory, so I thought it would be reasonable to pack the directory up in a temporary file. I ended up writing:
class temp_tarball( object ):
def __init__( self, path ):
self.tmp = tempfile.NamedTemporaryFile()
sel... |
First of all, I apologize for the length of this but I'm trying to show the data I'm working with and that I attempted to figure it out on my own.
I'm building a social site for musicians. I would like to take the whole list of songs from the database and rank each one based on its relevancy to the logged in user. One ... |
Some time ago I wrote a small routine to run some quick n' dirty queries (and with that I mean it is not used for large queries) against an Oracle DB, but also wanted to do it a bit easier to parse errors.
# Executes the query
#
# Will execute a query contained in the variable named
# in the parameter $4 and store the ... |
I'm a zeromq newb and have implemented the REQ/RES Lazy Pirate pattern with C#. It's essentially a port from the C example given in the documentation. It's harnessed by tests, and seems to be work to my expectations. I'm interested to know if I'm understanding the pattern correctly, or if I can improve the API. If anyo... |
This is a question regarding design of a service or business logic layer that returns or exposes messages meaningful to the user.
RegisterUser method that takes a user. What should it return? Should it always return
a Service Information object?
a newly created user?
a boolean, and based on the result, you can interr... |
Here's what I have at the moment. Any ideas for improving on this?
public static Snapshot[] GetSnapshots()
{
var arrayedSnapshot = new
{
Id = Enumerable.Range(1, 9),
ScenarioTimeInSeconds = new[] { 0, 0, 0, 60, 60, 60, 120, 120, 120 },
BearingInDegrees = new[] { 0, 120, 220, 0, 120, 220,... |
I know there is a lot of libraries with this built in $.get() etc... but as for writing this in pure JavaScript how does this look?
var get_request;
ajaxRequest(function() {
var activexmodes, i, _i, _len, _ref, _results;
activexmodes = ['Msxm12.XMLHTTP', 'Microsoft.XMLHTTP'];
if (window.ActiveXObject) {
... |
I'm working on a jQuery plugin for a client. Instead of finding one that was already out there I wanted to practice writing plugins since I hadn't in awhile. This plugin grabs all the images in a UL, creates a overlay for the page, and puts them in a image zoomer that gets opened when a user clicks on a thumbnail ima... |
This works but feels like alot of code for what it accomplishes. I feel like I'm maybe missing something obvious.
// When current month is same as target month, then return the current day of the month.
// Else return the number of days in the target month.
static int DefaultDaysToSynch()
{
var now = DateTime.Now;
... |
Image<Bgr, Byte> frame = _capture.QueryFrame();
Image<Gray, Byte> grayFrame = frame.Convert<Gray, Byte>();
grayFrame._EqualizeHist();
MCvAvgComp[][] facesDetected = grayFrame.DetectHaarCascade(_faces, 1.1, 1,
Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.FIND_BIGGEST_OBJECT, new Size(20, 20));
if (facesDetected[0].Length ==... |
I am developing a small compiler like tool. In the process, I wrote a Class<?> wrapper, JavaClass:
public class JavaClass {
...
public List<GenericEntry> getAllGenericEntries() {
return GenericEntriesFinder.getAllGenericEntries(this);
}
}
I've at first written the bellow shown code inside JavaCla... |
I use this function in my wordpress site to add genres to an album:
What is it that makes this code so bulky?
Is it have for the server or it just looks like?
/**
* Creates a genere. If one already exists it will return an error
* @author Junaid Qadir Baloch <shekhanzai.baloch@gmail.com>
* @global type $wpdb
* @pa... |
I have written a class who is responsible for both enumerating primes and testing the primality of a number.
Here is the code :
public static class Primes
{
private static ulong g_MaxTested;
private static ulong g_MaxFound;
private static readonly HashSet<ulong> g_KnownPrimes;
static Primes()
{
... |
I want to create pair, where new UnorderedPair(ObjA, ObjB) == UnorderedPair(ObjB, ObjA) returns true. I also want to avoid any (un)boxing.
Have I gone about this in the correct way?
public struct UnorderedPair<T> : IEquatable<UnorderedPair<T>>
{
public T A;
public T B;
public UnorderedPair(T a, T b)
{
... |
I often need to parse tab-separated text (usually from a huge file) into records. I wrote a generator to do that for me; is there anything that could be improved in it, in terms of performance, extensibility or generality?
def table_parser(in_stream, types = None, sep = '\t', endl = '\n', comment = None):
header = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.