segunda-feira, 14 de maio de 2012

KVM: uma opção fácil ao VirtualBox e ao VMware

Embora seja um software open-source bastante antigo e conhecido, o Qemu nunca foi muito usado, pois era muito lento. Diferente do VMware e do VirtualBox, que são virtualizadores, capazes de rodarem outros sistemas operacionais com um overhead relativamente baixo, o Qemu é um emulador, que funciona de forma similar aos emuladores de consoles antigos, que usamos para rodar jogos de SNES e Mega-Drive no PC.
Em vez de utilizar um sistema de virtualização, ele tenta processar todas as instruções, o que acaba demorando mais tempo e fazendo com que a performance seja menor. Em geral, o VMware consegue fazer com que o sistema guest rode com de 70 a 90% do desempenho que teria se estivesse rodando diretamente, enquanto que o Qemu obtém de 5 a 10%.
Em 2005 o Qemu ganhou um módulo adicional, o Kqemu, um "acelerador" que faz com que ele passe a ser capaz de virtualizar as instruções, passando a oferecer um desempenho muito melhor. O Kqemu melhorou consideravelmente o desempenho do Qemu, mas, ainda assim, ele continuou atrás do VMware em questão de desempenho. Como o Kqemu era um componente proprietário, ele continuou sendo pouco usado.
O segundo salto veio em 2007, com o lançamento do KVM (http://kvm.qumranet.com/kvmwiki), um sistema de virtualização incluído diretamente no Kernel, disponível a partir da versão 2.6.20. O KVM substituiu o Kqemu como "acelerador" e, por ser licenciado sob a GPL, passou a ser desenvolvido de forma ativa, incorporando melhorias rapidamente, se tornando uma opção viável de virtualização, que passou a ser cada vez mais usado em servidores, concorrendo com o Xen, o VMware e o Virtuozzo.
Em se tratando de desktops, a principal vantagem do KVM é a facilidade de instalação e de criação das máquinas virtuais, combinada com o baixo impacto sobre o desempenho do sistema host, diferente do VMware, onde o processador fica ocupado o tempo todo enquanto a VM está ativa, mesmo que nada esteja sendo feito dentro dela.
O KVM pode ser instalado rapidamente sobre praticamente qualquer distribuição atual (com kernel 2.6.20 ou mais recente); basta procurar pelos pacotes "kvm" e "qemu". No caso do Debian Lenny e do Ubuntu 8.10, você pode instalá-los diretamente via apt.
O primeiro passo é instalar os dois pacotes. A grande vantagem do KVM é que, por ser um virtualizador open-source, ele é bastante simples de instalar nas distribuições atuais. O módulo vem incluído diretamente no kernel e os demais componentes podem ser instalados usando o gerenciador de pacotes:
# apt-get install kvm qemu
Depois de instalar, adicione o usuário que estiver utilizando no grupo "kvm", para que ele tenha permissão para usar o acelerador:
# adduser gdh kvm
Com isso a instalação está concluída. Falta apenas começar a criar os discos virtuais e rodar as VMs. Assim como no caso do VMware, o KVM suporta o uso de discos virtuais dinâmicos, que começam como arquivos vazios e vão crescendo conforme você instala coisas dentro da VM. O comando para criar os discos virtuais é o "qemu-img create nome.img -f qcow tamanho", como em: $ qemu-img create ubuntu.img -f qcow 10G
Este comando deve ser executado com o seu login de usuário (e não mais como root), já que ele é quem deve ser o dono do arquivo. Se você criar as imagens usando o root, você não terá permissão para escrever dentro dos arquivos ao usar o KVM, o que vai fazer com que a instalação dentro da VM falhe com uma mensagem "não é possível escrever no disco", ou similar.
Como pode imaginar, o "ubuntu.img" é o nome do arquivo e o "10G" é o limite máximo de tamanho para o disco virtual. Ele é originalmente criado como um arquivo vazio, que ocupa apenas alguns kbytes e pode crescer até o limite especificado.
É recomendável agrupar os discos virtuais em uma mesma pasta, para fins de organização, mas isso fica a seu critério. Se quiser espelhá-los pelo HD, não há problema. :)
Com o disco virtual criado, falta apenas inicializar a VM usando o CD/DVD ou a imagem ISO com o sistema de boot e começar a instalação do sistema.
O comando agora é o "kvm", seguido pelo arquivo ISO com a imagem de boot (pode ser tanto o ISO de uma distribuição Linux quanto uma imagem de uma mídia de instalação do Windows), seguido pelo disco virtual que será usado, a quantidade de memória RAM reservada à VM (em MB) e a opção "-boot d", que faz com que o KVM inicialize a VM a partir do CD-ROM:
$ kvm -cdrom /dev/cdrom -hda ubuntu.img -m 512 -boot d
Se quiser usar diretamente um CD ou DVD gravado dentro do drive, especifique o dispositivo "/dev/cdrom", que permite acesso direto à mídia dentro do drive:
$ kvm -cdrom /dev/cdrom -hda ubuntu.img -m 512 -boot d
Assim como em outros virtualizadores, uma nova janela é aberta e o boot ocorre da maneira tradicional. Ao clicar sobre a janela, o mouse fica "preso" dentro dela; para soltá-lo, pressione Ctrl+Alt:
kvm_html_m2556625b
O KVM não possui uma opção de tela cheia, mas você pode aumentar o espaço útil removendo a borda da janela, o que no KDE é feito clicando com o botão direito na barra de título e usando a opção "Avançado > Sem Borda" (pressione "Alt+F3" para que ela volte a ser exibida). Você pode também mover a janela (o que é muito útil em casos em que o sistema dentro da VM configura o vídeo com uma resolução vertical maior que a área útil da tela), segurando a tecla Alt e arrastando a janela usando o botão esquerdo do mouse.
Em alguns casos (que estão se tornando cada vez mais raros, conforme o software evolui), o KVM pode apresentar erros diversos durante a instalação de alguns sistemas operacionais específicos. Nesse caso, você tem a opção de desativar o KVM, ficando apenas com o Qemu sem aceleração que, embora muito mais lento, consegue completar a instalação na maioria dos casos. Para isso, basta executar o mesmo comando, substituindo o "kvm" por "qemu -no-kvm":
$ qemu -no-kvm -cdrom /dev/cdrom -hda ubuntu.img -m 512 -boot d
Estes problemas se manifestam apenas durante a instalação, de maneira que você pode voltar a usar o KVM normalmente depois que ela estiver concluída.
Outra opção destinada a solucionar problemas de instalação é a "-no-acpi" (que era necessária para instalar o Windows em versões anteriores do KVM), que pode ser adicionada no final do comando, como em:
$ kvm -cdrom winxp.iso -hda xp.img -m 256 -boot d -no-acpi
Depois de instalado o sistema dentro da VM, o comando para inicializá-la daí em dia é bem mais simples, indicando apenas o disco virtual e a quantidade de memória reservada, como em:
$ kvm -hda ubuntu.img -m 512
Para facilitar, crie ícones de atalho para as VMs criadas. Basta indicar o comando, especificando o caminho completo para o arquivo do disco virtual:
kvm_html_427657c9

