Memoize your functions with an extension method

by rsutton 5. August 2009 04:32

Recently I made a post on how to create memoized functions using a class.  Well today I came across a post that shows how to do the same thing using an extension method, so I thought I would share the code.

 

    public static class Extensions

    {

        public static Func<A, R> Memoize<A, R>(this Func<A, R> f)

        {

          var map = new Dictionary<A, R>();

          return a =>

            {

              R value;

              if (map.TryGetValue(a, out value))

                return value;

              value = f(a);

              map.Add(a, value);

              return value;

            };

        }

    }

 

Then you use it like so.

 

    class TestIt

    {

        public int DoIt(string parameter)

        {

            // Do lots of processing...    

 

            return 0;    

        }

 

        public void Test()

        {

            // Wrap the function and then use the Memoize extension method.

            var func = new Func<string, int>(DoIt).Memoize();

 

            // The function can then be executed as it if were a normal function.

            // This is different than before because you had to call execute.

            var result = func("process me");

        }

    }

 

The only limitation is that you have to create different extension methods based on the number of parameters.

Tags:

Development

How to use the same email address for multiple twitter accounts

by rsutton 3. August 2009 03:15

As anyone who has multiple twitter accounts knows you have to have a unique email address for each account.  Well this is of course a pain if you are like me and use gmail for pretty much everything.  There is a work around for this which will allow you to use the same email address for multiple twitter accounts.  It involves using a little know part of the standard used for email addresses.  Basically if you add a plus sign after the first part of your address you can add anything you want after it and it will still go to your account.  Here are some examples.

theman@domain.com

theman+twitteracct1@domain.com

theman+twitteracct2@domain

If you are using gmail or some other email host that supports this portion of the standard all of these emails will go to theman@domain.com.  So in your twitter account settings you can use something like theman+twitter1@domain.com for the first account, then theman+twitter2@domain.com for the second and so on and so forth.  This is also useful for filtering, so instead of giving out your normal address to websites you can give out addresses like theman+spamsite@domain.com and then just create a filter in gmail that will send any emails directly to the trash.

 

P.S.  Please don’t send email to theman@domain.com because I don’t know who that is.

Tags:

Remove Visual Studio Navigation Bar

by rsutton 31. July 2009 06:12

It has been my quest recently to maximize my Visual Studio real estate.  Today I just realized that the drop down list that always appears at the top of my source files (something I never use) is called the navigation bar.  With this info I was able to remove one more space waster that I never use.

 

Before

image

Turn it off

image

After

image

Tags:

Speed Test Reflection vs IronPython

by rsutton 30. July 2009 08:10

I was getting ready to write some code that will apply rules to an object using reflection, when I realized I could do the same thing using IronPython.  My only concern was the performance implications, because what I was doing needed to be fast.

 

Here are the results of basically setting properties on an object using both python and reflection.

image

Here is the code.  Nothing fancy.  I didn’t notice that there is a hit with the initial run, but after that IronPython is much faster.  If you look at the code you will notice that the time does not include setting up the engine, scope, etc.  You can play with those yourself, because here is the code.

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("Running 1000");

            RunIteration(1000);

 

            Console.WriteLine("Running 10000");

            RunIteration(10000);

 

            Console.WriteLine("Running 100000");

            RunIteration(100000);

 

            Console.WriteLine("Running 1000000");

            RunIteration(1000000);

 

            Console.WriteLine("Running 10000000");

            RunIteration(10000000);

 

            Console.WriteLine("Running 10000000");

            RunIteration2(10000000);

 

            Console.ReadLine();

        }

 

        static void RunIteration(int iterations)

        {

            Console.WriteLine("Reflection Iteration.");

            TestReflection(iterations);

            Console.WriteLine("Python Iteration.");

            TestPython(iterations);

            Console.WriteLine("Testing Complete.");

            Console.WriteLine();

        }

 

        static void RunIteration2(int iterations)

        {

            Console.WriteLine("Reflection Iteration 2.");

            TestReflection(iterations);

            Console.WriteLine("Python Iteration 2.");

            TestPython2(iterations);

            Console.WriteLine("Testing Complete.");

            Console.WriteLine();

        }

 

        static void TestReflection(int iterations)

        {

            var test = new TestClass();

            var type = test.GetType();

 

            var st = new Stopwatch();

            st.Start();

 

            for (var i = 0; i < iterations; i++)

            {

                type.GetProperty("Id").SetValue(test, 1, null);

                type.GetProperty("Name").SetValue(test, "New Name", null);

            }

 

            st.Stop();

 

            Console.WriteLine("Time {0} ms", st.ElapsedMilliseconds);

        }

 

        static void TestPython(int iterations)

        {

            var engine = Python.CreateEngine();

            var sourceengine.CreateScriptSourceFromFile("test.py");

            var scope = engine.CreateScope();

 

            var test = new TestClass();

 

            source.Engine.SetVariable(scope, "test", test);

            source.Engine.SetVariable(scope, "iterations", iterations);

 

            var st = new Stopwatch();

            st.Start();

            source.Execute(scope);

            st.Stop();

 

            Console.WriteLine("Time {0} ms", st.ElapsedMilliseconds);

        }

 

        static void TestPython2(int iterations)

        {

            var engine = Python.CreateEngine();

            var sourceengine.CreateScriptSourceFromFile("test2.py");

            var scope = engine.CreateScope();

 

            var test = new TestClass2();

 

            source.Engine.SetVariable(scope, "test", test);

            source.Engine.SetVariable(scope, "iterations", iterations);

 

            var st = new Stopwatch();

            st.Start();

            source.Execute(scope);

            st.Stop();

 

            Console.WriteLine("Time {0} ms", st.ElapsedMilliseconds);

        }

    }

 

    public class TestClass

    {

        public int Id { get; set; }

        public string Name { get; set; }

    }

 

    public class TestClass2

    {

        public int Id2 { get; set; }

        public string Name2 { get; set; }

    }

