Books
jmitchem
If books had been invented after the computer, they would have been considered a big breakthrough. Books have several hundred simultaneous paper-thin, flexible displays. They boot instantly. They run on very low power at a very low cost.
-- Prof. Joseph M. Jacobson, MIT Media Lab

Improved Breathing --> Improved Health
jmitchem
Many moons ago while randomly navigating the Internet, I stumbled upon a novel idea: improve your breathing and improve your health.

(Sidenote 1: it was only about 1 moon ago. Sidenote 2: when I use "navigate", I think sailing, but "stumbling" is clearly not very nautical. Does web browsing lend itself better to sea-based or land-based metaphors?)

Maybe the idea itself wasn't so novel, but the subsequent explanations, details, and theory to back it were fairly interesting. It was the application of actual science that made it interesting, not any new-age spirituality mumbo-jumbo.

(Sidenote 3: For now, I'm sticking with the standard "western view of the world is correct, and eastern ideas should be dismissed until proven otherwise" rhetorical approach. Personally, I'm more pragmatic. Things that work, work. I'd rather have an explanation based in science or medicine, rather than religion or spirituality, but I don't discount the results.)

If you read a handful of new-agey health stuff -- often a western "hippie" or "magical" reinterpretation of eastern knowledge -- there are a lot of recurring themes that revolve around the breath. E.g., "deep breathing" and "belly/diaphramagtic breathing" are good for you. Clustered in with these are concepts like "meditation", "[progressive] relaxation", "calming the mind", "mindfulness"... and slightly further out from that conceptual core is stuff like "aromatherapy", "accupressure", "developing the chakras", and even slightly more socially acceptable things like "herbal remedies", "raw/organic/paleo/whatever diets", "anti-genetically modified foods", etc.

In my experience, almost all of those get lumped together, and there's a love/hate reaction.

At one end of the spectrum, people just dismiss the whole lot.

At the other end, people go knee-deep in a bunch of pseudoscientific mysticism, thinking if they change [everything] in their lives and become more zen/in-tune-with-nature, that everything will become magically better, they'll end up happier. Some even become fad-chasers: take a million vitamins and you'll be "better"; reject modernization, and the world will be "better"; etc. There's a deep end, and a lot of people who get lost in it, one way or another.

Given that background, I found this breathing idea interesting precisely because it took the approach that the "eastern" techniques and results are valid, but that there's a "western" explanation as to why. Additionally, once you acquire the "western" understanding, the techniques can be optimized. Not only just to be more effective, but also to avoid the spiritual nuances in the original techniques.

A very incomplete example: Pranayama breathing in yoga focuses on extracting more "prana/life-force" from the air. Likewise, studies have shown that pranayama breathing allows more physical energy to be produced from a single breath, as compared to a single breath of the average American. Remove the "yoga" and "life-force" part, and you can effectively say "there are ways to improve your breathing that will give you more energy". Something relevant to everyone.

So what follows is my very naive summarization of what I've researched and learned. This isn't meant to be any end-all repository of knowledge. I found it interesting, and I'm no expert, but what I have learned I think is worth sharing.

--