O KVM inclui um sistema de compartilhamento de conexão, que simplesmente compartilha a conexão de rede via NAT, permitindo que o sistema guest configure a rede via DHCP. Graças a isso, você não precisa executar nenhum passo adicional para que a VM acesse a web, basta deixar que ela obtenha a configuração de rede via DHCP durante a instalação. Este modo é equivalente às opções "-net nic -net user", que precisavam ser especificadas manualmente em versões antigas.
Concluindo, se ao abrir a VM você receber um erro como:
open /dev/kvm: Permission denied
Could not initialize KVM, will disable KVM support
... significa que o KVM não está carregado, ou que (mais provável) as permissões de acesso ao dispositivo virtual não foram ajustadas corretamente ao instalar o pacote. Nesse caso, carregue o módulo (apenas por desencargo) e ajuste as permissões manualmente, como em:
# modprobe kvm
# chown root:kvm /dev/kvm
# adduser gdh kvm
Se você é o único que utiliza o PC, pode simplesmente abrir as permissões do dispositivo, de modo a não precisar mais se preocupar com isso:
# chmod 666 /dev/kvm
A principal limitação do KVM é que ele funciona apenas em processadores com suporte a virtualização via hardware, o que deixa de fora a maioria das máquinas antigas. Você pode checar se o processador possui ou não suporte à virtualização usando o comando "cat /proc/cpuinfo", onde o campo "flags" deve incluir o "vmx" ou o "svm", como em:
flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt rdtscp lm 3dnowext 3dnow rep_good nopl pni cx16 lahf_lm cmp_legacy svm extapic cr8_legacy 3dnowprefetch
É necessário também que o suporte a virtualização esteja ativado no Setup (caso a opção esteja disponível. Procure pela opção "Enable SVM" ou "Virtualization support".
Caso o processador não suporte nenhum dos dois, você ainda poderá usar o Qemu em modo de emulação (usando os mesmos comandos), mas tudo ficará muito lento. Nesse caso, o melhor seria partir para o VMware ou o VirtualBox, que não dependem de suporte especial por parte do processador.

segunda-feira, 5 de dezembro de 2011

Problemas para Alinhar Icones Jquery na mema Linha

Solução para alinhamento de icones jquery na mesma linha???

Basta apenas criar o icon-container com "display:inline-block"


Link para o post
javascript - jQuery UI Icons trouble - how do I get just the image displayed - Stack Overflow

quarta-feira, 28 de abril de 2010

PostgreSQL Date

9.9. Date/Time Functions and Operators

Table 9-26 shows the available functions for date/time value processing, with details appearing in the following subsections. Table 9-25 illustrates the behaviors of the basic arithmetic operators (+, *, etc.). For formatting functions, refer to Section 9.8. You should be familiar with the background information on date/time data types from Section 8.5.

All the functions and operators described below that take time or timestamp inputs actually come in two variants: one that takes time with time zone or timestamp with time zone, and one that takes time without time zone or timestamp without time zone. For brevity, these variants are not shown separately. Also, the + and * operators come in commutative pairs (for example both date + integer and integer + date); we show only one of each such pair.

Table 9-25. Date/Time Operators

OperatorExampleResult
+date '2001-09-28' + integer '7'date '2001-10-05'
+date '2001-09-28' + interval '1 hour'timestamp '2001-09-28 01:00'
+date '2001-09-28' + time '03:00'timestamp '2001-09-28 03:00'
+interval '1 day' + interval '1 hour'interval '1 day 01:00'
+timestamp '2001-09-28 01:00' + interval '23 hours'timestamp '2001-09-29 00:00'
+time '01:00' + interval '3 hours'time '04:00'
-- interval '23 hours'interval '-23:00'
-date '2001-10-01' - date '2001-09-28'integer '3'
-date '2001-10-01' - integer '7'date '2001-09-24'
-date '2001-09-28' - interval '1 hour'timestamp '2001-09-27 23:00'
-time '05:00' - time '03:00'interval '02:00'
-time '05:00' - interval '2 hours'time '03:00'
-timestamp '2001-09-28 23:00' - interval '23 hours'timestamp '2001-09-28 00:00'
-interval '1 day' - interval '1 hour'interval '23:00'
-timestamp '2001-09-29 03:00' - timestamp '2001-09-27 12:00'interval '1 day 15:00'
*interval '1 hour' * double precision '3.5'interval '03:30'
/interval '1 hour' / double precision '1.5'interval '00:40'

Table 9-26. Date/Time Functions

FunctionReturn TypeDescriptionExampleResult
age(timestamp,timestamp)intervalSubtract arguments, producing a "symbolic" result that uses years and monthsage(timestamp '2001-04-10', timestamp '1957-06-13')43 years 9 mons 27 days
age(timestamp)intervalSubtract from current_dateage(timestamp '1957-06-13')43 years 8 mons 3 days
current_datedateToday's date; see Section 9.9.4
current_timetime with time zoneTime of day; see Section 9.9.4
current_timestamptimestamp with time zoneDate and time; see Section 9.9.4
date_part(text,timestamp)double precisionGet subfield (equivalent to extract); see Section 9.9.1date_part('hour', timestamp '2001-02-16 20:38:40')20
date_part(text,interval)double precisionGet subfield (equivalent to extract); see Section 9.9.1date_part('month', interval '2 years 3 months')3
date_trunc(text,timestamp)timestampTruncate to specified precision; see also Section 9.9.2date_trunc('hour', timestamp '2001-02-16 20:38:40')2001-02-16 20:00:00
extract(field fromtimestamp)double precisionGet subfield; see Section 9.9.1extract(hour from timestamp '2001-02-16 20:38:40')20
extract(field frominterval)double precisionGet subfield; see Section 9.9.1extract(month from interval '2 years 3 months')3
isfinite(timestamp)booleanTest for finite time stamp (not equal to infinity)isfinite(timestamp '2001-02-16 21:28:30')true
isfinite(interval)booleanTest for finite intervalisfinite(interval '4 hours')true
localtimetimeTime of day; see Section 9.9.4
localtimestamptimestampDate and time; see Section 9.9.4
now()timestamp with time zoneCurrent date and time (equivalent to current_timestamp); see Section 9.9.4
timeofday()textCurrent date and time; see Section 9.9.4

In addition to these functions, the SQL OVERLAPS operator is supported:

( start1, end1 ) OVERLAPS ( start2, end2 ) ( start1, length1 ) OVERLAPS ( start2, length2 )

This expression yields true when two time periods (defined by their endpoints) overlap, false when they do not overlap. The endpoints can be specified as pairs of dates, times, or time stamps; or as a date, time, or time stamp followed by an interval.

SELECT (DATE '2001-02-16', DATE '2001-12-21') OVERLAPS        (DATE '2001-10-30', DATE '2002-10-30'); Result: true SELECT (DATE '2001-02-16', INTERVAL '100 days') OVERLAPS        (DATE '2001-10-30', DATE '2002-10-30'); Result: false

9.9.1. EXTRACT, date_part

EXTRACT (field FROM source)

The extract function retrieves subfields such as year or hour from date/time values. source must be a value expression of type timestamp, time, or interval. (Expressions of type datewill be cast to timestamp and can therefore be used as well.) field is an identifier or string that selects what field to extract from the source value. The extract function returns values of type double precision. The following are valid field names:

century

The century

SELECT EXTRACT(CENTURY FROM TIMESTAMP '2000-12-16 12:21:13'); Result: 20 SELECT EXTRACT(CENTURY FROM TIMESTAMP '2001-02-16 20:38:40'); Result: 21

The first century starts at 0001-01-01 00:00:00 AD, although they did not know it at the time. This definition applies to all Gregorian calendar countries. There is no century number 0, you go from -1 to 1. If you disagree with this, please write your complaint to: Pope, Cathedral Saint-Peter of Roma, Vatican.

PostgreSQL releases before 8.0 did not follow the conventional numbering of centuries, but just returned the year field divided by 100.

day

The day (of the month) field (1 - 31)

SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40'); Result: 16
decade

The year field divided by 10

SELECT EXTRACT(DECADE FROM TIMESTAMP '2001-02-16 20:38:40'); Result: 200
dow

The day of the week (0 - 6; Sunday is 0) (for timestamp values only)

SELECT EXTRACT(DOW FROM TIMESTAMP '2001-02-16 20:38:40'); Result: 5

Note that extract's day of the week numbering is different from that of the to_char function.

doy

The day of the year (1 - 365/366) (for timestamp values only)

SELECT EXTRACT(DOY FROM TIMESTAMP '2001-02-16 20:38:40'); Result: 47
epoch

For date and timestamp values, the number of seconds since 1970-01-01 00:00:00-00 (can be negative); for interval values, the total number of seconds in the interval

SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-08'); Result: 982384720  SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours'); Result: 442800