test.py

for i in range(0,iterations):

    test.Id = 1

    test.Name = 'New Name'

test2.py

for i in range(0,iterations):

    test.Id2 = 1

    test.Name2 = 'New Name'

Tags:

Development

Simple IronPython and C# Interaction Example

by rsutton 29. July 2009 01:47

I have yet to find a simple example of executing an IronPython script from C#, so here is mine.  Note that the Project I created is called ByFeatureApp and the WebScrapper class is public.  I also show setting a variable (the) in C# and then the python script prints the value.

 

C# Code

namespace ByFeatureApp

{

    class Program

    {

        static void Main(string[] args)

        {

            var the = "hello I'm the the string";

 

            var engine = Python.CreateEngine();

            var source = engine.CreateScriptSourceFromFile("Scripts\\test.py");

            var scope = engine.CreateScope();

            source.Engine.SetVariable(scope, "the", the);

            source.Execute(scope);

 

            Console.ReadLine();

        }

    }

 

    public class WebScraper

    {

        public void LoadUrl(string url)

        {

            Html = new WebClient().DownloadString(url);

        }

 

        public string Html { get; set; }

    }

}

 

IronPython Script

import clr

clr.AddReference('ByFeatureApp')

from ByFeatureApp import *

 

print the

 

ws = WebScraper()

ws.LoadUrl('http://www.barchart.com')

 

istart = ws.Html.find('<tr><td><a href="http://quote.barchart.com/quote.asp?sym=GCQ9">Gold</a>')

iend = ws.Html.find('</tr>', istart)

 

print ws.Html[istart:iend+5]

 

Anyway I hope this is useful.

Tags:

Development

Memoized Function in C# for Scope Limited Results Caching

by rsutton 22. June 2009 06:18

The other day while reading a book on JavaScript I came across an interesting pattern known as memoization.  Basically the purpose of this pattern is to cache the results of function execution so that only one unique parameter set needs to be evaluated.  This of course will greatly speed up the execution of a function that repeatedly calculates the same value.

 

Today I came upon the need to populate a property of a list of objects where the property was set based on a value in the database.  A simple example of this would be if you have a list of ids and some of those ids were duplicates.  If you did this the plain vanilla way you would end up getting the same results from the database multiple times, because the id of what you are fetching appears multiple times.

 

I guess you could setup some sort of caching layer and deal with all the issues that has, but that seemed like way too much work.  What I really wanted was a way to cache the results, but only while in the current scope.  I figured that would be sufficient for my needs and keep things simple.  Here is what I came up with.

 

The usage is like so.

 

    1 
    2 var todo = new List<int> { 1, 2, 3, 1, 3, 2, 3, 4, 2, 3 };
    3 
    4 var func = new MemoizedFunction<int, string>(GetData);
    5 var results = new List<string>();
    6 
    7 foreach (var t in todo)
    8     results.Add(func.Execute(t));
    9 

 

Here is the implementation of the MemoizedFunction class.

 

    1 
    2 class MemoizedFunction<TVal,TRet>
    3 {
    4     // Dictionary to hold already calculated values.
    5     private Dictionary<TVal, TRet> memo = new Dictionary<TVal, TRet>();
    6 
    7     // Function to be executed.
    8     private Func<TVal,TRet> func = null;
    9 
   10     public MemoizedFunction(Func<TVal,TRet> func)
   11     {
   12         this.func = func; 
   13     }
   14 
   15     public TRet Execute(TVal val)
   16     {
   17         // If the value has not been calculated add it to the dictionary.
   18         if (!memo.ContainsKey(val))
   19             memo.Add(val, func(val));
   20 
   21         // Return the value from the dictionary.
   22         return memo[val];
   23     }
   24 }
   25 

 