One of the core ideas is that most people chronically OVER breathe. (Red herring: in "health" articles, you'll often see claims that Americans breathe shallowly with their chests, and that somehow conclude with telling you to breathe with your belly/diaphragm. The only real explanation is that "deeper breathing is better".)

A significant set of research findings shows that people with chronic diseases actually breathe far more air than a healthy person. As in, 2-3x as much air. Healthy people should breathe around 6-7 liters per minute. In contrast, people with Heart Disease breathe 12-16L/min; Cancer at 12L/min; Diabetes at 10-15L/min; Asthma and COPD at 12-15L/min; Cystic Fibrosis at 10-18L/min; etc. There's a lot of data, but the correlation is the same.

So we can say without much dispute: sick people breathe much more than healthy people.

What's a bit harder to quantify is "breathing less air (per minute) will make you healthier". For that, we need some basic physiology. I'm only getting a grasp of this myself.

Most people were taught that carbon dioxide is a "bad thing". Thus the faulty conclusion that if you breathe more, you get rid of more carbon dioxide and get more oxygen, which will make you healthier. This ties in with the whole "deep belly breathing is a 'good thing'" idea.

It turns out the truth is not quite as simple. Not only is carbon dioxide necessary, the body actually regulates CO2 levels far more precisely than oxygen levels. Additionally, if it weren't for CO2 in the bloodstream, your organs and muscles and other tissues wouldn't be able to get enough oxygen.

It's the fact that "you need carbon dioxide for your body to get oxygen from the blood" that's counter-intuitive based on my education (and probably yours too). Since oxygen requirements can vary from moment to moment, there are mechanisms to deliver more oxygen to some places and less to others. One of these is called the Bohr effect, and it says that areas with higher CO2 need more oxygen. Another is the process of vasodilation and vasoconstriction: your blood vessels get bigger to let more blood through, or smaller to restrict the blood supply.

Both of these processes -- vasodilation/vasoconstriction and the Bohr effect -- depend on carbon dioxide in the bloodstream. Simply stated... if you don't have enough CO2, your body isn't getting enough oxygen from your blood. The blood might have enough oxygen, but your body isn't getting it. (Other areas of physiology have shown that insufficient oxygen at the cellular level is the root of almost every illness.)

And that's one reason why certain breathing techniques work: they increase the carbon dioxide in your blood.

Increased CO2 is called "hypercapnia". In medical jargon, "Hyper" = "more" and "Capnia" = "carbon dioxide".

The techniques vary, but hypercapnia can be induced by two primary means: 1) keeping more CO2 in the lungs, 2) breathing in more CO2. To keep more CO2 in your lungs, you can hold your breathe or exhale slower. To breathe in more CO2, you can introduce "dead space" that captures the air you exhale, and breathe it back in (mixed with fresh air). One simple way is to breathe through your nose all the time; your nasal passages and sinus cavities trap some of the air you exhale and when you breathe it in, you get a higher concentration of CO2. There are other techniques like breathing through a gas mask, or through a paper bag.

Once this discovery of the relationship between hypercapnia and body oxygen was made, several techniques were developed. There are specialized breathing techniques that involve breathing at the same speed, but not as deep. Others involve breathing deeper, but breathing very slowly (potentially 1 breath a minute or slower.) There are also several devices that enforce rebreathing the exhaled CO2.

So, increased body oxygenation through hypercapnia is part of it, but there's more.

Another pseudoscience health topic these days refers to acidic and alkaline foods, and their respective effects on the body. Some doctors have said there's absolutely no truth to it, other "natural" healers say that this is one of the most important discoveries ever.

Regardless of the validity of the food pH argument, pH in the bloodstream is incredibly important. The body has a two primary means of regulating the acidity of the blood: respiration/breathing, and removing bicarbonates in the kidneys.

A few prerequisites:

Just like how baking soda (sodium bicarbonate) neutralizes acids like vinegar, the body produces bicarbonates to "buffer" the acidity of the bloodstream. If the bloodstream is too alkaline, the kidneys will remove these bicarbonates from the bloodstream, and the blood will become more acidic.

On the other hand, while carbon dioxide is a gas in the air, in the bloodstream it is "carbonic acid". As you exhale carbon dioxide, you remove the carbonic acid from the blood, and it becomes less acidic.

So, breathing makes blood less acidic, the kidneys make it more acidic. These two mechanisms serve to keep the blood pH at the right levels.

However, something can go wrong when you start to over breathe. The body has a very strong reaction when the blood becomes too acidic, but it doesn't react nearly the same when it's too alkaline.

(Acidic blood is part of what causes you to breathe in the first place; if you hold your breath long enough and let the carbonic acid build up, muscles will begin to convulse and eventually force you to breathe. Breathing gets rid of this acid buildup via exhaling CO2. As another example, physical exercise releases acid into the bloodstream, so you end up breathing more to neutralize the acidity.)

Unfortunately, there aren't anywhere near as strong mechanisms to increase the acidity of the bloodstream if it gets too low. The kidneys remove the bicarbonates which makes it more acidic, but those bicarbonates are now no longer available for use elsewhere. Likewise, there's a finite supply of bicarbonates.

What ends up happening is that chronic overbreathing can lead to chronically alkaline blood. Very rarely is it alkaline enough to cause any problem on its own, but over time it can cause damage and other chronic symptoms. Unfortunately, I don't know enough to elaborate. From what I've read, this can cause spasms in the smooth muscle lining the digestive system, thus affecting how well the body is able to get energy from food.