Here is how you can convert an epoch value back to a time stamp:

SELECT TIMESTAMP WITH TIME ZONE 'epoch' + 982384720 * INTERVAL '1 second';
hour

The hour field (0 - 23)

SELECT EXTRACT(HOUR FROM TIMESTAMP '2001-02-16 20:38:40'); Result: 20
microseconds

The seconds field, including fractional parts, multiplied by 1 000 000. Note that this includes full seconds.

SELECT EXTRACT(MICROSECONDS FROM TIME '17:12:28.5'); Result: 28500000
millennium

The millennium

SELECT EXTRACT(MILLENNIUM FROM TIMESTAMP '2001-02-16 20:38:40'); Result: 3

Years in the 1900s are in the second millennium. The third millennium starts January 1, 2001.

PostgreSQL releases before 8.0 did not follow the conventional numbering of millennia, but just returned the year field divided by 1000.

milliseconds

The seconds field, including fractional parts, multiplied by 1000. Note that this includes full seconds.

SELECT EXTRACT(MILLISECONDS FROM TIME '17:12:28.5'); Result: 28500
minute

The minutes field (0 - 59)

SELECT EXTRACT(MINUTE FROM TIMESTAMP '2001-02-16 20:38:40'); Result: 38
month

For timestamp values, the number of the month within the year (1 - 12) ; for interval values the number of months, modulo 12 (0 - 11)

