Jacob Carpenter’s Weblog

March 12, 2009

Google Reader Tip

Filed under: Uncategorized — Jacob @ 12:10 pm

Sorry to break a long hiatus with such a lame, non-programming post. But, here’s a tip for Google Reader users:

A coworker of mine appears in my google talk list, but was not able to see my shared items in his Reader. We checked the settings a number of times, but to no avail.

Another coworker recommended the “try changing this, and then changing it back” strategy. I was skeptical, but reluctantly tried it…

And it worked!

So, if you use Google Reader and share items, check to make sure you’re sharing with everyone you intend to:

1. Click sharing settings on the left-hand side of Reader:

Reader-001

2. Click “Change” on the right-hand side of the newly displayed page:

Reader-002

3. Toggle the radio button to “Share with ‘Friends’” and click Save:

Reader-003

Repeat steps 2 and 3, but select “Share with all of my chat contacts,” the second time.

Hope this helps.

October 6, 2008

C# compiler eccentricity of the day: throwing lambda

Filed under: csharp — Jacob @ 4:21 pm

Here at work (gratuitous link; oh yeah, and we’re hiring), we have a Verify helper class. Verify lets you succinctly validate (or verify, if you will) various method invariants. For instance, non-nullness:

Verify.IsNotNull(name);

The problem with these helper methods is that when an invariant is violated, an exception is thrown far from the actual affected bit of code. Always moving one frame up the call stack to see the real code that’s failing quickly gets annoying.

I started thinking about how to mitigate this problem, and realized that with Visual Studio’s excellent debugger support for delegates, the call site could include an Action<Exception> that just threw (throw-ed?):

Verify.IsNotNull(name, ex => throw ex);

Except that doesn’t compile.

Wrap the lambda body in curly braces (don’t forget the extra semi-colon) and everything works as expected (including the debugger breaking within the lambda!):

Verify.IsNotNull(name, ex => { throw ex; });

But unfortunately that adds so much syntax that the “solution” is more annoying than the problem I was initially trying to solve.

Has anyone run into anything like this before? Does it make any sense why that statement wouldn’t be valid as a lambda expression?

July 21, 2008

C# reminder of the day

Filed under: csharp — Jacob @ 4:24 pm

Static data is not shared among constructed generic types.

That is, the final line of output from the following program:

using System;

class Program
{
    static void Main()
    {
        NonGeneric.PrintCount(); // "Called 1 time."
        NonGeneric.PrintCount(); // "Called 2 times."

        Generic<int>.PrintCount(); // "Called 1 time."
        Generic<string>.PrintCount(); // ?
    }

    public static void DoPrintCount(int count)
    {
        Console.WriteLine("Called {0} time{1}.",
            count, count > 1 ? "s" : "");
    }
}

class NonGeneric
{
    public static void PrintCount() { Program.DoPrintCount(++count); }
    static int count;
}

class Generic<T>
{
    public static void PrintCount() { Program.DoPrintCount(++count); }
    static int count;
}

Is “Called 1 time.”

July 16, 2008

Strange Framework design decision of the day…

Filed under: csharp — Jacob @ 3:19 pm

Today I encountered the strangest .NET Framework design decision I’ve seen in recent times:

HashSet<T>’s GetEnumerator method returns a public struct HashSet<T>.Enumerator.

Let’s count how many Framework Design Guidelines this violates:

1. Avoid publicly exposed nested types.

  • violation: duh.

Do not define a structure [instead of a class] unless the type has all of the following characteristics [including]:

2. It is immutable.

  • violation: calling MoveNext mutates the enumerator object.

3. It will not have to be boxed frequently.

  • violation: passing a HashSet<T> as a parameter to a method that accepts IEnumerable<T> (Linq, anyone?) will hide the class’ GetEnumerator method. Therefore, any calls to GetEnumerator call the interface method which requires boxing the HashSet<T>.Enumerator to return an IEnumerator<T>.

4. [Any others you see? Leave a comment.]

 

I really want to hear the arguments in favor of the shipping design.

June 18, 2008

.Any overload

Filed under: Uncategorized — Jacob @ 4:12 pm

Nice:

if (folderPaths.Any(path => !Directory.Exists(path)))
    throw new DirectoryNotFoundException();

Nicer:

string pathNotFound;
if (folderPaths.Any(path => !Directory.Exists(path), out pathNotFound))
    throw new DirectoryNotFoundException("Could not find path: " + pathNotFound);