A final (but not THE final) factor is that reduced oxygen levels -- hypoxia -- can actually be good for you. There is a lot of sports science that involves hypoxic training for better performance; sometimes this is done by training in the mountains with the thinner air. There are numerous studies discussing the benefits of hypoxia, but I'm not entirely sure how it works. The net result seems to be that the body becomes more efficient at using less oxygen.

--

These factors -- hypoxia, hypercapnia and blood pH -- seem to lead to better health, and so there are different techniques that can be used to generate those effects.

The Buteyko breathing method focuses on reduced breathing, slower and or shallower with some breath holding; yoga Pranayama focuses on deep and slow abdominal breathing with resistance (one nostril at a time) with breath holding; and the Frolov device and variants provide resistance, dead air space for hypercapnia, and use slow controlled abdominal breathing.

There's a ton of information on all of these topics, and the more I dig, the more I learn. While nothing is conclusive, the evidence and studies indicate that improved breathing can help manage symptoms and potentially eliminate chronic diseases. And, now that we know some of these mechanisms, there are things you can do at home with minimal effort to get these same results for yourself.


Some sources of information:
http://www.normalbreathing.com/
http://www.intellectbreathing.com/principle/
http://amurklub.narod.ru/index.html (in russian)
http://www.shout.net/~jmh/clinic/science_of_breath/
http://www.apneamania.com/code/training_main.asp
http://freedivingexplained.blogspot.com/2008/03/freediving-training-static-tables.html
google searches about freediving and apnea training
youtube and google searches of capnography (used by paramedics and anesthesiologists to monitor CO2 levels)

Proposal: a profit-sharing model for Software Development
jmitchem
Definitions: A "contractor" is the single person or company that has a contract to do work for the "organization". If a company is the contractor, the individuals doing the work are employees of the contractor, but not contractors themselves.

A software contractor doesn't deliver merely one-time gains to an organization, but contractors usually only get paid once for building a solution. This is great for the organization; not so great for the contractor.

If I implement a change which increases revenue by $300/day, and saves $200/day in costs, this is a $500 increase in daily profit. If that change remains in production for 5 years — let's say 260 business days a year — that's a total benefit of $650,000 from that change.

But software billing is usually per-hour, so it may have taken me 40 hours for that change, at $150/hr. That's $6k spent in order to get a $650k gain. Not bad. Every additional year provides another $130k for the organization, and an additional $0 for me.

However, lets say I write the contract to be paid $100/hr for development, AND ALSO 5% of all increased profit for the production lifetime of the change.

I get $4k upfront, and an additional $6.5k/yr it's in production. How much does this cost the organization in REAL money on an ongoing basis? Nothing. If the change fails to influence profits, it doesn't cost a dime.

Over 5 years, the organization makes $617.5k and I make an additional $32.5k -- $36.5 total. A tad more than the $6k of the earlier [greedier, short-term] approach. 33% less upfront turned into more than 6x the original revenue.

Now let's consider incentive.

If a contractor charges $150/hr for 40 hours, they get paid $6k. While they are required to perform a task, there is no incentive to improve the organization's bottom-line (nor to work efficiently). An organization can very easily waste that $6k and get nothing out of it. Many do that already.

However, if the contractor gets an ongoing percentage of the profit differential, both the organization AND the contractor are motivated to focus activity on profit-generation. While daily activities are many layers abstracted from the bottom line, the profit motivation now provides high-level guidance that's otherwise ambiguous. What's good for the contractor is good for the organization. Win-win.

It's not much of a stretch to imagine what a profit-sharing model will do for the long-term relationship between the contractor and the organization. If the contractor figures out how to increase that revenue to $1000/day, they just doubled everyone's profit.

There's an additional long-term benefit from this approach: a focus on profit is fundamentally a focus on efficiency — producing more value with less. This focus on efficiency can influence the training goals and decision processes. Not only can we improve efficiency today, but we continually improve these efficiencies into the future.

Many people continue to see software as a "product". What they don't see is how software provides a layer of organizational abstraction on top of real-world businesses. This is a systemic change that can increase organizational adaptability, and with that, the ability to evolve and optimize business models. Without the typical lag involved with implementing managerial incentives, the feedback loop is more rapid, which leads to long-term cyclical benefits.