You can see that the function is passed into the constructor and then the Execute method is called for each evaluation.  Once the evaluation is complete, it is stored in a dictionary.  In the future, if the parameter matches what is stored then you will just get the result.  Like I said the beauty of this approach is that you get caching of the evaluation only while the “func” object, in the first set of code, is in scope.  This way I never have to worry about expiring the cache and other complexity.  I get greatly improved performance and the usage AND implementation is very straight forward and simple.  Of course because it is simple you could customize the MemoizedFunction class to meet your individual parameter needs.  I hope this makes sense.  If not please leave a comment.

Tags:

Development

America is bankrupt

by rsutton 8. June 2009 23:54

For a while now I have been concerned about the very bleak and dire situation we in America are in economically.  There are many who think that a recovery is on its way and that we just need to “grease the wheels'” of the economy by adding more credit and things will go back to how they were before.  First of all it is my belief that things will never again be like they are today.  America has had it’s day in the sun and now that sun is setting as we have spent away our future thanks to easy credit.  We are a nation with a very large debt burden that we cannot repay.  We make up a large portion of the worlds economic output, but as far as population goes we make up a much smaller portion.

 

What happens when a person cannot be repay their debts?  They go bankrupt.  What happens when a nation cannot repay its debts?  It goes bankrupt.  What happens when a nation that is bankrupt can print money?  It tends to print more.  This is where the danger lies.  Up until the seventies our currency could be redeemed internationally for gold.  If a country had one million dollars they effectively had one million dollars in gold and that one million dollars could be exchanged for that amount of gold.  In the seventies we printed too much money and were unable to continue to exchange gold for dollars so the the international gold standard was eliminated.

 

Fast forward to the 2008 crash in the stock market.  The stock market lost a significant portion of its value and many have suffered greatly.  Many joke about how their 401K is now a 200.5K and in many cases that is correct and I’m sure some wish they were so lucky.  The question what remains for the future?

 

The truth is the real crash has yet to come.  In other words, the stock market crash was only a precursor to something much bigger and more severe.  What we have to fear most is the collapse of our currency the US Dollar.  I believe the collapse of our currency will cause a depression so severe that they will rename the Great Depression to something like The First Depression.  Our depression will be far more severe because unlike the Great Depression what dollars we do have will be worth far less than they are today due to inflation.

 

To briefly explain, inflation is the expansion of the supply of currency.  This is generally followed by higher prices.  To illustrate, let’s say you live in a town where there are ten farmers and one new tractor for sale.  One day two of the farmers’ tractors break down and so they go to buy new ones.  If each farmer has $10,000 then the maximum possible price each farmer could possibly pay would be $10,000.  Now if each farmer has $1,000,000 then the tractors could easily go for $50,000 or $100,000 or maybe even $500,000.  So you see prices are affected by how much currency people have, so the more currency people have the more likely it is that prices increase.  Now think about the trillions of dollars the government making available.

 

Often I have trouble communicating with others what the next decade or so will be like, because it is hard to imagine a life other than what we live today.  The other day I came across a blog post that I thought provided a pretty clear explanation of what is likely to be in our future.  I believe that most if not all of what is said is very likely to occur, so hopefully you are prepared for what lies ahead.

The Worst Case Scenario (Someone Has to Say It)

 

To conclude I would just like to say that there is hope for a better future.  There is much pain we must endure for our past choices and this cannot be avoided, but we can look to make the changes necessary in our own lives so that a similar situation will be avoided in the future.  Hopefully we will return to prudence and save for the things we desire.

Tags:

Misc

A function for timing your JavaScript functions

by rsutton 28. May 2009 06:02

I’m doing some loading of data into a grid and I wanted to have a simple way of timing various method calls in JavaScript, so here is what I came up with.

    function timeIt(func) { 
        var start = (new Date()).getTime(); 
        var ret = func(); 
        var end = (new Date()).getTime(); 
        alert(end - start); 
        return ret; 
    } 
 

You can take code like this.

var json = parseJson(data); 
dataBindGrid('TheGrid', json);

 

And turn it into this.

var json = timeIt(function() { return parseJson(data); }); 
timeIt(function() { dataBindGrid('TheGrid', json); });

 

Notice that if you need a return value from the function you are timing you must place a return in the anonymous function that is passed in so that your variable is assigned.  In this case the variable being assigned is “json”.

Tags:

Development

Shutdown and Reboot in Windows from the Command Line

by rsutton 20. May 2009 05:19

Reboot Command

shutdown /r /t 0

Shutdown Command

shutdown /s /t 0

Tags:

Can’t access C$ share in Windows 7

by rsutton 15. May 2009 04:40

I kept trying to do the old \\mymachine\c$ to access the c drive of a machine in my network and it I couldn’t get it to work.  Now this machine was Windows 7 and ever since Vista file sharing has been really weird and in my opinion pretty messed up.  The solution of course was to DISABLE UAC.  That’s right.  If you disable User Account Control then this will work just fine.

Tags:

IT | Development

Powered by BlogEngine.NET 1.4.5.0
Theme by Extensive SEO

Profile

Member of the Church of Jesus Christ of Latter-Day Saints, Developer and IT Professional