SELECT EXTRACT(MONTH FROM TIMESTAMP '2001-02-16 20:38:40'); Result: 2  SELECT EXTRACT(MONTH FROM INTERVAL '2 years 3 months'); Result: 3  SELECT EXTRACT(MONTH FROM INTERVAL '2 years 13 months'); Result: 1
quarter

The quarter of the year (1 - 4) that the day is in (for timestamp values only)

SELECT EXTRACT(QUARTER FROM TIMESTAMP '2001-02-16 20:38:40'); Result: 1
second

The seconds field, including fractional parts (0 - 59[1])

SELECT EXTRACT(SECOND FROM TIMESTAMP '2001-02-16 20:38:40'); Result: 40  SELECT EXTRACT(SECOND FROM TIME '17:12:28.5'); Result: 28.5
timezone

The time zone offset from UTC, measured in seconds. Positive values correspond to time zones east of UTC, negative values to zones west of UTC.

timezone_hour

The hour component of the time zone offset

timezone_minute

The minute component of the time zone offset

week

The number of the week of the year that the day is in. By definition (ISO 8601), the first week of a year contains January 4 of that year. (The ISO-8601 week starts on Monday.) In other words, the first Thursday of a year is in week 1 of that year. (for timestamp values only)

Because of this, it is possible for early January dates to be part of the 52nd or 53rd week of the previous year. For example, 2005-01-01 is part of the 53rd week of year 2004, and2006-01-01 is part of the 52nd week of year 2005.