These localized efficiencies — coupled with increased adaptability — are obviously valuable to the profitability and survivability of any organization. However, as an aggregate, this produces a continually-improving economic machine focused on efficient utilization of resources. Assuming properly operating market forces (i.e., minimal monopolistic behavior), this can simultaneously drive down prices and increase corporate profitability.

At this point, decreased prices, which means increased value per dollar — i.e., consumer spending efficiency — can [arguably] lead to higher quality of life. What's good for me is good for you is good for everyone.

The bottom line? A profit-sharing model for software development is a Good IdeaTM for contractors and organizations alike. Additionally, it has the potential for long-term transformative effects on the economy.

Caveat: most organization's accounting structures are not conducive to measuring the profit impact of business initiatives. Actually enforcing a contractual clause such as "n% of the profit differential for the lifetime of the change" can be difficult, although the improved client relationship and long-term focus should limit these risks.

Constraining form instances by a key
jmitchem

  1. Set the constructor as private

    private ContactForm(IndividualDetails indiv)


  2. Write a public static CreateInstance method using the same signature as the constructor

    public static CreateInstance(IndividualDetails indiv)


  3. Define a "form builder" function within the CreateInstance method.  This "form builder" uses the unique key to construct the form.

    Func<IndividualDetails, ContactForm> formBuilder = i => new ContactForm(i);


  4. Flesh out the rest of the CreateInstance method by calling FormService's get method with the key and the formBuilder

    public static ContactForm CreateInstance(IndividualDetails indiv)
    {
        Func<IndividualDetails, ContactForm> formBuilder = i => new ContactForm(i);
    
        return FormService<IndividualDetails, ContactForm>.GetByKey(indiv, formBuilder);
    }


  5. Use the new modifier to replace the Show and ShowDialog methods

    public new void Show()
    {
        FormService.Show(this);
    }
    
    public new DialogResult ShowDialog()
    {
        return FormService.ShowDialog(this);
    }


  6. Replace all usages of the constructor with the CreateInstance method

    ContactForm form = ContactForm.CreateInstance(indiv);



That's it. Everything should work as before.


"form.Show()" creates a new instance if that key's not been used, otherwise it uses the existing form for that key. "form.ShowDialog()" does the same, except it will turn a modeless form into a modal form.


Before


internal class ContactForm : Form
{
    public ContactForm(IndividualDetails indiv)
    {
        // Initialization
    }

    // Body
}

After


internal class ContactForm : Form
{
    private ContactForm(IndividualDetails indiv)
    {
        // Initialization
    }

    public static ContactForm CreateInstance(IndividualDetails indiv)
    {
        Func<IndividualDetails, ContactForm> formBuilder = i => new ContactForm(i);

        return FormService<IndividualDetails, ContactForm>.GetByKey(indiv, formBuilder);
    }

    public new void Show()
    {
        FormService.Show(this);
    }

    public new DialogResult ShowDialog()
    {
        return FormService.ShowDialog(this);
    }

    // Body
}


Implementation


using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace MultiFormTest
{
    public static class FormService
    {
        /// <summary>
        /// Shows the specified form, brings it to the front and activates it.
        /// </summary>
        /// <param name="form">The form.</param>
        public static void Show<TForm>(TForm form) where TForm : Form
        {
            form.Show();
            form.BringToFront();
            form.Activate();
        }

        /// <summary>
        /// Shows the form as a modal dialog.  Can take a nonmodal form and make it modal.
        /// </summary>
        /// <param name="form">The form.</param>
        /// <returns></returns>
        public static DialogResult ShowDialog<TForm>(TForm form) where TForm : Form
        {
            form.Visible = false;
            return form.ShowDialog();
        }
    }

    public static class FormService<TKey, TForm> where TForm : Form
    // this guarantees it's a form, so it has IsDisposed, Show, BringToFront, etc.
    {
        static Dictionary<TKey, TForm> _mapping = new Dictionary<TKey, TForm>();

        public static TForm GetByKey(TKey key, Func<TKey, TForm> formBuilder)
        {
            if (formBuilder == null)
            {
                throw new ArgumentNullException("formBuilder");
            }

            if (!_mapping.ContainsKey(key) || _mapping[key].IsDisposed)
            // the 2nd condition will be evaluated if it contains the key
            {
                TForm newForm = formBuilder(key);
                _mapping[key] = newForm;
            }

            return _mapping[key];
        }
    }
}

