Caso tenha iniciado o vagrant com sudo e depois tente iniciar com a sua conta, vai ter uma erro sobre o ID com que a maquina foi criada e com o que esta atentar iniciar, a correção do problema é simples .
Dentro da pasta onde tem os setings do vagrant vai ter uma pasta .vagrant , faça o chown dessa pasta para o se utilizador , dentro dessa mesma pasta vai ter um um ficheiro chamada creator_id edite e coloque o se id de utilizador .
Depois na sua pasta de utilizador vai ter uma pasta oculta .vagrant.d faça também o own dele para o seu utilizador .
vagrant up e tudo deve de correr bem.
domingo, 6 de setembro de 2015
quinta-feira, 13 de agosto de 2015
Window 10 Dark Mode
Abrir o regedit , ir para a chave HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize, criar uma DWORD SystemUsesLightTheme com o valor 0.
Para volta ao original basta mudar o valor da chave para 1 o removela .
Simples ;)
Fonte: http://www.winbeta.org/news/how-enable-dark-mode-windows-10-insider-preview-build-10074
Para volta ao original basta mudar o valor da chave para 1 o removela .
Simples ;)
Fonte: http://www.winbeta.org/news/how-enable-dark-mode-windows-10-insider-preview-build-10074
segunda-feira, 5 de janeiro de 2015
Asus k450J sem WIFI no Ubuntu
O Asus K450J também pode ter problema em iniciar o WIFI no Ubuntu, no entanto aqui o problema é diferente do X550CC.
Vamos verificar se o o modulo "acer" esta ativo:
$ lsmod | grep acer
Se sim então o sistema então temos que o desabilitar com o seguinte comando :
$ echo "blacklist acer_wmi" | sudo tee -a /etc/modprobe.d/blacklist.conf
Um reboot e o problema esta resolvido.
Vamos verificar se o o modulo "acer" esta ativo:
$ lsmod | grep acer
Se sim então o sistema então temos que o desabilitar com o seguinte comando :
$ echo "blacklist acer_wmi" | sudo tee -a /etc/modprobe.d/blacklist.conf
Um reboot e o problema esta resolvido.
Asus x550CC sem WIFI no Ubuntu
Quando se instala o Ubuntu 14.04 ou 14.10 pode acontecer que o WIFI não ligue.
Ora bem pontos a verificar :
$ lsmod | grep -e ath9k -e asus
se no output do comando encontrarmos o "asus_nb_wmi" e o
$ rfkill list all
listar "Hard blocked: yes"
Então a solução é simples, fn+F1 para o portátil entrar em suspensão e depois resumir a suspensão , e o WIFI fica ativado.
Para um fix permanente, em modo root :
$ echo "options asus_nb_wmi wapf=1" > /etc/modprobe.d/asus.conf
Reboot e o WIFI fica ativado, no entanto se com o wapf=1 não funcionar podem tentar com 0 ou 4 .
Ora bem pontos a verificar :
$ lsmod | grep -e ath9k -e asus
se no output do comando encontrarmos o "asus_nb_wmi" e o
$ rfkill list all
listar "Hard blocked: yes"
Então a solução é simples, fn+F1 para o portátil entrar em suspensão e depois resumir a suspensão , e o WIFI fica ativado.
Para um fix permanente, em modo root :
$ echo "options asus_nb_wmi wapf=1" > /etc/modprobe.d/asus.conf
Reboot e o WIFI fica ativado, no entanto se com o wapf=1 não funcionar podem tentar com 0 ou 4 .
domingo, 17 de novembro de 2013
KitKat 4.4
Já estão disponíveis as imagens para o kitkat 4.4, isto claro para quem não pode esperar pelo OTA, aqui fica o link podem fazer o download , dentro da pasta estão as instruções como instalar.
domingo, 25 de agosto de 2013
Comprimir uma directoria LINUX
Ora bem é um comando muito simples e útil para comprimir uma directoria completa e enviar por SFTP num ficheiro unico .
tar -zcvf archive-name.tar.gz directory-name
sábado, 25 de maio de 2013
Remove Old Kernel on Ubuntu
Open terminal and check your current kernel:
DO NOT REMOVE THIS KERNEL!
Next, type the command below to view / list all installed kernels on your system.
Find all the kernels that lower than your current kernel.
Finally, run the commands below to update grub2
Reboot your system.
uname -r
DO NOT REMOVE THIS KERNEL!
Next, type the command below to view / list all installed kernels on your system.
dpkg --list | grep linux-image
Find all the kernels that lower than your current kernel.
When you know which kernel to remove, continue below to remove it.
Run the commands below to remove the kernel you selected.
sudo apt-get purge linux-image-x.x.x.x-generic
Finally, run the commands below to update grub2
sudo update-grub2
Reboot your system.
quarta-feira, 30 de janeiro de 2013
XBMC 12.0 'Frodo'
XBMC Media Center 12.0 "Frodo" foi lançado hoje, com áudio HD, TV ao vivo e suporte PVR e muitas outras melhorias. Além disso, o aplicativo já está disponível para Android e Pi Raspberry (embora haja nenhum funcionário Raspberry Pi constrói fornecida pelo XBMC).
Aqui estão os novos recursos e melhorias no último XBMC 12.0 "Frodo":
- Suporte para Raspberry Pi, mas não há versões oficiais são fornecidos: você pode usar OpenELEC, Raspbmc, Xbian ou Raspbian. Download aqui;
- Android apoio - versões oficiais já estão disponíveis para download, mas somente a partir xbmc.org (XBMC não está disponível na loja do Google Play ainda);
- TV ao vivo e suporte PVR. Isso permite que os usuários com um sintonizador de TV para assistir TV ao vivo, ouvir rádio, ver um EPG, agendar gravações, etc backends suportados incluem: DVBViewer, MythTV, Tvheadend, VDR, Argus TV / ForTheRecord, NextPVR, Njoy Digital, MediaPortal e mais ;
- HD suporte de áudio, incluindo DTS-MA e Dolby True HD;
- Nova e unificada "Audioengine" quadro abstração de áudio com uma API e afunda plataforma;
- h.264 10bit (aka Hi10P) software de decodificação de vídeo para o anime;
- Suporte AirPlay melhorado;
- Suporte do controlador de melhoria;
- Video Tags biblioteca e filtragem biblioteca avançadas;
- Partilha UPnP avançada;
- Adicionado suporte para reprodução direta de arquivos de imagem ISO para a mídia Blu-ray;
- Adicionado Bluray sustentação do menu hdmv (mas não BD-J / BD-Live menus);
- Suporte para reprodução melhorada de arquivos não criptografados Bluray BDMV e mpls sem menus;
- Adicionado opção para definir uma preferência padrão para legendas e faixas de áudio com base na linguagem;
- Adicionado HLS (HTTP Live Streaming) e M3U8 (M3U Extensão) apoio lista;
- Linux: melhor VAAPI (Video Acceleration API) e apoio VDPAU (Nvidia);
- Linux: adicionado AMLPlayer dedicado e players de vídeo OMXPlayer para hardware acelerado de decodificação de vídeo em dispositivos Amlogic e IL OpenMAX API;
Publicada por
Unknown
à(s)
22:01
0
comentários
Enviar a mensagem por emailDê a sua opinião!Partilhar no XPartilhar no FacebookPartilhar no Pinterest
Etiquetas:
12.0,
frodo,
xbmc,
xbmc 12.0 Frodo
segunda-feira, 28 de janeiro de 2013
Definir IP estático no Ubuntu
Para definir um IP estático no Ubuntu em modo consola temos que fazer os seguintes passos:
Eu uso o vi mas podem também usar o nano .
Depois é só adicionar as seguintes linhas
Depois para activar a configuração basta reiniciar a maquina ou reiniciar o serviço de network.
sudo vi /etc/network/interfaces
Eu uso o vi mas podem também usar o nano .
Depois é só adicionar as seguintes linhas
auto eth0
iface eth0 inet static
address 192.168.1.100
netmask 255.255.255.0
gateway 191.168.1.1
dns-nameservers 8.8.8.8 8.8.8.4
Depois para activar a configuração basta reiniciar a maquina ou reiniciar o serviço de network.
domingo, 6 de janeiro de 2013
Ubuntu Phone OS - requisitos
Ao contrário do Android , o Ubuntu Phone OS foi desenvolvido com o objectivo de oferecer uma experiência única em dispositivos com baixo processamento.
Shuttleworth referiu inclusive que esta será a chave do sucesso do sistema operativo e que levará certamente muitos utilizadores a adpota-lo.
Soube-se entretanto que o Ubuntu Phone OS estará disponível para dois tipos de smartphones:
Smartphones de baixa performance “low end”
Smartphones de alta performance
Para dispositivos de baixa performance (low end), é necessário que cumpram os seguintes requisitos mínimos:
Para os “superphones” é necessário que sejam cumpridos os seguintes requisitos minimos:
Soube-se entretanto que o Ubuntu Phone OS estará disponível para dois tipos de smartphones:
Smartphones de baixa performance “low end”
Smartphones de alta performance
Para dispositivos de baixa performance (low end), é necessário que cumpram os seguintes requisitos mínimos:
- CPU: Cortex A9 a 1 Ghz
- RAM: 512 MB/1 GB
- Memoria de armazenamento: eMMC+SD de 4GB a 8 GB
- Multi-touch
Para os “superphones” é necessário que sejam cumpridos os seguintes requisitos minimos:
- CPU: Quad-core A9 ou Intel Atom
- RAM: Mínimo de 1 GB
- Memoria de armazenamento: Mínimo de 32GB eMMC + SD
- Multi-touch
- Convergência de Desktop
terça-feira, 18 de dezembro de 2012
Percona XtraBackup 2.0.4
Percona XtraBackup 2.0.4
Bugs Fixed:
Bug fix for #932623 introduced the regression in XtraBackup 2.0.2 which caused incremental backups to fail because the init parameter values were not normalized to the values used inside InnoDB. Bug fixed #1062684 (Sergei Glushchenko).
Bug fix for #932623 introduced the regression in XtraBackup 2.0.2 because it didn’t take the separate doublewrite tablespace into an account. Bug fixed #1066843 (Sergei Glushchenko).
XtraBackup was handling the separate doublewrite buffer file incorrectly. File path of the doublewrite buffer wasn’t added to the backup-my.cnf and after the restore old doublewrite buffer file was used instead of one made during the prepare stage. Bug fixed #1068470 (Sergei Glushchenko).
XtraBackup now accepts the --innodb=force option, previously it would throw an error if the option was set. Bug fixed#528752 (Laurynas Biveinis).
Option safe-slave-backup wasn’t working correctly. Bug fixed #887803 (Alexey Kopytov).
In case safe-slave-backup-timeout was reached when using the safe-slave-backup option, SQL_THREAD was left in stopped state causing the slave thread to lag behind. This was fixed by checking the initial SQL_THREAD state and starting it before terminating with a timeout error and starting the SQL_THREAD only if it was running initially. Bug fixed#1037379 (Alexey Kopytov).
XtraBackup would fail on --apply-log when filesystem didn’t support Linux AIO. Bug fixed #1065561 (Alexey Kopytov).
XtraBackup binary would ignore innodb_use_native_aio when it’s specified either in my.cnf or as a command line option. Bug fixed #1068459 (Alexey Kopytov).
XtraBackup would print a warning message during the prepare stage about innodb_file_io_threads being deprecated, even if the variable wasn’t set. Bug fixed #1068485 (Alexey Kopytov).
XtraBackup Galera tests can now be run concurrently. Bug fixed #1077800 (Stewart Smith).
Download -> http://www.percona.com/downloads/XtraBackup/XtraBackup-2.0.4/
Publicada por
Unknown
à(s)
18:31
0
comentários
Enviar a mensagem por emailDê a sua opinião!Partilhar no XPartilhar no FacebookPartilhar no Pinterest
Etiquetas:
mysql,
percona,
xtrabackup
domingo, 28 de outubro de 2012
MacBook5,1 8GB Ram
Com o passar do tempo e o evoluir dos sistemas operativos os nossos computadores vão ficando lentos e nem sempre e um problema de vírus ou malware , por vezes o hardware já não chega para o trabalho que fazemos.
Deparei-me com esse problema há uns tempo e foi ver o que o fabricante me dizia sobre o aumento de memoria do meu MacBook5,1.
Segundo a Apple este modelo só suporta ate 4GB de memoria RAM, no entanto decidi fazer o teste com 8 GB , dois simm de 4 e funciona, no meu caso utilizei dois módulos da Kingston.
O sistema reconhece os 8 GB e toma partido deles.
Google no Windows 8
Com a chegada do Windows 8 muitos pensaram que este sistema só iria permitir ser utilizado com contas Microsoft.
Bom a Google dá uma ajudinha para podermos manter a sua experiência no windows 8.
http://www.google.com/homepage/windows8/
segunda-feira, 1 de outubro de 2012
Sincronizar tabelas entre servidores MySQL
Este é um tutorial muito simples, mostra como sincronizar tabelas entre servidores MySQL, recorrendo a uma ferramenta da Percona, o Percona Toolkit .
Depois de termos instalado o Toolkit, basta correr o seguinte comando:
Depois de termos instalado o Toolkit, basta correr o seguinte comando:
pt-table-sync --execute u="utilizador mysql DE",p="password do utilizador",h="servidor DE",D="BD DE",t="tabela DE" h="servidor PARA",u="utilizador PARA",p="password",D="BD PARA"
Com este estas opções não estamos a o processo vai fazer uma copia da tabela do servidor DE para o PARA mantendo o nome da tabela.
Se fizermos um script e colocarmos na Cron o processo vai se encarregar de manter sempre a tabela sincronizada do DE -> PARA, se por exemplo tivermos o srcipt a correr de hora em hora, se fizermos uma alteração no servidor DE, no máximo ao fim de uma hora estará no servidor PARA.
O script para colocar na Cron pode ser algo do género :
#!/bin/bash SYNC="$(which pt-table-sync)" OPC="--execute u=user ,p=pass,h=host,D=BD,t=tabela h=host,u=user,p=pass,D=tabela" $SYNC $OPC
Publicada por
Unknown
à(s)
21:05
0
comentários
Enviar a mensagem por emailDê a sua opinião!Partilhar no XPartilhar no FacebookPartilhar no Pinterest
Etiquetas:
cron job,
linu,
mysq,
percona toolkit,
sync
segunda-feira, 24 de setembro de 2012
Como usar o rsync para mover ficheiros
Gostaria de mover todos os arquivos, ~ / Downloads / * avi do seu desktop para o laptop: ~ Download / / usando rsync.
E ao mesmo tempo excluir o arquivo de origem após transferência bem sucedida.
Excluir origem após transferência bem-sucedida com o rsync
A sintaxe é:
Pode sempre pode realizar um teste sem alterações feitas usando a opção - dry-run:
E ao mesmo tempo excluir o arquivo de origem após transferência bem sucedida.
Excluir origem após transferência bem-sucedida com o rsync
A sintaxe é:
rsync - fonte-remove-files-options / caminho / para / src / / caminho / para / dest
rsync - fonte-remove-files-options / caminho / para / src / ComputerB :/ caminho / para / dest
rsync -. fonte-remove-files-av / caminho / para / src / * avi ComputerB :/ caminho / para / dest
Pode sempre pode realizar um teste sem alterações feitas usando a opção - dry-run:
rsync - dry-run - fonte-remove-files-AZV / caminho / para / Download / * avi laptop: ~ / Download
sexta-feira, 21 de setembro de 2012
Mac OS X 10.8.2
inicio de sessão único no Facebook;
opção de partilhar Iigações e fotografias no Facebook;
possibilidade de integrar a informação de contacto e fotografias dos amigos do Facebook na aplicação Contactos;
notificações do Facebook na central de notificações.
Game Center
partilhe resultados no Facebook, Twitter, Mail ou Mensagens;
amigos do Facebook incluídos nas recomendações do Game Center;
botão Gostar do Facebook para jogos;
desafie os seus amigos a baterem os seus recordes e proezas.
Outras funcionalidades novas
suporte para Power Nap em computadores MacBook Air (modelos de finais de 2010);
iMessages enviadas para o seu numero de telefone podem agora ser recebidas na aplicacao Mensagens, no Mac;
possibilidade de adicionar cartões ao Passbook no iPhone ou iPod touch com iOS 6 a partir do Safari e do Mail no Mac;
listas de Lembretes partilhadas;
recepção de chamadas FaceTime feitas para o seu numero de telefone;
novas opções de ordenação permitem organizar as notas por titulo, por data de edição e de criação;
a funcionalidade de Ditado suporta agora mandarim, cantonês, espanhol, coreano, inglês (Canada) e italiano;
a aplicação Dicionário inclui agora o idioma francês;
possibilidade de adicionar aos Contactos fotografias de perfil do Sina Weibo;
A actualização 10.8.2 inclui igualmente correcções de erros que melhoram a estabilidade, compatibilidade e segurança do sistema operativo, incluindo correcções que visam especificamente:
uma opção para não guardar as alterações efectuadas a um documento original ao escolher Guardar como;
rascunhos por enviar abertos automaticamente ao abrir o Mail;
recepção de notificações do Twitter de publicacées de qualquer pessoa;
os URL são reduzidos ao enviar tweets da central de notificações;
a desactivação das notificações durante a utilização da projecção AirPlay;
suporte SSL para pesquisas no Google no campo de pesquisa inteligente no Safari;
preferência nova no Safari para abrir a aplicação com as páginas abertas anteriormente;
segunda-feira, 17 de setembro de 2012
Top 20+ MySQL Best Practices
Database operations often tend to be the main bottleneck for most web applications today. It’s not only the DBA’s (database administrators) that have to worry about these performance issues. We as programmers need to do our part by structuring tables properly, writing optimized queries and better code. Here are some MySQL optimization techniques for programmers.
1. Optimize Your Queries For the Query Cache
Most MySQL servers have query caching enabled. It’s one of the most effective methods of improving performance, that is quietly handled by the database engine. When the same query is executed multiple times, the result is fetched from the cache, which is quite fast.
The main problem is, it is so easy and hidden from the programmer, most of us tend to ignore it. Some things we do can actually prevent the query cache from performing its task.
view plaincopy to clipboardprint?
// query cache does NOT work
$r = mysql_query("SELECT username FROM user WHERE signup_date >= CURDATE()");
// query cache works!
$today = date("Y-m-d");
$r = mysql_query("SELECT username FROM user WHERE signup_date >= '$today'");
The reason query cache does not work in the first line is the usage of the CURDATE() function. This applies to all non-deterministic functions like NOW() and RAND() etc… Since the return result of the function can change, MySQL decides to disable query caching for that query. All we needed to do is to add an extra line of PHP before the query to prevent this from happening.
2. EXPLAIN Your SELECT Queries
Using the EXPLAIN keyword can give you insight on what MySQL is doing to execute your query. This can help you spot the bottlenecks and other problems with your query or table structures.
The results of an EXPLAIN query will show you which indexes are being utilized, how the table is being scanned and sorted etc…
Take a SELECT query (preferably a complex one, with joins), and add the keyword EXPLAIN in front of it. You can just use phpmyadmin for this. It will show you the results in a nice table. For example, let’s say I forgot to add an index to a column, which I perform joins on:
After adding the index to the group_id field:
Now instead of scanning 7883 rows, it will only scan 9 and 16 rows from the 2 tables. A good rule of thumb is to multiply all numbers under the “rows” column, and your query performance will be somewhat proportional to the resulting number.
3. LIMIT 1 When Getting a Unique Row
Sometimes when you are querying your tables, you already know you are looking for just one row. You might be fetching a unique record, or you might just be just checking the existence of any number of records that satisfy your WHERE clause.
In such cases, adding LIMIT 1 to your query can increase performance. This way the database engine will stop scanning for records after it finds just 1, instead of going thru the whole table or index.
view plaincopy to clipboardprint?
// do I have any users from Alabama?
// what NOT to do:
$r = mysql_query("SELECT * FROM user WHERE state = 'Alabama'");
if (mysql_num_rows($r) > 0) {
// ...
}
// much better:
$r = mysql_query("SELECT 1 FROM user WHERE state = 'Alabama' LIMIT 1");
if (mysql_num_rows($r) > 0) {
// ...
}
4. Index the Search Fields
Indexes are not just for the primary keys or the unique keys. If there are any columns in your table that you will search by, you should almost always index them.
As you can see, this rule also applies on a partial string search like “last_name LIKE ‘a%’”. When searching from the beginning of the string, MySQL is able to utilize the index on that column.
You should also understand which kinds of searches can not use the regular indexes. For instance, when searching for a word (e.g. “WHERE post_content LIKE ‘%apple%’”), you will not see a benefit from a normal index. You will be better off using mysql fulltext search or building your own indexing solution.
5. Index and Use Same Column Types for Joins
If your application contains many JOIN queries, you need to make sure that the columns you join by are indexed on both tables. This affects how MySQL internally optimizes the join operation.
Also, the columns that are joined, need to be the same type. For instance, if you join a DECIMAL column, to an INT column from another table, MySQL will be unable to use at least one of the indexes. Even the character encodings need to be the same type for string type columns.
view plaincopy to clipboardprint?
// looking for companies in my state
$r = mysql_query("SELECT company_name FROM users
LEFT JOIN companies ON (users.state = companies.state)
WHERE users.id = $user_id");
// both state columns should be indexed
// and they both should be the same type and character encoding
// or MySQL might do full table scans
6. Do Not ORDER BY RAND()
This is one of those tricks that sound cool at first, and many rookie programmers fall for this trap. You may not realize what kind of terrible bottleneck you can create once you start using this in your queries.
If you really need random rows out of your results, there are much better ways of doing it. Granted it takes additional code, but you will prevent a bottleneck that gets exponentially worse as your data grows. The problem is, MySQL will have to perform RAND() operation (which takes processing power) for every single row in the table before sorting it and giving you just 1 row.
view plaincopy to clipboardprint?
// what NOT to do:
$r = mysql_query("SELECT username FROM user ORDER BY RAND() LIMIT 1");
// much better:
$r = mysql_query("SELECT count(*) FROM user");
$d = mysql_fetch_row($r);
$rand = mt_rand(0,$d[0] - 1);
$r = mysql_query("SELECT username FROM user LIMIT $rand, 1");
So you pick a random number less than the number of results and use that as the offset in your LIMIT clause.
7. Avoid SELECT *
The more data is read from the tables, the slower the query will become. It increases the time it takes for the disk operations. Also when the database server is separate from the web server, you will have longer network delays due to the data having to be transferred between the servers.
It is a good habit to always specify which columns you need when you are doing your SELECT’s.
view plaincopy to clipboardprint?
// not preferred
$r = mysql_query("SELECT * FROM user WHERE user_id = 1");
$d = mysql_fetch_assoc($r);
echo "Welcome {$d['username']}";
// better:
$r = mysql_query("SELECT username FROM user WHERE user_id = 1");
$d = mysql_fetch_assoc($r);
echo "Welcome {$d['username']}";
// the differences are more significant with bigger result sets
8. Almost Always Have an id Field
In every table have an id column that is the PRIMARY KEY, AUTO_INCREMENT and one of the flavors of INT. Also preferably UNSIGNED, since the value can not be negative.
Even if you have a users table that has a unique username field, do not make that your primary key. VARCHAR fields as primary keys are slower. And you will have a better structure in your code by referring to all users with their id’s internally.
There are also behind the scenes operations done by the MySQL engine itself, that uses the primary key field internally. Which become even more important, the more complicated the database setup is. (clusters, partitioning etc…).
One possible exception to the rule are the “association tables”, used for the many-to-many type of associations between 2 tables. For example a “posts_tags” table that contains 2 columns: post_id, tag_id, that is used for the relations between two tables named “post” and “tags”. These tables can have a PRIMARY key that contains both id fields.
9. Use ENUM over VARCHAR
ENUM type columns are very fast and compact. Internally they are stored like TINYINT, yet they can contain and display string values. This makes them a perfect candidate for certain fields.
If you have a field, which will contain only a few different kinds of values, use ENUM instead of VARCHAR. For example, it could be a column named “status”, and only contain values such as “active”, “inactive”, “pending”, “expired” etc…
There is even a way to get a “suggestion” from MySQL itself on how to restructure your table. When you do have a VARCHAR field, it can actually suggest you to change that column type to ENUM instead. This done using the PROCEDURE ANALYSE() call. Which brings us to:
10. Get Suggestions with PROCEDURE ANALYSE()
PROCEDURE ANALYSE() will let MySQL analyze the columns structures and the actual data in your table to come up with certain suggestions for you. It is only useful if there is actual data in your tables because that plays a big role in the decision making.
For example, if you created an INT field for your primary key, however do not have too many rows, it might suggest you to use a MEDIUMINT instead. Or if you are using a VARCHAR field, you might get a suggestion to convert it to ENUM, if there are only few unique values.
You can also run this by clicking the “Propose table structure” link in phpmyadmin, in one of your table views.
Keep in mind these are only suggestions. And if your table is going to grow bigger, they may not even be the right suggestions to follow. The decision is ultimately yours.
11. Use NOT NULL If You Can
Unless you have a very specific reason to use a NULL value, you should always set your columns as NOT NULL.
First of all, ask yourself if there is any difference between having an empty string value vs. a NULL value (for INT fields: 0 vs. NULL). If there is no reason to have both, you do not need a NULL field. (Did you know that Oracle considers NULL and empty string as being the same?)
NULL columns require additional space and they can add complexity to your comparison statements. Just avoid them when you can. However, I understand some people might have very specific reasons to have NULL values, which is not always a bad thing.
From MySQL docs:
“NULL columns require additional space in the row to record whether their values are NULL. For MyISAM tables, each NULL column takes one bit extra, rounded up to the nearest byte.”
12. Prepared Statements
There are multiple benefits to using prepared statements, both for performance and security reasons.
Prepared Statements will filter the variables you bind to them by default, which is great for protecting your application against SQL injection attacks. You can of course filter your variables manually too, but those methods are more prone to human error and forgetfulness by the programmer. This is less of an issue when using some kind of framework or ORM.
Since our focus is on performance, I should also mention the benefits in that area. These benefits are more significant when the same query is being used multiple times in your application. You can assign different values to the same prepared statement, yet MySQL will only have to parse it once.
Also latest versions of MySQL transmits prepared statements in a native binary form, which are more efficient and can also help reduce network delays.
There was a time when many programmers used to avoid prepared statements on purpose, for a single important reason. They were not being cached by the MySQL query cache. But since sometime around version 5.1, query caching is supported too.
To use prepared statements in PHP you check out the mysqli extension or use a database abstraction layer like PDO.
view plaincopy to clipboardprint?
// create a prepared statement
if ($stmt = $mysqli->prepare("SELECT username FROM user WHERE state=?")) {
// bind parameters
$stmt->bind_param("s", $state);
// execute
$stmt->execute();
// bind result variables
$stmt->bind_result($username);
// fetch value
$stmt->fetch();
printf("%s is from %s\n", $username, $state);
$stmt->close();
}
13. Unbuffered Queries
Normally when you perform a query from a script, it will wait for the execution of that query to finish before it can continue. You can change that by using unbuffered queries.
There is a great explanation in the PHP docs for the mysql_unbuffered_query() function:
“mysql_unbuffered_query() sends the SQL query query to MySQL without automatically fetching and buffering the result rows as mysql_query() does. This saves a considerable amount of memory with SQL queries that produce large result sets, and you can start working on the result set immediately after the first row has been retrieved as you don’t have to wait until the complete SQL query has been performed.”
However, it comes with certain limitations. You have to either read all the rows or call mysql_free_result()before you can perform another query. Also you are not allowed to use mysql_num_rows() ormysql_data_seek() on the result set.
14. Store IP Addresses as UNSIGNED INT
Many programmers will create a VARCHAR(15) field without realizing they can actually store IP addresses as integer values. With an INT you go down to only 4 bytes of space, and have a fixed size field instead.
You have to make sure your column is an UNSIGNED INT, because IP Addresses use the whole range of a 32 bit unsigned integer.
In your queries you can use the INET_ATON() to convert and IP to an integer, and INET_NTOA() for vice versa. There are also similar functions in PHP called ip2long() and long2ip().
view plaincopy to clipboardprint?
$r = "UPDATE users SET ip = INET_ATON('{$_SERVER['REMOTE_ADDR']}') WHERE user_id = $user_id";
15. Fixed-length (Static) Tables are Faster
When every single column in a table is “fixed-length”, the table is also considered “static” or “fixed-length”. Examples of column types that are NOT fixed-length are: VARCHAR, TEXT, BLOB. If you include even just 1 of these types of columns, the table ceases to be fixed-length and has to be handled differently by the MySQL engine.
Fixed-length tables can improve performance because it is faster for MySQL engine to seek through the records. When it wants to read a specific row in a table, it can quickly calculate the position of it. If the row size is not fixed, every time it needs to do a seek, it has to consult the primary key index.
They are also easier to cache and easier to reconstruct after a crash. But they also can take more space. For instance, if you convert a VARCHAR(20) field to a CHAR(20) field, it will always take 20 bytes of space regardless of what is it in.
By using “Vertical Partitioning” techniques, you can separate the variable-length columns to a separate table. Which brings us to:
16. Vertical Partitioning
Vertical Partitioning is the act of splitting your table structure in a vertical manner for optimization reasons.
Example 1: You might have a users table that contains home addresses, that do not get read often. You can choose to split your table and store the address info on a separate table. This way your main users table will shrink in size. As you know, smaller tables perform faster.
Example 2: You have a “last_login” field in your table. It updates every time a user logs in to the website. But every update on a table causes the query cache for that table to be flushed. You can put that field into another table to keep updates to your users table to a minimum.
But you also need to make sure you don’t constantly need to join these 2 tables after the partitioning or you might actually suffer performance decline.
17. Split the Big DELETE or INSERT Queries
If you need to perform a big DELETE or INSERT query on a live website, you need to be careful not to disturb the web traffic. When a big query like that is performed, it can lock your tables and bring your web application to a halt.
Apache runs many parallel processes/threads. Therefore it works most efficiently when scripts finish executing as soon as possible, so the servers do not experience too many open connections and processes at once that consume resources, especially the memory.
If you end up locking your tables for any extended period of time (like 30 seconds or more), on a high traffic web site, you will cause a process and query pileup, which might take a long time to clear or even crash your web server.
If you have some kind of maintenance script that needs to delete large numbers of rows, just use the LIMIT clause to do it in smaller batches to avoid this congestion.
view plaincopy to clipboardprint?
while (1) {
mysql_query("DELETE FROM logs WHERE log_date <= '2009-10-01' LIMIT 10000");
if (mysql_affected_rows() == 0) {
// done deleting
break;
}
// you can even pause a bit
usleep(50000);
}
18. Smaller Columns Are Faster
With database engines, disk is perhaps the most significant bottleneck. Keeping things smaller and more compact is usually helpful in terms of performance, to reduce the amount of disk transfer.
MySQL docs have a list of Storage Requirements for all data types.
If a table is expected to have very few rows, there is no reason to make the primary key an INT, instead of MEDIUMINT, SMALLINT or even in some cases TINYINT. If you do not need the time component, use DATE instead of DATETIME.
Just make sure you leave reasonable room to grow or you might end up like Slashdot.
19. Choose the Right Storage Engine
The two main storage engines in MySQL are MyISAM and InnoDB. Each have their own pros and cons.
MyISAM is good for read-heavy applications, but it doesn't scale very well when there are a lot of writes. Even if you are updating one field of one row, the whole table gets locked, and no other process can even read from it until that query is finished. MyISAM is very fast at calculating SELECT COUNT(*) types of queries.
InnoDB tends to be a more complicated storage engine and can be slower than MyISAM for most small applications. But it supports row-based locking, which scales better. It also supports some more advanced features such as transactions.
MyISAM Storage Engine
InnoDB Storage Engine
20. Use an Object Relational Mapper
By using an ORM (Object Relational Mapper), you can gain certain performance benefits. Everything an ORM can do, can be coded manually too. But this can mean too much extra work and require a high level of expertise.
ORM's are great for "Lazy Loading". It means that they can fetch values only as they are needed. But you need to be careful with them or you can end up creating to many mini-queries that can reduce performance.
ORM's can also batch your queries into transactions, which operate much faster than sending individual queries to the database.
Currently my favorite ORM for PHP is Doctrine. I wrote an article on how to install Doctrine with CodeIgniter.
21. Be Careful with Persistent Connections
Persistent Connections are meant to reduce the overhead of recreating connections to MySQL. When a persistent connection is created, it will stay open even after the script finishes running. Since Apache reuses it's child processes, next time the process runs for a new script, it will reuse the same MySQL connection.
mysql_pconnect() in PHP
It sounds great in theory. But from my personal experience (and many others), this features turns out to be not worth the trouble. You can have serious problems with connection limits, memory issues and so on.
Apache runs extremely parallel, and creates many child processes. This is the main reason that persistent connections do not work very well in this environment. Before you consider using the mysql_pconnect() function, consult your system admin.
sexta-feira, 7 de setembro de 2012
Kindle Fire HD da Amazon
A esta o novo brinquedo vindo da Amazon, o Kindle Fire HD.
Este bicho vai dar cartas de certo no mercado, primeiro o preço 499 para um tablet com 4G ??
Ui isto vai doer a outros fabricantes, e depois o resto das características .
- Display de 8,9″, com resolução máxima de 1920×1200
- Processador: TI OMAP 4470 a 1.5Ghz dual-core
- GPU: Imagination PowerVR 3D
- Memória de armazenamento: 32 GB ou 64 GB
- Conectividade 4G LTE
- Interface: USB 2.0, Micro-HDMI
- Dolby audio stereo
- Wifi Dual-band (2.4GHz, 5GHz, suporte para a tecnologia MIMO).
- Suporte integrado para Facebook, Twitter, Gmail, Hotmail, Yahoo e muito mais
- Dimensões: 240 mm x 164 mm x 8.8 mm
- Peso: 575 gramas
Linux Command To Find SATA Link Speed
Qual a minha velocidade de conexão SATA?
Como posso ter certeza que meu disco rígido SATA está a trabalhar a uma velocidade de 6 Gbps e como posso verificar isso em Linux ?
Simples: dmesg | grep -i sata | grep 'link up'
domingo, 19 de agosto de 2012
Windows 8
O Windows 8 esta ai, alvo já de muitas controvérsias, tanto pelos utilizadores como pelos developers, algumas empresas que desenvolvem jogos já disseram abandonar o windows para passar para linux.
O novo ambiente de trabalho Metro não agrada a todos, pois e uma mudança muito grande para o utilizador.
Publicada por
Unknown
à(s)
11:41
0
comentários
Enviar a mensagem por emailDê a sua opinião!Partilhar no XPartilhar no FacebookPartilhar no Pinterest
Etiquetas:
8,
microsoft,
MS windows 8,
windows,
windows 8
Subscrever:
Mensagens (Atom)