SELECT EXTRACT(WEEK FROM TIMESTAMP '2001-02-16 20:38:40'); Result: 7
year

The year field. Keep in mind there is no 0 AD, so subtracting BC years from AD years should be done with care.

SELECT EXTRACT(YEAR FROM TIMESTAMP '2001-02-16 20:38:40'); Result: 2001

The extract function is primarily intended for computational processing. For formatting date/time values for display, see Section 9.8.

The date_part function is modeled on the traditional Ingres equivalent to the SQL-standard function extract:

date_part('field', source)

Note that here the field parameter needs to be a string value, not a name. The valid field names for date_part are the same as for extract.

SELECT date_part('day', TIMESTAMP '2001-02-16 20:38:40'); Result: 16  SELECT date_part('hour', INTERVAL '4 hours 3 minutes'); Result: 4

9.9.2. date_trunc

The function date_trunc is conceptually similar to the trunc function for numbers.

date_trunc('field', source)

source is a value expression of type timestamp or interval. (Values of type date and time are cast automatically, to timestamp or interval respectively.) field selects to which precision to truncate the input value. The return value is of type timestamp or interval with all fields that are less significant than the selected one set to zero (or one, for day and month).

Valid values for field are:

microseconds
milliseconds
second
minute
hour
day
week
month
quarter
year
decade
century
millennium

Examples:

SELECT date_trunc('hour', TIMESTAMP '2001-02-16 20:38:40'); Result: 2001-02-16 20:00:00  SELECT date_trunc('year', TIMESTAMP '2001-02-16 20:38:40'); Result: 2001-01-01 00:00:00

9.9.3. AT TIME ZONE

The AT TIME ZONE construct allows conversions of time stamps to different time zones. Table 9-27 shows its variants.

Table 9-27. AT TIME ZONE Variants