Lispy C#
jmitchem
At some point in time, I started writing LISP-style code in C#; it's lost the nice symmetry of the C languages it derived from. Now it's all like a waterfall about to crash off the right hand side of the screen.

var emotionsWithVariance =
    emotions
        .Select(
            emotion =>
            new EmotionWithVariance
                {
                    Emotion = emotion,
                    Variance =
                        Math.Sqrt(
                            Math.Pow(targetPad.Pleasure - emotion.Pad.Pleasure, 2)
                            + Math.Pow(targetPad.Arousal - emotion.Pad.Arousal, 2)
                            + Math.Pow(targetPad.Dominance - emotion.Pad.Dominance, 2))
                })
        .OrderBy(emotionWithVariance => emotionWithVariance.Variance);

Camel Case enum to Sentence Case
jmitchem
private static string ConvertCamelCaseToSpacedSentenceCase(string camelCase)
{
var titleCase = Regex.Replace(camelCase,@"(\B[A-Z])",@" $1");

var lowerCase = titleCase.ToLowerInvariant();

return
lowerCase.First().ToString().ToUpperInvariant()
+ new string(lowerCase.Skip(1).ToArray());
}

Swapping switch/case return values with vim
jmitchem
:%s/case \(.*\)\(:\n\s*return \)\(.*\);/case \3\2\1;/g

Outlook is [More] Powerful [than expected]
jmitchem
I don't like Outlook much, I haven't ever liked it. And I never liked Thunderbird since it just seemed to be a less-feature-rich Outlook. My biases have always been toward Gmail.

After actually having to deal with a high volume of work email, I'm starting to really understand that Outlook has most of the power I'd been missing from gmail... it's just not as easy to get to or configure, but it's there.
  • Conversation View? Outlook has that.
  • One click Archive? Use a macro and a custom toolbar.
  • Keyboard shortcut navigation? Macros + custom toolbar + keyboard shortcuts (alt-j and altl-k to go up and down instead of 'j' and 'k'; alt-y to archive instead of 'y')
  • Labels + Label Views? Categories + Search Folders
  • Filters? Use rules to Auto-Archive or apply Categories or mark as read
  • "All Items" view? Create a Search Folder
  • Priority Inbox? Use rules to apply categories, then use a search folder
  • Keyword search criteria? Supports from, to, has attachment searches, and if you set it to search the "All Items" search folder, it works like gmail

Took much more work to set it up, but email management is better now.

I'm a troll? For trying to learn Lisp?
jmitchem
StackOverflow closed a "Learning Lisp" question of mine as "Subjective/Argumentative".

I've been trying to learn Lisp, and trying to determine whether to invest further in it.

I was looking for encouragement, ideas, insights, and I attempted to assess it objectively. The reaction was definitely not the warm-fuzzy feeling I was expecting.

On the plus side, two important points:

  • DSLs and symbolic manipulation via macros seem to be very important, and because I don't get it yet, I'm unable to see how important it really is

  • "Interactive Development" is really really nice (from personal experience; I have a post here about it somewhere too.)




Fyi, the offending post: http://stackoverflow.com/questions/5058179/c-dev-ive-tried-lisps-but-i-dont-get-it

Functional Programming in C#
jmitchem
I'm just posting this as an example of FP in C#.

Extracts words from text, cleans it up, and returns word frequencies

public static Dictionary<string,int> GetWordFrequencyDictionary( string text )
{
    return text
        .Split(new []{'\n', '\r', '\t', ' '}, StringSplitOptions.RemoveEmptyEntries) // split words
        .Select(w => w.Trim(new[] {'.', '!', ',', '?', '"', '\'', '(', ')', ':', ';'})) // trim punctuation
        .Select(w => w.ToLowerInvariant()) // unify case
        .GroupBy(w => w) // group by word
        .Select(group => new {Key = group.Key, Value = group.Sum(x => 1)}) // tally the sums
        .ToDictionary(item => item.Key, item => item.Value); // convert to dictionary
}

?

Log in