August 2010
1 post
1 tag
[JS] Fastest way for searching a monodimensional...
var myAr = ['apple', 5, 6]; if(String('^' + myAr.join('^')).indexOf("^5") != -1) console.log("found!"); else console.log("not found :(");
Aug 4th
July 2010
1 post
3 tags
[JS] jQuery random number plugin
I’ve taken this little piece of code around the Web (sorry, I forgot the original source) and it’s a good example on how to develop a plugin for jQuery: /** Usage: * $.random(int); * $.randomBetween(min, max); */ jQuery.extend({ random: function(X) { return Math.floor(X * (Math.random() % 1)); }, randomBetween: function(MinV, MaxV) { return MinV + jQuery.random(MaxV - MinV +...
Jul 27th
1 note
June 2010
1 post
1 tag
fglrx patch arch_fglrx_2.6.34.patch fails
user@host:~$ sudo updatedb user@host:~$ locate arch_fglrx_2.6.34.patch /usr/src/fglrx-8.732/patches/arch_fglrx_2.6.34.patch /var/lib/dkms/fglrx/8.732/build/patches/arch_fglrx_2.6.34.patch # substitute first two lines of each file with these lines (without #) # --- a/kcl_wait.c 2010-04-13 20:02:46.494496561 +0200 # +++ b/kcl_wait.c 2010-04-13 19:52:00.054563389 +0200 user@host:~$ sudo vim...
Jun 1st
1 note
May 2010
4 posts
4 tags
A view fro MySQL triggers
Here it is a small view to see all triggers stored in the DBMS. IMHO it’s more usable than going into INFORMATION_SCHEMA database and browse TRIGGERS records. CREATE VIEW `List_triggers` AS SELECT `TRIGGER_NAME` AS `Name`, `TRIGGER_SCHEMA` AS `Database`, `EVENT_OBJECT_TABLE` AS `Table`, CONCAT_WS(" ", ACTION_TIMING, EVENT_MANIPULATION) AS `Action` FROM...
May 24th
1 tag
May 20th
2 tags
How to restore Ubuntu gnome panel and menu items
As simple as: gconftool-2 --shutdown rm -rf ~/.gconf/apps/panel pkill gnome-panel If you want to restore, in example, Games menu from Applications, you have to: cd ~/.config/menus vim applications.menu and then remove (in my case) Deleted node: <Menu> <Name>Games</Name> <Exclude> ...
May 14th
4 tags
Chosing java-6-sun instead of OpenJDK on Ubuntu
I was disappointed when I figured out that Vuze didn’t work anymore after having upgraded to Lucid Lynx. So I launched the program in the shell and I discovered it couldn’t find some Swing stuff for creating the GUI. Back to Java Sun 6, so: chris@sirio:~$ sudo update-java-alternatives -l java-6-openjdk 1061 /usr/lib/jvm/java-6-openjdk java-6-sun 63...
May 7th
January 2010
2 posts
3 tags
[Browser] My favourite Chrome extensions
The development release of Chrome allow to install extension as for Firefox, but the process of installation (and even of creation as I heard from some developers) is faster. Here it is my list: AdThwart: Block ads on websites. Supports EasyList and many other ad blocker filter lists. RSS Subscription Extension: Adds one-click subscription to your toolbar. Chrome Gestures: Chrome Mouse...
Jan 14th
2 notes
3 tags
[PHP] Email validation considering PHP version
function isValidEmail($email) { if(version_compare(PHP_VERSION, '5.2.0', '>=') return filter_var($email, FILTER_VALIDATE_EMAIL); else return eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$', $email); }
Jan 7th
November 2009
2 posts
3 tags
[Links] Online services and tools for regex...
Regular expressions are a very powerful weapon for the developer if he can deals with all the pain of testing, debugging and learning the quirks of this matter. I’m collecting some links to be red one day, when I’ll got time to dive more deeply in the argument: Regular Expression Tester: online service which has a .NET desktop application porting too; Regular Expression Test Page:...
Nov 17th
Nov 17th
91 notes
October 2009
3 posts
6 tags
[PHP] Resources for programming with PDO
I’ve asked Twitter user what kind of PHP class would have used for a project and I was (and I am) in doubt between MDB2 (a PEAR Abstraction layer class) and mysqli extension. Someone has pointed out PDO, so I’m collecting some links to see what does this extension do: PDO on PHP web site: surely the first place to look at; Introduction to PDO on PHPPro: a big article which...
Oct 21st
[JS] How to get a querystring value given the key
Suppose you have an URL like this: www.host.com?m=5&lang=it. If you want to retrive the value of lang, you could simply use this function: function parseURL(url,key) { var reQS = new RegExp("[?&]"+key+"=([^&$]*)", "i"); var offset = url.search(reQS); return ( offset >= 0 ) ? RegExp.$1 : null; } // usage var myKey = parseURL("www.host.com?m=5&lang=it","lang") Via...
Oct 5th
Oct 5th
135 notes
September 2009
13 posts
5 tags
[JS] How to get the time and unixtime
Self explanatory code: var T = { getUnixTime: function() { return parseInt(new Date().getTime().toString().substring(0, 10)); }, // format hh:mm:ss getTime: function() { var d= new Date(); var time = new Array(); var hours = d.getHours(); time.push(hours); var minutes = d.getMinutes().toString().length < 2 ? "0"+d.getMinutes() : d.getMinutes(); time.push(minutes); var...
Sep 22nd
1 note
3 tags
[JS] How to extend Array object to get the index...
The code is self explanatory: you have an array and you want to know what index has the element “pippo” or “5”. So I extended the array object with prototype keyword to scan the array and to return the index if found, -1 otherwise. var points = [56,12,36]; Array.prototype.getIndex = function(aVal) { for(item in this) if(aVal == this[item]) return item; ...
Sep 22nd
3 tags
[Bash] How much memory consume a process
ps -aylC geany |grep "geany" |awk '{print $8'} |sort -n |tail -n 1
Sep 17th
1 note
[MySQL] Using information_schema instead of SHOW...
PHP can handle data returned by SHOW commands, but information about all databases and tables are stored in information_schema database. Some useful queries: 1) Getting only columns name: SELECT `column_name` FROM information_schema.columns WHERE `table_name`="mytable"; The SHOW statement show columns from t5_user; shows extra information that must be filtered with PHP. In example if you...
Sep 15th
1 note
2 tags
[jQuery] How to use Prototype or MooTools with...
Since many libraries make use of the $ identifier, we need a way to prevent collisions between these names. jQuery provides a method called .noConflict() to return control of the $ identifier back to other libraries. Typical usage of .noConflict() follows the following pattern: jQuery.noConflict(); First, the other library (Prototype in this example) is included. Then, jQuery itself is...
Sep 10th
3 tags
[jQuery] How to add a CSS class to external links
// apply a class to all <a> which respect the filter selection. $('a').filter(function() { return this.hostname && this.hostname != location.hostname; }).addClass('external');
Sep 10th
3 tags
[MySQL] How to install mytop on CentOS 5.3
For the ones who don’t know what mytop is, it’s a simple perl script that shows mysql’s porcesses list (SHOW PROCESSLIST) like top does for system’s processes. First of all, let’s assure what distro you’re using by typing: [root@localhost ~]# cat /etc/issue CentOS release 5.3 (Final) Kernel \r on an \m Then let’s import GPG key: rpm --import...
Sep 10th
3 tags
[MySQL] How to create a random day for a date
If you have extracted with PHP or a SQL function a date (“YYYY-MM-DD”) and you want to change the day with a random day, here is it a series of SELECT for doing it: SELECT date FROM ( -- generates a number x between 1 and 27 SELECT @rand:=( SELECT FLOOR(1 + (RAND() * 27)) ) as rand, DATE_ADD('2006-05-01',INTERVAL @rand DAY) as date ) as t; -- give an alias, otherwise it's...
Sep 9th
2 tags
[MySQL] How to check if a value is a number
Here it is a function for checking if a field value represent a number. Floating point and negative numbers are also considered. CREATE FUNCTION IsNumeric (sIn varchar(1024)) RETURNS tinyint RETURN sIn REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$'; Via: Stack Overflow.
Sep 9th
2 tags
[MySQL] How to clean URL with a function
Suppose that you have a table with a column named “referer” which stores referring urls and suppose that you want to update this column by cutting off everything but the domain and subdomain. Here it is a small function that does the job: delimiter // drop function if exists sub_domain; CREATE FUNCTION sub_domain (url text(1000)) RETURNS CHAR(100) BEGIN DECLARE str1...
Sep 8th
2 tags
[MySQL] How to swap columns values in a table
I find a very useful webpage on how to swap columns values in MySQL. In that article are presented three methods, of which I’ve chosen the following one which makes use of a temporary variable: UPDATE table SET x=(@temp:=x), x = y, y = @temp WHERE condition....
Sep 4th
4 tags
[JS] Firefox debugging with Firebug Console API
I’ve found always useful using Bin-Blog’s dump function to explore the properties of an object or an array (like a PHP print_r) but now I’ve discovered that console.dir function does the same: a = ['a', 1, true]; console.dir(a); console.dir function will produce in output console this result: >>> a = ['a', 1, true]; console.dir(a) 0 "a" 1 1 2 true
Sep 3rd
2 tags
[SQL] How to concatenate a string with a result of...
If the subquery returns a string, you can use safely CONCAT operator to join the strings: SELECT CONCAT('my',(SELECT string FROM table WHERE condition = 1)) as aName You can use CONCAT_WS if you want to specify a separator for the strings.
Sep 1st
2 notes
August 2009
1 post
4 tags
[PHP] How to retrive urls in Google sitemap into...
This code makes use of SimpleXMLElement class. function sitemap2array($http_url) { $sitemap = simplexml_load_file($http_url); if($sitemap !== FALSE) { $arr = array(); foreach($sitemap->children() as $b) if($b->getName() == "url") $arr[]= (string)$b->{'loc'}; return $arr; } }
Aug 6th
July 2009
4 posts
2 tags
[PHP] How to catch warnings inside a script
Put the case you’re doing a FTP upload of a file. If the transmission fails for whatever problem, you’ll receive a warning but your app won’t stop, you’ll only be able to see that an error occurred. So you can define an error handler to catch those warnings: // error handler function function myErrorHandler($errno, $errstr, $errfile, $errline) { switch ($errno)...
Jul 8th
2 tags
[PHP] How much memory does your app consume?
Here it is a simple function to display how much memory your PHP script is consuming. // debug function with time, memory consumption (MB) and optional custom message public function getMemoryUsage($message="", $echo=1) { $mem_used = memory_get_usage(true)/ 1024 / 1024; $mem_peak = memory_get_peak_usage(true) / 1024 / 1024; preg_match("/(\d)+/",ini_get('memory_limit'),$matches); // regexp,...
Jul 7th
3 tags
[PHP] How to beautify XML code
If you manually write XML code without using a class like DOMDocument or SimpleXML, you’ll probably obtain a “one line file”, unless you intentionally insert break lines. As it’s a tedious work, there’s a useful PEAR class, XML_Beautifier, to do such a job. Here it is how to use it: first of all install it with pear by command line: sudo pear install --alldeps...
Jul 7th
2 tags
[JS] How to test if a variable is defined
// returns 1 if defined, 0 otherwise. function isDefined(anObj) { switch(typeof(anObj)) { case "string": if(anObj != "") return 1; else return 0; case "undefined": return 0; case "object": if(anObj != null) return 1; else return 0; default: return 0; } }
Jul 1st
3 notes
June 2009
9 posts
3 tags
How to export to an array a MySQL query with 3...
By reading a good contribution on PHP site, I discovered this method for exporting to an array a query submitted to MySQL: $result = mysql_query("SELECT * FROM table"); for($i = 0; $array[$i] = mysql_fetch_assoc($result); $i++) ; array_pop($array); // removes last empty array It produces: Array ( [0] => Array ( [id] => 1 [user] => myuser ...
Jun 21st
tumblrMap - generate xml sitemaps for your tumblr...
andreaolivato: Just a quick post to let every tumblr friend know that I created a simple web app which creates xml sitemaps for tumblr blog and auto-submit them too google. This should improve any tumblr blog seo a lot! Take a look! http://tumblrmap.net/
Jun 21st
3 tags
[PHP-MySQL] MySQL transaction with PHP
// require MySQL Version 4.0.12 using InnoDB type tables. @mysql_connect("localhost","username", "password") or die(mysql_error()); @mysql_select_db("test") or die(mysql_error()); $query = "INSERT INTO trans (id,item,quantity) values (null,'Baseball',4)"; begin(); // transaction begins $result = @mysql_query($query); if(!$result) { rollback(); // transaction rolls back echo "you rolled...
Jun 10th
2 tags
[SQL] How to compare two SQL schema with sqlfairy
First of all, install sqlfairy on your machine if you haven’t done yet, then simply give in input to the program the path to the SQL schemas: sqlt-diff -d -c schema_to_update.sql=MySQL updated_schema.sql=MySQL 2>/dev/null|grep -v "DROP TABLE" Notes on this command: -d: prints debug info; -c: case insensitive; 2>/dev/null: don’t print warning and error messages so you can...
Jun 8th
1 tag
[PHP] How to retrive HTTP headers
$var = "REQUEST"; foreach (apache_request_headers() as $name => $value) { $var.= "$name: $value "; } $var.= "RESPONSE"; foreach (apache_response_headers() as $name => $value) { $var.= "$name: $value "; } echo $var; Anyway response header returned by apache_response_headers() consists only of server signature in my case, but in firebug I can see a lot more of them.
Jun 5th
1 note
1 tag
Trim,ltrim & rtrim in #javascript
andreaolivato: Simple class to trim,ltrim and rtrim as it’s common in other languages. trim = { both : function(str,ch) { # Equivalent to trim return trim.lead(trim.trail(str,ch),ch); }, lead : function(str,ch) { # Equivalent to ltrim if (!ch) ch="\\s" return str.replace( new RegExp("^["+ch+"]+", "g"), "" ); }, trail : function(str,ch) { # Equivalent to rtrim if...
Jun 5th
2 tags
[PHP] How to test if a string is a number (with...
If you use is_numeric function, you could note that 45,362.00 or 45.362,00 are not numbers for this function (only one dot is permitted). So here it is a function (taken from this comment) that uses regular expression to extend is_numeric functionality: function my_is_numeric($value) { $american = preg_match ("/^(-){0,1}([0-9]+)(,[0-9][0-9][0-9])*([.][0-9]){0,1}([0-9]*)$/" ,$value) == 1; ...
Jun 5th
2 tags
[Shell] How to modify bash shell prompt
The UNIX shell displays a command prompt when the system is ready to accept commands on the command line. To customize your prompt you will need to modify the PS1 (“prompt string 1”) shell variable. For example if you want to show “user@host:working_path”, you have to set PS1 variable in this way in your .bash_profile: # ~/.bash_profile: executed by bash(1) for login...
Jun 3rd
2 tags
How to read/write root's attributes in...
If you use SimpleXMLElement to read and write your XML documents, this trick is useful to read/write root element attributes. Suppose to have such a document: this is an example ... If you want to modify count or uniqueCount in PHP, you only need to do this: try{ // load the file $xml = simplexml_load_file($this->xl_sharedStrings); } catch(Exception $e) { die(" Cannot parse...
Jun 3rd
March 2009
1 post
3 tags
Which quotes have more than X services?
SELECT id, COUNT(productid) as numProd FROM `vtiger_inventoryproductrel` WHERE id IN (SELECT quoteid FROM vtiger_quotes, vtiger_crmentity WHERE quoteid = crmid AND deleted = 0) GROUP BY id HAVING numProd > 4
Mar 4th
February 2009
1 post
First post
So this is the first post on tumblr. I’ve created an account here to write all things that don’t need an entire post on my blog. Short thoughts, notes, quotes, snippets of code and everything longer than 140 chars (for Twitter) but shorter than a normal blog post will land here. :-)
Feb 15th