Javascript: Maximizando janela automáticamente com javascript

Posted on July 19th, 2010

Hoje eu precisei de uma função em Javascript para maximizar uma janela do usuário. Vou mostrar para vocês as duas formas de fazer:

1º) Colocando a função no começo do body
<body onload=”window.resizeTo(screen.width,screen.height)” onresize=”window.resizeTo(screen.width,screen.height)”>

2º) Adicionando na tag da página head

<script language="Javascript1.2">top.window.moveTo(0,0);if (document.all) {top.window.resizeTo(screen.availWidth,screen.availHeight);}else if (document.layers||document.getElementById) {if (top.window.outerHeight<screen.availHeight||top.window.outerWidth<screen.availWidth){top.window.outerHeight = screen.availHeight;top.window.outerWidth = screen.availWidth;}}</script>

Desenvolvimento: sistema de comentários online

Posted on May 22nd, 2010


Todo desenvolvedor e arquiteto de sistema web sabe o quanto problemático é o armazenamento de comentários. Além de gastar um espaço gigante no servidor o desenvolvedor precisa ficar atento ao tipo de dado que é gravado no banco de dados para evitar furos de segunça.

O site http://www.intensedebate.com/ possibilita que você crie um sistema de comentários eficiente e com vários recursos interessantes sem ter que gastar o espaço em disco do seu servidor.

O serviço vale a pena.

Developer: Mensagens de alerta em Ajax

Posted on April 21st, 2010

Substitua o comando alert do Javascript por elementos com estilo em Ajax e Jquery

http://labs.abeautifulsite.net/projects/js/jquery/alerts/demo/

Utilizando o título da página como link na URL com mod_rewrite

Posted on August 14th, 2009

Este é o primeiro tutorial para utilização do Mod Rewrite para que suas páginas sejam linkadas pelo título do post.

1) Utilize a função abaixo para eliminar a acentuação e separar as palavras por - Ex:

Eu gosto de filmes de ação

eu-gosto-de-filmes-de-acao

function toAscii($str) {
$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/”, ”, $str);
$clean = strtolower(trim($clean, ‘-’));
$clean = preg_replace(”/[\/_|+ -]+/”, ‘-’, $clean);

return $clean;
}

Fazendo uma Div com cantos arredondados sem imagem

Posted on February 23rd, 2009

Esta dica vai para os “Webers” que estão cansados de Div quadradonas em seus layouts, eu não sou web designer porém algumas vezes sou obrigado a “meter a mão em codificação”.

Este código é muito simples você deve apenas adicionar um .js em seu arquivo e criar o seu respectivo CSS, muito simples.

Olhem o exemplo no link a seguir: http://www.curvycorners.net/examples/demo.html

Tutorial XPath XML

Posted on March 14th, 2005

Colabora??o: Ot?vio Augusto Bizetto Penatti

