Arithmetic / Statistical Mode in C#

August 17, 2008 01:39 by frank

So recently, I needed a method to give me a statistical (or arithmetic) mode of an array of numbers. I searched the internet for a breif moment and didn't find any pre-coded solutions in C# so I just wrote my own. The following is that method. Two things to note, it uses generics so it works equally well for an int array or a double array, et cetera. Also, it will find a mode not all modes for a given array. You'd have to modify the method to return all (and I just needed one for my application).

If I did something silly, feel free to let me know.

public static T GetStatisticalMode(T[] array) {
Dictionary dictionary = new Dictionary();
// get a count of how often each item in the array occurs
foreach (T item in array) {
if (dictionary.ContainsKey(item)) {
dictionary[item] = dictionary[item] + 1;
} else {
dictionary.Add(item, 1);
}
}
// get the first largest mode encountered
int largestOccurance = 0;
T largestOccuranceKey = dictionary.Keys.GetEnumerator().Current;
foreach (T key in dictionary.Keys) {
if (dictionary[key] > largestOccurance) {
largestOccurance = dictionary[key];
largestOccuranceKey = key;
}
}
return largestOccuranceKey;
}

New Look

July 24, 2008 09:36 by frank

The website has a new look. It's very "green". It seems to work for both Firefox (3) and Internet Explorer (7) as well as Safari (3 - Windows). Let me know if there's any issues.

Alternative Programming Languages Anyone?

June 9, 2007 11:24 by frank

All good programmers should know a bunch of different programming languages. We should also keep up to date on the latest and greatest languages. Therefore, I present to you Whitespace, Shakespeare, Var’qa, LOLCODE, 133t, Beatnik, and BF–new languages that every programmer should learn immediately.

Whitespace

Whitespace used in “standard” programming languages can make a unreadable section of code and make it readable again. It’s an incredibly important thing! However, most modern compilers completely ignore this whitespace when they do their thing–compile. I find this to be a complete injustice and, evidently, so does Edwin Brady and Chris Morris, the inventors of the programming language “Whitespace”.

The following is an code snippet from a program which asks for a name then outputs it (select the “text” in the box below to “see” it):

         
  
    
  
  
 

Also translated to (s = space, t = tab, r = carriage return)

ssttstrtrsstrssrt

Advantages of Whitespace? From the Whitespace website:

Whitespace is a particularly useful language for spies. Imagine you have a top secret program that you don’t want anyone to see. What do you do? Simply print it out and delete the file, ready to type in at a later date. Nobody will know that your blank piece of paper is actually vital computer code!

There’s a prototype compiler available for linux.

Get it now.

Shakespeare Programming Language

If you thought Shakespeare was hard to read in High School, then you’ll love programming in it! I honestly decided not to try and figure out how this language works (yep, I quit, just like when I tried to read King Lear). They have an example “Hello World” program on the official website. “Hello World” weighs in at around 253 lines of code (whitespace included, of course!).

Here’s one “scene” (method? meh?) from the “primes.spl” file.

                    Act II: Determining divisibility.
 
                    Scene I: A private conversation.
 
Juliet:
Art thou more cunning than the Ghost?
 
Romeo:
If so, let us proceed to scene V.
 
[Exit Romeo]
 
[Enter Hamlet]
 
Juliet:
You are as villainous as the square root of Romeo!
 
Hamlet:
You are as lovely as a red rose.

Bravo, good sir, bravo!

You can download it from sourceforge.

Var’aq

That’s right, the link is to a geocities site. As well it should be.

Brian Connors wondered what a computer program on a Klingon space ship would look like (Klingon is a made up race of black people from the Star Trek universe, btw). Like all great men, he didn’t leave his questions for musing over coffee with friends but instead wrote what he calls the Klingon Basic.

Here’s a Var’aq program written to pick the winning 6 lotto numbers at random.