ExpressionReturn TypeDescription
timestamp without time zone AT TIME ZONE zonetimestamp with time zoneConvert local time in given time zone to UTC
timestamp with time zone AT TIME ZONE zonetimestamp without time zoneConvert UTC to local time in given time zone
time with time zone AT TIME ZONE zonetime with time zoneConvert local time across time zones

In these expressions, the desired time zone zone can be specified either as a text string (e.g., 'PST') or as an interval (e.g., INTERVAL '-08:00'). In the text case, the available zone names are those shown in Table B-4. (It would be useful to support the more general names shown in Table B-6, but this is not yet implemented.)

Examples (supposing that the local time zone is PST8PDT):

SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'MST'; Result: 2001-02-16 19:38:40-08  SELECT TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-05' AT TIME ZONE 'MST'; Result: 2001-02-16 18:38:40

The first example takes a zone-less time stamp and interprets it as MST time (UTC-7) to produce a UTC time stamp, which is then rotated to PST (UTC-8) for display. The second example takes a time stamp specified in EST (UTC-5) and converts it to local time in MST (UTC-7).

The function timezone(zone, timestamp) is equivalent to the SQL-conforming construct timestamp AT TIME ZONE zone.

9.9.4. Current Date/Time

The following functions are available to obtain the current date and/or time:

CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURRENT_TIME ( precision ) CURRENT_TIMESTAMP ( precision ) LOCALTIME LOCALTIMESTAMP LOCALTIME ( precision ) LOCALTIMESTAMP ( precision )

CURRENT_TIME and CURRENT_TIMESTAMP deliver values with time zone; LOCALTIME and LOCALTIMESTAMP deliver values without time zone.

CURRENT_TIME, CURRENT_TIMESTAMP, LOCALTIME, and LOCALTIMESTAMP can optionally be given a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field. Without a precision parameter, the result is given to the full available precision.

Note: Prior to PostgreSQL 7.2, the precision parameters were unimplemented, and the result was always given in integer seconds.

Some examples:

SELECT CURRENT_TIME; Result: 14:39:53.662522-05  SELECT CURRENT_DATE; Result: 2001-12-23  SELECT CURRENT_TIMESTAMP; Result: 2001-12-23 14:39:53.662522-05  SELECT CURRENT_TIMESTAMP(2); Result: 2001-12-23 14:39:53.66-05  SELECT LOCALTIMESTAMP; Result: 2001-12-23 14:39:53.662522

The function now() is the traditional PostgreSQL equivalent to CURRENT_TIMESTAMP.

There is also the function timeofday(), which for historical reasons returns a text string rather than a timestamp value:

SELECT timeofday(); Result: Sat Feb 17 19:07:32.000126 2001 EST

It is important to know that CURRENT_TIMESTAMP and related functions return the start time of the current transaction; their values do not change during the transaction. This is considered a feature: the intent is to allow a single transaction to have a consistent notion of the "current" time, so that multiple modifications within the same transaction bear the same time stamp.timeofday() returns the wall-clock time and does advance during transactions.

Note: Other database systems may advance these values more frequently.

All the date/time data types also accept the special literal value now to specify the current date and time. Thus, the following three all return the same result:

SELECT CURRENT_TIMESTAMP; SELECT now(); SELECT TIMESTAMP 'now';

Tip: You do not want to use the third form when specifying a DEFAULT clause while creating a table. The system will convert now to a timestamp as soon as the constant is parsed, so that when the default value is needed, the time of the table creation would be used! The first two forms will not be evaluated until the default value is used, because they are function calls. Thus they will give the desired behavior of defaulting to the time of row insertion.

Notes

[1]

60 if leap seconds are implemented by the operating system


User Comments


Christos Evaggelou
18 Jul 2005 17:48:33

To validate a date, I use the following method. You should be able to adjust it to your needs by simply modifying validFormat to match your needs.

DROP FUNCTION isValidDate(CHAR);

/*
* Just replace 'validFormat' with a valid date format
* string for your locale.
*/
CREATE FUNCTION isValidDate(CHAR) RETURNS bool AS '
DECLARE
result BOOL;
validFormat TEXT := \'DD-MM-YYYY\';
BEGIN
SELECT TO_CHAR(TO_DATE($1,validFormat),validFormat) = $1
INTO result;
RETURN result;
END;