The implementation of

    public static bool Any<T>(this IEnumerable<T> source,
        Func<T, bool> predicate, out T found)

left as a trivial exercise to the reader.

June 16, 2008

Hello, world!

Filed under: Uncategorized — Jacob @ 9:12 am

Jonas Adam Carpenter

Jonas Adam Carpenter; born June 4th @ 6 lbs. 3 oz., 19 in.

(Sorry for the entirely non-technical post. I’ll be blogging more C# again, soon.)

April 23, 2008

C# abuse of the day: SwitchOnType

Filed under: csharp, extension methods — Jacob @ 5:30 pm

Today I encountered a situation where I wanted to switch based on a type. Maybe I stayed up a little too late reading Foundations of F#, last night.

While this is certainly no pattern matching, it didn’t seem like terrible C#:

DefinitionBase definitionBase = /*...*/;

var targetProperty = definitionBase.SwitchOnType(
        (ColumnDefinition col) => ColumnDefinition.WidthProperty,
        (RowDefinition row) => RowDefinition.HeightProperty);

Note that the lambdas require type decoration (you really don’t want to explicitly declare the generic parameters on this method).

Here’s the implementation (taking two Func projections—feel free to overload to your heart’s content):

public static TResult SwitchOnType<T, T1, T2, TResult>(this T source,
    Func<T1, TResult> act1, Func<T2, TResult> act2)
{
    if (source is T1)
        return act1((T1) source);

    if (source is T2)
        return act2((T2) source);

    throw new InvalidOperationException("No matching delegate found");
}

As you can see from the implementation, the method returns the result of the first delegate for which source can be converted into a parameter.

For a default case, add a final delegate that takes object.

April 16, 2008

PC#1: A solution

Filed under: LINQ, challenge, csharp, extension methods — Jacob @ 12:21 pm

So, when I initially posed the programming challenge #1 I stated:

… since I intended to output HTML, ASP.NET seemed a logical choice. But I was amazed at the amount of code required for such a seemingly simple task (not to mention how ugly code containing <% and %> is!).

Well, it turns out, using plain old C# with a little LINQ to XML functional construction made my solution a lot nicer.

Prerequisites

I created a few DateTimeExtensions to enhance readability, though I could have easily inlined the implementation of each of those methods without any LOC impact.

public static class DateTimeExtensions
{
    public static DateTime ToFirstDayOfMonth(this DateTime dt)
    {
        return new DateTime(dt.Year, dt.Month, 1);
    }
    public static DateTime ToLastDayOfMonth(this DateTime dt)
    {
        return new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month));
    }
    public static DateTime ToFirstDayOfWeek(this DateTime dt)
    {
        return dt.AddDays(-((int) dt.DayOfWeek));
    }
    public static DateTime ToLastDayOfWeek(this DateTime dt)
    {
        return dt.AddDays(6 - ((int) dt.DayOfWeek));
    }
}

I also relied on the Slice extension method I’ve previously blogged about.

Solution

static void Main(string[] args)
{
    DateTime today = DateTime.Today;
    DateTime firstDayOfMonth = today.ToFirstDayOfMonth();
    DateTime startCalendar = firstDayOfMonth.ToFirstDayOfWeek();
    DateTime lastDayOfMonth = today.ToLastDayOfMonth();
    DateTime endCalendar = lastDayOfMonth.ToLastDayOfWeek();

    var calendarPrefix =
        from day in Enumerable.Range(startCalendar.Day, (firstDayOfMonth - startCalendar).Days)
        select new XElement("td", new XAttribute("class", "prevMonth"), day);
    var calendarMonth =
        from day in Enumerable.Range(1, lastDayOfMonth.Day)
        select new XElement("td", day == today.Day ? new XAttribute("class", "today") : null, day);
    var calendarSuffix =
        from day in Enumerable.Range(1, (endCalendar - lastDayOfMonth).Days)
        select new XElement("td", new XAttribute("class", "nextMonth"), day);

    var calendar = calendarPrefix.Concat(calendarMonth).Concat(calendarSuffix);

    var table = new XElement("table",
        new XElement("thead",
            new XElement("tr",
                from offset in Enumerable.Range(0, 7)
                select new XElement("th", startCalendar.AddDays(offset).ToString("ddd")))),
        new XElement("tbody",
            from week in calendar.Slice(7)
            select new XElement("tr", week)));

    Console.WriteLine(table);
}

