JS Tip: Revealing Module Pattern
From Christian Heilmann. Nothing too fancy for those who are used to write jQ plugins, but nice to save it for reference...
var myApp = function(){ var nome = 'Mauricio Wolff'; var idade = 35; function insertPessoa(){ // [...] } function updatePessoa(){ // [...] } function setPessoa () { // [ usa insert ou update ] } function getPessoa () { // [...] } return{ set: setPessoa, get: getPessoa } }(); // Example usage: myApp.get();
How to Make an HTML5 iPhone App
This is nice. An article on SixRevisions, short version here for my Archive.
If you write a couple meta tags, your html5 app will look like any other iPhone App, but will also work on Android, PalmPre, etc...
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0"/> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black" /> <link rel="apple-touch-icon" href="iphone_icon.png"/> <link rel="apple-touch-startup-image" href="startup.png" /> <link rel="stylesheet" href="styles.css" type="text/css" media="screen, mobile" title="main" charset="utf-8">
- apple-mobile-web-app-capable: This is another tip-off that we want to be an offline app.
- apple-mobile-web-app-status-bar-style: This hides the status bar, and nav bar when the app is offline.
- apple-touch-icon:This is the pointer to the image that want to be the icon.
- apple-touch-startup-image: This is a url pointing to the startup image.
Application Cache
Application caching allows browsers to determine in advance all the files a web page will need for the web page to work.
One tricky part to this whole thing is that the manifest (the list of files that need to be cached offline) has to be passed with a filetype Header set to text/manifest. That is why you need access to a web server that can set HTTP headers.
CACHE MANIFEST
# Version 3
style.css
index.html
init.js
# offline icons
startup.png
iphone_icon.pngOffline Data
Along with the ability to keep files that are needed offline, you can also store user data in an offline database. There are two major APIs for per user and/or per page data. The first is localStorage. localStorage, is an easy to use key-value store with a dead simple API.
localStorage.dataToStore = 5; console.log(localStorage.dataToStore); // 5
Its also possible to use a webdatabase (SQLite):
// Try and get a database object var db; try { if (window.openDatabase) { db = openDatabase("NoteTest", "1.0", "HTML5 Database API example", 200000); if (!db) alert("Failed to open the database on disk. This is probably because the version was / bad or there is not enough space left in this domain's quota"); } else alert("Couldn't open the database. Please try with a WebKit nightly with this feature enabled"); } catch(err) { } // Check and see if you need to initalize the DB db.transaction(function(tx) { tx.executeSql("SELECT COUNT(*) FROM WebkitStickyNotes", [], function(result) { loadNotes(); }, function(tx, error) { tx.executeSql("CREATE TABLE WebKitStickyNotes (id REAL UNIQUE, note TEXT, timestamp / REAL, left TEXT, top TEXT, zindex REAL)", [], function(result) { loadNotes(); }); }); }); // Insert a test Note. var note = { id: "1", text:" This is a test note", timestamp: "112123000", left:10, top:10, zIndex:2 }; db.transaction(function (tx) { tx.executeSql("INSERT INTO WebKitStickyNotes (id, note, timestamp, left, top, zindex) VALUES / (?, ?, ?, ?, ?, ?)", [note.id, note.text, note.timestamp, note.left, note.top, note.zIndex]); }); // Get all the notes out of the database. db.transaction(function(tx) { tx.executeSql("SELECT id, note, timestamp, left, top, zindex / FROM WebKitStickyNotes", [], function(tx, result) { for (var i = 0; i < result.rows.length; ++i) { var row = result.rows.item(i); var note = new Note(); note.id = row['id']; note.text = row['note']; note.timestamp = row['timestamp']; note.left = row['left']; note.top = row['top']; note.zIndex = row['zindex']; if (row['id'] > highestId) highestId = row['id']; if (row['zindex'] > highestZ) highestZ = row['zindex']; } if (!result.rows.length) newNote(); }, function(tx, error) { alert('Failed to retrieve notes from database - ' + error.message); return; }); });
Python x PHP: Finding IPs with regex
Sometimes I just like to write code in Python and PHP to compare them, and admire both...
Here's a little code to find IP adressess inside strings (returned from a nslookup). The code is not optimal, but illustrate how both languages works. Just for some friday fun...
Python
Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> a = 'yahoo.com IN A 69.147.114.224 18774s (05:12:54)' >>> a += 'yahoo.com IN A 209.131.36.159 18774s (05:12:54)' >>> a += 'yahoo.com IN A 209.191.93.53 18774s (05:12:54)' >>> print a 'yahoo.com IN A 69.147.114.224 18774s (05:12:54)yahoo.com IN A 209.131.36.159 18774s (05:12:54)yahoo.com IN A 209.191.93.53 18774s (05:12:54)' >>>; import re >>> p = re.compile('(?:\d{1,3}\.){3}\d{1,3}') >>>; p.findall(a) ['69.147.114.224', '209.131.36.159', '209.191.93.53'] >>>
PHP
$a = 'yahoo.com IN A 69.147.114.224 18774s (05:12:54)'; $a .= 'yahoo.com IN A 209.131.36.159 18774s (05:12:54)'; $a .= 'yahoo.com IN A 209.191.93.53 18774s (05:12:54)'; print $a; /* saida: yahoo.com IN A 69.147.114.224 18774s (05:12:54)yahoo.com IN A 209.131.36.159 18774s (05:12:54)yahoo.com IN A 209.191.93.53 18774s (05:12:54) */ $re = '/(\d+).(\d+).(\d+).(\d+)/'; preg_match_all($re, $a, $matches); var_dump($matches[0]); // saida 1 var_dump($matches); // saida 2 /* saida 1: array(3) { [0]=> string(14) "69.147.114.224" [1]=> string(14) "209.131.36.159" [2]=> string(13) "209.191.93.53" } saida 2: array(5) { [0]=> array(3) { [0]=> string(14) "69.147.114.224" [1]=> string(14) "209.131.36.159" [2]=> string(13) "209.191.93.53" } [1]=> array(3) { [0]=> string(2) "69" [1]=> string(3) "209" [2]=> string(3) "209" } [2]=> array(3) { [0]=> string(3) "147" [1]=> string(3) "131" [2]=> string(3) "191" } [3]=> array(3) { [0]=> string(3) "114" [1]=> string(2) "36" [2]=> string(2) "93" } [4]=> array(3) { [0]=> string(3) "224" [1]=> string(3) "159" [2]=> string(2) "53" } } */
Porque adoro jQuery
Pedido: Fazer com que todos os links de uma determinada página sejam externos.
- Abordagem 1: Alterar a classe em php, genérica, para ver se o link é externo e acrescentar o target; por regex.
- Abordagem 2: Colocar no init.js
$("a[href^='http://']").attr("target","_blank");
E todo site fica assim; links externos, para fora!
Aff... que doce.
Lifesaver snippets
Alguns códigos são simplesmente salvadores da pátria...
Por exemplo: Tens de subir um site por 3g, e mesmo targzipando o site ele fica com 12Mb por causa dos .svn escondidos...
tar --exclude='.svn' -czvf file.tar.gz ./*
6MB. Simples e eficaz...
facyBox, um mashup do facebox + fancybox
Gosto de trabalhar com o facebox, mas é muito facebook alike; gosto do fancybox, mas não acho tão flexível quando o facebox.
Solução? fazer um mashup dos dois e dar origem à facybox!!!
Disponível no github e aqui no bitbonsai labs.

mySQL Backup e Restore
Backup
Método 1
mysqldump -u root -h mysqserver -p --result-file=dbname_dbtable.sql dbname dbtable
Método 2
mysql>mysqldump -u root -p dbname > dbname_dbtable.sql
Restaurar
mysql -u root -h mysqserver -p dbname < dbname_dbtable.sql
IphoneApp – Hello World
Decidi escrever iPhoneApps. Primeiro passo? Aprender Objective-C.
Com uma cópia do Learn Objective-C on the Mac, de Mark Dalrymple & Scott Knaster coloquei a mão na massa. Como já tenho uma noção de C, não é tão estranho assim… claro que pensei que emNSString o NS era de NameSpace e não de NextStep, mas para essas informações super úteis um livro é essencial.
A primeira coisa, depois de baixar os 1,5GB do SDK (acho que vem com o XCode junto, que já tinha instalado) é escrever um Hello World, certo? Nada muito impressionante, mas é preciso começar por algum lugar…
Como preciso fazer algo mais bonito que o sample do livro, coloquei o fundo preto e um título na app. O grande lance é fazê-lo girar em qualquer direção e a App acompanhar. Aeae…
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation { return YES; }