lI'moH Do' { (* Lucky *)
    6 {
        52 mIS (* pick a number between 0 and 52 *)
        Hab (* Round to the nearest integer *)
        cha' (* Slap it onscreen *)
    } vangqa' (* Do it five more times *)
} pong

After you download the language… make sure you check out the incredibly garish page that contains the code snippet I used above.

Also interesting to note… Firefox’s spell check recognizes “Klingon” as valid… thank goodness.

LOLCODE

It’s possible you’re all to familiar (and sick of) LOLCATS. It’s also possible that you’ve never even heard of it or didn’t know it had a name. If you epitomize the latter, read the wikipedia entry and then rush off to I CAN HAS CHEEZBURGER or LOL BOTS. Go on, I’ll wait… okay, I assume you wasted either 5 minutes and have returned thinking LOLCATS are incredibly dumb, or you wasted 5 hours and still find it funny. Either way, I now introduce LOLCODE.

LOLCODE brings the horrible grammar/spelling of LOLCATS to the everyday programmer. If you, too, are to lazy to type out “you are” but instead write “ur” then this could be the language for you. No real explanation is necessary just check out the code sample.

HAI
I HAS A CHEEZBURGER ITZ 1
 
IM IN YR LOOP
  VISIBLE "I has dis many: " N CHEEZBURGER
  IZ CHEEZBURGER BIGGER THAN 11 O RLY?
    YA RLY
      GTFO
    NO WAI
      UP CHEEZBURGER!!1
  KTHX
KTHX
 
KTHXBYE

I must say, I find the “YA RLY GTFO” syntax hilarious. I know you do too.

Others

There are many more wonderful (joke) programming languages. Here’s a quick rundown of some I’m to lazy to talk more about.

l33t

This snippet loops forever, printing all 255 ASCII characters.

ph34r my l3Et 5kIlLZ!!!!!!
nErDs 41n't cool 3v3ry1!!!
y0u b1g g33kS r teh g33kY sux0rs!
PHE4R! LOLOLOLOLOLOL!!!

Beatnik

This program simply prints “Hi” to the screen.

Baa, badassed areas!
Jarheads' arses
      queasy nude adverbs!
    Dare address abase adder? *bares baser dadas* HA!
Equalize, add bezique, bra emblaze.
  He (quezal), aeons liable.  Label lilac "bulla," ocean sauce!
Ends, addends,
   duodena sounded amends.

BF (Brainfuck)

Hello world!

++++++++++
[>+++++++>++++++++++>+++>+<<<<-] The initial loop to set up useful values in the array
>++.                             Print 'H'
>+.                              Print 'e'
+++++++.                         Print 'l'
.                                Print 'l'
+++.                             Print 'o'
>++.                             Print ' '
<<+++++++++++++++.               Print 'W'
>.                               Print 'o'
+++.                             Print 'r'
------.                          Print 'l'
------–.                        Print 'd'
>+.                              Print '!'
>.                               Print newline

Still interested in joke programming languages?? Sheesh. Fine… check out the list on the esoteric programming languages wiki.

Query String Encryption

March 22, 2007 15:28 by frank

Recently I need to secure a page that was accessed by query string. When you went to the page with “x.aspx?id=5″ it showed a sample of the overall product. After you purchase the product, you are sent to the page with “x.aspx?id=5&showMeTheRealThingPlease=true”. Obviously, this is far from secure as you can add that query string parameter to any page and get the purchased item.

So, this query string needs encryption. It needs government style lock down (not as in optical scanners and briefcases handcuffed to your arm but think more along the lines of a black marker on classified documents). So I started writing my own encryption methods in .NET but writing code is so much work. I’d much rather use someone else’s good idea.