I’d love to see more ways to solve this. If you’ve got a simpler or more beautiful implementation in your favorite programming langauge/web application framework, let me know in the comments of the original post.

April 15, 2008

Programming Challenge #1: HTML calendar

Filed under: challenge, web — Jacob @ 1:44 pm

While playing around at lunchtime today, I decided to write a quick little HTML calendar generator.

I consider C# my native programming language, and since I intended to output HTML, ASP.NET seemed a logical choice. But I was amazed at the amount of code required for such a seemingly simple task (not to mention how ugly code containing <% and %> is!).

The challenge

Using your favorite programming language / web application framework output the following html fragment:

<table class="calendar">
<thead>
<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>
</thead>
<tbody>
<tr><td class="prevMonth">30</td><td class="prevMonth">31</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>
<tr><td>6</td><td>7</td><td class="today">8</td><td>9</td><td>10</td><td>11</td><td>12</td></tr>
<tr><td>13</td><td>14</td><td>15</td><td>16</td><td>17</td><td>18</td><td>19</td></tr>
<tr><td>20</td><td>21</td><td>22</td><td>23</td><td>24</td><td>25</td><td>26</td></tr>
<tr><td>27</td><td>28</td><td>29</td><td>30</td><td class="nextMonth">1</td><td class="nextMonth">2</td><td class="nextMonth">3</td></tr>
</tbody>
</table>

Whitespace is insignificant; class="today" should be applied to the current day’s cell; favor simplicity and elegance over efficiency.

Blog your solution and leave a comment; I’ll link to it from this post.

Please don’t comment suggesting I use some pre-built control. This is about the fun of writing such a thing, not about some specific calendaring need.

To avoid influencing your initial attempt, I’ll post my solution after awhile.

UPDATE:

Will Asrari contributed a submission at http://www.willasrari.com/blog/coding-for-fun—html-calendar-challenge/000298.aspx.

I posted my solution at http://jacobcarpenter.wordpress.com/2008/04/16/pc1-a-solution/.

kick it on DotNetKicks.com

April 4, 2008

Euler 14

Filed under: Euler, LINQ, Ruby, csharp, extension methods — Jacob @ 12:41 pm

When I read Dustin Campbell’s latest post, I couldn’t help but feel a bit like Steve Carrell in this clip from the Office. While his solution is an admirably close port of the original F# solution, it makes me feel a little bit yucky.

Of course, it’s completely hypocritical of me to say so, since I’ve abused C# to make it exhibit F#-like behavior in the past.

But Project Euler invites elegantly simple solutions (like the original F#). Different languages have different idioms, and a literal port typically doesn’t exhibit the same beauty as the original.

If I was solving project Euler 14 in C# (with “elegance and brevity in mind”), my code would look more like:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Euler14
{
    class Program
    {
        static void Main(string[] args)
        {
            var iterativeSequences = from start in 1.To(1000000L)
                select new
                {
                    Start = start,
                    Length = SequenceUtility.Generate(start,
                        n => n % 2 == 0 ? n / 2 : 3 * n + 1,
                        n => n == 1).Count()
                };

            Stopwatch sw = Stopwatch.StartNew();

            var longestSequence = iterativeSequences.Aggregate(
                (longest, current) => current.Length > longest.Length ? current : longest
            );

            sw.Stop();

            Console.WriteLine("Longest sequence starts with {0:#,#} (found in {1:#,#.000} seconds)",
                longestSequence.Start, (float) sw.ElapsedTicks / (float) Stopwatch.Frequency);
        }
    }

    public static class SequenceUtility
    {
        // Can also overload To by changing the end value's type;
        // example: "int excludedEnd" returns "IEnumerable<int>"
        public static IEnumerable<long> To(this int start, long excludedEnd)
        {
            for (long i = start; i < excludedEnd; i++)
                yield return i;
        }

        public static IEnumerable<T> Generate<T>(T first, Func<T, T> getNext, Func<T, bool> isLast)
        {
            T value = first;
            yield return value;

            while (!isLast(value))
            {
                value = getNext(value);
                yield return value;
            }
        }
    }
}

Which runs in an acceptable ~5 seconds on my machine.

[Okay. You caught me: I stole the idea for that To extension method from Ruby's upto. I'm a huge hypocrite and take back everything I said before.

Do invest time learning the idoms of other programming languages, and try applying them to your native language. You may discover something beautiful, after all.]

Older Posts »

Blog at WordPress.com.