<?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>foreach &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/foreach/</link>
	<description>Feed of posts on WordPress.com tagged "foreach"</description>
	<pubDate>Sun, 29 Nov 2009 21:15:14 +0000</pubDate>

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

<item>
<title><![CDATA[Java Recorrer Colecciones [ Collection ] usando for/while Parte 1]]></title>
<link>http://estebanfuentealba.wordpress.com/2009/11/29/java-recorrer-colecciones-collection-usando-forwhile-parte-1/</link>
<pubDate>Sun, 29 Nov 2009 19:18:47 +0000</pubDate>
<dc:creator>estebanfuentealba</dc:creator>
<guid>http://estebanfuentealba.wordpress.com/2009/11/29/java-recorrer-colecciones-collection-usando-forwhile-parte-1/</guid>
<description><![CDATA[Bueno aquí pondré algunas formas de recorrer Colecciones, Primero partiré por Las clases que Impleme]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Bueno aquí pondré algunas formas de recorrer Colecciones, Primero partiré por Las clases que Implementan Collection, son las mas fáciles de recorrer.</p>
<p>Para recorrer ArrayList,Vector,HashSet,TreeSet y todos los List y Set podemos usar lo siguiente:</p>
<p>Primero Crearé una clase y un metodo main que tendrá un ArrayList para poder recorrerlo y mostrar por pantalla lo que tiene dicho ArrayList</p>
<pre class="brush: java;">
/**
 * @(#)Persona.java
 *
 *
 * @author Esteban Fuentealba
 * @version 1.00 2009/11/29
 */

import java.util.ArrayList;
public class Persona {
	private String rut;
	private String nombre;

	public Persona() {}
    public Persona(String rut,String nombre) {
    	this.rut 	= rut;
    	this.nombre = nombre;
    }

    public String getRut() {
    	return this.rut;
    }
    public String getNombre() {
    	return this.nombre;
    }

    public static void main(String[] args) {
    	ArrayList&#60;Persona&#62; lista = new ArrayList&#60;Persona&#62;();
    	lista.add(new Persona(&#34;111-1&#34;,&#34;Juan&#34;));
    	lista.add(new Persona(&#34;222-2&#34;,&#34;Pedro&#34;));
    	lista.add(new Persona(&#34;333-3&#34;,&#34;Luis&#34;));

    }

}
</pre>
<p>Bien , es un ArrayList Genérico de Persona. Ahora veamos la primera forma de recorrer, es parecida cuando recorremos arrays</p>
<h1><strong>Simple For</strong>:</h1>
<pre class="brush: java;">
for(int i=0; i&#60; lista.size(); i++) {
    		System.out.println(lista.get(i));
    	}
</pre>
<p>Es un for , le damos un contador de donde empezará (Desde la posición 0 de la lista), la condición (que se mantenga el ciclo siempre que nuestro contador sea menor al largo de la lista) y que debe hacer cuando cumpla un ciclo (aumentar el contador para ir a la siguiente posición).<br />
Esto nos debe mostrar por pantalla lo siguiente:</p>
<pre class="brush: java;">
Persona@3e25a5
Persona@19821f
Persona@addbf1
</pre>
<p>¿ Por que ? Yo quería que mostrara los datos de la persona =(<br />
Mostró eso porque el programa recorre el arraylist, saca un objeto de la posición que este recorriendo, he imprime el objeto, el objeto es de la Clase Persona por lo que el programa va a ir a esa clase y buscará si esta el método toString() y como no lo encuentra imprimirá el toString() del padre, en este caso el de Object (Todo hereda de Object) que me devuelve El nombre de la Clase &#8220;Persona&#8221; @ &#8220;hashCode&#8221;.<br />
Para solucionar esto le pondré el método (sobrescrito) toString() a la clase Persona, quedará así:</p>
<pre class="brush: java;">
/**
 * @(#)Persona.java
 *
 *
 * @author
 * @version 1.00 2009/11/29
 */

import java.util.ArrayList;
public class Persona {
	private String rut;
	private String nombre;

	public Persona() {}
    public Persona(String rut,String nombre) {
    	this.rut 	= rut;
    	this.nombre = nombre;
    }

    public String getRut() {
    	return this.rut;
    }
    public String getNombre() {
    	return this.nombre;
    }

    public String toString() {
    	return &#34;[Rut: &#34;+this.getRut()+&#34;] [Nombre: &#34;+this.getNombre()+&#34;]&#34;;
    }
    public static void main(String[] args) {
    	ArrayList&#60;Persona&#62; lista = new ArrayList&#60;Persona&#62;();
    	lista.add(new Persona(&#34;111-1&#34;,&#34;Juan&#34;));
    	lista.add(new Persona(&#34;222-2&#34;,&#34;Pedro&#34;));
    	lista.add(new Persona(&#34;333-3&#34;,&#34;Luis&#34;));

    	for(int i=0; i&#60; lista.size(); i++) {
    		System.out.println(lista.get(i));
    	}
    }
}
</pre>
<p>Compilo y corro el programa, la salida muestra por pantalla lo siguiente:</p>
<pre class="brush: java;">
[Rut: 111-1] [Nombre: Juan]
[Rut: 222-2] [Nombre: Pedro]
[Rut: 333-3] [Nombre: Luis]
</pre>
<p>Bien Ahora si mostró lo que queríamos que mostrara.</p>
<h1><strong>Iterator</strong>:</h1>
<p>Otra forma de recorrer el arraylist es usando el metodo iterator() del ArrayList , para entender de mejor forma como funciona iterator() dejo la siguiente imagen:<br />
<a href="http://estebanfuentealba.wordpress.com/files/2009/11/iterator2.png"><img class="aligncenter size-medium wp-image-732" title="iterator" src="http://estebanfuentealba.wordpress.com/files/2009/11/iterator2.png?w=300" alt="" width="300" height="169" /></a><br />
Lo que esta en verde es nuestra lista. Ojo Iterator no tiene índice, pero la mejor forma de entenderlo es imaginandose el indice, es por eso que puse en la imagen.<br />
Lo que hace iterator() es:</p>
<ol>
<li>Poner el iterador al principio de la lista. (Imaginariamente en la posición -1, fuera de la lista)</li>
<li>Luego con el metodo hasNext() pregunta si hay un elemento siguiente.</li>
<li>Si hay un elemento debo sacarlo con el metodo next() y vuelvo a preguntar con el hashNext(), así hasta que no exista ningún elemento siguiente.</li>
</ol>
<p>Lo anterior llevado a código quedaría de la siguiente forma:</p>
<pre class="brush: java;">
Iterator it = lista.iterator();
    	while(it.hasNext()) {
    		System.out.println(it.next());
    	}
</pre>
<p>la salida por pantalla es la siguiente:</p>
<pre class="brush: java;">
[Rut: 111-1] [Nombre: Juan]
[Rut: 222-2] [Nombre: Pedro]
[Rut: 333-3] [Nombre: Luis]
</pre>
<p>Cumple la misma función que la primera forma de recorrer.</p>
<p>&#160;</p>
<h1><strong>Foreach</strong>:</h1>
<p>La siguiente forma de recorrer es con foreach, desde Java 5 que se incluyó el bucle foreach para iterar sobre colecciones de objetos.<br />
La forma de ocuparlo es la siguiente</p>
<pre class="brush: java;">
for(Clase nombre : lista) {
	//...
}
</pre>
<p>Donde &#8220;lista&#8221; es la collection a recorrer,&#8221;Clase&#8221; es de que clase es la &#8220;lista&#8221; y &#8220;nombre&#8221; es un nombre de variable.<br />
Acá llevado al ejemplo de Persona:</p>
<pre class="brush: java;">
for(Persona p : lista) {
    		System.out.println(p);
    	}
</pre>
<p>La salida por pantalla es:</p>
<pre class="brush: java;">
[Rut: 111-1] [Nombre: Juan]
[Rut: 222-2] [Nombre: Pedro]
[Rut: 333-3] [Nombre: Luis]
</pre>
<p>Según yo ,foreach, es la forma mas fácil de recorrer colecciones.</p>
<p>&#160;</p>
<p>Bueno ahí puse tres formas de recorrer una Collection (Set,List,Queue)</p>
<p>Espero que les sirva, en el siguiente post pondré como recorrer Map<br />
Acá les dejo el código con las tres formas,</p>
<pre class="brush: java;">
/**
 * @(#)Persona.java
 *
 *
 * @author
 * @version 1.00 2009/11/29
 */

import java.util.ArrayList;
import java.util.Iterator;
public class Persona {
	private String rut;
	private String nombre;

	public Persona() {}
    public Persona(String rut,String nombre) {
    	this.rut 	= rut;
    	this.nombre = nombre;
    }

    public String getRut() {
    	return this.rut;
    }
    public String getNombre() {
    	return this.nombre;
    }

    public String toString() {
    	return &#34;[Rut: &#34;+this.getRut()+&#34;] [Nombre: &#34;+this.getNombre()+&#34;]&#34;;
    }
    public static void main(String[] args) {
    	ArrayList&#60;Persona&#62; lista = new ArrayList&#60;Persona&#62;();
    	lista.add(new Persona(&#34;111-1&#34;,&#34;Juan&#34;));
    	lista.add(new Persona(&#34;222-2&#34;,&#34;Pedro&#34;));
    	lista.add(new Persona(&#34;333-3&#34;,&#34;Luis&#34;));

    	System.out.println(&#34;Recorrer Collection con simple for:&#34;);
    	for(int i=0; i&#60; lista.size(); i++) {
    		System.out.println(lista.get(i));
    	}
    	System.out.println(&#34;Recorrer Collection con Iterator:&#34;);
    	Iterator it = lista.iterator();
    	while(it.hasNext()) {
    		System.out.println(it.next());
    	}
    	System.out.println(&#34;Recorrer Collection con foreach:&#34;);
    	for(Persona p : lista) {
    		System.out.println(p);
    	}
    }
}
</pre>
<p>Saludos!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Removendo itens de uma List&lt;&gt;]]></title>
<link>http://jpleonidas.wordpress.com/2009/11/27/removendo-itens-de-uma-list/</link>
<pubDate>Fri, 27 Nov 2009 19:43:10 +0000</pubDate>
<dc:creator>jpaulorio</dc:creator>
<guid>http://jpleonidas.wordpress.com/2009/11/27/removendo-itens-de-uma-list/</guid>
<description><![CDATA[Olá, estava dando uma vasculhada em uns emails antigos e achei uma mensagem que havia enviado para u]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Olá,</p>
<p>estava dando uma vasculhada em uns emails antigos e achei uma mensagem que havia enviado para uma lista de discussão de dot.net sobre como remover itens de uma coleção do tipo List&#60;T&#62;.</p>
<p>Se tentarmos remover um item de uma lista enquanto estivermos iterando sobre a mesma utilizando o foreach, uma exceção será lançada, por exemplo:</p>
<p>private List&#60;string&#62; lista;</p>
<p>lista = new List&#60;string&#62;();</p>
<p>lista.Add(&#8220;a&#8221;);</p>
<p>lista.Add(&#8220;b&#8221;);</p>
<p>lista.Add(&#8220;c&#8221;);</p>
<p>foreach (string s in lista)</p>
<p>lista.Remove(s);</p>
<p>O código acima lançará uma exceção pois estamos removendo um item da coleção enquanto estamos iterando sobre a mesma.</p>
<p>Uma alternativa é utilizar o código abaixo que utiliza o método ForEach da classe List&#60;&#62; e o conceito de delegates. Podemos pensar num delegate como sendo um ponteiro de função:</p>
<p>private List&#60;string&#62; lista;</p>
<p>lista = new List&#60;string&#62;();</p>
<p>lista.Add(&#8220;a&#8221;);</p>
<p>lista.Add(&#8220;b&#8221;);</p>
<p>lista.Add(&#8220;c&#8221;);</p>
<p>lista.ForEach(Action);</p>
<p>}</p>
<p>private void Action(string s)</p>
<p>{</p>
<p>if (s.Equals(&#8220;a&#8221;))</p>
<p>lista.Remove(s);</p>
<p>}</p>
<p>É possível utilizar ainda um delegate anônimo, aonde não precisaríamos definir o método Action e o código do mesmo seria inserido inline, mas acho que essa solução prejudica a legibilidade, vejamos:</p>
<p>lista.ForEach(delegate(string s) { if (s.Equals(&#8220;a&#8221;)) ls.Remove(s); });</p>
<p>Vale a pena lembrar que ainda existem, pelo menos, duas formas de se conseguir o mesmo objetivo. Uma utilizando goto, que é altamente condenado, mas que nesse caso não vejo tantos problemas:</p>
<p>laco:</p>
<p>for (int i = 0; i &#60; lista.Count; i++)</p>
<p>{</p>
<p>string s = lista[i];</p>
<p>if (s.Equals(&#8220;a&#8221;))</p>
<p>{</p>
<p>lista.Remove(s);</p>
<p>goto laco;</p>
<p>}</p>
<p>}</p>
<p>e outra é utilizando for:</p>
<p>for (int i = 0; i &#60; lista.Count; i++)</p>
<p>{</p>
<p>string s = lista[i];</p>
<p>if (s.Equals(&#8220;a&#8221;))</p>
<p>{</p>
<p>lista.Remove(s);</p>
<p>i&#8211;;</p>
<p>}</p>
<p>}</p>
<p>É isso aí. Só quis mais uma vez compartilhar conhecimento. Gostaria de saber de alguém de Java se essas alternativas também se aplicam nessa linguagem.</p>
<p>Abraços e até a próxima!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Usando foreach() no PHP]]></title>
<link>http://mamura.wordpress.com/2009/11/12/usando-foreach-no-php/</link>
<pubDate>Thu, 12 Nov 2009 17:06:51 +0000</pubDate>
<dc:creator>mamura</dc:creator>
<guid>http://mamura.wordpress.com/2009/11/12/usando-foreach-no-php/</guid>
<description><![CDATA[A maneira mais fácil de se fazer uma simples interação em um array() no PHP é, sem sombra de dúvidas]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>A maneira mais fácil de se fazer uma simples interação em um <em>array()</em> no PHP é, sem sombra de dúvidas, usando o construtor <em>foreach()</em>. Esse construtor simplesmente percorre um array do inicio ao fim, sem fazer nenhum tratamento de ponteiros ou índices do array.</p>
<p>A grande maioria dos que programam em PHP sabem disso e fazem um grande uso desse construtor nas soluções dos seus problemas, o que muitos não sabem é de alguma peculiaridades do <em>foreach()</em>. Por exemplo, o <em>foreach()</em> trabalha com uma cópia do array em si, o que significa que as alterações feitas no array dentro do loop não são refletidas na interação. Vejam:</p>
<div id="attachment_42" class="wp-caption alignnone" style="width: 237px"><img class="size-full wp-image-42" title="foreach por valor" src="http://mamura.wordpress.com/files/2009/11/foreach1.png" alt="foreach por valor" width="227" height="154" /><p class="wp-caption-text">foreach por valor</p></div>
<p><span style="color:#000080;">* Resultado:  ([0]=&#62;1, [1]=&#62;2, [2]=&#62;3);</span></p>
<p>No PHP5 podemos alterar diretamente o valor do array atribuindo o valor de cada elemento para a variável de interação por referência:</p>
<div id="attachment_43" class="wp-caption alignnone" style="width: 248px"><img class="size-full wp-image-43" title="foreach por referência" src="http://mamura.wordpress.com/files/2009/11/foreach2.png" alt="foreach por referência" width="238" height="148" /><p class="wp-caption-text">foreach por referência</p></div>
<p><span style="color:#000080;">* Resultado:  ([0]=&#62;2, [1]=&#62;3, [2]=&#62;4);</span></p>
<p>Essa técnica pode ser bastante útil, mas se não usada com cautela poderá deixar você acordado e trabalhando por mais algumas horas. Vejam o seguinte exemplo:</p>
<div id="attachment_44" class="wp-caption alignnone" style="width: 302px"><img class="size-full wp-image-44" title="mistério do foreach" src="http://mamura.wordpress.com/files/2009/11/foreach3.png" alt="mistério do foreach" width="292" height="204" /><p class="wp-caption-text">mistério do foreach</p></div>
<p><span style="color:#000080;">* Resultado:  ([0]=&#62;”zero”, [1]=&#62;”um”, [2]=&#62;”um”);</span></p>
<p>Teoricamente, essas interações não deveriam causar mudança alguma no array, mas ao final da execução desse script o array terá o valor: Array ([0]=&#62;”zero”, [1]=&#62;”um”, [2]=&#62;”um”).</p>
<p>Não, isso não é um bug e explicarei como isso acontece. O primeiro foreach não faz absolutamente nada no array, como se é de se esperar, mas ao final da interação a variável $v é uma referência a $a[2]. Assim, quando se inicia o segundo foreach $v é atribuído a cada valor do array, no entanto $v  já é uma referência para $a[2] e, portanto, qualquer valor atribuido a ele será copiado para o último elemento do array $a.</p>
<p>“Ô Mamura, num tô intendendo o_O&#8230;”</p>
<p>Simples:<br />
$v é uma referência para $a[2], logo $a[2] = $v;<br />
No primeiro loop $a[2] = $v = $a[0] = “zero”;<br />
No segundo loop $a[2] = $v = $a[1] = “um”;<br />
No terceiro loop $a[2] = $v = $a[2] = “um”;</p>
<p>Para não termos esse tipo de problema, é só usarmos o unset() para destruir a variável após a interação.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[php foreach untuk memecah variable array]]></title>
<link>http://diazscript.wordpress.com/2009/11/11/php-foreach-untuk-memecah-variable-array/</link>
<pubDate>Wed, 11 Nov 2009 10:23:27 +0000</pubDate>
<dc:creator>diazscript</dc:creator>
<guid>http://diazscript.wordpress.com/2009/11/11/php-foreach-untuk-memecah-variable-array/</guid>
<description><![CDATA[Bingung  jika terkadang memiliki variable array yang sudah terlanjur kita buat, terkadang kita ingin]]></description>
<content:encoded><![CDATA[Bingung  jika terkadang memiliki variable array yang sudah terlanjur kita buat, terkadang kita ingin]]></content:encoded>
</item>
<item>
<title><![CDATA[.NET Challenge &ndash; for or foreach?]]></title>
<link>http://ramanisandeep.wordpress.com/2009/11/02/net-challenge-for-or-foreach/</link>
<pubDate>Mon, 02 Nov 2009 07:20:48 +0000</pubDate>
<dc:creator>ramanisandeep</dc:creator>
<guid>http://ramanisandeep.wordpress.com/2009/11/02/net-challenge-for-or-foreach/</guid>
<description><![CDATA[Question: for should be used instead of foreach to iterate over collections in performance-critical ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><strong>Question:</strong> </p>
<p><strong>for</strong> should be used instead of <strong>foreach</strong> to iterate over collections in performance-critical loops. </p>
<p><strong>Answer:</strong> True </p>
<p align="justify"><strong>foreach</strong> uses an enumerator which can sometimes be slower than the simple iteration of a variable in a for loop. Enumerators, such as those contained in the .NET Framework, have both managed heap and virtual function overhead. The amount of overhead depends on the collection used and the version of the .NET Framework. As always, the best way to determine the overhead between techniques is to run a performance test and compare.</p>
<p align="justify">To illustrate the performance impact, 10 strings were concatenated 100 times using the techniques outlined below.&#160; </p>
<p align="justify">Running against .NET Framework 3.5 using an ArrayList, a generic List and a LinkedList with 5,000 strings, the following results were obtained using Ants Performance Profiler 5: </p>
<table cellspacing="0" cellpadding="2" width="400" border="0">
<tbody>
<tr>
<td valign="top" width="133"><strong>Wall Clock Time (ms)</strong></td>
<td valign="top" width="133"><strong>Loop</strong></td>
<td valign="top" width="133"><strong>Structure (5,000 strings)</strong></td>
</tr>
<tr>
<td valign="top" width="133">25.003</td>
<td valign="top" width="133">for</td>
<td valign="top" width="133">LinkedList&#60;string&#62;</td>
</tr>
<tr>
<td valign="top" width="133">0.037</td>
<td valign="top" width="133">foreach</td>
<td valign="top" width="133">LinkedList&#60;string&#62;</td>
</tr>
<tr>
<td valign="top" width="133">0.039</td>
<td valign="top" width="133">for</td>
<td valign="top" width="133">ArrayList</td>
</tr>
<tr>
<td valign="top" width="133">0.053</td>
<td valign="top" width="133">foreach</td>
<td valign="top" width="133">ArrayList</td>
</tr>
<tr>
<td valign="top" width="133">0.019</td>
<td valign="top" width="133">for</td>
<td valign="top" width="133">List&#60;string&#62;</td>
</tr>
<tr>
<td valign="top" width="133">0.034</td>
<td valign="top" width="133">foreach</td>
<td valign="top" width="133">List&#60;string&#62;</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<p>Except for the LinkedList, the for loop is faster. </p>
<p align="justify">The for loop is thought by many developers to be less readable and maintainable than foreach. Using foreach also makes it possible to iterate across anything that&#8217;s IEnumerable, allowing for the creation of more general algorithms and the use of &#34;yield&#34; to build custom collections. </p>
<p>It is normally good practice to code for clarity rather than micro-optimization. </p>
<p>Reference : <a href="http://www.red-gate.com/products/ants_performance_profiler/dotnet_challenge_question_1.htm?utm_source=simpletalk&#38;utm_medium=email&#38;utm_content=dotnetchallengeq1&#38;utm_campaign=antsperformanceprofiler" target="_blank">Rad-gate</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Como acessar um array smarty com foreach]]></title>
<link>http://dilbertorosa.wordpress.com/2009/10/22/como-acessar-um-array-smarty-com-foreach/</link>
<pubDate>Thu, 22 Oct 2009 19:21:01 +0000</pubDate>
<dc:creator>dilbertorosa</dc:creator>
<guid>http://dilbertorosa.wordpress.com/2009/10/22/como-acessar-um-array-smarty-com-foreach/</guid>
<description><![CDATA[Neste post tratarei de um assunto básico e extremamente útil com smarty: Foreach em array! Vamos def]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Neste post tratarei de um assunto básico e extremamente útil com <em>smarty</em>: <em>Foreach </em>em <em>array</em>!</p>
<p>Vamos definir inicialmente o nome dos atributos pra você se familiarizar com o assunto:</p>
<p><em>from </em>- Neste ítem você define o array que está sendo acessado;<br />
<em>item </em>- É o nome da variável onde está o elemento atual dentro do loop;<br />
<em>key </em>- E o nome da variável que contém a chave do array dentro do ítem atual no loop;<br />
<em>name </em>- Este ítem é o nome do looping foreach para acessar as propriedades do foreach;</p>
<p>vamos à um exemplo simples?<br />
<strong><br />
1) No PHP definimos o array com o conteúdo que está sendo passado via smarty para um template qualquer:</strong></p>
<p>$arr = array(100, 200, 300, 400);<br />
$smarty-&#62;assign(&#8216;arrayConteudo&#8217;, $arr);</p>
<p><strong> 2) Agora vamos para o Template. Aqui, conforme o assign do smarty, criamos uma variável arrayConteudo que será acessada no template:</strong></p>
<p>{foreach from=$arrayConteudo item=conteudo}<br />
{$conteudo}<br />
{foreach}</p>
<p>Pronto! Teremos a seguinte saída html:</p>
<ul>
<li>100</li>
<li>200</li>
<li>300</li>
<li>400</li>
</ul>
<p>Mas se eu quiser acessar o <em>índice </em>do array? Simples! Mudamos o foreach da seguinte forma:<br />
{foreach from=$arrayConteudo key=chave item=conteudo}<br />
{$chave}: {$conteudo}<br />
{foreach}</p>
<p>Saída HTML:</p>
<ul>
<li>0: 100</li>
<li>1: 200</li>
<li>2: 300</li>
<li>3: 400</li>
</ul>
<p>É isso! Abraço!</p>
<p>Fonte:<br />
<a href="http://www.smarty.net/manual/en/language.function.foreach.php">smarty.net</a></p>
<p>Tradução e Comentários:<br />
<a href="mailto:dilbertorosa@gmail.com">Dilberto Rosa</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[The wonders of foreach]]></title>
<link>http://vzemlys.wordpress.com/2009/10/13/the-wonders-of-foreach/</link>
<pubDate>Tue, 13 Oct 2009 13:30:45 +0000</pubDate>
<dc:creator>vzemlys</dc:creator>
<guid>http://vzemlys.wordpress.com/2009/10/13/the-wonders-of-foreach/</guid>
<description><![CDATA[Frequently I find myself having to write something like this in R: for (nm in names(x)) { l &lt;- x[]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Frequently I find myself having to write something like this in R:</p>
<pre class="hl"><span class="kwa">for</span> <span class="sym">(</span>nm <span class="kwa">in</span> names<span class="sym">(</span>x<span class="sym">)) {</span>
    l <span class="sym">&#60;-</span> x<span class="sym">[[</span>nm<span class="sym">]]</span>
    ss <span class="sym">&#60;-</span> summary<span class="sym">(</span>l<span class="sym">)</span>  <span class="slc"># produce nice table for writing</span>
    write.csv<span class="sym">(</span>ss<span class="sym">,</span>file<span class="sym">=</span>paste<span class="sym">(</span>nm<span class="sym">,</span><span class="str">&#34;.csv&#34;</span><span class="sym">,</span>sep<span class="sym">=</span><span class="str">&#34;&#34;</span><span class="sym">))</span>
<span class="sym">}</span>
</pre>
<p>Here x is some list, where each element contains some fitted model.  This always bugs me, since I cannot use lapply, or other fancy functions like *lply (from package <a href="http://had.co.nz/plyr/">plyr</a>). The problem is that I need to keep the name of the list element, and all of functions mentioned, do not do that. So if I have a generic function:</p>
<pre class="hl">fun <span class="sym">&#60;-</span> <span class="kwa">function</span><span class="sym">(</span>l<span class="sym">,</span> nm<span class="sym">) {</span>
    l  <span class="sym">&#60;-</span> x<span class="sym">[[</span>nm<span class="sym">]]</span>
    ss <span class="sym">&#60;-</span> summary<span class="sym">(</span>l<span class="sym">)</span>
    write.csv<span class="sym">(</span>ss<span class="sym">,</span>file<span class="sym">=</span>paste<span class="sym">(</span>nm<span class="sym">,</span><span class="str">&#34;.csv&#34;</span><span class="sym">,</span>sep<span class="sym">=</span><span class="str">&#34;&#34;</span><span class="sym">))</span>
<span class="sym">}</span></pre>
<p>I cannot use it with lapply like this</p>
<pre class="hl">
 lapply<span class="sym">(</span>x<span class="sym">,</span>fun<span class="sym">)</span>
</pre>
<p>since then I need to pass different nm for each list element. </p>
<p> With <a href="http://cran.r-project.org/web/packages/foreach/index.html">foreach</a> however it is very easy to do:</p>
<pre class="hl">
foreach<span class="sym">(</span>l<span class="sym">=</span>x<span class="sym">,</span>nm<span class="sym">=</span>names<span class="sym">(</span>x<span class="sym">)) %</span>do<span class="sym">% {</span>
    ss <span class="sym">&#60;-</span>  summary<span class="sym">(</span>l<span class="sym">)</span>
    write.csv<span class="sym">(</span>ss<span class="sym">,</span>file<span class="sym">=</span>paste<span class="sym">(</span>nm<span class="sym">,</span><span class="str">&#34;.csv&#34;</span><span class="sym">,</span>sep<span class="sym">=</span><span class="str">&#34;&#34;</span><span class="sym">))</span>
<span class="sym">}</span>
</pre>
<p>Or I can use my super-convenient function:</p>
<pre class="hl">
foreach<span class="sym">(</span>l<span class="sym">=</span>x<span class="sym">,</span>nm<span class="sym">=</span>names<span class="sym">(</span>x<span class="sym">)) %</span>do<span class="sym">%</span> fun<span class="sym">(</span>l<span class="sym">,</span>nm<span class="sym">)</span>
</pre>
<p>You can even do some interesting stuff with parallelization, since foreach supports it.  So if your computer has processor with several cores you can use both for intensive calculations. BTW if anyone knows easy way of highlighting R code in wordpress, let me know.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[basic of C# (part 14)]]></title>
<link>http://sevenlamp.wordpress.com/2009/08/12/foreach/</link>
<pubDate>Wed, 12 Aug 2009 05:06:31 +0000</pubDate>
<dc:creator>sevenlamp</dc:creator>
<guid>http://sevenlamp.wordpress.com/2009/08/12/foreach/</guid>
<description><![CDATA[တခါတေလ ကြၽန္ေတာ္တို႔ Looping ေတြထဲမွာ looping variable မပါတာမ်ိဳးလည္း ရွိပါတယ္။ looping ကို အၾကိမ္အေ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p style="text-align:justify;">တခါတေလ ကြၽန္ေတာ္တို႔ Looping ေတြထဲမွာ looping variable မပါတာမ်ိဳးလည္း ရွိပါတယ္။ looping ကို အၾကိမ္အေရအတြက္ အတိအက် မဟုတ္ပဲ looping variable မပါတဲ႔ looping မ်ိဳး သံုးဖို႔ လိုလာျပီ ဆိုရင္ေတာ့ while နဲ႔ do-while ကိုသံုးေလ့ရွိပါတယ္။ ဥပမာ.. ကြၽန္ေတာ္က user ဆီက character တစ္လံုးလက္ခံမယ္၊ ျပီးရင္ အဲ့ဒီ character ရဲ႕ ASCII value ကိုျပန္ျပီးထုတ္ျပေပးမယ္။ ဒီအလုပ္ကိုပဲ user ၾကိဳက္သေလာက္ လုပ္နိုင္တယ္။ မလုပ္ခ်င္ေတာ့ဘူးဆိုရင္ ESC key ႏွိပ္ျပီးထြက္ရမယ္။ ဟုတ္ျပီေနာ္ ဒီ program ေလးေရးၾကည့္ရေအာင္။</p>
<div style="background-color:lightgray;padding:5px;">
<pre>using System;
class forlooptest
{
    static void Main()
    {
        bool stop = false;
        do
        {
            Console.Write("Enter a char to see ASCII value of it (or) press ESC to close.");
            ConsoleKeyInfo cki = Console.ReadKey();
            if (cki.Key != ConsoleKey.Escape)
                Console.WriteLine("\n{0} = {1}\n", cki.Key.ToString(), (int)cki.KeyChar);
            else
                stop = true;
        } while (stop==false);
    }
}</pre>
</div>
<p style="text-align:justify;">ဒီ program ေလးမွာ looping ဆက္လုပ္မလား မလုပ္ေတာ့ဘူးလား ဆိုတာကို stop ဆိုတဲ႔ boolean variable ေလးနဲ႔ ထိန္းထားတယ္။ default value အေနနဲ႔ false ထည့္ေပးထားတယ္(program မပိတ္ဖူးလို႔ ဆိုလိုတာေပါ့) user ဆီကေန key တစ္ခုထဲလက္ခံမယ္ဆိုရင္ Console.ReadKey() function ကိုသံုးရတယ္။ သူက ConsoleKeyInfo ဆိုတဲ႔ structure ေလး return ျပန္တယ္။ အဲ့ဒီ ConsoleKeyInfo structure ထဲမွာ Key ဆိုတဲ႔ property က user ရိုက္လိုက္တဲ႔ ConsoleKey အမ်ိဳးအစားျဖစ္ျပီး၊ KeyChar ကေတာ့ character ျပန္ထုတ္ေပးတယ္။ ဒါေၾကာင့္ user ရိုက္လိုက္တဲ႔ key က Escape နဲ႔ မတူဘူးဆိုရင္ user ကို output ထုတ္ျပတယ္။ တူတယ္ဆိုရင္ေတာ့ program ပိတ္ဖို႔အတြက္ stop ထဲကို true ထည့္ေပးလိုက္တယ္။ ေနာက္ဆံုးမွ while condition မွာ stop ထဲက တန္ဖိုးဟာ false နဲ႔ ညီလား စစ္လိုက္တယ္။ ညီရင္ looping ကို ေနာက္တစ္ေခါက္ျပန္လုပ္မယ္။ မညီဘူးဆိုရင္ program ပိတ္သြားမွာပါ။</p>
<p style="text-align:justify;"><span style="color:#ff00ff;"><strong>foreach looping</strong></span><br />
foreach looping ကို collection(အစုအေ၀း) တစ္ခုအတြင္းမွာ ရွိသေလာက္ အားလံုး လုပ္ခ်င္တယ္ဆိုရင္ သံုးေလ႔ရွိပါတယ္။ array ထဲမွာ ရွိသေလာက္လုပ္ခ်င္တယ္၊ class ထဲက property ေတြအားလံုးလုပ္ခ်င္တယ္၊ ဒီလို အေျခအေနမ်ိဳးမွာ foreach loop ကိုသံုးပါတယ္။ ဥပမာ.. ကြၽန္ေတာ့္ ဘေလာ့ကို လာၾကည့္တဲ႔ သူငယ္ခ်င္းေတြ အားလံုးကို တစ္ေယာက္ laptop တစ္လံုး လက္ေဆာင္ေပးခ်င္တယ္ ဆိုရင္ foreach ကိုသံုးျပီး ဒီလို ေရးရမွာပါ.. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<div style="background-color:lightgray;padding:5px;">
<pre>foreach( People p in myBlog.visitors )
{
	p = “a laptop”;
}</pre>
</div>
<p style="text-align:justify;">foreach ကိုသံုးလိုက္ျခင္းအားျဖင့္ ကြၽန္ေတာ့ ဘေလာ့ကို လာၾကည့္တဲ႔သူ ဘယ္ေလာက္ရွိလဲ ဆိုတာကို သိေနစရာ မလိုေတာ့ပါဘူး။ visitor မကုန္မခ်င္း ဒီ looping က အလုပ္လုပ္မွာပါ။ foreach looping မွာေတာ့ start ေတြ stop ေတြ step ေတြ မလိုပါဘူး။ in keyword ရဲ႕ ေရွ႕မွာ colletion အတြင္းမွာ ရွိတဲ႔ value ေတြရဲ႕ datatype ကိုေၾကျငာရျပီး in ရဲ႕ ေနာက္မွာေတာ့ collection name ကိုေပးရပါတယ္။ အခု foreach ကိုသံုးျပီး program ေလးတစ္ခု ေရးၾကည့္ရေအာင္။ ကြၽန္ေတာ္က user ဆီက စာေၾကာင္းတစ္ေၾကာင္းလက္ခံမယ္။ ျပီးရင္ အဲ့ဒီ စာေၾကာင္းထဲမွာ ရွိတဲ႔ character ေတြရဲ့ ASCII value ကို ျပန္ျပီး ျပမယ္။</p>
<div style="background-color:lightgray;padding:5px;">
<pre>using System;
class forlooptest
{
    static void Main()
    {
            string st;
            Console.Write("Enter a string : ");
            st = Console.ReadLine();
            foreach (char c in st)
            {
                Console.WriteLine("{0} = {1}", c, (int)c);
            }
            Console.Read();
    }
}</pre>
</div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Listando imagens de uma pasta com PHP]]></title>
<link>http://davidchc.wordpress.com/2009/08/11/listando-imagens-de-uma-pasta-com-php/</link>
<pubDate>Tue, 11 Aug 2009 00:37:39 +0000</pubDate>
<dc:creator>davidchc</dc:creator>
<guid>http://davidchc.wordpress.com/2009/08/11/listando-imagens-de-uma-pasta-com-php/</guid>
<description><![CDATA[Nessa video aula iremos aprender a como listar as imagens de um pasta, de também organizá-la de acor]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Nessa video aula iremos aprender a como listar as imagens de um pasta, de também organizá-la de acordo da data de modificação, da mais recente para mais antiga. Vamos utilizar o slide show da video aula sobre jquery. Bons Estudos.</p>
<p><span style='text-align:center; display: block;'><br />
<object type="application/x-shockwave-flash" width="500" height="300" data="http://www.vimeo.com/moogaloop.swf?clip_id=6041278&amp;server=www.vimeo.com&amp;fullscreen=1&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=01AAEA"><param name="quality" value="best" /><param name="allowfullscreen" value="true" /><param name="scale" value="showAll" /><param name="movie" value="http://www.vimeo.com/moogaloop.swf?clip_id=6041278&amp;server=www.vimeo.com&amp;fullscreen=1&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=01AAEA" /></object><br />
</span></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[How var fixes a type hole in C#]]></title>
<link>http://smellegantcode.wordpress.com/2009/08/05/how-var-fixes-a-type-hole-in-c/</link>
<pubDate>Wed, 05 Aug 2009 16:46:00 +0000</pubDate>
<dc:creator>earwicker</dc:creator>
<guid>http://smellegantcode.wordpress.com/2009/08/05/how-var-fixes-a-type-hole-in-c/</guid>
<description><![CDATA[Assuming we have: public class Base {} public class Derived : Base {} public class Unrelated {} We c]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Assuming we have:</p>
<pre class="brush: csharp;">
public class Base {}
public class Derived : Base {}
public class Unrelated {}
</pre>
<p>We can make a list of <code>Base</code>:</p>
<pre class="brush: csharp;">
List&lt;Base&gt; baseList = new List&lt;Base&gt;();
</pre>
<p>And we can loop through the list:</p>
<pre class="brush: csharp;">
foreach (Base item in baseList)
</pre>
<p>What other types can we use for the loop variable? We would expect to be able to use a type from which the collection&#8217;s item type is derived. In this case, that&#8217;s <code>object</code>:</p>
<pre class="brush: csharp;">
foreach (object item in baseList)
</pre>
<p>And that&#8217;s fine, it makes perfect sense, because everything on our list is surely an object. If we had a list of <code>Derived</code> it would also make sense to let us use <code>Base</code> as the type of the loop variable. All good.</p>
<p>It wouldn&#8217;t make sense to let us use <code>Unrelated</code>:</p>
<pre class="brush: csharp;">
foreach (Unrelated item in baseList)
</pre>
<p>It&#8217;s a certainty that the objects on our list are not of that type, so it has no hope of working. So we get a compiler error &#8211; good call!</p>
<p>But what about:</p>
<pre class="brush: csharp;">
foreach (Derived item in baseList)
</pre>
<p>Now, the items on our list could be of that type &#8211; it&#8217;s certainly possible. But they could be of other types derived from <code>Base</code>. This is called a downcast, and if you need to do that, it&#8217;s often (but not always) a sign that there&#8217;s a kludge in your design.</p>
<p>What may be surprising is that the compiler allows this to compile. In other words, it silently inserts a downcast. This is unfortunate, because it&#8217;s probably a mistake. Most situations where you required a downcast, you would do this instead:</p>
<pre class="brush: csharp;">
foreach (Derived item in baseList.OfType&lt;Derived&gt;())
</pre>
<p>That way, anything that couldn&#8217;t be cast to the required type would be safely skipped over.</p>
<p>Fortunately, the <code>var</code> keyword comes to the rescue. Always use <code>var</code> to declare the loop variable and you won&#8217;t fall into this hole.</p>
<pre class="brush: csharp;">
foreach (var item in baseList)
</pre>
<p>The compiler uses the static type argument of the <code>IEnumerable</code> interface.</p>
<p>Note that <code>var</code> with a non-generic collection will be equivalent to <code>object</code>. But you can use the <code>OfType</code> trick again:</p>
<pre class="brush: csharp;">
ArrayList whatever = new ArrayList();

foreach (var x in whatever.OfType&lt;Unrelated&gt;())
</pre>
<p>The <code>foreach</code> keyword predates generic collections, which is why it has the ability to silently cast; before generic collections, any code that looped through the contents of a collection would require a downcast, so it made a kind of sense to build it into the <code>foreach</code> keyword. Now we have generic collections, it makes almost no sense; but it&#8217;s not so bad because we have <code>var</code> to plug the hole, so we can&#8217;t fall into it.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Mappen und Falten: Origami für Anfänger]]></title>
<link>http://dgronau.wordpress.com/2009/07/22/mappen-und-falten-origami-fur-anfanger/</link>
<pubDate>Wed, 22 Jul 2009 20:37:25 +0000</pubDate>
<dc:creator>dgronau</dc:creator>
<guid>http://dgronau.wordpress.com/2009/07/22/mappen-und-falten-origami-fur-anfanger/</guid>
<description><![CDATA[Bisher war in meinem Scala-Blog noch kein Fitzelchen Scala zu sehen, und jetzt kommt auch gleich mei]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Bisher war in meinem Scala-Blog noch kein Fitzelchen Scala zu sehen, und jetzt kommt auch gleich mein erstes kleines Problem: Der Syntax-Highlighter bei wordpress.com unterstützt kein Scala (das letzte SyntaxHighlighter-<strong>Plugin</strong> allerdings sehr wohl). Ich habe deshalb ganz lieb bei WordPress um Aktualisierung gebeten, und Heather vom Support hat ganz lieb geantwortet, dass sie es auf die grooooße Liste gesetzt hat. Warten wir ab und leben solange mit java-gehighlightetem Scala. Deshalb hier auch eher leichte Kost mit kurzen Schnipseln. Aber genug der Vorrede&#8230;</p>
<p>Scala besitzt wie Java Listen, Sets und Maps, allerdings gleich doppelt: Veränderlich und unveränderlich. Allerdings sind im Gegensatz zu Java die <strong>unveränderlichen</strong> Collections der &#8220;Standard&#8221;. Wie man sich leicht denken kann, unterscheidet sich deren Arbeitsweise erheblich von der der Java-Versionen, denn die Devise heißt jetzt &#8220;transformieren statt mutieren&#8221;.</p>
<p>Ich will hier die fünf mit Abstand wichtigsten Methoden der Scala-Collections behandeln: foreach, map, flatMap, reduce[Left/Right], fold[Left/Right]. Auch wenn das nur ein grober Überblick im Schnelldurchlauf sein kann, denke ich doch, dass ich das generelle &#8220;Flair&#8221; des Konzepts vermitteln kann.</p>
<p><strong>foreach</strong><br />
&#8230;unterscheidet sich kaum von ähnlichen Konstrukten in Skriptsprachen, und ist auch ziemlich eng mit Javas erweiterter for-Schleife verwandt. foreach führt eine Operation auf jedem Element der Liste aus, ein eventuelles &#8220;Ergebnis&#8221; wird ignoriert. Ein typisches Beispiel sind I/O-Operationen:</p>
<pre class="brush: java;">List(1,2,3,4,5).foreach(x =&gt; println(x*x))</pre>
<p>Ausgabe:<br />
1<br />
4<br />
9<br />
16<br />
25</p>
<p><strong>map</strong><br />
&#8230;ist meiner Meinung nach das &#8220;Herzstück&#8221; der Scala Collections: Es transformiert eine Collection eines Types in eine Collection eines beliebigen anderen Typs. Angenommen obiger Code hätte eine String-Liste als Ausgangspunkt, dann könnte man schreiben:</p>
<pre class="brush: java;">List(&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;).map(_.toInt).foreach(x =&gt; println(x*x))</pre>
<p>oder, wenn man &#8220;sofort&#8221; die Quadrate berechnen will:</p>
<pre class="brush: java;">List(&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;).map(x =&gt; x.toInt * x.toInt).foreach(println)</pre>
<p><strong>flatMap</strong><br />
&#8230; funktioniert wie map, kommt aber bei &#8220;geschachtelten&#8221; Konstruktionen (etwa eine Liste von Sets oder ein Set von Options) zum Einsatz. Zusätzlich zur Transformation wird die Datenstruktur auch noch &#8220;geplättet&#8221;.</p>
<pre class="brush: java;">List(Set(&quot;1&quot;,&quot;2&quot;,&quot;3&quot;),Set(&quot;4&quot;,&quot;5&quot;)).flatMap(_.map(_.toInt)).foreach(x =&gt; println(x*x))</pre>
<p>Das map wandelt unsere String-Sets zu Int-Sets um. flatMap macht dann diese Int-Sets &#8220;platt&#8221;, das heißt aus der Liste von Sets wird eine Liste von Ints. Danach drucken wir die Quadrate aus wie gehabt. </p>
<p><strong>reduceLeft und reduceRight</strong><br />
&#8230; &#8220;dampft&#8221; eine Collection &#8220;ein&#8221;, indem immer wieder dieselbe Operation angewandt wird (wobei man sich aussuchen kann, ob man links oder rechst anfängt)</p>
<pre class="brush: java;">println(List(1,2,3,4,5).reduceLeft((x,y) =&gt; x*y))</pre>
<p>Ausgabe: 120<br />
Die Rechnung läuft so ab: println((((1*2)*3)*4)*5)<br />
Natürlich spielt -Left oder -Right bei kommutativen Operationen wie der Multiplikation keine Rolle (außer bezüglich der Performance).<br />
Man kann obiges Beispiel übrigens auch kürzer schreiben als</p>
<pre class="brush: java;">println(List(1,2,3,4,5).reduceLeft(_*_))</pre>
<p>Neben Summen und Differenzen ist auch die Minimum- oder Maximumsuche eine typische Anwendung:</p>
<pre class="brush: java;">println(List(2,5,3,1,4).reduceLeft(_ max _))</pre>
<p>Ausgabe: 5</p>
<p><strong>foldLeft und foldRight</strong><br />
&#8230; ist eng verwandt mit den reduce-Methoden. Der Unterschied ist, dass man einen Startwert vorgeben kann. Hat der Startwert den gleichen Typ wie die Collection, funktionieren beide Methoden fast identisch (nur halt foldLeft/foldRight mit einem zusätzlichen Wert). Interessant wird es, wenn sich der Typ unterscheidet, denn dann wird dieser neue Typ &#8220;durchgereicht&#8221;. Das Verfahren eignet sich für alle möglichen Aufgaben, die irgendwie mit &#8220;Daten sammeln&#8221; umschrieben werden können. Hier &#8220;sammelt&#8221; z.B. ein StringBuilder unsere Listenwerte auf:</p>
<pre class="brush: java;">println(List(1,2,3,4,5).foldLeft(new StringBuilder)(_.append(_)))</pre>
<p>Ausgabe: 12345<br />
Oder von rechts (jetzt stimmt die Reihenfolge unserer Parameter nicht mehr, so dass sie &#8220;abgekürzte&#8221; Schreibweise mit den Unterstrichen nicht möglich ist):</p>
<pre class="brush: java;">println(List(1,2,3,4,5).foldRight(new StringBuilder)((i,sb) =&gt; sb.append(i)))</pre>
<p>Ausgabe: 54321<br />
Die zwei Argumentlisten von foldLeft/foldRight wirken erst einmal befremdlich, aber es gibt einen guten Grund dafür und man gewöhnt sich daran. Ich würde empfehlen, das erst einmal einfach so &#8220;hinzunehmen&#8221;, die Neugierigen seien auf das Stichwort &#8220;Currying&#8221; verwiesen (was weniger mit Kochkunst als mit dem Mathematiker und Logiker Haskell Curry zu tun hat, dem auch der Sprache Haskell ihren Namen verdankt).</p>
<p>Diesen Herbst soll übrigens Scala 2.8 herauskommen, in dem u.a. die Collections völlig überarbeitet werden sollen. Allerdings sind obige Schnipsel so elementar, dass sie aller Wahrscheinlichkeit nach auch dort laufen werden.</p>
<p>Ich hoffe, dass ich einen einigermaßen verständlichen ersten Einblick vermitteln konnte. Man kann übrigens ganz einfach und ohne Installation online auf <a>Simply Scala</a> mit solchen Snippets herumspielen. Dadurch bekommt man schnell ein Gefühl für die Arbeitsweise &#8211; und Spaß macht es auch <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to fill all textboxes in a form with 0?]]></title>
<link>http://cshark.wordpress.com/2009/05/09/how-to-fill-all-textboxes-in-a-form-with-0/</link>
<pubDate>Sat, 09 May 2009 12:47:26 +0000</pubDate>
<dc:creator>udhaya47</dc:creator>
<guid>http://cshark.wordpress.com/2009/05/09/how-to-fill-all-textboxes-in-a-form-with-0/</guid>
<description><![CDATA[foreach (Control c in this.Controls) { if (c is TextBox) { if (((TextBox)c).Text == &#8220;&#8221;) ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>foreach (Control c in this.Controls)</p>
<p>{</p>
<p>if (c is TextBox)</p>
<p>{</p>
<p>if (((TextBox)c).Text == &#8220;&#8221;)</p>
<p>((TextBox)c).Text = &#8220;0&#8243;;</p>
<p>}</p>
<p>}</p>
<p><a title="Silica gel" href="http://www.kpsco.in" target="_blank">Udhaya</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[ucfirst]]></title>
<link>http://prafulkr.wordpress.com/2009/04/25/ucfirst/</link>
<pubDate>Sat, 25 Apr 2009 06:19:38 +0000</pubDate>
<dc:creator>Praful</dc:creator>
<guid>http://prafulkr.wordpress.com/2009/04/25/ucfirst/</guid>
<description><![CDATA[ucfirst :: (PHP 4, PHP 5) &nbsp; &nbsp; &nbsp; &nbsp; ucfirst — Make a string&#8217;s first characte]]></description>
<content:encoded><![CDATA[ucfirst :: (PHP 4, PHP 5) &nbsp; &nbsp; &nbsp; &nbsp; ucfirst — Make a string&#8217;s first characte]]></content:encoded>
</item>
<item>
<title><![CDATA[Foreach y Arrays Asociativos]]></title>
<link>http://juncalcepeda.wordpress.com/2009/04/19/foreach-y-arrays-asociativos/</link>
<pubDate>Sun, 19 Apr 2009 21:00:40 +0000</pubDate>
<dc:creator>Juncal Cepeda</dc:creator>
<guid>http://juncalcepeda.wordpress.com/2009/04/19/foreach-y-arrays-asociativos/</guid>
<description><![CDATA[¡Buenas a todos! Hoy os explicaré una sentencia de control de datos, un tipo de bucle. El cual nos p]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p class="MsoNormal">¡Buenas a todos!</p>
<p class="MsoNormal">Hoy os explicaré una sentencia de control de datos, un tipo de bucle. El cual nos permite recorrer<span>  </span>matrices o<span>  </span>arrays asociativos.</p>
<p class="MsoNormal">La diferencia entre las matrices y los arrays asociativos es muy simple : <span> </span>en los arrays el índice lo marca<span>  </span>un valor numérico desde el 0 hasta X, sin embargo<span>  </span>en estos arrays el índice lo marca un valor.</p>
<blockquote>
<p class="MsoNormal">&#60;?php</p>
<p class="MsoNormal"><span lang="EN-US">$colores = array(</span></p>
<p class="MsoNormal"><span lang="EN-US"><span>   </span>&#8220;Rojo&#8221; =&#62; Red,</span></p>
<p class="MsoNormal"><span lang="EN-US"><span>   </span>&#8220;Azul&#8221; =&#62; Blue,</span></p>
<p class="MsoNormal"><span lang="EN-US"><span>   </span>&#8220;Blanco&#8221; =&#62; White,</span></p>
<p class="MsoNormal"><span lang="EN-US"><span>   </span>&#8220;Negro&#8221; =&#62; Black);</span></p>
<p class="MsoNormal"><span lang="EN-US">foreach($colores as $indice =&#62; $valor)</span></p>
<p class="MsoNormal">{</p>
<p class="MsoNormal"><span>  </span>echo $indice.&#8217; =&#62;&#8217; .$valor.&#8221;&#60;br&#62;&#8221;;</p>
<p class="MsoNormal">}</p>
<p class="MsoNormal">?&#62;</p>
</blockquote>
<p class="MsoNormal">En<span>  </span>las primeras líneas de código creamos<span>  </span>el array asociativo $colores.Guardamos como índice el<span>  </span>nombre en castellano de un color,<span>  </span>este índice contiene la traducción<span>  </span>en Ingles de él mismo.</p>
<p class="MsoNormal">Después recorremos este vector<span>  </span>y mostramos en<span>  </span>pantalla tanto el índice como el valor de él.<span>  </span></p>
<p class="MsoNormal">Os invito a que probéis el uso tanto de la sentencia foreach como de este tipo de arrays.</p>
<p class="MsoNormal">¡Un saludo!</p>
<p class="MsoNormal">Juncal Cepeda</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Tcl/Tk: Criar vários nomes para um comando (alias) ]]></title>
<link>http://codare.net/2009/03/30/tcltk-criar-varios-nomes-para-um-comando-alias/</link>
<pubDate>Mon, 30 Mar 2009 12:00:18 +0000</pubDate>
<dc:creator>LES</dc:creator>
<guid>http://codare.net/2009/03/30/tcltk-criar-varios-nomes-para-um-comando-alias/</guid>
<description><![CDATA[Além de renomear comandos em Tcl/Tk, também é possível criar &#8220;apelidos&#8221; para os comandos]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Além de <a href="http://codare.net/2009/03/20/tcltk-renomear-e-remover-comandos/">renomear comandos em Tcl/Tk</a>, também é possível criar &#8220;apelidos&#8221; para os comandos com o [interp alias]. Por exemplo, o comando [file exists] verifica se um determinado arquivo existe:</p>
<pre>% if { [file exists "/caminho/do/arquivo.txt"] == 1 } {
       puts "O arquivo existe"
}</pre>
<p>Se você achar que &#8220;file exists&#8221; é muito longo e/ou tiver saudade do <a href="http://codare.net/category/shell/">Bash</a>, pode criar o apelido &#8220;-e&#8221;:</p>
<pre>% interp alias {} -e {} file exists

% if { [-e "/caminho/do/arquivo.txt"] == 1 } {
       puts "O arquivo existe."
}</pre>
<p>Todos os outros comandos -[letra] do Bash podem ser recriados e carregados no início do programa:</p>
<pre>interp alias {} -e {} file exists
interp alias {} -f {} file isfile
interp alias {} -d {} file isdirectory
interp alias {} -r {} file readable
interp alias {} -w {} file writable
interp alias {} -x {} file executable
interp alias {} -o {} file owned</pre>
<p>Apelido &#8220;@&#8221; para o foreach, se você sentir saudade de Perl:</p>
<pre>% interp alias {} @ {} foreach

% @ x "1 2 3" { puts $x }
1
2
3</pre>
<p>Para quem gosta muito de <a href="http://codare.net/category/php/">PHP</a>:</p>
<pre>% interp alias {} strtolower {} string tolower

% puts [strtolower "GRITARIA"]
gritaria</pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Smarty - kleine Tricks - preg_match;)]]></title>
<link>http://christianzinke.wordpress.com/2009/02/26/smarty-kleine-tricks/</link>
<pubDate>Thu, 26 Feb 2009 09:55:42 +0000</pubDate>
<dc:creator>xisoiax</dc:creator>
<guid>http://christianzinke.wordpress.com/2009/02/26/smarty-kleine-tricks/</guid>
<description><![CDATA[Nachdem ich gestern schon auf die verbindung von Ajax uns Smarty zu sprechen kam, habe ich doch glat]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Nachdem ich gestern schon auf die verbindung von Ajax uns Smarty zu sprechen kam, habe ich doch glattweg n bissl im Internet gesurft, dabei ist mir ziemlich schnell <a href="http://kpumuk.info/ajax/ajax-enabled-smarty-plugins/">DAS HIER</a> aufgefallen. Das sieht schon sehr sehr gut aus, hoffe die Smartyentwickler haben das auch gesehn, den in den offziellen Listen scheint es nicht dabei zu sein.<br />
Nunja,<br />
ich musste heute ein wenig suchen, und habe wiedermal festgestellt das smarty top ist, quasi spitze <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /><br />
Ich hatte ein schönes Array gebaut, und wollte nun nur die INT Schlüßel ausgeben lassen, weil alle anderen Schlüssel Text beinhalten,<br />
das heißt, eine Foreach schleife, mit anschließender Prüfung auf INT Schlüssel, das ganze sieht dann so aus:</p>
<p><code><br />
{foreach key=arr_key item=value from=$array}<br />
        {if preg_match('~^[0-9]+$~', $arr_key)}<br />
          Inhalt<br />
        {/if}<br />
{/foreach}<br />
</code></p>
<p>Das ganze war so strukturiert das alle INT Schlüßel wieder ein Array beinhalten &#8211; nur falls sich jemand nach dem Sinn fragt.<br />
Der Clou ist aber das der preg_match Filter ohne Probleme in smarty eingebaut werden kann, und quasi in letzter Instanz sogar als Outputfilter genutzt werden kann.<br />
___________________________________________________<br />
Yesterday I talked about the combination of Smarty and Ajax, and I just surf and find: <a href="http://kpumuk.info/ajax/ajax-enabled-smarty-plugins/">THIS</a> &#8211; very fast, but I dont find it in the offiziell lists. So I hope this version will be integrated in the new smarty version&#8230;<br />
And today: Just normal work &#8211; but I just need  &#8211; a bit of &#8211; time to find a solution for a little Problem, but its a very nice Solutions. In Smarty you can easy use preg_match, so You can easy test some varibles on type &#8211; test if they are Numeric, String etc..<br />
In this example(up), I test the array keys &#8211; I just build an array with numeric keys and string keys &#8211; so all numeric keys had array values and all other had sting values -<br />
but i the end, smarty enables you to use it as a last-output-filter, if you wanne <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Flex Tutorials and samples]]></title>
<link>http://newflexworld.wordpress.com/2009/02/01/flex-tutorials-and-samples/</link>
<pubDate>Sun, 01 Feb 2009 10:18:06 +0000</pubDate>
<dc:creator>ursprakash</dc:creator>
<guid>http://newflexworld.wordpress.com/2009/02/01/flex-tutorials-and-samples/</guid>
<description><![CDATA[Flex is a highly productive, free open source framework for building and maintaining expressive web ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Flex is a highly productive, free open source framework for building and maintaining expressive web applications that deploy consistently on all major browsers, desktops, and operating systems -Adobe</p>
<p> </p>
<p><strong><a href="http://gnanz-flexworld.blogspot.com">Adobe Flex</a></strong> is a collection of technologies released by Adobe Systems for the development and deployment of cross platform rich Internet applications based on the proprietary Adobe Flashplatform. The initial release in March 2004 by Macromedia included a software development kit, anIDE, and a J2EE integration application known as Flex Data Services. Since Adobe acquired Macromedia in 2005, subsequent releases of Flex no longer require a license for Flex Data Services, which has become a separate product rebranded as LiveCycle Data Services. -Wikipedia</p>
<p> </p>
<p> </p>
<p>There are many sites providing the tutorials and samples in net.Here is my <a title="Flex Sanples blog" href="http://gnanz-flexworld.blogspot.com" target="_blank">Flex samples blog </a>,</p>
<p> </p>
<p><a title="http://gnanz-flexworld.blogspot.com" href="http://gnanz-flexworld.blogspot.com" target="_blank">http://gnanz-flexworld.blogspot.com</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Recent bits and bobs - Switch, Save/Load, For:each, Iterator]]></title>
<link>http://chilloxk.wordpress.com/2009/01/31/recent-bits-and-bobs-switch-saveload-foreach-iterator/</link>
<pubDate>Sat, 31 Jan 2009 00:49:39 +0000</pubDate>
<dc:creator>chilloxk</dc:creator>
<guid>http://chilloxk.wordpress.com/2009/01/31/recent-bits-and-bobs-switch-saveload-foreach-iterator/</guid>
<description><![CDATA[The lab for monday is almost entirely the same as the DVD labs. Here I&#8217;ll post some minor bits]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>The lab for monday is almost entirely the same as the DVD labs. Here I&#8217;ll post some minor bits we went over in lectures which might help a bit.</p>
<p><strong>Switch Statements</strong></p>
<p>These are handy for checking specific things like numbers&#8217; equality. They are useful if you want to have menus and use numbers for imput and the like.</p>
<p>eg:</p>
<p>we have a menu that says &#8216;please enter a number to select an option&#8217;, which is stored in an int called choice:</p>
<p>println(&#8220;please enter a number to select an option: &#8220;);</p>
<p>int choice = readInt();</p>
<p>the syntac for switch is:</p>
<p>switch (expression){</p>
<p>case n:</p>
<p>method();</p>
<p>break;</p>
<p>case n+1:</p>
<p>method2();</p>
<p>break;</p>
<p>}</p>
<p>this checks if expression is equal to n, if not, n+1, and will keep going down the list. it will execute the methods inside the case: until it comes to break; which ends the statement.</p>
<p><strong>SAVE / LOAD<br />
</strong></p>
<p>as in the lectures:</p>
<p>save:</p>
<p>saveToFile(dvds, &#8220;DVDs.xml&#8221;);</p>
<p>in this case, what happens is the contents of dvds(which is an arrayList of type String) is saved in the file called DVDs.xml in the directory your project is saved in.</p>
<p>load:</p>
<p>dvds = (ArrayList&#60;String&#62;) readFromFile(&#8220;DVDs.xml&#8221;);</p>
<p>this overwrited the file dvds (which is an ArrayList&#60;String&#62;) with the contents of the file DVDs.xml in the project directory.</p>
<p><strong>FOR:EACH LOOP</strong></p>
<p>Watch out with these, in a for:each loop, you cycle through elements of an array, arraylist or whatever, but you cannot modify the contents of the thing you are cycling though. It actually gives you a copy of what is contained, not the file itself.</p>
<p>syntax:     for(type anyname: listname)</p>
<p>type: String, int, DVD, Song.</p>
<p>anyname: the name which you will refer to each element by.</p>
<p>listname: the exact name of the array/ArrayList.</p>
<p>eg:</p>
<p>public void listDVDs(){</p>
<p>for(String moo: dvds)</p>
<p>{    println(dvd);    }</p>
<p>}</p>
<p>This will pick the first element in the arrayList &#8216;dvds&#8217; (which holds String names), which shall be refered to as moo, and then execute whatever is inside the curly brackets. in this case it prints them out.</p>
<p>If it held DVD types, this would print the names of the dvds:</p>
<p>public void listDVDs(){</p>
<p>for(DVD moo: dvds)</p>
<p>{   print( moo.getTitle() );    }</p>
<p>}</p>
<p>Because we would get each DVD object stored in the arrayList, and all its methods inside it too, like a normal for loop.</p>
<p><strong>ITERATOR</strong></p>
<p>Don&#8217;t entirely know much about these, just that they are ways of cycling through and altering elements in lists/sets. Similar to a for-loop but with it&#8217;s own methods.</p>
<p>import the use of it by using: import java.util.Iterator;</p>
<p>we create it by the following: (not sure on the capital or small &#8216;i&#8217;/'I&#8217;)</p>
<p>Iterator&#60;Type&#62; iteratorname = collection.iterator();</p>
<p>eg: Iterator&#60;DVD&#62; it = dvds.iterator();</p>
<p>this creates an iterator which can cycle through DVD objects, we will call it &#8216;it&#8217;, and it will be attached to the dvds arrayList collection.</p>
<p>this iterator has its own methods;</p>
<p>hasNext() &#8211; which returns a true/false if there is another element in the list.</p>
<p>and next() &#8211; which gets the next element.</p>
<p>used generally (for the moment) like this:</p>
<p>while(it.hasNext() )</p>
<p>{ it.next(); }</p>
<p>to print the name of the DVDs:</p>
<p>while(it.hasNext() )</p>
<p>{ println(it.next().getTitle() ); }</p>
<p>Next: HashSets and HastMaps</p>
<p>specific questions to chilloxk[-at-]hotmail(-dot-).COM</p>
<p><strong><br />
</strong></p>
<p><strong><br />
</strong></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[For vs For Each loops - Performance Issues.]]></title>
<link>http://nickmasao.wordpress.com/2009/01/26/for-vs-for-each-loops-performance-issues/</link>
<pubDate>Mon, 26 Jan 2009 15:29:46 +0000</pubDate>
<dc:creator>Nick Masao</dc:creator>
<guid>http://nickmasao.wordpress.com/2009/01/26/for-vs-for-each-loops-performance-issues/</guid>
<description><![CDATA[I&#8217;m sure one of you has come to a point where they thought, should I use a For loop or a For E]]></description>
<content:encoded><![CDATA[I&#8217;m sure one of you has come to a point where they thought, should I use a For loop or a For E]]></content:encoded>
</item>
<item>
<title><![CDATA[Prototype.js Breaks JavaScript Foreach Loops]]></title>
<link>http://zurahn.wordpress.com/2009/01/11/prototypejs-breaks-javascript-foreach-loops/</link>
<pubDate>Sun, 11 Jan 2009 23:21:07 +0000</pubDate>
<dc:creator>Zurahn</dc:creator>
<guid>http://zurahn.wordpress.com/2009/01/11/prototypejs-breaks-javascript-foreach-loops/</guid>
<description><![CDATA[This site uses the Prototype.js JavaScript library, primarily for the excellent AJAX methods.  But t]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>This site uses the Prototype.js JavaScript library, primarily for the excellent AJAX methods.  But there&#8217;s a lot more to the library designed to simplify cumbersome methods and make your code work cross-browser without worries.</p>
<p>The developers, though, have gone a bit overboard in places, not letting standards get in their way of imposing their own will on language semantics, including modifying core JavaScript objects.  Adding onto the Array object caused the return of functions with the IN keyword.</p>
<p>In simplistic terms, they broke a keyword (or the keyword was broken, just not fully implemented, per se).</p>
<p>To write a foreach loop (a loop that goes through every element in an array without requiring the knowledge of the key for each element) can be written like this:</p>
<p><span style="font-family:'courier new';"><br />
for(var key IN array) {<br />
  &#8230;<br />
}<br />
</span></p>
<p>Where <em>key</em> is the array index key for the element for each time through the loop, allowing you to access the element by simply <em>array[key]</em>.</p>
<p>Here&#8217;s an example<br />
<span style="font-family:'courier new';"><br />
&#60;script type=&#34;text/javascript&#34;&#62;<br />
var array = ['A', 'B', 'C'];<br />
for (var key in array)<br />
{<br />
  document.write(array[key]);<br />
}<br />
&#60;/script&#62;<br />
</span></p>
<p>Nice and easy, outputs</p>
<p>ABC</p>
<p>Now let&#8217;s do nothing to the code at all, but import the Prototype.js file.  Remember, Prototype doesn&#8217;t execute anything when you load it.</p>
<p><span style="font-family:'courier new';"><br />
&#60;script type=&#34;text/javascript&#34; src=&#34;http://thevgpress.com/js/prototype.js&#34;&#62;&#60;/script&#62;<br />
&#60;script type=&#34;text/javascript&#34;&#62;<br />
var array = ['A', 'B', 'C'];<br />
for (var key in array)<br />
{<br />
  document.write(array[key]);<br />
}<br />
&#60;/script&#62;<br />
</span></p>
<p>Let&#8217;s check the output:</p>
<p>ABCfunction(iterator,context){var index=0;iterator=iterator.bind(context);try{this._each(function(value){iterator(value,index++)})}catch(e){if(e!=$break)throw e;}return this}function(number,iterator,context){iterator=iterator?iterator.bind(context): Prototype.K;var index=-number,slices=[],array=this.toArray();while((index+=number)=result)result=value});return result}function(iterator,context){iterator=iterator?iterator.bind(context): Prototype.K;var result;this.each(function(value,index){value=iterator(value,index);if(result==undefined&#124;&#124;valueb?1:0}).pluck(&#8216;value&#8217;)}function(){return[].concat(this)}function(){var iterator=Prototype.K,args=$A(arguments);if(Object.isFunction(args.last()))iterator=args.pop();var collections=[this].concat(args).map($A);return this.map(function(value,index){return iterator(collections.pluck(index))})}function(){return this.length}function(){return&#8217;['+this.map(Object.inspect).join(', ')+']&#8216;}function(iterator,context){iterator=iterator.bind(context);var result;this.each(function(value,index){if(iterator(value,index)){result=value;throw $break;}});return result}function(iterator,context){iterator=iterator.bind(context);var results=[];this.each(function(value,index){if(iterator(value,index))results.push(value)});return results}function(object){if(Object.isFunction(this.indexOf))if(this.indexOf(object)!=-1)return true;var found=false;this.each(function(value){if(value==object){found=true;throw $break;}});return found}function(){return this.map()}function () { [native code] }function () { [native code] }function(){this.length=0;return this}function(){return this[0]}function(){return this[this.length-1]}function(){return this.select(function(value){return value!=null})}function(){return this.inject([],function(array,value){return array.concat(Object.isArray(value)?value.flatten():[value])})}function(){var values=$A(arguments);return this.select(function(value){return!values.include(value)})}function(){return this.length&#62;1?this:this[0]}function(sorted){return this.inject([],function(array,value,index){if(0==index&#124;&#124;(sorted?array.last()!=value:!array.include(value)))array.push(value);return array})}function(array){return this.uniq().findAll(function(item){return array.detect(function(value){return item===value})})}function(){return[].concat(this)}function(){var results=[];this.each(function(object){var value=Object.toJSON(object);if(value!==undefined)results.push(value)});return&#8217;['+results.join(', ')+']&#8216;}</p>
<p>Not exactly what we want.</p>
<p>There are a couple ways to work around this.  If you want to continue to the use the conventional JavaScript foreach loop using the IN keyword, here&#8217;s an example of how to dodge the weird Prototype glitch:</p>
<p><span style="font-family:'courier new';"><br />
&#60;script type=&#34;text/javascript&#34;&#62;<br />
var array = ['A', 'B', 'C'];<br />
var len = array.length;<br />
var count = 0;<br />
for (var key in array)<br />
{<br />
  if(count &#62;= len)<br />
    break;<br />
  else<br />
    ++count;<br />
  document.write(array[key]);<br />
}<br />
&#60;/script&#62;<br />
</span></p>
<p>This doesn&#8217;t affect the actual length of the array and the functions it returns are at the end, so making sure you only process the correct number of elements eliminates the problem.</p>
<p>Alternatively, you can use the Prototype built-in function for enumerating elements (though this only works on numeric indexes).</p>
<p><span style="font-family:'courier new';"><br />
&#60;script type=&#34;text/javascript&#34;&#62;<br />
var array = ['A', 'B', 'C'];<br />
array.each(function(element) {<br />
  document.write(element);<br />
});<br />
&#60;/script&#62;<br />
</span></p>
<p>Or, perhaps simplest, setting the array initially to an Object type to wipe out any extension, and hence any weird returns.  This however, is dependent on Object not being extended.</p>
<p><span style="font-family:'courier new';"><br />
&#60;script type=&#34;text/javascript&#34;&#62;<br />
var array = new Object();<br />
array = ['A', 'B', 'C'];<br />
for (var key in array)<br />
{<br />
  document.write(array[key]);<br />
}<br />
&#60;/script&#62;<br />
</span></p>
<p>Having to work around Prototype defeats its purpose in the first place.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Basit Yedekleme Programı – 2  / Klasör Kopyalama İşlemleri]]></title>
<link>http://abacigil.wordpress.com/2008/11/07/basit-yedekleme-programi-%e2%80%93-2-klasor-kopyalama-islemleri/</link>
<pubDate>Fri, 07 Nov 2008 17:34:02 +0000</pubDate>
<dc:creator>abacigil</dc:creator>
<guid>http://abacigil.wordpress.com/2008/11/07/basit-yedekleme-programi-%e2%80%93-2-klasor-kopyalama-islemleri/</guid>
<description><![CDATA[  Bu makale toplam 3 bölümden oluşmaktadır ve küçük bir projeyi anlatmaktadır. 3 bölümde birbirinden]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://abacigil.files.wordpress.com/2008/11/fileinfo1.jpg"></a> </p>
<table class="MsoTableGrid" style="border-collapse:collapse;background:silver;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="background-color:transparent;width:460.6pt;border:windowtext 1pt solid;padding:0 5.4pt;" width="614" valign="top">
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Bu makale toplam 3 bölümden oluşmaktadır ve küçük bir projeyi anlatmaktadır. 3 bölümde birbirinden farklı konular içerir ve <strong>yalnız başlarına da okunabilir</strong>. Makaleye ait projeyi, 3 yazınında sonundaki linkten elde edebilirsiniz.</span></p>
<p class="MsoNormal" style="margin:0;"><strong><span style="font-family:Verdana;font-size:10pt;"> </span></strong></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin:0;"><strong><span style="font-family:Verdana;font-size:10pt;"> </span></strong></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Merhaba,</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Bu bölümün 2. yazısında, bir klasörü alt klasörleri ile birlikte başka bir yere kopyalama işlemini anlatacağım. </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Proje aslında basit bir program fakat, içerdiği kodlar işinize yarayacak bilgiler olabilir.</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Öncelikle, bu konumuzu içeren projemizde kullanmamız gereken namespace’leri ve kullanacağımız nesneleri belirtelim.</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<table class="MsoTableGrid" style="border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="background-color:transparent;width:157.8pt;border:silver 1pt solid;padding:0 5.4pt;" width="210" valign="top">
<p class="MsoNormal" style="margin:0;"><strong><span style="text-decoration:underline;"><span style="font-family:Verdana;font-size:10pt;">Konu</span></span></strong></p>
</td>
<td style="border-bottom:silver 1pt solid;border-left:#f0f0f0;background-color:transparent;width:164.25pt;border-top:silver 1pt solid;border-right:silver 1pt solid;padding:0 5.4pt;" width="219" valign="top">
<p class="MsoNormal" style="margin:0;"><strong><span style="text-decoration:underline;"><span style="font-family:Verdana;font-size:10pt;">Namespace</span></span></strong></p>
</td>
<td style="border-bottom:silver 1pt solid;border-left:#f0f0f0;background-color:transparent;width:142.35pt;border-top:silver 1pt solid;border-right:silver 1pt solid;padding:0 5.4pt;" width="190" valign="top">
<p class="MsoNormal" style="margin:0;"><strong><span style="text-decoration:underline;"><span style="font-family:Verdana;font-size:10pt;">Nesneler</span></span></strong></p>
</td>
</tr>
<tr>
<td style="border-bottom:silver 1pt solid;border-left:silver 1pt solid;background-color:transparent;width:157.8pt;border-top:#f0f0f0;border-right:silver 1pt solid;padding:0 5.4pt;" width="210" valign="top">
<p class="MsoNormal" style="margin:0;"><strong><span style="font-family:Verdana;font-size:10pt;">Dosya İşlemleri</span></strong></p>
</td>
<td style="border-bottom:silver 1pt solid;border-left:#f0f0f0;background-color:transparent;width:164.25pt;border-top:#f0f0f0;border-right:silver 1pt solid;padding:0 5.4pt;" width="219" valign="top">
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">System.IO</span></p>
</td>
<td style="border-bottom:silver 1pt solid;border-left:#f0f0f0;background-color:transparent;width:142.35pt;border-top:#f0f0f0;border-right:silver 1pt solid;padding:0 5.4pt;" width="190" valign="top">
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;color:#2b91af;font-size:10pt;">DirectoryInfo</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;color:#2b91af;font-size:10pt;">FileInfo</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;color:#2b91af;font-size:10pt;">FileStream</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Şimdi, kısaca bu bölümde kullanacağımız birkaç kod ve işlevlerinden bahsedelim.</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;color:#2b91af;font-size:10pt;">DirectoryInfo</span><span style="font-family:Verdana;font-size:10pt;"> InfoKaynak = <span style="color:blue;">new</span> <span style="color:#2b91af;">DirectoryInfo</span>(<span style="color:#a31515;">&#8220;C:\Projelerim&#8221;</span>);</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Burada <span style="color:#2b91af;">DirectoryInfo </span>türünden InfoKaynak adında bir nesne ürettik ve klasör yolunu da <span style="color:#a31515;">&#8220;C:\Projelerim&#8221; </span>olarak belirledik. Yaptığımız işlemde, bize belirlediğimiz bu klasör hakkında bilgi edinme, dosyalara erişebilme ve onlarla ilgili işlemler olanağı ortaya çıkıyor. Aşağıdaki resimde örnek bir klasörün <span style="color:#2b91af;">DirectoryInfo </span>nesnesine gönderildiğinde, içerdiği bilgileri gösteriyor.</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"> </p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><a href="http://abacigil.files.wordpress.com/2008/11/directoryinfo.jpg"><img class="alignnone size-full wp-image-57" title="directoryinfo" src="http://abacigil.wordpress.com/files/2008/11/directoryinfo.jpg" alt="directoryinfo" width="460" height="171" /></a> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;color:#2b91af;font-size:10pt;">DirectoryInfo</span><span style="font-family:Verdana;font-size:10pt;"> ile türettiğimiz InfoKaynak’ın GetFiles() methodu ile klasördeki dosyalara ait bilgiler elde edebiliriz. Fakat burada şöyle bir durum sözkonusu;</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">GetFiles() methodu +2 overload içerir. </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">1- <span style="color:#2b91af;">FileInfo</span>[] DosyaBilgileri = InfoKaynak.GetFiles();</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">2- <span style="color:#2b91af;">FileInfo</span>[] DosyaBilgileri = InfoKaynak.GetFiles(<span style="color:#a31515;">&#8220;*.*&#8221;</span>);,</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">3- <span style="color:#2b91af;">FileInfo</span>[] DosyaBilgileri = InfoKaynak.GetFiles(<span style="color:#a31515;">&#8220;*.*&#8221;</span>, <span style="color:#2b91af;">SearchOption</span>.AllDirectories);</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><strong><em><span style="font-family:Verdana;font-size:10pt;">GetFiles() :</span></em></strong><span style="font-family:Verdana;font-size:10pt;"> O andaki bulunan klasörün içerisindeki dosyalara ait bilgileri alır. Altklasörlerin içindeki dosyaları almaz.</span></p>
<p class="MsoNormal" style="margin:0;"><strong><em><span style="font-family:Verdana;font-size:10pt;">GetFiles(string searchPattern) :</span></em></strong><span style="font-family:Verdana;font-size:10pt;"> GetFiles() ile aynı işlemi görür fakat burada dosyaları filtreleme şansına sahipsiniz. Yani GetFiles(<span style="color:#a31515;">&#8220;*.*&#8221;</span>),<span style="color:#a31515;"> </span>GetFiles(<span style="color:#a31515;">&#8220;*.txt&#8221;</span>) şeklinde kullabilirsiniz. Unutmayın, burada da lat klasörler dahil değildir.</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><strong><em><span style="font-family:Verdana;font-size:10pt;">GetFiles(string searchPattern, SearchOption searchOption) : </span></em></strong><span style="font-family:Verdana;font-size:10pt;">Bu overload ise, yine size dosya filtreleme şansı veriyor ve aynı zamanda alt klasördeki dosyalara ait bilgileri de elde etmenizi sağlıyor. GetFiles(<span style="color:#a31515;">&#8220;*.*&#8221;</span>, <span style="color:#2b91af;">SearchOption</span>.AllDirectories) şeklinde ana klasör altında tüm dosyalara ulaşabilirsiniz, alt klasörlerde dahil olmaz üzere.</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"> <a href="http://abacigil.files.wordpress.com/2008/11/fileinfo1.jpg"><img class="alignnone size-full wp-image-59" title="fileinfo1" src="http://abacigil.wordpress.com/files/2008/11/fileinfo1.jpg" alt="fileinfo1" width="460" height="170" /></a></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Yukarıda göreceğiniz gibi, ana klasörümüzün alt klasörleri ile birlikte içerdiği bütün dosyaların bilgilerini elde ettik. Toplam 906 dosya olduğunu belirtiyor ve her bir dosya için ayrı ayrı bütün bilgiler yer alıyor.</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><strong><span style="font-family:Verdana;font-size:10pt;">Klasörün boyutunu hesaplama</span></strong></p>
<p class="MsoNormal" style="margin:0;"><strong><span style="font-family:Verdana;font-size:10pt;"> </span></strong></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Ana klasörünüzün alt klasörleri ile birlikte tüm boyutunu öğrenmek için herhangi bir method yok. Bu yüzden tek tek dosyaların boyutlarını elde edip toplama yapmamız gerekiyor.</span></p>
<div style="border-bottom:windowtext 1pt solid;border-left:medium none;border-top:medium none;border-right:medium none;padding:0 0 1pt;">
<p class="MsoNormal" style="margin:0;padding:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
</div>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;color:#2b91af;font-size:10pt;">FileInfo</span><span style="font-family:Verdana;font-size:10pt;">[] DosyaBoyutu = InfoKaynak.GetFiles(<span style="color:#a31515;">&#8220;*.*&#8221;</span>, <span style="color:#2b91af;">SearchOption</span>.AllDirectories);</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;color:blue;font-size:10pt;">long</span><span style="font-family:Verdana;font-size:10pt;"> size = 0;</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;color:blue;font-size:10pt;">foreach</span><span style="font-family:Verdana;font-size:10pt;">(<span style="color:#2b91af;">FileInfo</span> file <span style="color:blue;">in</span> DosyaBoyutu)</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">{</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>     </span>size += file.Length;</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">}</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<div style="border-bottom:windowtext 1pt solid;border-left:medium none;border-top:medium none;border-right:medium none;padding:0 0 1pt;">
<p class="MsoNormal" style="margin:0;padding:0;"><span style="font-family:Verdana;color:blue;font-size:10pt;">string </span><span style="font-family:Verdana;font-size:10pt;">Boyut<span style="color:blue;"> </span>= (size/1048576).ToString() + <span style="color:#a31515;">&#8221; MB&#8221;</span>;</span></p>
<p class="MsoNormal" style="margin:0;padding:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
</div>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Her bir dosyanın boyutunu alarak toplama işlemi yapıyoruz ve MB hesabı yapabilmek için, <em>1 mb = 1048576</em> <em>byte</em> diyerek matematiksel işlemi gösteriyoruz.</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><strong><span style="font-family:Verdana;font-size:10pt;">Klasör içerisindeki toplam dosya sayısı</span></strong></p>
<p class="MsoNormal" style="margin:0;"><strong><span style="font-family:Verdana;font-size:10pt;"> </span></strong></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">C# ile bunu çok basit bir şekilde elde edebiliyoruz. Yine GetFiles() methodunun 3. overload’unu kullanıyoruz.Böylece, alt klasörler de dahil toplam dosya sayısını elde edeceğiz.İşlemimiz bir klasörü ilgilendirdiği için <span style="color:#2b91af;">DirectoryInfo </span>sınıfından türettiğimiz nesneyi kullanacağız.</span></p>
<p class="MsoNormal" style="margin:0;"><strong><span style="font-family:Verdana;font-size:10pt;"> </span></strong></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;color:#2b91af;font-size:10pt;">DirectoryInfo</span><span style="font-family:Verdana;font-size:10pt;"> InfoKaynak = <span style="color:blue;">new</span> <span style="color:#2b91af;">DirectoryInfo</span>(<span style="color:#a31515;">&#8220;C:\Projelerim&#8221;</span>);</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;color:blue;font-size:10pt;">int </span><span style="font-family:Verdana;font-size:10pt;">ToplamDosyaSayisi =<span>  </span>InfoHedef.GetDirectories(<span style="color:#a31515;">&#8220;*.*&#8221;</span>, <span style="color:#2b91af;">SearchOption</span>.AllDirectories).Length.ToString();</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">GetFiles methodunun Lenght property’si ile amacımıza ulaşıyoruz.</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><strong><span style="font-family:Verdana;font-size:10pt;">Klasörü Kopyalama</span></strong></p>
<p class="MsoNormal" style="margin:0;"><strong><span style="font-family:Verdana;font-size:10pt;"> </span></strong></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Şimdi ise, bir klasörü alt klasörleri ile birlikte nasıl başka bir yere kopyalarız onu öğreneceğiz. Mantık olarak olması gereken şudur;</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Önce ana klasörü elde edip, içerisindeki dosyaları hedef klasöre kopyalamak, daha sonra ana klasör içerisindeki diğer klasörlere tek tek girerek, içerisindeki dosyaları hedef klasördeki yere kopyalamak. Dosya kopyalama işlemi yapılırken kaynak klasördeki, dosyaya ait klasörün hedef klasörde var olup olmadığı kontrol edilmeli, yok ise bu klasör oluşturulmalı.</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Şimdi kod kısmını inceleyelim,</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;color:green;font-size:10pt;"><span>            </span>//burada basit bir kontrol yaparak</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:green;">//kopyalanacak klasörün var olup olmadığını kontrol ediyoruz.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:green;">//yoksa klasörü belirtilen yolda oluşturuyoruz.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:blue;">if</span> (!HedefKlasor.Exists)</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span>{</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>                </span>HedefKlasor.Create();</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span>}</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:green;">//Burada kaynak klasör içerisindeki dosyaları elde ediyoruz,</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:green;">//dikkat edin, alt klasörlerin içerisindeki dosyalar burada alınmıyor.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:green;">//çünkü yapacağımız işlem, her bir klasör ve bunlara ait dosyaları birebir kopyalamak.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:green;">//bu yüzden de, önce bulunduğumuz klasör içerisindeki dosyaları kopyalıyoruz.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:green;">//daha sonra 2. foreach döngüsünde göreceksiniz, kaynak klasör içerisindeki </span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:green;">//tüm klasörleri alıyoruz. ve sıra sıra hepsinin içine girip aynı şekilde kopyalıyoruz.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:#2b91af;">FileInfo</span>[] Dosyalar = KaynakKlasor.GetFiles();</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:green;">//her bir dosya için kopyalama işlemeni başlatıyoruz.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:blue;">foreach</span> (<span style="color:#2b91af;">FileInfo</span> dosya <span style="color:blue;">in</span> Dosyalar)</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span>{</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>                </span><span style="color:green;">//CopyTo methodu ile dosyamızı, hedef klasörümüze, aynı dosya adı ile gönderiyoruz.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>                </span><span style="color:green;">//Path.Combine methoduna bakarsanız 2. bir argument&#8217;i var &#8220;true&#8221; değerinde,</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>                </span><span style="color:green;">//true vermemizin nedeni eğer bu dosya daha öcneden bu klasör içerisinde var ise,</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>                </span><span style="color:green;">//üzerine yazmasına izin veriyoruz.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>                </span>dosya.CopyTo(<span style="color:#2b91af;">Path</span>.Combine(HedefKlasor.FullName, dosya.Name), <span style="color:blue;">true</span>);</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:green;">//şimdi asıl olaya gelelim.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:green;">//burada her bir klasör için bu fonksiyon tekrar çağırılacak.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:green;">//çünkü yukarıdaki işlemler o anda bulunduğunuz klasörün içerisindeki dosyaları kopyaladı.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:green;">//ama eğer, altklasörler varsa bu sefer bu klasörlerin de içine girip tekrar aynı işlemleri yapmalı.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:green;">//işte şimdi kaynak klasördeki tüm klasörleri alıyoruz.alt klasörlerde dahil.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:#2b91af;">DirectoryInfo</span>[] Klasorler = KaynakKlasor.GetDirectories();</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span><span style="color:blue;">foreach</span> (<span style="color:#2b91af;">DirectoryInfo</span> Klasor <span style="color:blue;">in</span> Klasorler)</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span>{</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>                </span><span style="color:green;">//ve sıra sıra bulunduğumuz klasörleri tekrar bu fonksiyona gönderiyoruz</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>                </span><span style="color:green;">//ta ki, tüm klasörler bitene kadar.</span></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>                </span>KlasorleriKopyala(Klasor, <span style="color:blue;">new</span> <span style="color:#2b91af;">DirectoryInfo</span>(<span style="color:#2b91af;">Path</span>.Combine(HedefKlasor.FullName, Klasor.Name)));</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><span>            </span>}</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Evet, 2. yazımız burada bitiyor. Dosya işlemlerine kısa bir giriş yaptık. En çok kullanılan,ihtiyaç duyulan ve sorun yaşanılan işlemleri kısaca inceledik. Umarım yazım yardımcı olmuştur.</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Herkese kolay gelsin, iyi çalışmalar.</span></p>
<p class="MsoNormal" style="margin:0;">
<p class="MsoNormal" style="margin:0;"> </p>
<p><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">Projeyi aşağıda linkten indirebilirsiniz.</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;">RapidShare Link:</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Arial;color:black;font-size:9pt;"><a href="http://rapidshare.com/files/161500396/QWYedekleme.rar"><span style="color:#0000ff;">http://rapidshare.com/files/161500396/QWYedekleme.rar</span></a></span></p>
<p class="MsoNormal" style="margin:0;"> </p>
<div></div>
<p><span style="font-family:Arial;color:black;font-size:9pt;"></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><a href="http://abacigil.wordpress.com/2008/11/07/basit-yedekleme-programi-%e2%80%93-1-xml-dosyasi-okuma-ve-yazma-islemleri"><span style="color:#0000ff;">Basit Yedekleme Programı – 1 <span> </span>/ XML Dosyası Okuma ve Yazma İşlemleri</span></a></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><a href="http://abacigil.wordpress.com/2008/11/07/basit-yedekleme-programi-%e2%80%93-2-klasor-kopyalama-islemleri"><span style="color:#0000ff;">Basit Yedekleme Programı – 2<span>  </span>/ Klasör Kopyalama İşlemleri</span></a></span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"><a href="http://abacigil.wordpress.com/2008/11/07/basit-yedekleme-programi-%e2%80%93-3-backgroundworker-ile-calismak"><span style="color:#0000ff;">Basit Yedekleme Programı – 3<span>  </span>/ BackGroundWorker ile çalışmak.</span></a></span></p>
<p class="MsoNormal" style="margin:0;"> </p>
<p> </p>
<p></span></p>
<p class="MsoNormal" style="margin:0;"> </p>
<p class="MsoNormal" style="margin:0;"> </p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Arial;color:black;font-size:9pt;">-</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-family:Verdana;font-size:10pt;"> </span></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Iterator, Iterable, foreach - und wo ist mein Schleifenzähler?]]></title>
<link>http://laptopundlederhosn.wordpress.com/2008/10/28/iterator-iterable-foreach-und-wo-ist-mein-schleifenzahler/</link>
<pubDate>Tue, 28 Oct 2008 08:32:28 +0000</pubDate>
<dc:creator>Andi</dc:creator>
<guid>http://laptopundlederhosn.wordpress.com/2008/10/28/iterator-iterable-foreach-und-wo-ist-mein-schleifenzahler/</guid>
<description><![CDATA[Irgendwie ist es schon ein Kreuz mit Schleifen. Die klassische Variante ist ja: for (int iPage = 0; ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Irgendwie ist es schon ein Kreuz mit Schleifen. Die klassische Variante ist ja:</p>
<p><code>for (int iPage = 0; iPage &#60; book.getPagesCount(); iPage++)<br />
{<br />
&#160;&#160;Page page = book.getPage(iPage);<br />
&#160;&#160;//...<br />
}</code></p>
<p>Das ist aber meiner Ansicht nach aus zwei Gründen hässlich:</p>
<ul>
<li>Wenn wir einfach nur alle Seiten der Reihe nach besuchen wollen, ist die Schreibweise mit dem Zähler viel zu unübersichtlich (wobei sich das Auge des Java-Programmierers mit der Zeit daran gewöhnt&#8230;), außerdem wiederholt sich an unzähligen Stellen im Programm die selbe Logik. Schöner wäre es, wenn wir diese Logik an einem einzigen Punkt im Programm zusammenfassen könnten.</li>
<li>Wir müssen davon ausgehen, dass man auf die Seiten des Buches mit <code>RandomAccess</code>, also mit konstanter Zeit, zugreifen kann, z.B. weil ein Array dahinter steht. Wenn wir es aber z.B. mit einer verketteten Liste zu tun haben, haben wir plötzlich lineare Zugriffszeit.</li>
</ul>
<p>Da scheint die seit Java 5 verfügbare foreach-Schleife die richtige Lösung zu sein:</p>
<p><code>for (Page page : book.getPages())<br />
{<br />
&#160;&#160;//...<br />
}</code></p>
<p>Eigentlich perfekt, oder? Die Schleifenlogik ist im jeweiligen <code>Iterable</code>-Objekt implementiert, und es kann uns egal sein, ob ein Array oder eine verkettete Liste oder etwas anderes dahinter steht.<br />
Was ist jetz aber, wenn wir in der Schleife die aktuelle Seitennummer brauchen? Vorher war das <code>iPage</code>, aber diese Variable steht uns nicht mehr zur Verfügung.</p>
<p>Die Lösung, die ich im Moment verwende, versucht, beide Vorteile zu kombinieren. Ich erstelle zuerst einen <code>Iterator</code>, der gleichzeitig das <code>Iterable</code>-Interface implementiert (warum das nicht jeder Iterator in Java tut, ist mir bis heute ein Rätsel &#8211; ein schlichtes <code>return this;</code> würde ja reichen?!), der aber intern auch den aktuellen Index speichert und eine Methode <code>getIndex()</code> zur Verfügung stellt.</p>
<p>Verwenden kann man den Iterator dann z.B. so:</p>
<p><code>It&#60;Page&#62; pages = new It&#60;Page&#62;(book.getPages());<br />
for (Page page : pages)<br />
{<br />
&#160;&#160;int pageIndex = pages.getIndex();<br />
&#160;&#160;//...<br />
}</code></p>
<p>Genauso könnten wir jetzt einen Iterator erstellen, der rückwärts durch die Collection geht, nur ungerade oder gerade Indices betrachtet usw. Vielleicht lässt sich das ganze ja ab Java 7 (Closures!) noch viel schöner machen.</p>
<p>Zum Abschluss noch der Code von <code>It</code> (ich habe die Gelegenheit auch gleich genutzt, Schreibschutz für die Collection zu setzen): <a href='http://laptopundlederhosn.files.wordpress.com/2008/10/it.pdf'>It-Klasse</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Build all your stylesheets...every time...]]></title>
<link>http://edsyrett.wordpress.com/2008/10/17/build-all-your-stylesheetsevery-time/</link>
<pubDate>Fri, 17 Oct 2008 16:14:23 +0000</pubDate>
<dc:creator>edsyrett</dc:creator>
<guid>http://edsyrett.wordpress.com/2008/10/17/build-all-your-stylesheetsevery-time/</guid>
<description><![CDATA[We have a whole bunch of stylesheets in our project.  Unfortunately, our release build had the filen]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>We have a whole bunch of stylesheets in our project.  Unfortunately, our release build had the filenames hard coded in, i.e. it was only building specific stylesheets. So when somebody added new css files, they didn&#8217;t get included in the build.  </p>
<p>There must be a way to automatically pick up all the css files and build them, we thought.  And here it is&#8230;.</p>
<p>This tip relies on the <em>foreach</em> and <em>propertyregexp</em> Ant tasks from the ant-contrib library.  You can download the ant-contrib distro from <a title="SourceForge - ANT-Contrib" href="http://sourceforge.net/project/showfiles.php?group_id=36177&#38;package_id=28636" target="_self">here</a>.  I found the easiest way to make use of this library is to just copy ant-contrib.jar to your Ant lib directory.</p>
<p>In your build file, simply add the following line, which will enable Ant to access the new tasks:</p>
<blockquote>
<pre><code>&#60;taskdef resource="net/sf/antcontrib/antlib.xml"/&#62;</code></pre>
</blockquote>
<p>and here&#8217;s the interesting bit:</p>
<blockquote>
<pre><code>&#60;target name="build-debug"&#62;
    &#60;foreach param="filename.css" target="css-build-debug"&#62;
        &#60;path&#62;
            &#60;fileset dir="${basedir}"&#62;
                &#60;include name="*.css"/&#62;
	    &#60;/fileset&#62;
        &#60;/path&#62;
    &#60;/foreach&#62;
&#60;/target&#62;

&#60;target name="css-build-debug"&#62;
    &#60;echo&#62;Building stylesheet ${filename.css} (DEBUG)&#60;/echo&#62;

    &#60;!-- Extract the base of the filename, i.e. for c:\Development\tls\...\v1.0\kn.css" we want "kn" --&#62;
    &#60;propertyregex property="basename" input="${filename.css}" regexp=".*\\(.*)\.css" select="\1"/&#62;

    &#60;java jar="${mxmlc.jar}" dir="${basedir}" failonerror="true" fork="true" maxmemory="256m"&#62;
      	&#60;arg line="+flexlib='${flexsdk.frameworks.dir}'"/&#62;
	&#60;arg line="${filename.css}"/&#62;
        &#60;arg line="-output 'bin/${basename}.swf'"/&#62;
    &#60;/java&#62;
&#60;/target&#62;</code></pre>
</blockquote>
<p>The <em>&#60;foreach&#62;</em> task is provided by the Ant-contrib library &#8211; in this case it iterates through all the files picked out by the <em>&#60;fileset&#62; </em>task and passes them to the target in the property <em>filename.css</em>.</p>
<p>The <em>&#60;propertyregex&#62;</em> task is another one from the Ant-contrib library.  This takes an input property, in this case <em>filename.css</em>,  performs a regex search for a substring, and puts the result back into another property, <em>basename</em>. </p>
<p>The clever bit is the actual regular expression &#8211; all it really does is extract the filename without the extension from <em>filename.css</em>.  We need this to be able to pass in the name of the output swf.</p>
<p>For those of you who love your regular expressions, here&#8217;s a synopsis of how it works:</p>
<li>.* &#8211; jump over any characters until&#8230;</li>
<li>\\ &#8211; .. you find a backslash.</li>
<li>(.*)\.css &#8211; Look for as sequence that ends in &#8220;.css&#8221;, with any characters before it.  Track backwards up to the previous search token (in this case a backslash) and put all the characters between this backslash and the &#8220;.css&#8221; in a group.</li>
<li>The value of the select attribute in the propertyregexp task defines which group is returned and copied to the basename property.</li>
<p>&#8230;and that&#8217;s it&#8230;.</p>
</div>]]></content:encoded>
</item>

</channel>
</rss>