Este tutorial ? uma tradu??o do tutorial de XPath da W3Schools (http://www.w3schools.com/), dispon?vel em http://www.w3schools.com/xpath/default.asp

Tutorial XPath
==============

XPath ? um conjunto de regras de sintaxe para definir partes de um documento XML.

XPath ? o elemento principal no padr?o W3C XSLT. Sem o conhecimento de XPath voc? n?o ser? capaz de criar documentos XSLT.

Introdu??o ao XPath
===================

XPath ? um conjunto de regras de sintaxe para definir partes de um documento XML.

O que ? XPath?
==============

- XPath ? uma sintaxe para definir partes de um documento XML
- XPath usa caminhos para definir elementos XML
- XPath define uma biblioteca de fun??es padr?o
- XPath ? o elemento principal em XSLT
- XPath n?o ? escrito em XML
- XPath ? um padr?o W3C

Como caminhos de arquivos tradicionais
======================================

XPath usa express?es de caminho para identificar n?s em um documento XML. Essas express?es de caminho se parecem muito com as express?es que voc? v? quando voc? trabalha num sistema de arquivos de um computador:

w3schools/xpath/default.asp

Exemplo de XPath
================

Veja esse documento XML simples:

< ?xml version="1.0" encoding="ISO-8859-1"?>

Bob Dylan

10.90

Bonnie Tyler

9.90

Dolly Parton

9.90

A express?o XPath abaixo seleciona o elemento RAIZ catalog:

/catalog

A express?o XPath abaixo seleciona todos os elementos cd do elemento catalog:

/catalog/cd

A express?o XPath abaixo seleciona todos os elementos price de todos os elementos cd do elemento catalog:

/catalog/cd/price

Nota: Se o caminho come?a com uma barra ( / ) ele representa um caminho absoluto para um elemento!

XPath define uma biblioteca de fun??es padr?o
=============================================

XPath define uma biblioteca de fun??es padr?o para trabalhar com strings, n?meros e express?es booleanas.

A express?o XPath abaixo seleciona todos os elementos cd que tem um elemento price que tem um valor maior que 10.80:

/catalog/cd[price>10.80]

XPath ? usado em XSLT
=====================

XPath ? o elemento principal do padr?o XSLT. Sem o conhecimento de XPath voc? n?o ser? capaz de criar documentos XSLT.

Voc? pode ler mais sobre XSLT no nosso tutorial XSLT em ingl?s (http://www.w3schools.com/xsl/default.asp) ou em portugu?s (xslt.htm).

XPath ? um padr?o W3C
=====================

XPath foi liberado com uma recomenda??o W3C em 16 de novembro de 1999 como uma linguagem para endere?ar partes de um documento XML.

XPath foi desenvolvido para ser usado por XSLT, XPointer e outros softwares XML parsing.

Voc? pode ler mais sobre padr?es XML e XSl em nosso tutorial W3C (http://www.w3schools.com/w3c/default.asp)

Sintaxe XPath
=============

XPath usa express?es de caminho para localizar n?s dentro de documentos XML.

Documento XML de Exemplo
========================

N?s usaremos esse documento XML simples para descrever a sintaxe XPath:

< ?xml version="1.0" encoding="ISO-8859-1"?>

Bob Dylan

10.90

Bonnie Tyler

9.90

Dolly Parton

9.90

Localizando N?s
===============

Documentos XML podem ser representados como ?rvores de n?s (muito similar ? vis?o em ?rvore das pastas do seu computador).

XPath usa uma express?o padr?o para identificar n?s em um documento XML. Um padr?o XPath ? uma lista nomes de elementos filhos separada por barras que descreve o caminho atrav?s do documento XML. O padr?o “seleciona” elementos que combinam com o caminho.

A express?o XPath a seguir seleciona todos os elementos pre?o de todos os elementos cd do elemento catalog:

/catalog/cd/price

Nota: Se o caminho come?a com uma barra ( / ) ele representa um caminho absoluto para um elemento!

Nota: Se o caminho come?a com duas barras ( // ) ent?o todos os elementos no documento que se encaixam no crit?rio ser?o selecionados (mesmo que eles estejam em n?veis diferentes da ?rvore XML)!

A express?o XPath a seguir seleciona todos os elementos cd no documento:

//cd

Selecionando elementos desconhecidos
====================================

Curingas ( * ) podem ser usados para selecionar elementos XML desconhecidos.

A express?o XPath a seguir seleciona todos os elementos filhos de todos os elementos cd do elemento catalog:

/catalog/cd/*

A express?o XPath a seguir seleciona todos os elementos price que s?o elementos netos do elemento catalog:

/catalog/*/price

A express?o XPath a seguir seleciona todos os elementos price que t?m dois ancestrais:

/*/*/price

A express?o XPath a seguir seleciona todos os elementos no documento:

//*

Selecionando Se??es
===================

Usando-se colchetes numa express?o XPath voc? pode especificar um elemento adiante.

A express?o XPath a seguir seleciona o primeiro elemento cd filho do elemento catalog:

/catalog/cd[1]

A express?o XPath a seguir seleciona o ?ltimo elemento cd filho do elemento catalog (Nota: n?o existe a fun??o first()):

/catalog/cd[last()]

A express?o XPath a seguir seleciona todos os elementos cd do elemento catalog que tem um elemento price:

/catalog/cd[price]

A express?o XPath a seguir seleciona todos os elementos cd do elemento catalog que tem um elemento price com valor de 10.90:

/catalog/cd[price=10.90]

A express?o XPath a seguir seleciona todos os elementos price de todos os elementos cd do elemento catalog que tem um elemento price com valor de 10.90:

/catalog/cd[price=10.90]/price

Selecionando v?rios caminhos
============================

Usando o operador “|” numa express?o XPath voc? pode selecionar v?rios caminhos.

A express?o XPath a seguir seleciona todos os elementos title e artist do elemento cd do elemento catalog:

/catalog/cd/title | /catalog/cd/artist

A express?o XPath a seguir seleciona todos os elementos title e artist do documento:

//title | //artist

A express?o XPath a seguir seleciona todos os elementos title, artist e price do documento:

//title | //artist | //price

A express?o XPath a seguir seleciona todos os elementos title do elemento cd do elemento catalog, e todos os elementos artist no documento:

/catalog/cd/title | //artist

Selecionando atributos
======================

Em XPath todos os atributos s?o especificados pelo prefixo “@”.

Esta express?o XPath seleciona todos os atributos chamados country:

//@country

Esta express?o XPath seleciona todos os elementos cd que tem um atributo chamado country:

//cd[@country]

Esta express?o XPath seleciona todos os elementos cd que tem algum atributo:

//cd[@*]

Esta express?o XPath seleciona todos os elementos cd que tem um atributo chamado country com valor ‘UK’:

//cd[@country='UK']

XPath Location Paths (Caminho Locais XPath)
===========================================

Uma express?o de caminho local (location path) resulta em um conjunto de n?s.

Express?o de Caminho Local
==========================

Um caminho local pode ser absoluto ou relativo.

Um caminho local absoluto come?a com uma barra ( / ) e um caminho local relativo n?o. Em ambos os casos o caminho local consiste de um ou mais n?veis de localiza??o, cada um separado por uma barra:

Um caminho local absoluto:

/step/step/…

Um caminho local relativo:

step/step

Os n?veis de localiza??o s?o avaliados em ordem um de cada vez, da esquerda pra direita. Cada n?vel ? avaliado segundo os n?s no conjunto de n?s atual. Se o caminho local ? absoluto, o conjunto de n?s atual ? o n? raiz. Se o caminho local ? relativo, o conjunto de n?s atual consiste do n? onde a express?o est? sendo usada. N?veis de localiza??o consistem de:
- um eixo (especifica a rela??o de ?rvore entre os n?s selecionados pelo n?vel de localiza??o e o n? atual)
- um n? teste (especifica o tipo de n? e o nome expandido dos n?s selecionados pelo n?vel de localiza??o)
- zero ou mais predicados (usa express?es para refinar mais o conjunto de n?s selecionado pelo n?vel de localiza??o)

A sintaxe para um n?vel de localiza??o ?:

nomeeixo::noteste[predicado]

Exemplo:

child::price[price=9.90]

Eixos e N?s de Teste
====================

Um eixo define um conjunto de n?s relativo ao n? atual. Um n? de teste ? usado para identificar um n? dentro de um eixo. N?s podemos executar um n? de teste por nome ou por tipo.

|| Nome do Eixo | Descri??o ||
| ancestor | Cont?m todos os ancestrais (pais, av?s, etc) do n? atual. Nota: Este eixo incluir? sempre o n? raiz, a menos que o n? atual seja o n? raiz |
| ancestor-or-self | Cont?m o n? atual mais todos os seus ancestrais (pai, av?, etc) |
| attribute | Cont?m todos os atributos do n? atual |
| child | Cont?m todos os filhos do n? atual |
| descendant | Cont?m todos os descendentes (filhos, netos, etc) do n? atual. Nota: Este eixo nunca cont?m atributos ou n?s namespace |
| descendant-or-self | Cont?m o n? atual mais todos os seus descendentes (filhos, netos, etc) |
| following | Cont?m tudo no documento depois da tag de fechamento do n? atual |
| following-sibling | Cont?m todos os irm?os depois do n? atual. Nota: Se o n? atual ? um n? atributo ou um n? namespace, este eixo estar? vazio |
| namespace | Cont?m todos os n?s namespace do n? atual |
| parent | Cont?m o pai do n? atual |
| preceding | Cont?m tudo no documento que est? antes da tag de abertura do n? atual |
| preceding-sibling | Cont?m todos os irm?os antes do n? atual. Nota: Se o n? atual ? um n? atributo ou um n? namespace, este eixo estar? vazio |
| self | Cont?m o n? atual |

Exemplos

|| Exemplo | Resultado ||
| child::cd | Seleciona todos os elementos cd que s?o filhos do n? atual (se o n? atual n?o tem cds filhos, ser? selecionado um conjunto vazio de n?s) |
| attribute::src | Seleciona o atributo src do n? atual (se o n? atual n?o tem atributo src, ser? selecionado um conjunto vazio de n?s) |
| child::* | Seleciona todos os elementos filhos do n? atual |
| attribute::* | Seleciona todos os atributos do n? atual |
| child::text() | Seleciona o n? texto filho do n? atual |
| child::node() | Seleciona todos os filhos do n? atual |
| descendant::cd | Seleciona todos os elementos cd descendentes do n? atual |
| ancestor::cd | Seleciona todos os cds ancestrais do n? atual |
| ancestor-or-self::cd | Seleciona todos os cds ancestrais do n? atual e, se o n? atual ? um elemento cd, seleciona o n? atual tamb?m |
| child::*/child::price | Seleciona todos os pre?os netos do n? atual |
| / | Seleciona a raiz do documento |

Predicados
==========

Um predicado filtra um conjunto de n?s em um novo conjunto de n?s. Um predicado fica dentro de colchetes ( [] ).

Exemplos

|| Exemplo | Resultado ||
| child::price[price=9.90] | Seleciona todos os elementos price que s?o filhos do n? atual com um pre?o igual a 9.90 |
| child::cd[position()=1] | Seleciona o primeiro cd filho do n? atual |
| child::cd[position()=last()] | Seleciona o ?ltimo cd filho do n? atual |
| child::cd[position()=last()-1] | Seleciona o pen?ltimo cd filho do n? atual |
| child::cd[position()<6] | Seleciona os primeiros cinco cds filhos do n? atual |
| /descendant::cd[position()=7] | Seleciona o s?timo elemento cd no documento |
| child::cd[attribute::type="classic"] | Seleciona todos os cds filhos do n? atual que t?m um atributo tipo com o valor “classic” |

Sintaxe Abreviada dos Caminhos Locais
=====================================

Abrevia??es podem ser usadas para descrever um caminho local.

A abrevia??o mais importante ? que child:: pode ser omitido de um n?vel de localiza??o.

|| Abrev. | Significado | Exemplo ||
| nada | child:: | cd ? o mesmo que child::cd |
| @ | attribute:: | cd[@type="classic"] ? o mesmo que child::cd[attribute::type="classic"] |
| . | self::node() | .//cd ? o mesmo que self::node()/descendant-or-self::node()/child::cd |
| .. | parent::node() | ../cd ? o mesmo que parent::node()/child::cd |
| //// | /descendant-or-self::node()/ | //cd ? o mesmo que /descendant-or-self::node()/child::cd |

Exemplos

|| Exemplo | Resultado ||
| cd | Seleciona todos os elementos cd que s?o filhos do n? atual |
| * | Seleciona todos os elementos filhos do n? atual |
| text() | Seleciona todos os n?s textos filhos do n? atual |
| @src | Seleciona o atributo src do n? atual |
| @* | Seleciona todos os atributos do n? atual |
| cd[1] | Seleciona o primeiro cd filho do n? atual |
| cd[last()] | Seleciona o ?ltimo cd filho do n? atual |
| */cd | Seleciona todos os cds netos do n? atual |
| /book/chapter[3]/para[1] | Seleciona o primeiro par?grafo do terceiro cap?tulo do livro |
| //cd | Seleciona todos os elementos cds descendentes da raiz do documento e assim seleciona todos os elementos cds no mesmo documento como o n? atual |
| . | Seleciona o n? atual |
| .//cd | Seleciona os elementos cds descendentes do n? atual |
| .. | Seleciona o pai do n? atual |
| ../@src | Seleciona o atributo src do pai do n? atual |
| cd[@type="classic"] | Seleciona todos os cds filhos do n? atual que t?m o atributo “type” com o valor “classic” |
| cd[@type="classic"][5] | Seleciona o quinto cd filho do n? atual que tem o atributo “type” com o valor “classic” |
| cd[5][@type="classic"] | Seleciona o quinto cd filho do n? atual se esse filho tem o atributo “type” com valor “classic” |
| cd[@type and @country ] | Seleciona todos os cds filhos do n? atual que t?m ambos os atributos “type” e “country” |

Express?es XPath
================

XPath suporta express?es num?ricas, de igualdade, relacionais e booleanas.

Express?es Num?ricas
====================

Express?es num?ricas s?o usadas para realizar opera??es aritm?ticas em n?meros.

|| Operador | Descri??o | Exemplo | Resultado ||
| + | Adi??o | 6 + 4 | 10 |
| - | Subtra??o | 6 - 4 | 2 |
| * | Multiplica??o | 6 * 4 | 24 |
| div | Divis?o | 8 div 4 | 2 |
| mod | M?dulo (resto da divis?o) | 5 mod 2 | 1 |

Nota: XPath sempre converte cada operando em um n?mero antes de realizar um express?o aritm?tica.

Express?es de Igualdade
=======================

Express?es de igualdade s?o usadas para testar a igualdade entre dois valores.

|| Operador | Descri??o | Exemplo | Resultado ||
| = | Igual | price=9.80 | true (se o pre?o ? igual a 9.80) |
| != | Diferente | price!=9.80 | false |

Testando um conjunto de n?s
===========================

Se ? testada a igualdade do valor de teste em rela??o a um conjunto de n?s, o resultado ? verdadeiro se o conjunto de n?s cont?m algum n? com um valor igual ao valor de teste.

Se ? testada a desigualdade do valor de teste em rela??o a um conjunto de n?s, o resultado ? verdadeiro se o conjunto de n?s cont?m algum n? com um valor diferente ao valor de teste.

O resultado ? que o conjunto de n?s pode ser igual e diferente ao mesmo tempo!!!

Express?es Relacionais
======================

Express?es relacionais s?o usadas para comparar dois valores.

|| Operador | Descri??o | Exemplo | Resultado ||
| < | Menor | price<9.80 | false (se o pre?o ? 9.80) |
| <= | Menor ou igual | price<=9.80 | true |
| > | Maior | price>9.80 | false |
| >= | Maior ou igual | price>=9.80 | true |

Nota: XPath sempre converte cada operando em um n?mero antes de fazer a avalia??o.

Express?es Booleanas
====================

Express?es booleanas s?o usadas para comparar dois valores.

|| Operador | Descri??o | Exemplo | Resultado ||
| or | Ou | price=9.80 or price=9.70 | true (se o pre?o ? 9.80) |
| and | E | price< =9.80 and price=9.70 | false |

Fun??es XPath
=============

XPath cont?m uma biblioteca de fun??es para convers?o de dados.

Biblioteca de Fun??es XPath
===========================

A biblioteca de fun??es XPath cont?m um conjunto de fun??es centrais para convers?o e tradu??o de dados.

Fun??es para Conjunto de N?s
============================

|| Nome | Descri??o | Sintaxe ||
| count() | Retorna o n?mero de n?s num conjunto de n?s | number=count(node-set) |
| id() | Seleciona elementos pelo seu ID ?nico | node-set=id(value) |
| last() | Retorna o n?mero da posi??o do ?ltimo n? na lista de n?s processados | number=last() |
| local-name() | Retorna a parte local de um n?. Um n? normalmente consiste de um prefixo, os dois pontos, seguidos pelo nome local | string=local-name(node) |
| name() | Retorna o nome do n? | string=name(node) |
| namespace-uri() | Retorna o namespace URI de um n? espec?fico | uri=namespace-url(node) |
| position() | Retorna a posi??o na lista de n?s do n? que est? sendo processado atualmente | number=position() |

Fun??es de Strings
==================

|| Nome | Descri??o | Sintaxe | Exemplo ||
| concat() | Retorna a concatena??o de todos os argumentos | string=concat(val1,val2,…) | concat(’The’,’ ‘,’XML’) -> Resultado: ‘The XML’ |
| contains() | Retorna verdadeiro se a segunda string est? contida dentro da primeira string, sen?o retorna falso | bool=contains(val,substr) | contains(’XML’,'X’) -> Restultado: true |
| normalize-space() | Remove espa?os antes e depois de uma string e substitui todas as seq??ncias internas de espa?os por um ?nico espa?o em branco | string=normalize-space(string) | normalize-space(’ The XML ‘) -> Resultado: ‘The XML’ |
| starts-with() | Retorna verdadeiro se a primeira string come?a com a segunda string, sen?o retorna falso | bool=starts-with(string,substr) | starts-with(’XML’,'X’) -> Resultado: true |
| string() | Converte o argumento em string | string(value) | string(314) -> Resultado: ‘314′ |
| string-length() | Retorna o n?mero de caracteres de uma string | number=string-length(string) | string-length(’Beatles’) -> Resultado: 7 |
| substring() | Retorna um peda?o da string | string=substring(string,start,length) | substring(’Beatles’,1,4) -> Resultado: ‘Beat’ |
| substring-after() | Retorna a parte da string que aparece depois do argumento substr | string=substring-after(string,substr) | substring-after(’12/10′,’/') -> Resultado: ‘10′ |
| substring-before() | Retorna a parte da string que aparece antes do argumento substr | string=substring-before(string,substr) | substring-before(’12/10′,’/') -> Resultado: ‘12′ |
| translate() | Realiza uma substitui??o caracter por caracter. Ela procura no argumento ‘value’ os caracteres contidos na ’string1′ e substitui cada caractere pelo caractere da mesma posi??o na ’string2′ | string=translate(value,string1,string2) | translate(’12:30′,’30′,’45′) ——-> Resultado: ‘12:45′ —————– translate(’12:30′,’03′,’54′) ——-> Resultado: ‘12:45′ —————– translate(’12:30′,’0123′,’abcd’) ——-> Resultado: ‘bc:da’ |

Fun??es Num?ricas
=================

|| Nome | Descri??o | Sintaxe | Exemplo ||
| ceiling() | Retorna o menor inteiro que n?o ? menor que o argumento (fun??o teto) | number=ceiling(number) | ceiling=(3.14) -> Resultado: 4 |
| floor() | Retorna o maior inteiro que n?o ? maior que o argumento (fun??o ch?o) | number=floor(number) | floor(3.14) -> Resultado: 3 |
| number() | Converte o argumento em um n?mero | number=number(value) | number(’100′) -> Resultado: 100 |
| round() | Arredonda o argumento para o inteiro mais pr?ximo | integer=round(number) | round(3.14) -> Resultado: 3 |
| sum() | Retorna o valor total de um conjunto de valores num?ricos num conjunto de n?s | number=sum(nodeset) | sum(/cd/price) |

Fun??es Booleanas
=================

|| Nome | Descri??o | Sintaxe ||
| boolean() | Converte o argumento ‘value’ em Booleano e retorna verdadeiro ou falso | bool=boolean(value) |
| false() | Retorna falso | false() Exemplo: number(false()) -> Resultado: 0 |
| lang() | Retorna verdadeiro se o argumento ‘language’ ? igual ao idioma do elemento xsl:lang, sen?o retorna falso | bool=lang(language) |
| not() | Retorna verdadeiro se o argumento ‘condition’ ? falso, e falso se o argumento ? verdadeiro | bool=not(condition) Exemplo: not(false()) |
| true() | Retorna verdadeiro | true() Exemplo: number(true()) -> Resultado: 1 |

Exemplos XPath
==============

N?s iremos usar o cat?logo de CDs do nosso tutorial de XML para demonstrar alguns exemplos XPath.

O cat?logo de CDs
=================

Se voc? estudou o nosso tutorial de XML voc? lembrar? de documento XML:
(Uma fra??o do catalogo)

< ?xml version="1.0" encoding="ISO-8859-1"?>

Bob Dylan
USA
Columbia

10.90 1985

Bonnie Tyler
UK
CBS Records

9.90 1988

.
.
.
.

Se voc? tem o IE 5 ou superior voc? pode ver o cdcatalog.xml (http://www.w3schools.com/xpath/cdcatalog.xml).

Selecionando N?s
================

N?s demonstraremos como selecionar n?s de um documento XML usando a fun??o selectNodes no Internet Explorer. Esta fun??o tem uma express?o de caminho local como argumento:

xmlobject.selectNodes(Xpath expression)

Selecionando N?s cd
===================

O exemplo a seguir seleciona somente o primeiro n? do cat?logo de cds:

xmlDoc.selectNodes(”/catalog/cd[0]“)

Se voc? tem o IE 5 ou superior voc? pode fazer mais testes (http://www.w3schools.com/xpath/tryit.asp?filename=try_xpath_select_cdnodes_first).

Nota: IE 5 implementou que [0] deveria ser o primeiro n?, mas de acordo com o padr?o W3C, deve ser [1].

Selecionando N?s price
======================

O exemplo a seguir seleciona todos os n?s price do cat?logo de cds:

xmlDoc.selectNodes(”/catalog/cd/price”)

Se voc? tem o IE 5 ou superior voc? pode fazer mais testes (http://www.w3schools.com/xpath/tryit.asp?filename=try_xpath_select_pricenodes).

Selecionando o texto dos N?s price
==================================

O exemplo a seguir seleciona apenas o texto dos n?s price:

xmlDoc.selectNodes(”/catalog/cd/price/text()”)

Se voc? tem o IE 5 ou superior voc? pode fazer mais testes (http://www.w3schools.com/xpath/tryit.asp?filename=try_xpath_select_pricenodes_text).

Selecionando N?s cd com price>10.80
===================================

O exemplo a seguir seleciona todos os n?s cd com price>10.80:

xmlDoc.selectNodes(”/catalog/cd[price>10.80]“)

Se voc? tem o IE 5 ou superior voc? pode fazer mais testes (http://www.w3schools.com/xpath/tryit.asp?filename=try_xpath_select_pricenodes_high).

Selecionando N?s price com price>10.80
======================================

O exemplo a seguir seleciona todos os n?s price com price>10.80:

xmlDoc.selectNodes(”/catalog/cd[price>10.80]/price”)

Se voc? tem o IE 5 ou superior voc? pode fazer mais testes (http://www.w3schools.com/xpath/tryit.asp?filename=try_xpath_select_pricenodes_1080).
——————————————————————–
Colabore com a Dicas-L. Publique seu coment?rio sobre esta mensagem
em http://www.Dicas-L.unicamp.br/dicas-l/20050314.php
——————————————————————–
As mensagens da lista Dicas-L s?o veiculadas diariamente
para 26859 assinantes.

Todas as mensagens da Dicas-L ficam armazenadas em
http://www.Dicas-L.unicamp.br/dicas-l/

A redistribui??o desta e outras mensagens da lista Dicas-L pode
ser feita livremente segundo a licen?a Creative Commons
http://creativecommons.org/licenses/by-nc-sa/2.0/br/deed.pt

Exmplo de algoritmo para solu??o da Torre de Hanoi

Posted on March 12th, 2005

to solve (present, final)
{
1 is maximum the total number of discs
2 are destiny the final site of maximum
3 are maximum disc =
repeat
4 while disc > 0 does
5 if disc already is in destiny,
6 or, to move disc to destiny are successful then
7 if maximum disc = then
8 decremente maximum in 1
9 if maximum = 0 then
10 finish // ready solution
aim-if
11 is destiny the final site of maximum
aim-if
si_no
12 are destiny the site different from destiny and from
site in where it is disc
aim-if
13 decremente disc in 1
aim-while
14 are p and q the sites different from destiny
15 are disc the minor of discs of the tops of p and q
16 are destiny the site between p and q with the greater top
aim-repeat
}

Tutorial de PERL

Posted on February 14th, 2005

Estamos disponibilizando para download um tutorial de Perl disponibilizando pelo projeto verdadeabsoluta.org

Para os interessados ai vai o link:

http://fsbox.org/repositorio/Documentos/cgi_perl.htm

Getting started with awk

Posted on December 6th, 2004

This qref is written for a semi-knowledgable UNIX user who has just come up against a problem and has been advised to use awk to solve it. Perhaps one of the examples can be quickly modified for immediate use.

* Pre-Info
o Ohhh ohh what flavor?
o For More Info
o References
* Introduction
* The Basics
* Some Samples
o Whats a pattern, whats an action?
o With a regular expression?
o Comparisons
o Negate Operator
o Booleans
o start and end
o BEGIN and END
o Multiple pattern action pairs
o Awk variables
o Awk for while do
o Awk arrays
o Awk from a file
o Awk to create C code
* Awk punctuation guide
* A large awk example

Ohhh ohh what flavor?
There are three popular versions of awk: awk, nawk, and gawk. The last two are compatible with the first one.

For More Info
If you are looking for a more in-depth online document about awk, you should read the “info” pages for gawk. The info pages contain both the official documentation for gawk and and a good introduction to gawk. To read the info pages, type

>info gawk

at a shell prompt. It is also possible to print out the info pages in a nice-looking format. Send email to help@cs.hmc.edu and ask how to do that.

References
A good reference for awk is the O’Reilly handbook for sed and awk. There should be a copy available in the CS Department library. Further references are the UNIX in a Nutshell and UNIX Power Tools books, also in the CS Department library. The Power Tools book seems to quote quite a bit from the Sed and Awk book, though. Once you know a bit about awk, the man pages become more useful.

The Awk Newsgroup
The newsgroup for awk is comp.lang.awk

back to the top

Introduction

* awk reads from a file or from its standard input, and outputs to its standard output. You will generally want to redirect that into a file, but that is not done in these examples just because it takes up space. awk does not get along with non-text files, like executables and FrameMaker files. If you need to edit those, use a binary editor like hexl-mode in emacs.

* The most frustrating thing about trying to learn awk is getting your program past the shell’s parser. The proper way is to use single quotes around the program, like so:

>awk ‘{print $0}’ filename

The single quotes protect almost everything from the shell. In csh or tcsh, you still have to watch out for exclamation marks, but other than that, you’re safe.

* The second most frustrating thing about trying to learn awk is the lovely error messages:

awk ‘{print $0,}’ filename
awk: syntax error near line 1
awk: illegal statement near line 1

gawk generally has better error messages. At least it tells you where in the line something went wrong:

gawk ‘{print $0,}’ filename
gawk: cmd. line:1: {print $0,}
gawk: cmd. line:1: ^ parse error

So, if you’re having problems getting awk syntax correct, switch to gawk for a while.

back to the top

Some basics:

* Awk recognizes the concepts of “file”, “record”, and “field”.
* A file consists of records, which by default are the lines of the file. One line becomes one record.
* Awk operates on one record at a time.
* A record consists of fields, which by default are separated by any number of spaces or tabs.
* Field number 1 is accessed with $1, field 2 with $2, and so forth. $0 refers to the whole record.

back to the top

Some Samples
Perhaps the quickest way of learning awk is to look at some sample programs. The one above will print the file in its entirety, just like cat(1). Here are some others, along with a quick description of what they do.

>awk ‘{print $2,$1}’ filename

will print the second field, then the first. All other fields are ignored.

>awk ‘{print $1,$2,sin($3/$2)}’ filename

will print the first and second fields, and then the sine of the third field divided by the second. So, the second and third field had better be numbers. Awk has other built in math functions like sine; read the manpage to see which ones.

“I still say awk ‘{print $1}’ a lot.”
the inventor of PERL, Larry Wall (lwall@netlabs.com)

What if you don’t want to apply the program to each line of the file? Say, for example, that you only wanted to process lines that had the first field greater than the second. The following program will do that:

>awk ‘$1 > $2 {print $1,$2,$1-$2}’ filename

The part outside the curly braces is called the “pattern”, and the part inside is the “action”. The comparison operators include the ones from C:

== != <> < = >= ?:

If no pattern is given, then the action applies to all lines. This fact was used in the sample programs above. If no action is given, then the entire line is printed. If “print” is used all by itself, the entire line is printed. Thus, the following are equivalent:

awk ‘$1 > $2′ filename
awk ‘$1 > $2{print}’ filename
awk ‘$1 > $2{print $0}’ filename

The various fields in a line can also be treated as strings instead of numbers. To compare a field to a string, use the following method:

>awk ‘$1==”foo”{print $2}’ filename

back to the top

Using regular expressions
What if you want lines in which a certain string is found? Just put a regular expression (in the manner of egrep(1) ) into the pattern, like so:

>awk ‘/foo.*bar/{print $1,$3}’ filename

This will print all lines containing the word “foo” and then later the word “bar”. If you want only those lines where “foo” occurs in the second field, use the ~ (”contains”) operator:

>awk ‘$2~/foo/{print $3,$1}’ filename

If you want lines where “foo” does not occur in the second field, use the negated ~ operator, !~

>awk ‘$2!~/foo/{print $3,$1}’ filename

This operator can be read as “does not contain”.

back to the top

Booleans
You can produce complicated patterns with the boolean operators from C, which are ! for “not”, && for “and”, and || for “or”. Parentheses can be used for grouping.

back to the top

Start and End
There are three special forms of patterns that do not fit the above descriptions. One is the start-end pair of regular expressions. For example, to print all lines between and including lines that contained “foo” and “bar”, you would use

>awk ‘/foo/,/bar/’ filename

back to the top

Begin and End
The other two special forms are similar; they are the BEGIN and END patterns. Any action associated with the BEGIN pattern will happen before any line-by-line processing is done. Actions with the END pattern will happen after all lines are processed.

But how do you put more than one pattern-action pair into an awk program? There are several choices.

1. One is to just mash them together, like so:

>

awk ‘BEGIN{print”fee”} $1==”foo”{print”fi”}
END{print”fo fum”}’ filename

2. Another choice is to put the program into a file, like so:

BEGIN{print”fee”}
$1==”foo”{print”fi”}
END{print”fo fum”}

Let’s say that’s in the file giant.awk. Now, run it using the “-f” flag to awk:

>awk -f giant.awk filename

3. A third choice is to create a file that calls awk all by itself. The following form will do the trick:

#!/usr/bin/awk -f
BEGIN{print”fee”}
$1==”foo”{print”fi”}
END{print”fo fum”}

If we call this file giant2.awk, we can run it by first giving it execute permissions,

>chmod u+x giant2.awk

and then just call it like so:

>./giant2.awk filename

awk has variables that can be either real numbers or strings. For example, the following code prints a running total of the fifth column:

>awk ‘{print x+=$5,$0 }’ filename

This can be used when looking at file sizes from an “ls -l”. It is also useful for balancing one’s checkbook, if the amount of the check is kept in one column.

back to the top

Awk variables
awk variables are initialized to either zero or the empty string the first time they are used. Which one depends on how they are used, of course.

Variables are also useful for keeping intermediate values. This example also introduces the use of semicolons for separating statements:

>awk ‘{d=($2-($1-4));s=($2+$1);print d/sqrt(s),d*d/s }’ filename

Note that the final statement, a “print” in this case, does not need a semicolon. It doesn’t hurt to put it in, though.

* Integer variables can be used to refer to fields. If one field contains information about which other field is important, this script will print only the important field:

>awk ‘{imp=$1; print $imp }’ filename

* The special variable NF tells you how many fields are in this record. This script prints the first and last field from each record, regardless of how many fields there are:

>awk ‘{print $1,$NF }’ filename

* The special variable NR tells you which record this is. It is incremented each time a new record is read in. This gives a simple way of adding line numbers to a file:

>awk ‘{print NR,$0 }’ filename

Of course, there are a myriad of other ways to put line numbers on a file using the various UNIX utilities. This is left as an exercise for the reader.

* The special variable FS (Field Separator) determines how awk will split up each record into fields. This variable can be set on the command line. For example, /etc/passwd has its fields separated by colons.

>awk -F: ‘{print $1,$3 }’ /etc/passwd
This variable can actually be set to any regular expression, in the manner of egrep(1).

The various fields are also variables, and you can assign things to them. If you wanted to delete the 10th field from each line, you could do it by printing fields 1 through 9, and then from 11 on using a for-loop (see below). But, this will do it very easily:

>awk ‘{$10=”"; print }’ filename

In many ways, awk is like C. The “for”, “while”, “do-while”, and “if” constructs all exist. Statements can be grouped with curly braces. This script will print each field of each record on its own line.

>awk ‘{for(i=1;i< =NF;i++) print $i }' filename

If you want to produce format that is a little better formatted than the “print” statement gives you, you can use “printf” just like in C. Here is an example that treats the first field as a string, and then does some numeric stuff

>awk ‘{printf(”%s %03d %02d %.15g\n”,$1,$2,$3,$3/$2); }’ filename

Note that with printf, you need the explicit newline character.

We can use “printf” to print stuff without the newline, which is useful in a for loop. This script prints each record with each of its fields reversed. Ok, so it isn’t very useful.

>awk ‘{for(i=NF;i > 0;i–) printf(”%s”,$i); printf(”\n”); }’ filename

back to the top

Awk Arrays
awk has arrays, but they are only indexed by strings. This can be very useful, but it can also be annoying. For example, we can count the frequency of words in a document (ignoring the icky part about printing them out):

>awk ‘{for(i=1;i < =NF;i++) freq[$i]++ }' filename

The array will hold an integer value for each word that occurred in the file. Unfortunately, this treats “foo”, “Foo”, and “foo,” as different words. Oh well. How do we print out these frequencies? awk has a special “for” construct that loops over the values in an array. This script is longer than most command lines, so it will be expressed as an executable script:

#!/usr/bin/awk -f
{for(i=1;i <=NF;i++) freq[$i]++ }
END{for(word in freq) print word, freq[word] }

This loop-over-an-array seems to go in no particular order. Thus, the output from a program like this must often be piped through sort(1) in order to be useful.

Multi-dimensional arrays are implemented in an odd way. The given indices are concatenated together (with a special separator) to get one string, and it is used as the index. This program will print the word-pair frequencies:

#!/usr/bin/awk -f
{for(i=1;i < NF;i++) freq[$i,$(i+1)]++ }
END{for(words in freq) print words, freq[words] }

Unfortunately, this will print out the separator, which is by default not a common character. You can change this by assigning something logical like a space to the variable SUBSEP using nawk or gawk (it’s not allowed in plain awk).

#!/usr/bin/awk -f
BEGIN{SUBSEP=”"}
{for(i=1;i < NF;i++) freq[$i,$(i+1)]++}
END{for(words in freq) print words, freq[words] }

Unfortunately (that word seems to occur a lot when talking about awk arrays), this doesn’t let you refer to the indices individually. The secret to this it to use the “split” function, which breaks a string up into an array.

#!/usr/bin/awk -f
BEGIN{SUBSEP=”" }
{for(i=1;i < NF;i++) freq[$i,$(i+1)]++}
END{ for(words in freq)
{
split(words,word,SUBSEP);
print word[1], freq[words],word[2];
}
}

When you’re using an awk script in a file, you can break your program across multiple lines to make it easier to read. Comments are started the same way as in sh programming, with a #

#!/usr/bin/awk -f
# this program prints the frequencies of word pairs
BEGIN{SUBSEP=”"} # set the index separator
# to a nice character
{for(i=1;i < NF;i++) freq[$i,$(i+1)]++}
END{ for(words in freq)
{
# just to show we can put a comment in here.
split(words,word,SUBSEP); # or here
print word[1], freq[words],word[2];
}
}

You can use awk to create text, as well as just process existing text. It is useful for quickly generating tables of function values, without the hassle of compiling a C program. For example, it can show that sin(x)/x approaches 1 as x approaches zero:

>awk ‘{x=1.0/NR; print x,sin(x)/x;}’

will print a new value each time it reads a new line. So, you can hit return until you have all the values you need. Alternately, if you need a set number of values, you can do

>awk ‘BEGIN{for(i=1;i < =30;i++){x=1.0/i;print x,sin(x)/x;}}' /dev/null

where 30 is the set number of values.

It seems twisted*, but awk can be used to generate C code that one doesn’t want to type by hand. For example, this script will generate an explicit 3×3 matrix multiplication routine:

gawk ‘BEGIN{
for(i=0;i<3;i++)
for(j=0;j<3;j++){
printf(”d[%d][%d]=”,i,j);
for(k=0;k<3;k++){
printf(”l[%d][%d]*r[%d][%d]%s”,
i,k,k,j,(k<2)?”+”:”;\n”);
}
}
}’

* ok, maybe it is twisted.

back to the top
Punctuation guide:

{}
used around the action, and to group statements in the action.

$
denotes a field. $1 is the first field, $0 is the whole record.

~
the “contains” operator. “foobar”~”foo” is true. Strings only.

!~
the “does not contain” operator. Strings only.

==
the equality operator. Works for numbers or strings

< > < = >= !=
inequality operators. Work for numbers or strings.

#
the begin-comment character

,
separates things in a “print” or “printf” statement.

;
separates statements.

//
used around a regular expression

&&
Boolean and

||
Boolean or

!
boolean not

()
used for grouping Boolean expressions, passing arguments to functions, and around conditions for “for”,”while”, etc.

back to the top
And now for a grand example:

# This awk program collects statistics on two
# “random variables” and the relationships
# between them. It looks only at fields 1 and
# 2 by default Define the variables F and G
# on the command line to force it to look at
# different fields. For example:
# awk -f stat_2o1.awk F=2 G=3 stuff.dat \
# F=3 G=5 otherstuff.dat
# or, from standard input:
# awk -f stat_2o1.awk F=1 G=3
# It ignores blank lines, lines where either
# one of the requested fields is empty, and
# lines whose first field contains a number
# sign. It requires only one pass through the
# data. This script works with vanilla awk
# under SunOS 4.1.3.
BEGIN{
F=1;
G=2;
}
length($F) > 0 && \
length($G) > 0 && \
$1 !~/^#/ {
sx1+= $F; sx2 += $F*$F;
sy1+= $G; sy2 += $G*$G;
sxy1+= $F*$G;
if( N==0 ) xmax = xmin = $F;
if( xmin > $F ) xmin=$F;
if( xmax < $F ) xmax=$F;
if( N==0 ) ymax = ymin = $G;
if( ymin > $G ) ymin=$G;
if( ymax < $G ) ymax=$G;
N++;
}

END {
printf(”%d # N\n” ,N );
if (N <= 1)
{
printf(”What’s the point?\n”);
exit 1;
}
printf(”%g # xmin\n”,xmin);
printf(”%g # xmax\n”,xmax);
printf(”%g # xmean\n”,xmean=sx1/N);
xSigma = sx2 - 2 * xmean * sx1+ N*xmean*xmean;
printf(”%g # xvar\n” ,xvar =xSigma/ N );
printf(”%g # xvar unbiased\n”,xvaru=xSigma/(N-1));
printf(”%g # xstddev\n” ,sqrt(xvar ));
printf(”%g # xstddev unbiased\n”,sqrt(xvaru));

printf(”%g # ymin\n”,ymin);
printf(”%g # ymax\n”,ymax);
printf(”%g # ymean\n”,ymean=sy1/N);
ySigma = sy2 - 2 * ymean * sy1+ N*ymean*ymean;
printf(”%g # yvar\n” ,yvar =ySigma/ N );
printf(”%g # yvar unbiased\n”,yvaru=ySigma/(N-1));
printf(”%g # ystddev\n” ,sqrt(yvar ));
printf(”%g # ystddev unbiased\n”,sqrt(yvaru));
if ( xSigma * ySigma <= 0 )
r=0;
else
r=(sxy1 - xmean*sy1- ymean * sx1+ N * xmean * ymean)
/sqrt(xSigma * ySigma);
printf(”%g # correlation coefficient\n”, r);
if( r > 1 || r < -1 )
printf(”SERIOUS ERROR! CORRELATION COEFFICIENT”);
printf(” OUTSIDE RANGE -1..1\n”);

if( 1-r*r != 0 )
printf(”%g # Student’s T (use with N-2 degfreed)\n&”, \
t=r*sqrt((N-2)/(1-r*r)) );
else
printf(”0 # Correlation is perfect,”);
printf(” Student’s T is plus infinity\n”);
b = (sxy1 - ymean * sx1)/(sx2 - xmean * sx1);
a = ymean - b * xmean;
ss=sy2 - 2*a*sy1- 2*b*sxy1 + N*a*a + 2*a*b*sx1+ b*b*sx2 ;
ss/= N-2;
printf(”%g # a = y-intercept\n”, a);
printf(”%g # b = slope\n” , b);
printf(”%g # s^2 = unbiased estimator for sigsq\n”,ss);
printf(”%g + %g * x # equation ready for cut-and-paste\n”,a,b);
ra = sqrt(ss * sx2 / (N * xSigma));
rb = sqrt(ss / ( xSigma));
printf(”%g # radius of confidence interval “);
printf(”for a, multiply by t\n”,ra);
printf(”%g # radius of confidence interval “);
printf(”for b, multiply by t\n”,rb);
}

back to the top

This documentation was originally written by Andrew M. Ross.

Copyright (c) HMC Computer Science Department. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with the no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License.”

HMC Computer Science Department
Olin Science Center
301 E. Twelfth Street Claremont, CA 91711-5980 USA
PH : (909) 621-8225 FX : (909) 621-8465
Info Email: CS Staff or Admission Office
Last Modified Tuesday, 29-May-2001 11:46:54 PDT

TCL-TK How-To

Posted on November 17th, 2004

Neste tutorial de TCL-TK voc? ter? uma id?ia abrangente de como usar esta linguagem de programa??o orientada a criar interfaces Guis p?ra script’s.

http://www.linuxdig.com/howto/ldp/TclTk-HOWTO.php#ss5.1

Creative Commons License
Jaccon - Blog by André Jaccon is licensed under a Creative Commons Atribuição 3.0 Brasil License.
Based on a work at jaccon.com.br.

© Jaccon • tecnologia com respeito desde 2003 • Powered by WordpressDesign.