Enter Mads Kristensen’s HttpModule. What does it do? Add his .cs file (1 x 1.55kb) to the App_Code of your project and a small change to your web.config (1-3 more lines) and magic happens. Every query string on your site is now encrypted. Best part is, you don’t have to change a single line of code on your existing pages. To access query string parameters, simply type "Request.Form["param"]" like you always have. Links show us as encrypted on their own as well (although an <a> tag will still show the unencrypted path in the status bar unless you explicitly set it with "QueryStringModule.Encrypt("user=123&account=456");)".

That’s all there is to it! Check it out.

Adding a New, Custom Item Template in Visual Studio 2005

January 22, 2007 17:06 by frank

I want some stability in my life. When I create a class, I want it to contain certain features that should be in each class I create such as comments, regions, and methods. Lucky, Visual Studio 2005 makes this rather easy.

Simply create a new file or ‘Item’ in Visual-Studio-ese (class in this case) and add to it the things you want. You can also add in certain keywords that can be created dynamically. To keep you from having to google them I include the list below. To use those keywords. Simply put a dollar sign (’$') in front and behind each keyword (eg. $itemname$).

itemname, safeitemname, safeitemrootname, projectname, safeprojectname, rootnamespace, guid[1-10], time, year, username, userdomain, machinename, clrversion, registered-organization, wizarddata

When you’re done, click on File > Export Template… and go through that wizard. The wizard should be straightforward enough. Just click the file you just created, name it appropriately, and Visual Studio will create a zip file with the file and required meta data to make it work in Visual Studio. (This file is also automatically imported as a template in Studio so you can start using immediately.)

Presto! Below is the template I use to create a new class.

using System;
 
namespace $rootnamespace$ {
 
    /// <summary>
    /// $safeitemrootname$: TODO $username$ further explain what this object is.
    /// </summary>
    /// <remarks>Created on: $time$</remarks>
    /// <author>$username$</author>
    public class $safeitemrootname$ {
 
        #region Constructors
 
        /// <summary>
        /// The default constructor to create a $safeitemrootname$.
        /// </summary>
        public $safeitemrootname$() { }
 
        #endregion Constructors
 
        #region Methods
 
        
 
        #endregion Methods
 
        #region Properties and Fields
 
        #endregion Properties and Fields
 
        #region Overide Object Methods
 
        /// <summary>
        /// Returns a string that represents this $safeitemrootname$ object.
        /// </summary>
        /// <returns>a string that represents this object</returns>
        public override string ToString() {
            return base.ToString();
        }
 
        /// <summary>
        /// Checks to see if two $safeitemrootname$ objects are equal.
        /// </summary>
        /// <param name="obj">the object with which to compare</param>
        /// <returns>true if parameter is an $safeitemrootname$ object</returns>
        public override bool Equals(object obj) {
            $safeitemrootname$ castObject = obj as $safeitemrootname$;
 
            if (castObject == null) {
                return false;
            }
 
            return base.Equals(obj);
        }
 
        /// <summary>
        /// Returns the hash code of this $safeitemrootname$ object.
        /// </summary>
        /// <returns>the hash code of this object</returns>
        public override int GetHashCode() {
            return base.GetHashCode();
        }
 
        #endregion
    }
 
}

Html/Css Standards and Best Practices

November 27, 2006 14:18 by frank

I’ve developed a Html/Css Standards & Best Practices document. This is a working list compiled from various tips on teh interweb as well logical rules I came up with. Like everything, it is a work in progress. Let me know if you have any thoughts.

Separate Design from Html Markup

There should be no way of telling what a page looks like by looking at the html markup. The html markup should look as friendly as possible to robots and screen readers. The CSS should make the page friendly to the regular user. Try to order sections as if you were to read the source and not the result (eg. header -> content -> navigation -> footer).

Tables are for Data

Tables are very useful for showing data arranged in rows and columns. They are not to be used as a structure for page layouts or wrappers around text. Use <p>, <br/>, <div>, and <span> tags when applicable.

Use Appropriate / Minimum Markup

Use html markup that makes sense for the application. Tables are for data. Navigation can often be represented in list form. Don’t use images for simple text buttons or navigation unless necessary. Use fieldsets (<fieldset>) within forms and labels (<label>) as the text before form elements.

Do not use a class declarations when modifying the html markup would suffice. Eg. <p class=”bodytx”> versus simply styling the <p> element. Also, don’t have div or span wrappers that are unnesessary. Example:

<!-- bad code -->
<div id="header">
  <div class="headerText">
    <span class="mainHeaderText">The Coolest Page Ever</span>
  </div>
</div>
 
<!-- good code -->
<div id="header">
  <h2>The Coolest Page Ever</h2>
</div>

Name Classes/Ids by Function, not Implementation

Class names like “smallText” or “red-bold” might make sense now, but after a few changes are made (and they will be made), they will make no sense. This also applies to layout elements like navigation (not “leftNavigation” but simply “navigation”).

Organize Rule Sets

Whether placing like-rules in the same file with commented dividors or in several different css files, keep them organized into logical sections.

  • Typography - This section is mostly about fonts. This is where you modify elements like p, h1 - h6, a (including :hover), ul, dl, et cetera. (example: here)
  • Layout - This section dictactes how the elements on the page are placed. These should be rather static rules that are highly reusable.
  • Forms - This dictates how all form elements are displayed. Typically, this modifies form, fieldset, legend, input, and any other markup that should appear differently when in a form (like p or ul).
  • Themes - This section should hold all the thematic elements such as colors and images. This way, a redesign could mean simply swaping “theme” css rules.
  • Content (Page Elements) - This section would dictate the special rules for html markup within special page elements (like the header, navigation, footer).
  • Miscellany - This section holds any tools or hacks that are used to make the page show up correctly.

Alphabetize Declarations

Alphabetize the declarations within your css. This may seem silly, but in complex rule sets it can become hard to find everything. Sometimes a duplicate property can be avoided (and therefore avoiding a lot of debugging time) with this approach.

Test with a Standards Complient Browser

Do not test only with Internet Explorer. Initially, test with a standards complient browser like Firefox or Opera and then, once things are done the correct way, modify the code slightly to work in Internet Explorer.

Minimize the number of Internet Explorer hacks. Try to write your css in such a way that as many browsers as possible interpret it correctly. Then, if necessary, add some invalid css to correct for IE.

Minimize Declaration Value Code

Don’t use “margin-left: #; margin-right: #;” et cetera. Instead, use “margin: # # # #”. Also, know the built in short cuts: “margin: 2px 2px 2px 2px;” and “margin: 2px;” are equivalent. Make sure you know your CSS Syntax Tips.

Use Consistent Formating

Whether you use camelCase, PascalCase, or hyphenated-words, be consistent with the naming conventions within the stylesheet.

Always use expaned rule sets. Having every declaration on the same line saves little file space but greatly decreases readability and maintainability. Remember, white space is often only one character extra (such as ‘\n’ or ‘\t’).

Indent rule sets within a hierarchy. This keeps a visual record of how things are organized. Example:

ul {
  margin: 0;
}
  ul li {
    margin: 2px;
  }
    ul li a {
      text-underline: none;
    }

Use Intelligent Size Units

Using pixels are not always advised. Widths and heights, margins or padding might be better described as percentages in some situations. Different units are good for use in different circumstances.

Fonts are best defined in percentages. The whole problem is with how IE (big suprise) displays font sizes. Fonts defined in pixels are not resizable with IE. Fonts defined with em’s are resizable but become unreadable if the em is less than 1. Percentages allow fonts to be flexable and readable across browsers. Some suggest defining all fonts in the body tag to be at 100% and then setting them with em’s in specific elements. This will also circumnavigate IE’s sizing bug. (See this)

Include a Colors Legend

Include (in the comments of the stylesheet) a legend of each and every color used in the style sheet. The will help make hex color values readable. Not everyone will recognize “#F67C01″ as “orange”. Example:

/* ---------------------------------– *
-- Color Code:
-- Very Light Orange: #faead3
-- Light Orange: #fed9a0
-- Orange: #f67c01
* ---------------------------------– */