' LANGUAGE plpgsql;

Christos Evaggelou
22 Jul 2005 22:53:04

A more generic version of the previously submited isValidDate(CHAR) function. Allows to specify format string as parameter. Hope it's (more) helpful.


CREATE OR REPLACE FUNCTION isValidDate(char, char) RETURNS boolean AS'
DECLARE
result BOOL;
BEGIN
SELECT TO_CHAR(TO_DATE($1,$2),$2) = $1
INTO result;
RETURN result;
END;
'LANGUAGE 'plpgsql';

David Sankel
30 Aug 2005 10:23:21

When you want a default timestamp to be the current time, here's how you'd do it:

CREATE TABLE stuff(
entry varchar,
entryCreationTime timestamp default now()
);

Nadeem Douba
06 Sep 2005 15:53:46

Here's a faster way to get your interval in hours. Ignore the first function I presented, it's about 2.5 time slower.

create or replace function interval_to_hours(interval) returns double precision as $$
begin
return extract(EPOCH from $1)/3600;
end $$ language plpgsql;

quarta-feira, 15 de julho de 2009

asdasdasd

asdasdasdasdassd

Site que analisa o teu conteúdo, e indica onde deve ser melhorado!

Web Page Analyzer - 0.98 - from Website Optimization

Website com ferramenta grátis de Análise da Velocidade da Página.

Exemplos CSS's e Menus muito legais


Noupe está fazendo um bom trabalho catalogação conteúdos, tais como a sua postagem great JavaScript CSS menu libraries que inclui:

  • Sexy Sliding Menu - Andrew Sellick decidiu usar mootools devido à suavidade dos seus efeitos, no entanto, ele desenvolveu um menu deslizante usando script.aculo.us
  • FastFind Menu Script - Este script permite a nested menus, baseado na dinâmica "Ajax" respostas. O menu também podem ser arrastados / caiu graças à jQuery Interface Biblioteca.
    Webber 2,0 Dock Menu - Grande exemplo de uma doca tipo navegação.
  • Webber 2.0 Dock Menu - Grande exemplo de uma doca tipo navegação.
  • Phatfusion- Image Menu - Imagem menu usando javascript, evento onClick mantém item selecionado para abrir e para fechá-la novamente.
  • Drag and Drop ordering in a TreePanel - Este exemplo mostra base arrastar e largar nó movendo-se em uma árvore. Nesta aplicação, não existem restrições e tudo pode ser retirado em qualquer lugar exceto anexando a nós marcado "folhas" (os arquivos).
  • Custom Menu Events - Esta é uma combinação de animação e eventos personalizados onde Pense Vitamina equipe mostrar-nos como itens do menu deslizando em vista e atirando fora subscribable eventos utilizando Yahoo! IU
  • Context Menu Functionality - Esta funcionalidade é uma combinação de animação e eventos personalizados onde Pense Vitamina equipe mostrar-nos como itens do menu deslizando em vista e atirando fora subscribable eventos utilizando Yahoo! UI.
  • LavaLamp jQuery Sliding Menu - É um deslizamento jQuery nifty efeito menu com peso leve e de código extra interface mais dois estilos.
    Slashdot Menu-DriveThis Dynamic é um elegante recolhível menu modelado após a navegação no menu encontrado Slashdot.
  • Slashdot Menu- Dynamic Drive - é um elegante recolhível menu modelado após a navegação no menu encontrado Slashdot.
  • Mootools menu with Accordeon and Effects - This arrefecer menu tem um nítido efeito de pairar sobre as ligações, nível 2 e abre um submenu com um acordeão.
  • CSS Dock Menu - Se você é um grande fã do Mac, você vai adorar este CSS dock menu que Nick La concebido. Ela está usando Jquery Javascript library e Fisheye componente de interface e de alguns dos seus ícones.
  • jQuery Plugin: Sliding Menu - Sliding Menu muito simples usando o menu deslizante efeitos fornecidos pela Interface plugin.
  • Accessible expanding and collapsing menu -