<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>generics &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://wordpress.com/tag/generics/</link>
	<description>Feed of posts on WordPress.com tagged "generics"</description>
	<pubDate>Fri, 10 Oct 2008 18:32:21 +0000</pubDate>

	<generator>http://wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Colecciones de datos en C#.NET (Parte V: Colecciones Gen&eacute;ricas)]]></title>
<link>http://developmania.wordpress.com/2008/10/07/colecciones-de-datos-en-cnet-parte-v-colecciones-genricas/</link>
<pubDate>Wed, 08 Oct 2008 02:25:15 +0000</pubDate>
<dc:creator>fzapataramirez</dc:creator>
<guid>http://developmania.fr.wordpress.com/2008/10/07/colecciones-de-datos-en-cnet-parte-v-colecciones-genricas/</guid>
<description><![CDATA[A diferencia de las colecciones de datos tratadas en los post anteriores, las colecciones genéricas]]></description>
<content:encoded><![CDATA[<p align="justify">A diferencia de las colecciones de datos tratadas en los post anteriores, las colecciones genéricas se encuentran en el namespace System.Collections.Generics ya que son colecciones con la misma funcionalidad que las colecciones no genéricas (las normales, las que están en el namespace System.Collections), con la diferencia que estas están orientadas a trabajar con un tipo de dato especifico.
<p align="justify">
<p align="justify">Con un tipo de dato especifico?. Si así es, porque a diferencia de las colecciones no genéricas en las que se pueden agregar cualquier tipo de elementos y todos son convertidos a System.Object, en este tipo de colecciones solo es posible almacenar elementos de un tipo de dato específico.
<p align="justify">
<p align="justify">Cuando comencé a leer sobre esta nueva característica ofrecida por el Framework 2.0, me preguntaba si el nombre verdaderamente correspondía a la definición de estas colecciones, ya que no entendía el porque llamarlas genéricas si solo era posible almacenar datos del mismo tipo. Por el contrario, parecían ser más genéricas las otras colecciones (las del namespace System.Collections) ya que me permitían almacenar cualquier tipo de dato.
<p align="justify">
<p align="justify">Pero finalmente y después de leer varios artículos y códigos de ejemplo, comprendí el porque del nombre generics y espero poder transmitirlo en este post.
<p align="justify">
<p align="justify">Definitivamente, una colección genérica solo puede almacenar datos de un tipo, pero dicho tipo de dato es definido por nosotros mismos al momento de declararla e instanciarla. Es decir, no hay una clase para diferenciar las colecciones que operan con enteros de las que operan con cadenas de texto ni de las que operan objetos de tipo Empleado (por ejemplo). Absolutamente todas están definidas en la misma clase, lo único que las diferencia es la manera en que se instancia y se declara cada una de ellas. Ese es el secreto del ser genérica. Para entender mejor el concepto de la colección genérica, veamos el siguiente ejemplo:
<p align="justify">
<p align="justify"><a href="http://developmania.files.wordpress.com/2008/10/clip-image002.jpg"><img style="border-right:0;border-top:0;border-left:0;border-bottom:0;" height="78" alt="clip_image002" src="http://developmania.files.wordpress.com/2008/10/clip-image002-thumb.jpg" width="362" border="0"></a></p>
<p align="justify">
<p align="justify">En el ejemplo se observa la implementación de la colección genérica List, que es la versión genérica del ArrayList tratado en un post anterior. Se puede deducir que la primera colección permitirá almacenar únicamente datos de tipo int, que la segunda almacenara solo cadenas de texto y que la última almacenara objetos de tipo TablaDatos, el cual es un tipo definido en una clase aparte. En las definición de las tres colecciones se utilizo la clase List, es decir, que hay una clase “genérica” capaz de trabajar con el tipo de dato que indiquemos al momento de inicializarla. (Realmente no es cualquier tipo de dato, sino los tipos de datos soportados por la clase).
<p align="justify">
<p align="justify">La diferencia para inicializar una clase genérica de una clase no genérica, es que en la primera se debe utilizar una parámetro adicional después del nombre de la clase y entre los caracteres &#60; y &#62;. Este parámetro debe ser un tipo de datos, que indica el tipo de datos con el que la colección deberá operar.
<p align="justify">
<p align="justify">Así como esta la colecciones List&#60;T&#62;, que es la versión genérica del ArrayList, también existen las colecciones genéricas Stack&#60;T&#62;, Queue&#60;T&#62; y Dictionary&#60;T&#62;, entre otras que son las versiones genéricas de las clases Snack, Queue y HashTable respectivamente.
<p align="justify">
<p align="justify">Un ejemplo de la clase genérica de Stack seria:
<p align="justify">
<p align="justify"><a href="http://developmania.files.wordpress.com/2008/10/clip-image004.jpg"><img style="border-right:0;border-top:0;border-left:0;border-bottom:0;" height="73" alt="clip_image004" src="http://developmania.files.wordpress.com/2008/10/clip-image004-thumb.jpg" width="301" border="0"></a></p>
<p align="justify">
<p align="justify">Se puede ver como se define una pila en la que únicamente se pueden almacenar datos de tipo entero, lo cual me permite obtener datos de la colección y tratarlos directamente como enteros sin necesidad de hacer algún tipo de cast, lo cual no seria posible con las colecciones no genéricas ya que el elemento es almacenado como un System.Object.
<p align="justify">
<p align="justify">El hecho de que las colecciones genéricas operen con un tipo de dato definido en el momento de su declaración, las hace mucho más eficientes, ya que evita tener que realizar boxing, unboxing y casting de objetos. Adicionalmente los desarrolladores, obtienen un mayor grado de control sobre la información almacenada en la colección ya que en caso de intentar ingresar un objeto de un tipo de dato diferente al establecido en la inicialización de la colección, se arroja una excepción.
<p align="justify">
<p align="justify">Además de esta ventaja que nos brindan las colecciones genéricas, tenemos la posibilidad de crear nuestras propias clases y métodos genérico cuyo comportamiento estará ligado al tipo de dato que se utilice al utilizarlo tal y como sucede con las colecciones. Para lograr esto debemos hacer uso de los “type parameters”, los cuales permiten establecer un parámetro cuyo tipo se desconocerá hasta que se indique en la declaración.
<p align="justify">
<p align="justify">Para comprender mejor el funcionamiento de los “type parameters” que nos permiten crear clases genéricas, he desarrollado una aplicación de muestra que consiste en una clase impresora “genérica”, que es capaz de almacenar en una cola, objetos de un tipo específico (del tipo que se define al momento de definir un objeto de esta clase). Adicionalmente expone un método “imprimir” que se encarga de imprimir en pantalla cada uno de los valores contenidos en la cola. A continuación presento los fragmentos principales del código.
<p align="justify">
<p align="justify"><a href="http://developmania.files.wordpress.com/2008/10/clip-image006.jpg"><img style="border-right:0;border-top:0;border-left:0;border-bottom:0;" height="239" alt="clip_image006" src="http://developmania.files.wordpress.com/2008/10/clip-image006-thumb.jpg" width="474" border="0"></a></p>
<p align="justify">
<p align="justify">En esta primera imagen, se observa como se ha definido una clase Impresora genérica. Note que en este caso se utiliza la letra T para representar el “type parameter”, sin embargo es posible utilizar cualquier letra o palabra. Mediante este parámetro estamos indicando que al momento de definir e instanciar un objeto de tipo Impresora, se debe pasar como parámetro entre &#60; y &#62; el tipo de datos con el que se desea trabajar.
<p align="justify">En el constructor de esta clase, se puede ver como la Queue genérica que tiene la clase Impresora como atributo toma su mismo tipo de dato, es decir, si al crear la clase Impresora indicamos el tipo de dato int, la Queue también tomara el tipo de dato int.
<p align="justify">
<p align="justify"><a href="http://developmania.files.wordpress.com/2008/10/clip-image008.jpg"><img style="border-right:0;border-top:0;border-left:0;border-bottom:0;" height="315" alt="clip_image008" src="http://developmania.files.wordpress.com/2008/10/clip-image008-thumb.jpg" width="427" border="0"></a></p>
<p align="justify">
<p align="justify">En esta segunda imagen se observa una propiedad que retorna una cola genérica, pero el type parameter para indicar que es una Queue genérica es el mismo utilizado en nuestra clase Impresora, lo cual indica que retornara una Queue del tipo de dato utilizado en la clase.
<p align="justify">Finalmente se observa el método imprimir, cuyo objetivo es indicar el tipo de Queue que se esta imprimiendo y además mostrar cada uno de los elementos que contiene.
<p align="justify">
<p align="justify">Como paso final, para comprobar el funcionamiento de la clase Impresora, se crea un objeto de tipo Impresora de enteros, así:
<p align="justify">
<p align="justify"><a href="http://developmania.files.wordpress.com/2008/10/clip-image010.jpg"><img style="border-right:0;border-top:0;border-left:0;border-bottom:0;" height="182" alt="clip_image010" src="http://developmania.files.wordpress.com/2008/10/clip-image010-thumb.jpg" width="408" border="0"></a></p>
<p align="justify">
<p align="justify">Otra de las ventajas que nos brinda la utilización de Generics, es que los “type parameters” se traducen en tiempo de compilación, lo cual implica que es posible darnos cuenta en el momento que desarrollamos nuestra aplicación, el tipo de datos con el que se esta trabajando en cada instancia de la clase Impresora, como se ve a continuación:
<p align="justify">
<p align="justify"><a href="http://developmania.files.wordpress.com/2008/10/clip-image012.jpg"><img style="border-right:0;border-top:0;border-left:0;border-bottom:0;" height="106" alt="clip_image012" src="http://developmania.files.wordpress.com/2008/10/clip-image012-thumb.jpg" width="448" border="0"></a></p>
<p align="justify">
<p align="justify">
<p align="justify">Finalmente, se observa el resultado de la ejecución de la aplicación en consola:
<p align="justify">
<p align="justify"><a href="http://developmania.files.wordpress.com/2008/10/clip-image014.jpg"><img style="border-right:0;border-top:0;border-left:0;border-bottom:0;" height="150" alt="clip_image014" src="http://developmania.files.wordpress.com/2008/10/clip-image014-thumb.jpg" width="431" border="0"></a></p>
<p align="justify">
<p align="justify">
<p align="justify">
<p align="justify">
<p align="justify">
<p align="justify">
<p align="justify">En conclusión, debemos utilizar las colecciones genéricas tanto como sea posible en lugar de utilizar las colecciones no genéricas, ya que las primeras incrementan el rendimiento de la aplicación ya que evita un sin numero de casting, boxing y unboxing lo que permite realizar un mejor manejo de la memoria y procesamiento.
<p align="justify">
<p align="justify">Además podemos crear propias clases y/o métodos genéricos para aumentar la flexibilidad y la posibilidad de reutilizar nuestro código.
<p align="justify"></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[dotCotaAções]]></title>
<link>http://rafrancoso.wordpress.com/?p=122</link>
<pubDate>Thu, 02 Oct 2008 19:08:10 +0000</pubDate>
<dc:creator>rafrancoso</dc:creator>
<guid>http://rafrancoso.fr.wordpress.com/2008/10/02/dotcotaacoes/</guid>
<description><![CDATA[Apesar dos contratempos nos últimos dias consegui iniciar um projeto antigo, aprender a utilizar o ]]></description>
<content:encoded><![CDATA[<p><img class="alignleft" title="gtksharp" src="http://upload.wikimedia.org/wikipedia/en/5/5f/Gtk_Sharp_Logo.png" alt="" width="168" height="88" />Apesar dos contratempos nos últimos dias consegui iniciar um projeto antigo, aprender a utilizar o Gtk# em aplicações Mono/C#, e o resultado de meus primeiros testes ficaram prontos e na verdade surgiu da curiosidade de implementar um cliente que rode no linux para o WebService da Bovespa que postei esses dias.<!--more--></p>
<p>Nesse pequeno e simples projeto aprendi a trabalhar com os conteiners do GTK, não é algo trivial pra quem é acostumado a desenhar interfaces no Delphi, não quis utilizar o Glade pra desenhar pois quero aprender a codificar o mesmo. Trabalhar com esses conteineres no início foi complicado por conta do alinhamento automático dos controles que estão dentro deles, o que seria equivalente ao alClient no Align dos componentes do Delphi, me senti tentado a utilizar o conteiner Fixed mas ao ler a documentação do Gtk# no site do projeto eu desisti :).</p>
[caption id="attachment_123" align="aligncenter" width="420" caption="ScreenShot do dotCotaAções"]<a href="http://rafrancoso.files.wordpress.com/2008/10/dotcotaacoes.jpg"><img class="size-full wp-image-123" title="dotcotaacoes" src="http://rafrancoso.wordpress.com/files/2008/10/dotcotaacoes.jpg" alt="ScreenShot do dotCotaAções" width="420" height="258" /></a>[/caption]
<p>Aprendí também uma forma de trabalhar com o TreeView de uma forma meio que automática, mas serviu pra mostrar os dados obtidos do WebService.</p>
<p>Disponibilizei os fontes do projeto no Google Code quem quiser baixar, alterar ou sugerir alterações, fique à vontade. link: <a title="dotCotaAcoes" href="http://code.google.com/p/dotcotaacoes/" target="_blank">dotCotaAcoes no GoogleCode</a></p>
<p><strong>Modo de usar:</strong> abra o arquivo "acoes.txt" e digite o nome dos papéis que deseja visualizar separados por uma linha, coloque esse arquivo no mesmo diretório do executável. Abra o programa e clique em Atualizar :). só pra lembrar, pra obter o índice da Bovespa, inclua o papel IBOV no arquivo.</p>
<p><strong>Expectativas:</strong> Não tenho nenhuma expectativa quanto a esse projeto, a não ser utilizá-lo para testar novas descobertas como por exemplo fazer um gráfico que mostraria a variação do valor das ações durante o dia usando Cairo, fazer com que ele atualize os dados automaticamente em um período de tempo, permitir a edição dos papéis direto na TreeView e por aí vai.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Combining Ordered Lists in .NET]]></title>
<link>http://alexreg.wordpress.com/?p=33</link>
<pubDate>Mon, 29 Sep 2008 16:02:26 +0000</pubDate>
<dc:creator>Alex</dc:creator>
<guid>http://alexreg.fr.wordpress.com/2008/09/29/combining-ordered-lists/</guid>
<description><![CDATA[I recently came across an issue with LINQ involving the combination of ordered (sorted) lists. The p]]></description>
<content:encoded><![CDATA[<p>I recently came across an issue with LINQ involving the combination of ordered (sorted) lists. The problem does not seem to have a simple solution within the core libraries of .NET 3.5, so I decided to write my own (short) function to accomplish the task. Extensions methods and the static <em>Enumerable</em> class usually contain all the possible methods you might need for dealing with lists (or more generally enumerable collections). Combining ordered lists, however, isn't quite so straightforward a process (to do efficiently) as it might first seem. Of course, you could simply do <em>Enumerable.Concat(listA, listB).OrderBy(keySelector)</em> but it should be apparent that this is very inefficient for large lists if you know your lists are already ordered. Moreover, the call will never return if either or both of the enumerable collections you pass are of infinite length. What you really want to do is select items from the lists by switching back and forth between them, picking whichever of the next items ought to come first (which is determined by the key selector and associated IComparable implementation).</p>
<p>You can find the code for the function <a href="http://pastebin.ca/1213690">here</a>. For example, within a static class called <em>Enumerable2</em>, you can call it as such:</p>
<pre><code>var combinedList = Enumerable2.CombineOrdered(listA, listB, keySelector);</code></pre>
<p>Note: The given implementation needs to take lists sorted in an ascending order and returns a combined list in the same order. To sort descending, change the &#60;= sign to a &#62;= sign in the code and insure that you pass lists sorted in a descending order.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Weathering the Storm]]></title>
<link>http://pennybuck.wordpress.com/?p=207</link>
<pubDate>Mon, 22 Sep 2008 19:01:29 +0000</pubDate>
<dc:creator>Penny and Buck</dc:creator>
<guid>http://pennybuck.fr.wordpress.com/2008/09/22/weathering-the-storm/</guid>
<description><![CDATA[Last week our area had a terrible storm with high winds. Trees came down all over the place and hun]]></description>
<content:encoded><![CDATA[<p>Last week our area had a terrible storm with high winds. Trees came down all over the place and hundreds of thousands of homes lost power. Many trees still have not been cleared away.</p>
<p>I was looking at some of those fallen trees today, both near my house and near where I work. How is it that, say, a big pine tree near my office snapped and fell to the ground, while other pine trees just a few feet away - trees of the same circumference and height - remain standing?</p>
<p>Plenty of factors must come into play - root strength, the condition of the surrounding soil, the health of the tree, etc. Whatever the reasons, it seems to me that <strong>it all comes down to flexibility</strong>. The vast majority of trees were flexible enough to not break under the strain. Some, however, just couldn't bend enough to last.</p>
<p>We're trying to bend as the financial winds (of our own making) lash at us. Tonight there's going to be a windstorm in our very own house: it's bill night. Will we be able to make this month's $1700 payment to our debt reduction program? What will we do if we can't make the payment? We don't know the answer to either question.</p>
<p>We slashed our discretionary spending, we got second jobs, we buy generic foods, we have no plans to travel (even for an upcoming family wedding), and we're praying (literally) that the cars and appliances all keep working. The last remaining luxury is cable TV. Internet remains a must because Buck often receives calls to work from home on evenings and weekends. Even if there was time for him to drive to work (and there isn't - these are urgent calls), the price of fuel means that it's cheaper to pay for internet and log in from home.</p>
<p><strong>We're trying to flexible.</strong> Let's hope that we can bend enough to weather this storm, because it's going to last for years.</p>
<p>To my fellow frugalites - specifically to those trying to recover from overwhelming debt - I wish you good luck and much flexibility during your own personal storm.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Generic drug industry: Ranbaxy hires Giuliani to help it with FDA ban: shares drop 10 pct as US bans drugs - Indian pharma companies]]></title>
<link>http://bsubra.wordpress.com/?p=2410</link>
<pubDate>Sat, 20 Sep 2008 01:54:42 +0000</pubDate>
<dc:creator>bsubra</dc:creator>
<guid>http://bsubra.fr.wordpress.com/2008/09/20/generic-drug-industry-ranbaxy-hires-giuliani-to-help-it-with-fda-ban-shares-drop-10-pct-as-us-bans-drugs-indian-pharma-companies/</guid>
<description><![CDATA[சிக்கலில் இந்தியாவின் மருத்து தயாரி]]></description>
<content:encoded><![CDATA[<p class="storytext"><strong>சிக்கலில் இந்தியாவின் மருத்து தயாரிப்பு நிறுவனம்</strong></p>
<p class="storytext">
<table border="0" cellspacing="0" cellpadding="0" width="208" align="right">
<tbody>
<tr>
<td rowspan="2" bgcolor="#ffffff"><img src="http://www.bbc.co.uk/f/t.gif" border="0" alt="" width="5" height="1" /></td>
<td>
<div><img src="http://www.bbc.co.uk/worldservice/images/2006/03/20060329101414ranbaxy203.jpg" alt="சிக்கலில் ரான்பேக்ஸி நிறுவனம்" width="203" height="152" /></div>
</td>
</tr>
<tr>
<td class="caption">சிக்கலில் ரான்பேக்ஸி நிறுவனம்</td>
</tr>
</tbody>
</table>
<p>இந்திய மருந்து தயாரிப்பு பெருநிறுவனமான, ரான்பாக்ஸி, அது தயாரிக்கும் 30க்கும் மேற்பட்ட வணிகப்பெயர்கள் அல்லாமல், ரசாயனப் பெயர்களை வைத்து மட்டுமே அறியப்படும் மருந்துகள் அமெரிக்காவுக்குள் இறக்குமதி செய்யப்பட, அமெரிக்க அரசு விதித்திருக்கும் தடை குறித்து தான் ஏமாற்றமடைந்திருப்பதாக கூறியுள்ளது.</p>
<p class="storytext">அமெரிக்க உணவு மற்றும் மருந்துத் துறை, எப்.டி.ஏ, இந்த நிறுவனத்தின் இரண்டு தொழிற்கூடங்களில் தயாரிப்பு தரம் குறித்த பிரச்சினைகளை தான் கண்டுபிடித்திருப்பதாகக் கூறியது.</p>
<p class="storytext">ரான்பேக்ஸியோ, எப்.டி.ஏ கடந்து இரண்டு ஆண்டுகளாக எழுப்பிய கவலைகள் ஒவ்வொன்றைக்குறித்தும், தான் நடவடிக்கை எடுத்திருப்பதாகவும், இந்த விஷயத்தில் முன்னேற்றம் ஏற்பட்டுவந்ததாகவே தான் கருதியதாகவும் கூறியுள்ளது.</p>
<p class="storytext">ஆயினும், தனது மருந்துகளின் பாதுகாப்பு மற்றும் குணப்படுத்தும் திறன் குறித்து எந்த வித கேள்விகளும் இல்லை என்று எப்.டி.ஏ முடிவிற்கு வந்திருப்பது பற்றி தான் திருப்தியடைந்திருப்பதாகவும் ரான்பேக்ஸி கூறியது.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[foreach in Java]]></title>
<link>http://jaksa.wordpress.com/?p=13</link>
<pubDate>Fri, 19 Sep 2008 13:23:31 +0000</pubDate>
<dc:creator>jaksa</dc:creator>
<guid>http://jaksa.fr.wordpress.com/2008/09/19/foreach-in-java/</guid>
<description><![CDATA[Here&#8217;s a cool but unfortunately useless example of java generics, combined with reflection, co]]></description>
<content:encoded><![CDATA[<p>Here's a cool but unfortunately useless example of java generics, combined with reflection, combined with dynamic proxies.</p>
<p><!--more--></p>
<pre><span><strong>import java.lang.reflect.InvocationHandler;</strong></span>
<span><strong>import java.lang.reflect.Method;</strong></span>
<span><strong>import java.lang.reflect.Proxy;</strong></span>
<span><strong>import java.util.ArrayList;</strong></span>
<span><strong>import java.util.List;</strong></span>

<span><strong>import sun.reflect.generics.reflectiveObjects.NotImplementedException;</strong></span>
<span><strong>import sun.reflect.generics.tree.ReturnType;</strong></span>

<strong>public</strong> <strong>class</strong> <span style="color:#2040a0;">Foreach</span> <span><strong>{</strong></span>
  @<span style="color:#2040a0;">SuppressWarnings</span><span><strong>(</strong></span><span style="color:#008000;">"unchecked"</span><span><strong>)</strong></span>
<strong>  public</strong> <strong>static</strong> <span>&#60;</span><span style="color:#2040a0;">T</span><span>&#62;</span> <span style="color:#2040a0;">T</span> <span style="color:#2040a0;">foreach</span><span><strong>(</strong></span><span style="color:#2040a0;">T</span>... <span style="color:#2040a0;">elements</span><span><strong>)</strong></span> <span><strong>{</strong></span>
<span style="color:#2040a0;">    ApplyOnArrray</span><span>&#60;</span><span style="color:#2040a0;">T</span><span>&#62;</span> <span style="color:#2040a0;">handler</span> <span>=</span> <strong>new</strong> <span style="color:#2040a0;">ApplyOnArrray</span><span>&#60;</span><span style="color:#2040a0;">T</span><span>&#62;</span><span><strong>(</strong></span><span style="color:#2040a0;">elements</span><span><strong>)</strong></span><span>;</span>
<strong>    return</strong> <span><strong>(</strong></span><span style="color:#2040a0;">T</span><span><strong>)</strong></span> <span style="color:#2040a0;">Proxy</span>.<span style="color:#2040a0;">newProxyInstance</span><span><strong>(</strong></span><span style="color:#2040a0;">elements</span><span><strong>[</strong></span><span style="color:#ff0000;">0</span><span><strong>]</strong></span>.<span style="color:#2040a0;">getClass</span><span><strong>(</strong></span><span><strong>)</strong></span>.<span style="color:#2040a0;">getClassLoader</span><span><strong>(</strong></span><span><strong>)</strong></span>,
<strong>      new</strong> <span style="color:#2040a0;">Class</span><span><strong>[</strong></span><span><strong>]</strong></span> <span><strong>{</strong></span> <span style="color:#2040a0;">elements</span><span><strong>[</strong></span><span style="color:#ff0000;">0</span><span><strong>]</strong></span>.<span style="color:#2040a0;">getClass</span><span><strong>(</strong></span><span><strong>)</strong></span>.<span style="color:#2040a0;">getInterfaces</span><span><strong>(</strong></span><span><strong>)</strong></span><span><strong>[</strong></span><span style="color:#ff0000;">0</span><span><strong>]</strong></span> <span><strong>}</strong></span>,
<span style="color:#2040a0;">      handler</span><span><strong>)</strong></span><span>;</span>
<span><strong>  }</strong></span>

<strong>  public</strong> <strong>static</strong> <span>&#60;</span><span style="color:#2040a0;">ReturnType</span><span>&#62;</span> <span style="color:#2040a0;">List</span><span>&#60;</span><span style="color:#2040a0;">ReturnType</span><span>&#62;</span> <span style="color:#2040a0;">get</span><span><strong>(</strong></span><span style="color:#2040a0;">ReturnType</span> <span style="color:#2040a0;">returnValue</span><span><strong>)</strong></span> <span><strong>{</strong></span>
<span style="color:#2040a0;">    Collector</span> <span style="color:#2040a0;">collector</span> <span>=</span> <span><strong>(</strong></span><span style="color:#2040a0;">Collector</span><span><strong>)</strong></span> <span style="color:#2040a0;">Proxy</span>.<span style="color:#2040a0;">getInvocationHandler</span><span><strong>(</strong></span><span style="color:#2040a0;">returnValue</span><span><strong>)</strong></span><span>;</span>
<strong>    return</strong> <span style="color:#2040a0;">collector</span>.<span style="color:#2040a0;">getReturnValues</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span>
<span><strong>  }</strong></span>

<strong>  public</strong> <strong>static</strong> <strong>void</strong> <span style="color:#2040a0;">main</span><span><strong>(</strong></span><span style="color:#2040a0;">String</span><span><strong>[</strong></span><span><strong>]</strong></span> <span style="color:#2040a0;">args</span><span><strong>)</strong></span> <span><strong>{</strong></span>
<span style="color:#2040a0;">    IFoo</span> <span style="color:#2040a0;">f1</span> <span>=</span> <strong>new</strong> <span style="color:#2040a0;">Foo</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span>
<span style="color:#2040a0;">    IFoo</span> <span style="color:#2040a0;">f2</span> <span>=</span> <strong>new</strong> <span style="color:#2040a0;">Foo</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span>
<span style="color:#2040a0;">    IFoo</span> <span style="color:#2040a0;">f3</span> <span>=</span> <strong>new</strong> <span style="color:#2040a0;">Foo</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span>
<span style="color:#2040a0;">    IFoo</span> <span style="color:#2040a0;">f4</span> <span>=</span> <strong>new</strong> <span style="color:#2040a0;">Foo</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span>

<span style="color:#2040a0;">    List</span><span>&#60;</span><span style="color:#2040a0;">IString</span><span>&#62;</span> <span style="color:#2040a0;">list</span> <span>=</span> <span style="color:#2040a0;">get</span><span><strong>(</strong></span><span style="color:#2040a0;">foreach</span><span><strong>(</strong></span><span style="color:#2040a0;">f1</span>, <span style="color:#2040a0;">f2</span>, <span style="color:#2040a0;">f3</span>, <span style="color:#2040a0;">f4</span><span><strong>)</strong></span>.<span style="color:#2040a0;">sayFoo</span><span><strong>(</strong></span><span><strong>)</strong></span><span><strong>)</strong></span><span>;</span>
<span style="color:#2040a0;">    System</span>.<span style="color:#2040a0;">out</span>.<span style="color:#2040a0;">println</span><span><strong>(</strong></span><span style="color:#2040a0;">list</span><span><strong>)</strong></span><span>;</span>
<span><strong>  }</strong></span>
<span><strong>}</strong></span>

<strong>class</strong> <span style="color:#2040a0;">Collector</span> <strong>implements</strong> <span style="color:#2040a0;">InvocationHandler</span> <span><strong>{</strong></span>
<strong>  private</strong> <strong>final</strong> <span style="color:#2040a0;">List</span> <span style="color:#2040a0;">returnValues</span><span>;</span>

<strong>  public</strong> <span style="color:#2040a0;">Collector</span><span><strong>(</strong></span><span style="color:#2040a0;">List</span> <span style="color:#2040a0;">returnValues</span><span><strong>)</strong></span> <span><strong>{</strong></span>
<strong>    this</strong>.<span style="color:#2040a0;">returnValues</span> <span>=</span> <span style="color:#2040a0;">returnValues</span><span>;</span>
<span><strong>  }</strong></span>

<strong>  public</strong> <span style="color:#2040a0;">List</span> <span style="color:#2040a0;">getReturnValues</span><span><strong>(</strong></span><span><strong>)</strong></span> <span><strong>{</strong></span>
<strong>    return</strong> <span style="color:#2040a0;">returnValues</span><span>;</span>
<span><strong>  }</strong></span>

<strong>  public</strong> <span style="color:#2040a0;">Object</span> <span style="color:#2040a0;">invoke</span><span><strong>(</strong></span><span style="color:#2040a0;">Object</span> <span style="color:#2040a0;">proxy</span>, <span style="color:#2040a0;">Method</span> <span style="color:#2040a0;">method</span>, <span style="color:#2040a0;">Object</span><span><strong>[</strong></span><span><strong>]</strong></span> <span style="color:#2040a0;">args</span><span><strong>)</strong></span> <strong>throws</strong> <span style="color:#2040a0;">Throwable</span> <span><strong>{</strong></span>
<span style="color:#444444;">    // TODO get(foreach(elements).method(args))</span>
<strong>    throw</strong> <strong>new</strong> <span style="color:#2040a0;">NotImplementedException</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span>
<span><strong>  }</strong></span>
<span><strong>}</strong></span>

<strong>interface</strong> <span style="color:#2040a0;">IString</span> <span><strong>{</strong></span> <span style="color:#2040a0;">String</span> <span style="color:#2040a0;">toString</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span> <span><strong>}</strong></span>

<strong>  class</strong> <span style="color:#2040a0;">StringImpl</span> <strong>implements</strong> <span style="color:#2040a0;">IString</span> <span><strong>{</strong></span>
<strong>    private</strong> <span style="color:#2040a0;">String</span> <span style="color:#2040a0;">s</span><span>;</span>
<strong>    public</strong> <span style="color:#2040a0;">StringImpl</span><span><strong>(</strong></span><span style="color:#2040a0;">String</span> <span style="color:#2040a0;">s</span><span><strong>)</strong></span> <span><strong>{</strong></span> <strong>this</strong>.<span style="color:#2040a0;">s</span> <span>=</span> <span style="color:#2040a0;">s</span><span>;</span> <span><strong>}</strong></span>
<strong>    public</strong> <span style="color:#2040a0;">String</span> <span style="color:#2040a0;">toString</span><span><strong>(</strong></span><span><strong>)</strong></span> <span><strong>{</strong></span> <strong>return</strong> <span style="color:#2040a0;">s</span><span>;</span> <span><strong>}</strong></span>
<span><strong>  }</strong></span>

<strong>interface</strong> <span style="color:#2040a0;">IFoo</span> <span><strong>{</strong></span> <span style="color:#2040a0;">IString</span> <span style="color:#2040a0;">sayFoo</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span> <span><strong>}</strong></span><span>;</span>

<strong>class</strong> <span style="color:#2040a0;">Foo</span> <strong>implements</strong> <span style="color:#2040a0;">IFoo</span> <span><strong>{</strong></span>
<strong>  public</strong> <span style="color:#2040a0;">IString</span> <span style="color:#2040a0;">sayFoo</span><span><strong>(</strong></span><span><strong>)</strong></span> <span><strong>{</strong></span>
<span style="color:#2040a0;">    System</span>.<span style="color:#2040a0;">out</span>.<span style="color:#2040a0;">println</span><span><strong>(</strong></span><span style="color:#008000;">"foo"</span><span><strong>)</strong></span><span>;</span>
<strong>    return</strong> <strong>new</strong> <span style="color:#2040a0;">StringImpl</span><span><strong>(</strong></span><span style="color:#008000;">"foo"</span><span><strong>)</strong></span><span>;</span>
<span><strong>  }</strong></span>
<span><strong>}</strong></span><span>;</span>

<strong>class</strong> <span style="color:#2040a0;">ApplyOnArrray</span><span>&#60;</span><span style="color:#2040a0;">T</span><span>&#62;</span> <strong>implements</strong> <span style="color:#2040a0;">InvocationHandler</span> <span><strong>{</strong></span>
<strong>  private</strong> <strong>final</strong> <span style="color:#2040a0;">T</span><span><strong>[</strong></span><span><strong>]</strong></span> <span style="color:#2040a0;">elements</span><span>;</span>

<strong>  public</strong> <span style="color:#2040a0;">ApplyOnArrray</span><span><strong>(</strong></span><span style="color:#2040a0;">T</span>... <span style="color:#2040a0;">elements</span><span><strong>)</strong></span> <span><strong>{</strong></span> <strong>this</strong>.<span style="color:#2040a0;">elements</span> <span>=</span> <span style="color:#2040a0;">elements</span><span>;</span> <span><strong>}</strong></span>

<strong>  public</strong> <span style="color:#2040a0;">Object</span> <span style="color:#2040a0;">invoke</span><span><strong>(</strong></span><span style="color:#2040a0;">Object</span> <span style="color:#2040a0;">proxy</span>, <span style="color:#2040a0;">Method</span> <span style="color:#2040a0;">method</span>, <span style="color:#2040a0;">Object</span><span><strong>[</strong></span><span><strong>]</strong></span> <span style="color:#2040a0;">args</span><span><strong>)</strong></span> <strong>throws</strong> <span style="color:#2040a0;">Throwable</span> <span><strong>{</strong></span>
<span style="color:#2040a0;">    Method</span> <span style="color:#2040a0;">targetMethod</span> <span>=</span> <span style="color:#2040a0;">elements</span><span><strong>[</strong></span><span style="color:#ff0000;">0</span><span><strong>]</strong></span>.<span style="color:#2040a0;">getClass</span><span><strong>(</strong></span><span><strong>)</strong></span>.<span style="color:#2040a0;">getMethod</span><span><strong>(</strong></span><span style="color:#2040a0;">method</span>.<span style="color:#2040a0;">getName</span><span><strong>(</strong></span><span><strong>)</strong></span>, <span style="color:#2040a0;">method</span>.<span style="color:#2040a0;">getParameterTypes</span><span><strong>(</strong></span><span><strong>)</strong></span><span><strong>)</strong></span><span>;</span>

<span style="color:#2040a0;">    List</span> <span style="color:#2040a0;">returnValues</span> <span>=</span> <strong>new</strong> <span style="color:#2040a0;">ArrayList</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span>
<strong>    for</strong> <span><strong>(</strong></span><span style="color:#2040a0;">T</span> <span style="color:#2040a0;">element</span> <span>:</span> <span style="color:#2040a0;">elements</span><span><strong>)</strong></span> <span style="color:#2040a0;">returnValues</span>.<span style="color:#2040a0;">add</span><span><strong>(</strong></span><span style="color:#2040a0;">targetMethod</span>.<span style="color:#2040a0;">invoke</span><span><strong>(</strong></span><span style="color:#2040a0;">element</span>, <span style="color:#2040a0;">args</span><span><strong>)</strong></span><span><strong>)</strong></span><span>;</span>

<span style="color:#444444;">    // return a proxy for the result</span>
<strong>    return</strong> <span><strong>(</strong></span><span style="color:#2040a0;">T</span><span><strong>)</strong></span> <span style="color:#2040a0;">Proxy</span>.<span style="color:#2040a0;">newProxyInstance</span><span><strong>(</strong></span><span style="color:#2040a0;">elements</span><span><strong>[</strong></span><span style="color:#ff0000;">0</span><span><strong>]</strong></span>.<span style="color:#2040a0;">getClass</span><span><strong>(</strong></span><span><strong>)</strong></span>.<span style="color:#2040a0;">getClassLoader</span><span><strong>(</strong></span><span><strong>)</strong></span>,
<strong>    new</strong> <span style="color:#2040a0;">Class</span><span><strong>[</strong></span><span><strong>]</strong></span> <span><strong>{</strong></span> <span style="color:#2040a0;">targetMethod</span>.<span style="color:#2040a0;">getReturnType</span><span><strong>(</strong></span><span><strong>)</strong></span> <span><strong>}</strong></span>,
<strong>    new</strong> <span style="color:#2040a0;">Collector</span><span><strong>(</strong></span><span style="color:#2040a0;">returnValues</span><span><strong>)</strong></span><span><strong>)</strong></span><span>;</span>
<span><strong>  }</strong></span>

<span><strong>}</strong></span></pre>
<p><code><span style="font-family:'Lucida Grande';">I had this idea in a dream (too much work) and fortunately I could still remember it in the morning. Who knows, I might have dreamt also a solution that works with classes.</span><br />
</code></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Cheap Eats: Popcorn]]></title>
<link>http://pennybuck.wordpress.com/?p=196</link>
<pubDate>Thu, 18 Sep 2008 13:16:46 +0000</pubDate>
<dc:creator>Penny and Buck</dc:creator>
<guid>http://pennybuck.fr.wordpress.com/2008/09/18/cheap-eats-popcorn/</guid>
<description><![CDATA[Last night we made popcorn as a snack, and I decided to crunch some numbers too.
We used 5 oz. of ke]]></description>
<content:encoded><![CDATA[<p>Last night we made popcorn as a snack, and I decided to crunch some numbers too.</p>
<p>We used 5 oz. of kernels (about 2/3 cup) to fill the air popper's cup. That was from a 23 oz. bag of generic popcorn kernels that cost $1.50. The portion that we used cost <strong>23 cents</strong>.</p>
<p>We added 1/2 stick of melted butter. That was from a 1 lb. package of generic butter that cost $3.12. The portion that we used cost <strong>39 cents</strong>.</p>
<p>The yield was <strong>18 rounded cups of popcorn</strong>, and it cost us <strong>62 cents</strong>. You absolutely cannot beat that price for a tasty, crunchy snack that was more than enough for 2 people.</p>
<p>Price comparison: At Buck's office, a bag of microwave popcorn from the vending machine costs <strong>$1.50</strong>. That's almost 3 times as much as our snack last night, for far less popcorn.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Generic Medications at a very good price!]]></title>
<link>http://preparedcitizens.wordpress.com/?p=388</link>
<pubDate>Mon, 15 Sep 2008 20:39:21 +0000</pubDate>
<dc:creator>preparedcitizens</dc:creator>
<guid>http://preparedcitizens.fr.wordpress.com/2008/09/15/generic-medications-at-a-very-good-price/</guid>
<description><![CDATA[$9.99 for a 90 day supply!
Give or take a penny or two this is the going rate for generic prescripti]]></description>
<content:encoded><![CDATA[<p style="text-align:center;"><strong>$9.99 for a 90 day supply!</strong></p>
<p>Give or take a penny or two this is the going rate for generic prescriptions at <strong><em>some</em></strong> of our local pharmacies.</p>
<p>Maybe I am the last one to know this...I need to get out more. I thought I would pass this information along for any of my fellow Monsonites (and beyond) who may not have this information about our local area retail pharmacies. <a href="http://www.stopandshop.com/shop_online/pharmacy/index.htm" target="_blank">Stop &#38; Shop</a> has a generic prescription drug program is called "The Real Deal". The store locater is at the top of the page. <a href="http://www.walmart.com/catalog/catalog.gsp?cat=546834" target="_blank">Wal-Mart's generic drug program</a> costs a penny more for the same supply. The pharmacy locater is on the left of the page. <a href="http://www.kmart.com/shc/s/dap_10151_10104_DAP_Kmart+Pharmacy+Generics?adCell=A3" target="_blank">Kmart</a> also has a generic medication program. Their list of medications is <a href="http://content.kmart.com/ue/home/this%20list_10_15.pdf" target="_blank">here</a>. <a href="http://sites.target.com/site/en/health/page.jsp?ref=nav%5Fpharmacy&#38;contentId=PRD03-004033" target="_blank">Target </a>pharmacies are also included in the list of somewhat local major retailers who have a generic medication program.</p>
<p>I did not find a similar program at <a href="http://www.bigy.com/market/phar/index.php">BigY</a>, <a href="http://www.riteaid.com/" target="_blank">Rite Aid</a>, <a href="https://www.cvs.com/CVSApp/user/rx/pharmacy_homepage.jsp;jsessionid=xpdRLTDBmKRCbzgTCN55h9WnG9b6rlV1VBZH6d9BTGn7DP5P1rGt!-939441462" target="_blank">CVS</a>, or <a href="http://www.walgreens.com/" target="_blank">Walgreens</a>. I may have missed the information on their websites but I did look pretty thoroughly.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[C++ Templates e Java Generics]]></title>
<link>http://0xc0de.wordpress.com/?p=4</link>
<pubDate>Sat, 13 Sep 2008 13:41:59 +0000</pubDate>
<dc:creator>0xc0de</dc:creator>
<guid>http://0xc0de.fr.wordpress.com/2008/09/13/c-templates-e-java-generics/</guid>
<description><![CDATA[O mecanismo de templates C++ é um recurso muito poderoso. Na minha opinião, o mais interessante de]]></description>
<content:encoded><![CDATA[<p>O mecanismo de templates C++ é um recurso muito poderoso. Na minha opinião, o mais interessante de toda a linguagem de programação C++. Apesar dos exemplos de uso mais comuns nas aulas de programação serem utilizando coleções como <code>std::list&#60;MeuTipo&#62;</code> ou <code>std::vector&#60;MeuTipo&#62;</code>, os templates de C++ podem realizar tarefas muito mais fascinantes do que simples definições de contêineres.</p>
<p>Além de serem fundamentais para a programação genérica, o principal paradigma de desenvolvimento da STL (Standard Template Library) , os templates de C++ são instrumentos indispensáveis na arte da meta-programação. Em poucas palavras, a meta-programação consiste de código-fonte que é manipulado pelo compilador para gerar mais código-fonte. Ou seja, o compilador gerando código-fonte para a gente!</p>
<p>Um exemplo clássico de meta-programação é o cálculo do fatorial de uma constante (em se tratando de templates, é necessário que a informação esteja disponível estaticamente, por isso digo uma constante) em tempo de compilação [<a href="http://en.wikipedia.org/wiki/Template_metaprogramming">Wikipedia</a>]. Mas há inúmeras situações interessantes onde a meta-programação é empregada. Muitas delas podem ser encontradas nas bibliotecas Boost. Considere, por exemplo, o seguinte código-fonte para converter uma constante entre a representação binária e decimal [D. Abrahams/A. Gurtovoy].</p>
<p>[sourcecode language='cpp']<br />
#include <iostream></p>
<p>template <unsigned long N><br />
struct binary<br />
{<br />
	static unsigned const value =<br />
		binary<N/10>::value * 2 + N%10;<br />
};</p>
<p>template <><br />
struct binary<0> //Specialization.<br />
{<br />
	static unsigned const value = 0;<br />
};</p>
<p>int main()<br />
{<br />
	std::cout << "1001 -> " << binary<1001>::value << std::endl;<br />
	std::cout << "101001 -> " << binary<101001>::value << std::endl;<br />
	return 0;<br />
}<br />
[/sourcecode]</p>
<p>Diferentemente do que acontece em C++, os generics de Java não definem tipos de verdade e são úteis, basicamente, para detecção de erros durante a compilação. Eles são implementados com uma técnica chamada <a href="http://java.sun.com/docs/books/tutorial/java/generics/erasure.html">Type Erasure</a> , a qual consiste da remoção dos parâmetros genéricos durante a geração do bytecode. Logo, não há informações disponíveis sobre eles em tempo de execução. Considere, por exemplo, a classe <code>Teste</code> abaixo e seu respectivo bytecode. Note que do ponto de vista de execução ambos os membros <code>a</code> e <code>b</code> são tipo <code>Object</code>.</p>
<p>[sourcecode language='java']<br />
public class Teste<T><br />
{<br />
    public T a;<br />
    public Object b;<br />
}<br />
[/sourcecode]</p>
<p><span><br />
[caption id="attachment_10" align="alignnone" width="450" caption="Bytecode"]<a href="http://0xc0de.wordpress.com/files/2008/09/bytecode.jpg"><img src="http://0xc0de.wordpress.com/files/2008/09/bytecode1.jpg?w=450" alt="Bytecode" title="Bytecode" width="450" height="212" class="size-large wp-image-10" /></a>[/caption]<br />
</span></p>
<p>Em Java é possível especificar restrições sobre os parâmetros genéricos através do uso de bounded types e wildcards. No padrão C++ atual não há um recurso equivalente. No entanto, qualquer quebra contratual em termos da interface esperada por um template resultará em um erro de compilação da mesma forma. Além disso, uma grande novidade esperada para o C++0x (provavelmente, C++09) são os conceitos (<em>concepts</em>), os quais contribuirão significativamente para o formalismo semântico e amigabilidade na utilização de templates.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Converting DataSets to Strongly-Typed DataSets]]></title>
<link>http://kobikobi.wordpress.com/?p=40</link>
<pubDate>Thu, 11 Sep 2008 09:05:32 +0000</pubDate>
<dc:creator>Kobi</dc:creator>
<guid>http://kobikobi.fr.wordpress.com/2008/09/11/converting-datasets-to-strongly-typed-datasets/</guid>
<description><![CDATA[One of the first things shown to me when I started working in my company was Microsoft&#8217;s Data ]]></description>
<content:encoded><![CDATA[<p>One of the first things shown to me when I started working in my company was Microsoft's Data Access Application Block. One thing that bothered me was that I constantly had to convert DataSets it returned to strongly typed DataSets used in our programs, which usually meant merging the returned data set with a newly created DataTable. To relieve myself of those repeating tedious 6 lines of code, I made this little class that converts untyped DataSets and DataTables to a strongly typed DataTable.<br />
In a first attempt to solve this problem, I used reflation to create an instance of the typed DataTable, so I had to pass the method the type of the DataTable, and cast it back to itself.<br />
This is a more elegant solution, using generics:<br />
[sourcecode language='csharp']<br />
/// <summary><br />
/// Helper methods and functions.<br />
/// </summary><br />
/// <typeparam name="T">A strongly type DataTable.<br />
/// A DataTable of type T will be returned from the DataSet.<br />
/// </typeparam><br />
public static class DataSetAdapter<T><br />
                          where T : DataTable, new()<br />
{<br />
    /// <summary><br />
    /// Convert the first DataTable from a DataSet to a<br />
    /// strongly-typed data table.<br />
    /// </summary><br />
    public static T convert(DataSet dataSet)<br />
    {<br />
        if (dataSet == null)<br />
            return null;<br />
        if (dataSet.Tables.Count == 0)<br />
            return null;<br />
        DataTable dataTable = dataSet.Tables[0];<br />
        return convert(dataTable);<br />
    }<br />
    /// <summary><br />
    /// Convert an ordinary DataTable to a strongly-typed<br />
    /// data table.<br />
    /// </summary><br />
    public static T convert(DataTable dataTable)<br />
    {<br />
        if (dataTable == null)<br />
            return null;<br />
        T stronglyTyped = new T();<br />
        // add data from the regular DataTable to the<br />
        // strongly typed DataTable.<br />
        stronglyTyped.Merge(dataTable);<br />
        return stronglyTyped;<br />
    }<br />
}<br />
[/sourcecode]</p>
<p>The use of the class if pretty straightforward, just pass the DataSet and the Type:[sourcecode language='csharp']<br />
DataSet employeesDataSet = OracleHelper.ExecuteDataset(<br />
 connectionString, storedProcedure, parameters);<br />
EmployeesDataTable employees =<br />
 DataSetAdapter<EmployeesDataTable>.convert(employeesDataSet);<br />
[/sourcecode]<br />
Links:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/cc511547.aspx">Data Application Block documentation by Microsoft</a></li>
<li><a href="http://www.koders.com/csharp/fid4700D828411F8CC19782B1E75CB44D6C719632A0.aspx?s=mdef%3Adataset">Data Application Block source code</a></li>
</ul>
]]></content:encoded>
</item>
<item>
<title><![CDATA["generic" types: what's in a name?]]></title>
<link>http://sinewalker.wordpress.com/?p=356</link>
<pubDate>Wed, 10 Sep 2008 04:00:37 +0000</pubDate>
<dc:creator>sinewalker</dc:creator>
<guid>http://sinewalker.fr.wordpress.com/2008/09/10/generic-types-whats-in-a-name/</guid>
<description><![CDATA[I&#8217;ve been stumbling over Java&#8217;s generic types for a while now&#8230;  I think I finally]]></description>
<content:encoded><![CDATA[<p><span>I've been stumbling over Java's generic types for a while now...  I think I finally understand what my problem is:</span></p>
<p style="text-align:center;">They should be called <strong>specific </strong>types, or <em><span>parametrised</span></em> <em>collections</em>!</p>
<p><!--more--></p>
<p>I think the feature is called "Java generics" because when you use a collection, say <code>List&#60;E&#62;</code>, that <code>List</code> contains elements of parameterised type <code>&#60;E&#62;</code>, a "generic type".  But the element type in the plain old-fashioned non-parametrised collection <code>List</code> is also generic!  In fact the non-parametrised <code>List</code> is more <em>generic</em> than the "generic" version (it can contain elements of <em>any</em> sub-class of <code>Object</code>)!  The distinction is that the elements in a <code>List&#60;String&#62;</code> are all of one <strong>specific</strong> type (<code>String</code>), whereas the elements in a <code>List</code> can be of any general type, and can even be of different types in the same <code>List</code> collection (leading to problems that "Java generics" was invented to address).</p>
<p><span><code>&#60;sarcasm&#62;</code>Gosh, what an epiphany.<code>&#60;/sarcasm&#62;</code></span></p>
<p><span>If you're a Java guru this is nothing new, of course.  But that took me <strong>ages</strong> to grasp.  I think I wasn't helped by the terminology.  </span>In fact whenever I'm reading Java literature, it helps if I swap "generic" for "specific".  This makes much more sense to me.  Actually I already do word substitutions for much of the Java canon.  For instance:</p>
<ul>
<li>"class Foo is instantiated"<br />
Translation: "a Foo object is created"</li>
<li>"invoke method X of class Y"<br />
Translation: "send message X to a Y object",<br />
or even "send class Y the X message"</li>
</ul>
<p><span>Probably the Java literature is strictly more "correct" or explicit, but it'd be much more clear and concise if people used the older <span>OOP</span> words for things...</span></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Free Drug Samples May End Up Costing More]]></title>
<link>http://healthnewschannel.wordpress.com/?p=4384</link>
<pubDate>Mon, 08 Sep 2008 02:20:38 +0000</pubDate>
<dc:creator>timeinctemp</dc:creator>
<guid>http://news.health.com/2008/09/07/free-drug-samples-costing-more/</guid>
<description><![CDATA[FRIDAY, Sept. 5 (HealthDay News) &#8212; Doctors who hand out drug companies&#8217; free samples to ]]></description>
<content:encoded><![CDATA[<p><img class="alignleft" src="http://www.healthday.com/images/editorial/prescription_18142.jpg" alt="" width="170" height="114" />FRIDAY, Sept. 5 (HealthDay News) -- Doctors who hand out drug companies' free samples to uninsured patients may actually be costing those patients more money over the long term, a new study finds.</p>
<p>That's because doctors tend to continue patients on the more expensive brand name drug in the sample, rather than switch them over to a cheaper generic later on, researchers say.<!--more--></p>
<p>"When physicians had access to brand name drug samples, they were much more likely to give uninsured patients prescriptions for that drug," said lead author Dr. David P. Miller, an internal medicine physician at the Wake Forest University Baptist Medical Center in Winston-Salem, N.C. "But when giving out drug samples is not an option, the same physicians are almost three times more likely to prescribe generic drugs to the uninsured. And generic drugs are often much cheaper than their brand-name counterparts."</p>
<p>"So, given that for many conditions there are very effective generic options, I think any patient who wants to save money on their medications is better off asking for an effective generic prescription rather than asking their physician for a free drug sample," Miller advised. "Because while the sample might be free in the short term, they might end up paying a lot more money in the long term."</p>
<p>The research team outlined its conclusions in the September issue of the <em>Southern Medical Journal</em>.</p>
<p>The current finding follows on the heels of a University of Chicago Medical Center study released this past spring that indicated that patients who receive free drug samples go on to incur significantly higher out-of-pocket expenses when filling their prescriptions than those who never get such freebies. In that instance, three-quarters of the patients had private insurance coverage.</p>
<p>In the new study, the researchers spent 18 months tracking prescriptions written for uninsured and/or Medicaid patients cared for by more than 70 physicians. All of the doctors worked at a large university-affiliated internal medicine practice.</p>
<p>Midway through the study period, the institution's so-called "drug sample closet" was closed due to a physical relocation of the facility -- meaning that for the next nine months, doctors were unable to distribute the free brand name drug samples that had been previously available.</p>
<p>Using a pharmacy database, Miller and his colleagues characterized the nearly 2,000 chronic prescriptions for blood pressure, diabetes, ulcers, and gastrointestinal problems that were issued during the first nine months, while drug samples were still available. They then compared those patterns with prescriptions issued by the same doctors over the next nine months.</p>
<p>According to the researchers, the overall percentage of money-saving generic drugs prescribed to uninsured patients more than doubled once samples became unavailable -- from 12 percent while supplies lasted to 30 percent when the flow of free samples dried up.</p>
<p>This dynamic, however, did not appear to be in play for Medicaid patients, who were typically prescribed generic drugs regardless of sample availability. According to the researchers, that might stem from the fact that doctors know that Medicaid patients typically incur the same minimal out-of-pocket expense for generic or brand name drugs, so there was less incentive to try and save the patient money with a free sample.</p>
<p>But for the uninsured, it's a different story. "Physicians assume they are helping out by giving a free sample to patients who have no insurance," Miller said. "But there are, nevertheless, unintended consequences to that action that physicians need to weigh when doing so."</p>
<p>A representative of the pharmaceutical industry took issue with the findings.</p>
<p>In a statement, Ken Johnson, senior vice president of the Pharmaceutical Research and Manufacturers of America (PhRMA), said the study, "overlooks the fact that Americas physicians prescribe medicines based on a wide range of factors, not simply receipt of samples." He added that, "free samples provide physicians valuable first-hand experience with new medicines. In many cases, samples help patients begin treatment sooner by quickly discovering the medicines that are best for them. And they can be an important option for patients in need of help."</p>
<p>But Reginald Frye, an associate professor in the department of pharmacy practice at the University of Florida College of Pharmacy in Gainesville, agreed that while free samples can benefit patients, they must be used carefully.</p>
<p>"For example, sometimes you have a question as to if a drug is going to work well for your patient, so you give him or her the free sample as a trial," he said. "And there's, of course, the initial intent to spare some expense. But I'm not too surprised that it would influence a patient's choice later on and perhaps not to that patient's benefit."</p>
<p>"So it's important," he added, "for a physician to discuss with patients all the options, such as the availability of generics at a cheaper cost. And for their part, patients should ask their pharmacists as well if a brand name drug is available as a generic."</p>
<p>More information</p>
<p>There's more on generic drugs at the <a href="http://www.fda.gov/cder/ogd/">U.S. Food and Drug Administration</a>.</p>
<p>SOURCES: David P. Miller, M.D., internal medicine physician, Wake Forest University Baptist Medical Center, Winston-Salem, N.C.; Reginald Frye, Ph.D., Pharm.D., associate professor, department of pharmacy practice, University of Florida College of Pharmacy, Gainesville; Sept. 5, 2008, news release, Pharmaceutical Research and Manufacturers of America; September 2008, <em>Southern Medical Journal </em></p>
<p>By Alan Mozes<br />
HealthDay Reporter</p>
<p>Last Updated: Sept. 05, 2008</p>
<p>Copyright © 2008 <a href="http://www.healthday.com/">ScoutNews, LLC</a>. All rights reserved.</p>
<div class="dotSepHr">
<hr /></div>
<p><strong>Related Links:</strong></p>
<div class="seeAll"><a href="http://pokedandprodded.health.com/2008/02/28/navigating-the/">Navigating the Prescription Drug Insurance Bureaucracy</a></div>
<div class="seeAll"><a href="http://living.health.com/2008/08/15/medicare-prescription-drug/">Medicare Prescription Drug Premiums to Rise in 09</a></div>
<div class="seeAll"><a href="http://living.health.com/2008/04/22/stay-healthy-for-way-less/">Stay Healthy for Way Less</a></div>
<div class="seeAll"><a href="http://www.health.com/health/condition-article/0,,20189832,00.html">5 Questions to Ask Your Doctor About Prescription Drugs</a></div>
<div class="seeAll">
<div class="dotSepHr">
<hr /></div>
<p><img class="alignleft" style="float:left;" src="http://img2.timeinc.net/health/images/healthy-living/healthnews/HEALTHDAY_Web_XSmall.jpg" alt="" width="118" height="46" /></div>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Relatos tragicómicos de un moderador de foro de programación - Capítulo 0x01]]></title>
<link>http://mundogris.wordpress.com/?p=232</link>
<pubDate>Mon, 01 Sep 2008 00:02:46 +0000</pubDate>
<dc:creator>elhombregris</dc:creator>
<guid>http://mundogris.fr.wordpress.com/2008/08/31/relatos-tragicomicos-de-un-moderador-de-foro-de-programacion-capitulo-0x01/</guid>
<description><![CDATA[¿Para qué escribir algo de cero si se puede copiar y pegar algo ya escrito? Una de las máximas de]]></description>
<content:encoded><![CDATA[<p>¿Para qué escribir algo de cero si se puede copiar y pegar algo ya escrito? Una de las máximas de la "programación" aplicada a esto del "blaaahg".</p>
<p>Moderar un foro de programación no es fácil, puedo decirlo por experiencia, pero tampoco es agotador. Los programadores somos gente difícil y poco tolerante hacia los "users", o sea, esa gente que usa la tecnología sin molestarse lo suficiente en comprenderla o por lo menos respetar su complejidad (y dejar a los que se dedican a ello preocuparse por los problemas mayores).</p>
<p>En fin, aquí va un pequeño relato de lo que acontece en los oscuros pasillos de internet, donde se trama la conquista del ciberespacio, un bit a la vez.</p>
<p><!--more--><br />
Dejarse llevar por la corriente lejos del tema de discusión es algo usual. <a href="http://foros.3dgames.com.ar/programacion.97/477277.protocolo_bittorrent.html#post8587744">Así es como alguien preguntando por el protocolo bittorrent puede llevar discusiones filosóficas con quotes como el siguiente</a>:</p>
<blockquote><p>De la misma manera que si un arbol se cae en el bosque y nadie lo escucha no hace ruido si uno comete un delito y nadie lo ve tampoco es delito, ¿no?</p></blockquote>
<p>Como moderador uno tiene que tratar de contener el tema de discusión en su cauce, aunque muchas veces resulta más interesante ver hasta donde pueda llegar el offtopic. <a href="http://foros.3dgames.com.ar/programacion.97/477277.protocolo_bittorrent.html#post8587744">A veces se me va la mano</a>.</p>
<blockquote><p>Si un árbol cae en el bosque y nadie lo escucha, es noticia en el<br />
diario "El argentino" y la culpa la tienen los gorilas golpistas por<br />
deforestar. Después hablarían de como la redistribución de la riqueza<br />
hubiera salvado al árbol y porque el nacional socialismo es la mejor<br />
forma de gobierno. El diario "Crítica" hubiera titulado: hicieron caer<br />
a un árbol y todos se hicieron los sordos. Crónica hubiera dedicado una<br />
de sus clásicas pantallas rojas y hubiera mostrado material exclusivo<br />
del árbol cayéndose, sin sonido, obviamente, porque nadie lo escucho<br />
caer. Y Tinelli hubiera hecho doble programa del baile del caño, no en<br />
homenaje al árbol caído sino porque tiene que levantar el rating.</p>
<p>Hagansé un favor y dejen al pobre árbol en paz.</p></blockquote>
<p><!--more-->Entre otras cosas interesantes que merecen ser comentadas:</p>
<p><a href="http://foros.3dgames.com.ar/programacion.97/477277.protocolo_bittorrent.html#post8587744">Discutiendo cual sería el algoritmo para encontrar el mejor equipo para El Gran DT</a></p>
<p><a href="http://foros.3dgames.com.ar/programacion.97/477379.java_generics_gotcha.html#post8555020">Discutiendo sobre los pormenores de mezclar legacy code con generics code en Java5</a></p>
<p><a href="http://foros.3dgames.com.ar/programacion.97/477087.optimizar_operaciones_con_sse.html#post8547212">Una interesante discusión sobre optimizaciones</a></p>
<p><a href="http://foros.3dgames.com.ar/programacion.97/478570.java_y_c_c_notaci_n_octal_mala_onda.html#post8585568">Preguntándose quien habra sido el infeliz que penso que la notación octal era una buena idea</a></p>
<p><a href="http://foros.3dgames.com.ar/programacion.97/478629.web_no_cortar_reproductor_mp3_al_navegar_el_sitio.html#post8587259">Tirando ideas de sobre como evitar que un reproductor en un sitio web deje de reproducir al navegar el sitio</a></p>
<p><a href="http://foros.3dgames.com.ar/programacion.97/478724.poo_y_gamedev.html#post8589607">Discutiendo sobre los prejuicios hacia la programación orientada a objetos en el mercado de desarrollo de videojuegos</a></p>
<p><!--more-->Pero lo mas importante es construir una buena y saludable comunidad, ayudando con lo que uno puede, tratando de enseñar tanto lo que uno sabe sobre programación como lo que uno aprendió sobre como tratarse con los demás en un ambiente donde el sarcasmo es inevitable. Un colega agradecido es la mejor recompensa, <a href="http://foros.3dgames.com.ar/programacion.97/479132.correr_internet_explorer_5_en_windows_xp.html#post8599718">aunque a veces se pasen en su entusiasmo</a></p>
<blockquote><p>Muchisimas gracias hombre gris ya van varias veces que me salvas los huevos, cuando tengas orientaciones homosexuales llamame :P</p></blockquote>
<p>I think I'll pass on that....</p>
<p>Y es impagable cuando <a href="http://foros.3dgames.com.ar/programacion.97/449069.php_como_hacer_que_una_variable_tome_una_palabra_desde_otra_variable_que_es_un_n.html#post8615140">dos colegas logran resolver sus diferencias</a> olvidando que la web es un espacio plagado de trolls que creen que el "anonimato" les da la libertad para comportarse como completos idiotas. Me sentiría orgulloso pero no es mi logro.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Adeus, Milo de quinta]]></title>
<link>http://afterthegoldrush.wordpress.com/?p=22</link>
<pubDate>Thu, 28 Aug 2008 17:52:30 +0000</pubDate>
<dc:creator>Amauri Gonzo</dc:creator>
<guid>http://afterthegoldrush.fr.wordpress.com/2008/08/28/adeus-milo-de-quinta/</guid>
<description><![CDATA[Daqui a algumas horas eu estarei subindo a Angélica rumo ao Milo Garage. Não sei o que vai acontec]]></description>
<content:encoded><![CDATA[<p>Daqui a algumas horas eu estarei subindo a Angélica rumo ao Milo Garage. Não sei o que vai acontecer direito -  a <a href="http://www.peligro.com.br/">programação</a> diz que o show está a cargo do projeto-solo do Telepata <a href="http://grandetratado.blogspot.com/">Stan Molina</a> (&#38; o <a href="http://www.myspace.com/departamentoceleste">Departamento Celeste</a>) tocando Pavement. E a programação também diz que vai ser a última festa da Peligro no <a href="http://www.milogarage.com/">Milo Garage</a>.</p>
<p>Eu não estava lá quando a Peligro no Milo inaugurou a casa. Eu acompanhava tudo à distância, em Londrina, informado por amigos como <a href="http://vitrola.blogspot.com/">Ronaldo</a>, <a href="http://www.flickr.com/photos/eugeniovieira/">Eugênio</a> e <a href="http://www.oesquema.com.br/trabalhosujo">Matias</a>. Mas sempre que eu visitava São Paulo dava um jeito de dar um pulo no "Milo de quinta", forma corriqueira de se referir à festa. Foi lá que em julho, um mês antes de me mudar pra SP, eu assisti pela primeira vez um show da <a href="http://www.myspace.com/lulina">Lulina</a>.</p>
<p>A questão que faz com que o fim da Peligro no Milo seja o "fim de uma era" é o senso de comunidade que se formou em torno da festa. Vinda das anárquicas noites na Generics (que, reza a lenda, teve uma festa de despedida de rachar o assoalho literalmente), a Peligro no Milo girava em torno de <a href="http://twitter.com/guipeligro">Gui Barrella</a> (dono do selo/distro que batiza a festa) e <a href="http://bimahead.blogspot.com/">Dago Donato</a>, metade do Centro Cultural Batidão que ficou sozinho quando <a href="http://hihowareyou.wordpress.com/">Eduardo Ramos</a> começou a rodar o mundo no cargo de produtor/ empresário de bandas indies (mas que nunca deixou de voltar ao Milo quando no Brasil).</p>
<p>Esse espírito de comunidade é quase invisível, é intangível e espontâneo. Quando eu saí de Londrina, me senti um estrangeiro no meu próprio país. Se lá eu conseguia ir ao Valentino ou ao Potiguá sozinho e sem nenhum planejamento e ainda assim encontrar pessoas, fazer presepadas, me divetir e beber, em São Paulo eu só me sentia deslocado, quase inconveniente.</p>
<p>Mas o Milo (que a partir de agora aparece neste texto como sinônimo da festa da Peligro) tornou-se a minha segunda casa, antes mesmo de eu me mudar para Higienópolis, a duas quadras do bar. Foi no Milo que fiz e reencontrei grandes amigos, e lá, por muito tempo, era o único lugar para o qual eu iria sem nenhuma companhia.</p>
<p>Muitas vezes eu não estive nos melhores momentos do Milo, muito por não morar aqui antes de 2006. Eu não vi a <a href="http://magoadecaboclo.wordpress.com/">Kátia</a> (que eu conheci numa reunião pré-Milo na casa do Ronaldo e da Gê) discotecar o samba-enredo da Viradouro de 96. Eu não estava lá quando o <a href="http://uk.youtube.com/user/redufit">Palugan</a> gravou a apresentação do <a href="http://www.myspace.com/canseidesersexy">CSS</a>. Eu não estava lá no show do <a href="http://tramavirtual.uol.com.br/moving_stairs">Moving Stairs</a>, banda que tinha dois terços da Folk This Town. Eu não vi o Diplo discotecar lá sob o pseudônimo de Wesley Pentz (na verdade o nome "civil"dele).</p>
<p><span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/AkZwgSRJKUU'></param><param name='wmode' value='transparent'></param><embed src='http://www.youtube.com/v/AkZwgSRJKUU&rel=0' type='application/x-shockwave-flash' wmode='transparent' width='425' height='350'></embed></object></span></p>
<p>Mas eu vi muita coisa boa no Milo. Vi o <a href="http://www.grenadeband.blogspot.com/">Grenade</a> pela primeira vez fora de Londrina, numa festa lotada. Vi o <a href="http://www.myspace.com/thejamesorrcomplex">James Orr Complex</a>, mal falando português, tocando para uma platéia atônita e plantando na minha cabeça a semente da <a href="http://folkthistown.wordpress.com/">Folk This Town</a>.  Vi o <a href="http://www.myspace.com/macacobong">Macaco Bong</a> num dos shows mais intensos EVER, tocando no melhor palco para <a href="http://albumvirtual.trama.uol.com.br/">artistas pedreiros</a> - o chão. Eu enfrentei fila e VI o show da <a href="http://www.myspace.com/mallumagalhaes">Mallu Magalhães</a>, que a maioria só ouviu. Vi o <a href="http://www.myspace.com/hellma">Elma</a> tocando <a href="http://www.portishead.co.uk/">Portishead</a>, <a href="http://www.myspace.com/ostelepatas">Telepatas</a> tocando <a href="http://www.wilcoworld.net/">Wilco</a>, <a href="http://lulina.blogspot.com">Lulina</a> tocando <a href="http://en.wikipedia.org/wiki/The_Velvet_Underground">Velvet</a>. Vi o Ronex e seu <a href="http://profile.myspace.com/index.cfm?fuseaction=user.viewprofile&#38;friendid=375704322">Royale</a> e ajudei o Palugan e a Susan na "iluminação" - e ainda carreguei o Ronex no colo no fim do show. Discotequei duas vezes, uma delas no meu aniversário. Ouvi o Dago discotecar "<a href="http://www.eltonography.com/songs/tiny_dancer.html">Tiny Dancer</a>", vi ele fazer um set indie/soul/rap de não deixar ninguém ir embora, passei horas na "cabine do DJ" só sacando o som que o Barba ia colocar. Ouvi o Eugênio e o Breno num duelo grunge. Fechei o bar, e também saí cedo demais. Perdi banda para ficar conversando no quintal e já dancei até as pernas ficarem doendo no dia seguinte. Tive uma revelação espiritual patrocinada pelo Massari. Vi o Plato Dvorak e vi o Walverdes tocando para quase ninguém. Aliás, eu estava lá no PIOR dia do Milo, apresentação de um tal de Bernhard Ghal. Não perguntem muito, mas foi horrível mesmo.</p>
<p><a href="http://www.flickr.com/photos/eugeniovieira/231275467/in/set-72157603737231701/"><img class="alignnone size-full wp-image-27" src="http://afterthegoldrush.wordpress.com/files/2008/08/royale_milo.jpg" alt="" width="400" height="270" /></a></p>
<p>Essa lista não é só minha - todos que consideravam-se parte da comunidade Peligro devem ter a sua. E cada uma dessas listas é a verdadeira história do Milo, pelo menos o Milo que me interessava de verdade.</p>
<p>E claro que a festa não morre, nem morre o bar. O Milo vai achar algo para as suas quintas, e a Peligro vai criar sua própria casa, a <a href="http://en.wikipedia.org/wiki/Neu!">Neu</a> ("novo" em alemão e nome de uma das bands mais influentes do krautrock).</p>
<p>E vai ser massa, porque o que vai prevalecer, muito além da geografia, é esse senso de comunidade - uma das coisas mais importantes da e para a boa música. É só pensar na Rough Trade do começo, é só pensar no Our Band Could Be Your Life. E o melhor e mais importante dessa turma é que a comunidade é receptiva, e recebe o novo, seja um indivíduo ou um novo gênero musical, de peito e braços abertos.</p>
<p>Por isso que eu não estou triste. Termina uma fase na vida de muita gente, uma nova fase se delineia no horizonte. Quando eu colocar minha camiseta do Sonic Youth, minha camisa de flanela xadrez e o meu all-star de flames, quando eu subir a Angélica e chegar lá, cumprimentar o segurança, ir comprar minha Skol de meio litro, eu não estarei triste. Eu vou estar feliz, celebrando ao lado dos meus amigos. Porque é o fim do Milo como o conhecemos. E eu me sinto bem.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Meta-Programming with Scala Part III: Partial function application]]></title>
<link>http://michid.wordpress.com/?p=71</link>
<pubDate>Wed, 27 Aug 2008 22:35:06 +0000</pubDate>
<dc:creator>michid</dc:creator>
<guid>http://michid.fr.wordpress.com/2008/08/27/meta-programming-with-scala-part-iii-partial-function-application/</guid>
<description><![CDATA[
In my previous post about Meta-Programming with Scala I suspected that there was no way to express ]]></description>
<content:encoded><![CDATA[<p>
In my <a href="http://michid.wordpress.com/2008/07/30/meta-programming-with-scala-part-ii-multiplication/">previous post</a> about <a href="http://en.wikipedia.org/wiki/Metaprogramming">Meta-Programming</a> with <a href="http://www.scala-lang.org/">Scala</a> I suspected that there was no way to express partial function application in Scala's type system. However <a href="http://matt.immute.net/">Matt Hellige</a> proofed me wrong in his <a href="http://michid.wordpress.com/2008/07/30/meta-programming-with-scala-part-ii-multiplication/#comment-69">comment</a>.
</p>
<p>
His solution uses a <a href="http://www.scala-lang.org/node/126">trait</a> for partially applying a function to some of its arguments. An <a href="http://www.scala-lang.org/node/105">abstract type</a> exposed by the trait represents the resulting function which takes the remaining arguments.
</p>
<p>[sourcecode language='java']<br />
object Partial {<br />
  // Partial application of f2 to x<br />
  trait papply[f2[_, _], x] {<br />
    type f1[y] = f2[x, y]<br />
  }</p>
<p>  // apply f to x<br />
  type apply[f[_], x] = f[x]</p>
<p>  trait X<br />
  trait Y<br />
  trait F[A1, A2]</p>
<p>  // Test whether applying the partial application of<br />
  // F to X to Y equals in the type F[X, Y]<br />
  case class Equals[A >: B <: B, B]<br />
  Equals[apply[papply[F, X]#f1, Y], F[X, Y]]<br />
}<br />
[/sourcecode]</p>
<p>
Having this solved we can define a type which encodes <a href="http://michid.wordpress.com/2008/07/30/meta-programming-with-scala-part-ii-multiplication/">multiplication on the Church Numerals</a>.
</p>
<p>[sourcecode language='java']<br />
    trait curry[n[_[_], _], s[_]] {<br />
      type f[z] = n[s, z]<br />
    }</p>
<p>    // Multiplication for this encoding<br />
    type mult[m[_[_], _], n[_[_], _], s[_], z] = m[curry[n, s]#f, z]<br />
[/sourcecode]</p>
<p>
A full working example is available from my <a href="http://michid.wordpress.com/code/meta-programming-with-scala-multiplication/">code page</a>. Note, the code takes forever (i.e. some minutes) to compile. Matt also noted an <a href="http://www.nabble.com/compiler-weirdness-with-crazy-types-td18781474.html">issue with squares</a>. With my version of the compiler (Ecipse plugin 2.7.2.r15874-b20080821120313) the issue does not show up however.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Cereal Addict Goes Generic]]></title>
<link>http://pennybuck.wordpress.com/?p=39</link>
<pubDate>Sun, 24 Aug 2008 18:23:15 +0000</pubDate>
<dc:creator>Penny and Buck</dc:creator>
<guid>http://pennybuck.fr.wordpress.com/2008/08/24/cereal-addict-goes-generic/</guid>
<description><![CDATA[

 

Faux Frosted Mini Wheats

Have you ever tried generic foods? It&#8217;s amazing that we had n]]></description>
<content:encoded><![CDATA[<div class="mceTemp">
<div class="mceTemp mceIEcenter" style="text-align:left;">
<div class="mceTemp mceIEcenter"> </div>
</div>
[caption id="attachment_44" align="aligncenter" width="300" caption="Faux Frosted Mini Wheats"]<img class="size-medium wp-image-44" src="http://pennybuck.wordpress.com/files/2008/08/2008-08-24-cereal-final1.png?w=300" alt="Faux Frosted Mini Wheats" width="300" height="218" />[/caption]
</div>
<p style="text-align:left;">Have you ever tried generic foods? It's amazing that we had never tried them. In fact, we never even <em>thought</em> about them. It was automatic to buy Kellogg's, Smuckers, Tostitos, etc. But times they are a-changin' and we decided to try some generics at Walmart.</p>
<p>Our only negative experiences have been with generic cheeses - specifically Great Value colby and Great Value shredded cheddar. Both were flavorless. We threw them away long before finishing them. We want to reduce our costs, but in doing so we consider <em>value</em>. Flavorless cheese costs less but has no value to us. So we're sticking with Kraft and Land-O-Lakes. Otherwise, we've been happy with all generics that we've tried - when it comes to both quality and price.</p>
<p>Which generic products do we like so far?</p>
<p style="padding-left:30px;"><span style="color:#008000;"><strong>Great Value Sour Cream.</strong> It's just like the name brands. No difference in appearance, taste or texture.</span></p>
<p style="padding-left:30px;"><span style="color:#008000;"><strong>Great Value Strawberry Preserves.</strong> I was raised on Smuckers and never bought anything else. GV has a different consistency, but the color and flavor are good. Once it's smooshed between bread and peanut butter, or spread onto toast, any difference in consistency is no longer noticeable.</span></p>
<p style="padding-left:30px;"><span style="color:#008000;"><strong>Sam's Choice Salsa.</strong> It'd be difficult to screw up salsa, so we had high hopes for this. GV did it right. Good texture, color and flavor. Not too chunky or too runny. We'll definitely be buying this again.</span></p>
<p>Now for the true test... generic cereal!</p>
<p style="padding-left:30px;"><strong><a href="http://www.malt-o-meal.com/pages/products/malt-o-meal-spooners.php?cereal=20&#38;title=Spooners" target="_blank"><span style="color:#008000;">Malt-O-Meal</span></a><span style="color:#008000;"> "</span><span style="color:#008000;">Frosted Mini Spooners".</span></strong><span style="color:#008000;"> These are the generic equivalent of Frosted Mini Wheats. Now, I'm a cereal fanatic. I adore it. It's the perfect meal or snack, any time of day. If I could live on cereal, I would. And one of my favorite cereals is Frosted Mini Wheats. I approached Frosted Mini Spooners with caution, ready to take one for the team, you know? Surpringly, I really like them! They're somewhat less sweet than the name brand, but what I like about the original is the texture, which is characterized by the sugar/wheat relationship and ratio. All of that remains in the generic and I'm completely satisfied with the product.</span></p>
[caption id="attachment_47" align="aligncenter" width="234" caption="Now I can feed my cereal habit for less."]<img class="size-full wp-image-47   " src="http://pennybuck.wordpress.com/files/2008/08/2008-08-24-bag-o-cereal-resized.png" alt="I'm so delicious!" width="234" height="350" />[/caption]
<p>We expect to find bargains and good value with generics in the long run. Maybe we're terribly late getting onto the generics train, but better late than never.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Easily Create DataTables For Unit Tests]]></title>
<link>http://jopinblog.wordpress.com/?p=89</link>
<pubDate>Fri, 22 Aug 2008 15:37:19 +0000</pubDate>
<dc:creator>jopincar</dc:creator>
<guid>http://jopinblog.fr.wordpress.com/2008/08/22/easily-create-datatables-for-unit-tests/</guid>
<description><![CDATA[Ideally, you have a data access layer that only returns domain objects or data transfer objects.  Th]]></description>
<content:encoded><![CDATA[<p>Ideally, you have a data access layer that only returns domain objects or data transfer objects.  The key is real, strongly-typed <strong>objects</strong>.  One of the many reasons for this is to make unit testing easier.  Unfortunately, sometimes you are stuck working with code that uses datatables.  I've recently written a function that takes most of the pain out of creating datatables for unit testing.  This function and the code that calls it takes advantage of several new c# features: lamda expressions, object initializers, list initializers, and auto-implemented properties.  It also uses generics and reflection.</p>
<p>The first thing that stinks about creating datatables from scratch is that you have to manually define the columns which is tedious.  The second thing that stinks is that you can only add rows to the datatable using an object array which means you have to count commas to keep track of which column you are populating.  Or you have to do something awkward like obj[datatable.Columns["FieldName"].Ordinal] = "somevalue".  To get around this, the first step is to define the structure of our rows by creating a simple class, EG:</p>
<p>[sourcecode language='csharp']<br />
public class Person<br />
{<br />
	public string LastName { get; set; }<br />
	public string FirstName { get; set; }<br />
	public DateTime DateOfBirth { get; set; }<br />
	public decimal Salary { get; set; }<br />
}<br />
[/sourcecode]</p>
<p>Now we can call the method with a very convenient syntax that capitalizes on object and list initializers:</p>
<p>[sourcecode language='csharp']<br />
public DataTable GetPeople()<br />
{<br />
	return ListToTable(new List<Person> {<br />
		new Person {<br />
			LastName = "Opincar",<br />
			FirstName = "John",<br />
			DateOfBirth = new DateTime(1901, 1, 1),<br />
			Salary = 250000.00M<br />
		},<br />
		new Person {<br />
			LastName = "Lincoln",<br />
			FirstName = "Abe",<br />
			DateOfBirth = new DateTime(1801, 1, 15),<br />
			Salary = 1000.00M<br />
		}<br />
	});<br />
}<br />
[/sourcecode]</p>
<p>If you've ever manually populated datatables you can really appreciate what a huge improvement this is.  </p>
<p>Finally, we discuss the method itself.  Using reflection, we can leverage the type information stored in Person to create our datatable columns in a generic method that takes a List as input and returns a datatable:</p>
<p>[sourcecode language='csharp']<br />
public DataTable ListToTable<T>(List<T> rows)<br />
{<br />
	var dt = new DataTable();<br />
	var props = typeof(T).GetProperties();<br />
	Array.ForEach(props, p => dt.Columns.Add(p.Name, p.PropertyType));<br />
	foreach ( var r in rows )<br />
	{<br />
		object[] vals = new object[props.Length];<br />
		for (int idx = 0; idx < vals.Length; idx++)<br />
		{<br />
			vals[idx] = props[idx].GetValue(r, null);<br />
		}<br />
		dt.Rows.Add(vals);<br />
	}<br />
	return dt;<br />
}<br />
[/sourcecode]</p>
<p>I hope you find this method as useful as I have.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Cast a generic List. C# and VB.NET]]></title>
<link>http://rasor.wordpress.com/?p=88</link>
<pubDate>Tue, 19 Aug 2008 11:01:49 +0000</pubDate>
<dc:creator>rasor</dc:creator>
<guid>http://rasor.fr.wordpress.com/2008/08/19/cast-a-generic-list-c/</guid>
<description><![CDATA[Cast a derived list to a base list gives a compile error:
Cannot implicitly convert type &#8216;Syst]]></description>
<content:encoded><![CDATA[<p>Cast a derived list to a base list gives a compile error:<br />
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List'<!--more--></p>
<p>Note that this example is a .NET3.5 example due to the lazy implementation of the property</p>
<p>[sourcecode language='csharp']<br />
    class Program<br />
    {<br />
        static void Main(string[] args)<br />
        {<br />
            List<MyDerivCls> derivCls = new List<MyDerivCls>();<br />
            derivCls.Add(new MyDerivCls("Hello World1"));<br />
            derivCls.Add(new MyDerivCls("Hello World2"));</p>
<p>            //Now I wan't to cast List<MyDerivCls> to List<IMyBase>, but that gives a compile error:<br />
            //Cannot implicitly convert type 'System.Collections.Generic.List<ConsoleListDownCast.MyDerivCls>' to 'System.Collections.Generic.List<ConsoleListDownCast.IMyBase>'<br />
            //List<IMyBase> baseList = derivCls;</p>
<p>            //Instead a helper function helps us out:<br />
            List<IMyBase> baseList = MyDerivCls.ToListOfBase(derivCls);</p>
<p>            IMyBase baseObj = baseList[0];<br />
            string myStr = baseObj.MyProperty;<br />
            Console.WriteLine(myStr); //"Hello World1"<br />
        }<br />
    }</p>
<p>    interface IMyBase {<br />
        string MyProperty { get; set; }<br />
    }</p>
<p>    class MyDerivCls: IMyBase<br />
    {<br />
        public MyDerivCls(string InitValue) {<br />
            MyProperty = InitValue;<br />
        }</p>
<p>        public string MyProperty { get; set; }</p>
<p>        /// <summary><br />
        /// Just return the object unchanged, since it can be down casted to IMyBase directly<br />
        /// </summary><br />
        ///</p>
<param name="fromO"></param>
        /// <returns></returns><br />
        private static IMyBase ToBase(MyDerivCls fromO){<br />
            return fromO;<br />
        }</p>
<p>        /// <summary><br />
        /// You can cast MyClass to IMyCommon, but can't when they are in a list.<br />
        /// That's why you must use a converter func<br />
        /// </summary><br />
        ///</p>
<param name="MyList"></param>
        /// <returns></returns><br />
        public static List<IMyBase> ToListOfBase(List<MyDerivCls> MyList) {<br />
            Converter<MyDerivCls, IMyBase> listDownConverter = new Converter<MyDerivCls, IMyBase>(MyDerivCls.ToBase);<br />
            //Cast the list using a converter function<br />
            List<IMyBase> csvList1 = MyList.ConvertAll<IMyBase>(listDownConverter);<br />
            return csvList1;<br />
        }<br />
    }<br />
[/sourcecode]</p>
<p>Note: The IMyBase interface could just as well have been a base class instead in this example.</p>
<p>And in VB.NET:</p>
<p>[sourcecode language='vb']<br />
Module Module1<br />
    Sub Main()<br />
        Dim derivCls As New List(Of MyDerivCls)<br />
        derivCls.Add(New MyDerivCls("Hello World1"))<br />
        derivCls.Add(New MyDerivCls("Hello World2"))</p>
<p>        'Now I wan't to cast List<MyDerivCls> to List<IMyBase>, but that gives a compile error:<br />
        'Cannot implicitly convert type 'System.Collections.Generic.List<ConsoleListDownCast.MyDerivCls>' to 'System.Collections.Generic.List<ConsoleListDownCast.IMyBase>'<br />
        'Dim baseList As List(Of IMyBase) = derivCls</p>
<p>        'Instead a helper function helps us out:<br />
        Dim baseList As List(Of IMyBase) = MyDerivCls.ToListOfBase(derivCls)</p>
<p>        Dim baseObj As IMyBase = baseList(0)<br />
        Dim myStr As String = baseObj.MyProperty<br />
        Console.WriteLine(myStr) '"Hello World1"<br />
    End Sub<br />
End Module</p>
<p>Public Interface IMyBase<br />
    Property MyProperty() As String<br />
End Interface</p>
<p>Public Class MyDerivCls<br />
    Implements IMyBase</p>
<p>    Public Sub New(ByVal InitValue As String)<br />
        MyProperty = InitValue<br />
    End Sub</p>
<p>    Private _myProperty As String<br />
    Public Property MyProperty() As String Implements IMyBase.MyProperty<br />
        Get<br />
            Return _myProperty<br />
        End Get<br />
        Set(ByVal value As String)<br />
            _myProperty = value<br />
        End Set<br />
    End Property</p>
<p>    ''' <summary><br />
    ''' Just return the object unchanged, since it can be down casted to IMyBase directly<br />
    ''' </summary><br />
    '''</p>
<param name="fromO"></param>
    ''' <returns></returns><br />
    ''' <remarks></remarks><br />
    Private Shared Function ToBase(ByVal fromO As MyDerivCls) As IMyBase<br />
        Return fromO<br />
    End Function</p>
<p>    ''' <summary><br />
    ''' You can cast MyClass to IMyCommon, but can't when they are in a list.<br />
    ''' That's why you must use a converter func<br />
    ''' </summary><br />
    '''</p>
<param name="MyList"></param>
    ''' <returns></returns><br />
    ''' <remarks></remarks><br />
    Public Shared Function ToListOfBase(ByRef MyList As List(Of MyDerivCls)) As List(Of IMyBase)<br />
        Dim listDownConverter As New Converter(Of MyDerivCls, IMyBase)(AddressOf MyDerivCls.ToBase)<br />
        'Cast the list using a converter function<br />
        Dim myList1 As List(Of IMyBase) = MyList.ConvertAll(Of IMyBase)(listDownConverter)<br />
        Return myList1<br />
    End Function<br />
End Class<br />
[/sourcecode]</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Type-safe Builder Pattern in Java]]></title>
<link>http://michid.wordpress.com/?p=64</link>
<pubDate>Wed, 13 Aug 2008 21:00:26 +0000</pubDate>
<dc:creator>michid</dc:creator>
<guid>http://michid.fr.wordpress.com/2008/08/13/type-safe-builder-pattern-in-java/</guid>
<description><![CDATA[In this post I deviate a bit from the topic of my recent posts about Meta-Programming with Scala. I ]]></description>
<content:encoded><![CDATA[<p>In this post I deviate a bit from the topic of my <a href="http://michid.wordpress.com/2008/04/18/meta-programming-with-scala-part-i-addition/">recent</a> <a href="http://michid.wordpress.com/2008/07/30/meta-programming-with-scala-part-ii-multiplication/">posts</a> about Meta-Programming with <a href="http://www.scala-lang.org/">Scala</a>. I will have more to say about the latter topic in upcoming posts however. </p>
<p>Recently I read this rather fascinating post about a <a href="http://blog.rafaelferreira.net/2008/07/type-safe-builder-pattern-in-scala.html">Type-safe Builder Pattern in Scala</a>. When <a href="http://www.javaspecialists.eu/index.jsp">Heinz Kabutz</a> mentioned the <a href="http://en.wikipedia.org/wiki/Builder_pattern">builder pattern</a> in his <a href="http://www.javaspecialists.eu/archive/Issue163.html">latest issues</a> of the <a href="http://www.javaspecialists.eu/archive/archive.jsp">The Java Specialists’ Newsletter</a> I decided to try to come up with a type safe version for Java. </p>
<p>What I finally came up with is not strictly a builder but something I rather call an initializer. The initializer contains the initial state required by the target object. The state is accumulated within the initializer. Only when the state is complete can it be passed to the targets object's constructor. Java's type system prevents passing a initializer with an incomplete state to the target class's constructor.</p>
<p>[sourcecode language='java']<br />
public class Foo {<br />
  private final int a;<br />
  private final int b;</p>
<p>  public Foo(Initializer<TRUE, TRUE> initializer) {<br />
    this(initializer.a, initializer.b);<br />
  }</p>
<p>  private Foo(int a, int b) {<br />
    super();<br />
    this.a = a;<br />
    this.b = b;<br />
  }</p>
<p>  public String toString() {<br />
    return "a = " + a + ", b = " + b;<br />
  }</p>
<p>  public static class Initializer<HA, HB> {<br />
    private int a;<br />
    private int b;</p>
<p>    private Initializer() {<br />
      super();<br />
    }</p>
<p>    private Initializer(int a, int b) {<br />
      super();<br />
      this.a = a;<br />
      this.b = b;<br />
    }</p>
<p>    public static Initializer<FALSE, FALSE>create() {<br />
      return new Initializer<FALSE, FALSE>();<br />
    }</p>
<p>    public Initializer<TRUE, HB> setA(int a) {<br />
      this.a = a;<br />
      return new Initializer<TRUE, HB>(a, this.b);<br />
    }</p>
<p>    public Initializer<HA, TRUE> setB(int b) {<br />
      this.b = b;<br />
      return new Initializer<HA, TRUE>(this.a, b);<br />
    }</p>
<p>    static abstract class TRUE {}<br />
    static abstract class FALSE {}<br />
  }</p>
<p>}<br />
[/sourcecode]</p>
<p>The basic technique is the same as for the <a href="http://blog.rafaelferreira.net/2008/07/type-safe-builder-pattern-in-scala.html">Type-safe Builder Pattern in Scala</a>: the phantom types <em>TRUE</em> and <em>FALSE</em> are used to keep track of the state. Only a complete state will result in a <em>Initialiter</em> instance which subsequently can be passed to <em>Foo</em>'s constructor.</p>
<p>Here is how this is used:</p>
<p>[sourcecode language='java']<br />
public class Main {<br />
  public static void main(String[] args) {<br />
    Initializer<?, ?> initializer = Initializer.create();</p>
<p>    // Foo.create(initializer);           // won't compile<br />
    // Foo.create(initializer.setB(1));   // won't compile<br />
    // Foo.create(initializer.setA(1));   // won't compile</p>
<p>    Foo foo = new Foo(initializer.setA(1).setB(2));<br />
    System.out.println(foo);<br />
  }<br />
}<br />
[/sourcecode]</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Define a generic method (VB.NET)]]></title>
<link>http://rasor.wordpress.com/?p=80</link>
<pubDate>Wed, 13 Aug 2008 06:22:52 +0000</pubDate>
<dc:creator>rasor</dc:creator>
<guid>http://rasor.fr.wordpress.com/2008/08/13/define-a-generic-method-vbnet/</guid>
<description><![CDATA[A reminder of how the VB.NET syntax is for defining a generic method.
Just a sample.
The New constra]]></description>
<content:encoded><![CDATA[<p>A reminder of how the VB.NET syntax is for defining a generic method.<br />
Just a sample.<!--more--></p>
<p>The <em>New constraint</em> must be the <span style="text-decoration:underline;">first</span> one, if needed.<br />
The <em>interface constraint</em> is to be able to use properties and methods on the generic type.<br />
It could be a base class also. The base class should then be placed before the interfaces.</p>
<p>[sourcecode language='vb']<br />
Imports System.Collections.Generic 'List(Of</p>
<p>        Public Sub MyGenericSub(Of T As {New, IImplementedByT})(ByRef MyList As List(Of T))<br />
            Dim myObj As New T<br />
            myObj.AMethodOnIImplementedByT()<br />
[/sourcecode]</p>
<p>And some C#:<br />
<a href="http://msdn.microsoft.com/en-us/library/d5x73970.aspx">http://msdn.microsoft.com/en-us/library/d5x73970.aspx</a><br />
The <em>New constraint</em> must be the <span style="text-decoration:underline;">last</span> one, if needed.</p>
<p>[sourcecode language='csharp']<br />
public bool MyMethod<T>(T t) where T : IMyInterface, new() { }<br />
[/sourcecode]</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Lookup with generic List and Dict (VB.NET)]]></title>
<link>http://rasor.wordpress.com/?p=75</link>
<pubDate>Wed, 13 Aug 2008 05:49:41 +0000</pubDate>
<dc:creator>rasor</dc:creator>
<guid>http://rasor.fr.wordpress.com/2008/08/13/lookup/</guid>
<description><![CDATA[When using a Dictionary the key have to be unique. If you want to lookup another property than the k]]></description>
<content:encoded><![CDATA[<p>When using a Dictionary the key have to be unique. If you want to lookup another property than the key, then you can use ToLookup(), if the property is unique.<br />
<a href="http://msdn.microsoft.com/en-us/library/bb549211.aspx" target="_blank">http://msdn.microsoft.com/en-us/library/bb549211.aspx<br />
</a></p>
<p>You could also choose to convert the List to a Dict using ToDictionary()<!--more--></p>
<p>[sourcecode language='vb']<br />
Imports System.Collections.Generic 'List<br />
Imports System.Linq '.NET3.0 extension methods: ToLookup(), ToDictionary()</p>
<p>Public Sub SomeSub()<br />
Dim my1stList As List(Of MyObject) = LoadMyList() 'Get some data</p>
<p>Dim my2ndList As List(Of MyObject)<br />
Dim myDict As Dictionary(Of String, MyObject)<br />
Dim myLookup As ILookup(Of String, MyObject)<br />
Dim myRow As MyObject = Nothing</p>
<p>'Following will crash in runtime if the key field userid on MyObject is not unique</p>
<p>'Example of using lookup with userid as key<br />
myLookup = my1stList.ToLookup(Function(o) o.userid) 'using IEnumerable.ToLookup()<br />
myRow = myLookup.Item("myuserid" )<br />
Console.WriteLine(myRow.someProperty)</p>
<p>'convert the List to a Dict<br />
myDict = my1stList.ToDictionary(Function(o) o.userid, Function(o) o)<br />
'or<br />
myDict = my1stList.ToDictionary(Of MyObject, String)(Function(o) o.userid)<br />
myRow = myDict("myuserid" )<br />
Console.WriteLine(myRow.someProperty)<br />
[/sourcecode]</p>
<p>C#:  </p>
<p>[sourcecode language='csharp']<br />
	myDict = my1stList.ToDictionary(p => p.userid, p => p);<br />
	//or<br />
	myDict = my1stList.ToDictionary<MyObject, string>(p => p.userid);<br />
[/sourcecode]</p>
]]></content:encoded>
</item>

</channel>
</rss>
