31 decembrie 2008

Cautare in diacritice

Lucrez la un site la care a trebuit sa fac cautare pe campuri text in care existau diacritice. Asa ca am facut clasicul SELECT FROM table WHERE field LIKE '%cautare%' , care mi-a dat buba, cautarea dupa 'mâna' (membru superior), am scris 'mana', si logic ca nu a gasit, asa ca am introdus in DB un camp suplimentar "field_fd" care sa contina textul fara diacritice, pe care l-am completat filosind
function diac($s) {
$p = array("ã","º","þ","î","â","Ã","ª","Þ","ă","ş","ţ","î","â","Ă","Ş","Ţ","Î","Â");
$r = array("a","s","t","i","a","A","S","T","a","s","t","i","a","A","S","T","I","A");
$ds = str_replace($p, $r, $s);
return $ds;
}
Asta va fi ultimul post pe 2008 asa ca  http://www.dancingsantacard.com/?santa=6591466  

Incarcare in MySQL pentru fisiere CSV de dimensiuni mari

Am avut o "mica" problema, de vreo 100 Mb, un fisier CSV care trebuia importat intr0o baza de date MySQL din  PHPMyAdmin sau script PHP.
Fisierul CSV se gaseste la
http://geolite.maxmind.com/download/geoip/database/GeoLiteCity_CSV/GeoLiteCity_20081201.zip
Daca foloseam :
<?php
$file=file_get_contents("blocks.csv"); $rows=explode("\n",$file);
foreach($rows as $r) mysql_query("INSERT INTO geolocate
VALUES($r)");?>

se genera Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 35 bytes), si chiar daca nu aparea asta, sigur aparea limitarea timpului de executie a scriptului PHP (de obicei 30 secunde). Mai tarziu a venit si ideea :
Creez tabelele :
 
CREATE TABLE `blocks` (
  `ipn1` int(11) NOT NULL,
  `ipn2` int(11) NOT NULL,
  `locid` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
 
CREATE TABLE `location` (
  `locid` int(11) NOT NULL,
  `country` varchar(5) NOT NULL,
  `region` varchar(5) NOT NULL,
  `city` varchar(150) NOT NULL,
  `postcode` varchar(20) NOT NULL,
  `lat` int(11) NOT NULL,
  `lng` int(11) NOT NULL,
  `metro` varchar(11) NOT NULL,
  `area` varchar(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
 
fac upload la fisierele CSV prin FTP,  si apoi
 
<?php 
 mysql_query("LOAD DATA INFILE 'path/blocks.csv' REPLACE INTO TABLE blocks FIELDS ENCLOSED BY '\"' TERMINATED BY ','") or die('Invalid query: ' . mysql_error());
 mysql_query("LOAD DATA INFILE 'path/location.csv' REPLACE INTO TABLE location FIELDS OPTIONALLY ENCLOSED BY '\"' TERMINATED BY ','") or die('Invalid query: ' . mysql_error());
?>

18 decembrie 2008

Verificare disponibilitate video Youtube

Exista destule video-uri de pe YouTube pe bloguri/siturie. Si stiti ce neplacut e cand descoperiti dupa un timp ca multe dintre ele nu mai sunt disponibile (cu pateticul black screen of death "We're sorry, this video is no longer available"). Solutia (PHP) este :
function curl_get_file_contents($URL)
{
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c) or die("SIZE ERROR<script type='text/javascript'>var t=setTimeout('timeFct()',5000)</script>");
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}

function urlfilesize($url,$thereturn) {
if (substr($url,0,4)=='http') {
$x = array_change_key_case(get_headers($url, 1),CASE_LOWER);
$x = $x['content-length'];
}
else { $x = @filesize($url); }
if (!$thereturn) { return $x ; }
elseif($thereturn == 'mb') { return round($x / (1024*1024),2) ; }
elseif($thereturn == 'kb') { return round($x / (1024),2) ; }
}
$vtemp = $_GET['v'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.youtube.com/watch?v=".$vtemp);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$info= curl_exec($ch);
$lun = strlen($info);
$pos1 = strpos($info,"&t=",$pos1);
$Stri=substr($info, $pos1+3, 32);
if($Stri!='') echo "Disponibil"; else echo "Indisponibil";


[EDITARE 19-12-2008] Sunt stupid, functiile nu isi au locul aici ! Asa ca codul poate incepe de la $vtemp = $_GET['v'];

24 noiembrie 2008

Programatori intelepti au zis :

There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies.
[C.A.R. Hoare]

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
[Brian W. Kernighan]


Testing can only prove the presence of bugs, not their absence.
[Edsger Dijkstra]

There's no obfuscated Perl contest because it's pointless.
[Jeff Polk]


If you lie to the compiler, it will get its revenge.
[Henry Spencer]

Java is, in many ways, C++--.
[Michael Feldman]

Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25.
[Andrew Rutherford]

Simplicity is prerequisite for reliability.
[Dijkstra]

The first 90% of the code accounts for the first 10% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.
[Tom Cargill]

Beware of bugs in the above code; I have only proved it correct, not tried it.
[Donald Knuth]

Most software today is very much like an Egyptian pyramid with millions of bricks piled on top of each other, with no structural integrity, but just done by brute force and thousands of slaves.
[Alan Kay]

Object-oriented programming is an exceptionally bad idea which could only have originated in California.
[Dijkstra]

Software and cathedrals are much the same - first we build them, then we pray.
[Anonymous]

To iterate is human, to recurse divine.
[Peter Deutsch]

Most of you are familiar with the virtues of a programmer. There are three, of course: laziness, impatience, and hubris.
[Larry Wall]

Any code of your own that you haven't looked at for six or more months might as well have been written by someone else.
[Eagleson's law]

Before software can be reusable it first has to be usable.
[Ralph Johnson]

There are two ways to write error-free programs; only the third works.
[Alan J. Perlis]

C programmers never die. They are just cast into void.
[Anonymous]

Real programmers can write assembly code in any language.
[Larry Wall]

Programming can be fun, so can cryptography; however they should not be combined.
[Kreitzberg and Shneiderman]

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
[Jamie Zawinski]

If debugging is the process of removing bugs, then programming must be the process of putting them in.
[Edsger Dijkstra]

PHP is a minor evil perpetrated and created by incompetent amateurs, whereas Perl is a great and insidious evil, perpetrated by skilled but perverted professionals.
[Jon Ribbens]

No matter how slick the demo is in rehearsal, when you do it in front of a live audience the probability of a flawless presentation is inversely proportional to the number of people watching, raised to the power of the amount of money involved.
[Mark Gibbs]

Trying to outsmart a compiler defeats much of the purpose of using one.
[Kernighan & Plauger]

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.
[Bill Gates]

I have always wished that my computer would be as easy to use as my telephone. My wish has come true. I no longer know how to use my telephone.
[Bjarne Stroustrup]

When we had no computers, we had no programming problem either. When we had a few computers, we had a mild programming problem. Confronted with machines a million times as powerful, we are faced with a gigantic programming problem.
[Dijkstra]

Saying that Java is good because it works on all platforms is like saying anal sex is good because it works on all genders.
[Anonymous]

The evolution of languages: FORTRAN is a non-typed language. C is a weakly typed language. Ada is a strongly typed language. C++ is a strongly hyped language.
[Ron Sercely]

I've finally learned what "upward compatible" means. It means we get to keep all our old mistakes.
[Dennie van Tassel]

Without C we only have Obol, Pasal and BASI.
[Michael Feldman]

…one of the main causes of the fall of the Roman Empire was that, lacking zero, they had no way to indicate successful termination of their C programs.
[Robert Firth]

COBOL programmers understand why women hate periods.
[Anonymous]

I have a pretty major problem with a language where one of the most common variables has the name $_
[Brian Hook, about PERL]

A Perl program is correct if it gets the job done before your boss fires you.
[Larry Wall]

If a million monkeys were typing on computers, one of them will eventually write a Java program. The rest of them will write Perl programs.
[Anonymous]

If you need more than 3 levels of indentation, you're screwed anyway, and should fix your program.
[Linux 1.3.53 CodingStyle documentation]

An infinite number of monkeys typing into GNU emacs would never make a good program.
[Linux CodingStyle documentation]

If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization.
[Weinberg's Second Law]

Don't get suckered in by the comments ... they can be terribly misleading.
[Dave Storer]

If in physics there's something you don't understand, you can always hide behind the uncharted depths of nature. You can always blame God. You didn't make it so complex yourself. But if your program doesn't work, there is no one to hide behind. You cannot hide behind an obstinate nature. If it doesn't work, you've messed up.
[Dijkstra]

The camel has evolved to be relatively self-sufficient. On the other hand, the camel has not evolved to smell good. Neither has Perl.
[Larry Wall]

Programming is one of the most difficult branches of applied mathematics; the poorer mathematicians had better remain pure mathematicians.
[Dijkstra]

With enough eyes, all bugs are shallow.
[Eric S. Raymond]

BASIC - A programming language. Related to certain social diseases in that those who have it will not admit it in polite company.
[Anonymous]

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to build bigger and better idiots. So far, the universe is winning.
[Rick Cook]

He who hasn't hacked assembly language as a youth has no heart. He who does as an adult has no brain.
[John Moore]

It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.
[Dijkstra]

29 octombrie 2008

Resurse care simplifica viata de Web Designer

Despre CSS, sau cat de varza sunt la asta

Am dat recent pe un post de blog de un nene (Stefano Mazzocchi mai precis) care-mi zicea (nu personal) ca sunt varza la CSS. Nimic mai adevarat ! De aceea m-a invatat urmatoarele :

1. intotdeauna sa pun : <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> si <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

2. Ca sa fac designu unui site sa folosesc Builderu' de Yahoo

3. Ca sa testez diferite tipur de scris (fonturi) sa folosesc TypeTesteru'

4. Sa folosesc palete de culori, ca se gasesc la Iubitorii de culori, sau chiar la Adobe Kuler. Pot genera palete de culori dintr-o poza (sic) la BigHugeLabs sau la DeGraEve.

5. In CSS exista urmatoarele :

  • h1 + h2 { margin-top: -1em; } - adica daca am h1 urmat de h2, se aplica CSS-u ala pentru h2
  • h1 > h2{ margin-top: -1em; } - adica daca am h2 intr-un h1, se aplica CSS-u ala pentru h2
  • q { font-family: "Georgia", serif; }
    q:before { content: "\201C"; padding-right: 0.1em; }
    q:after { content: "\201D"; padding-left: 0.1em; }
    se numesc Curly Quotes si cica sunt niste ghilimele mai misto.
  • Breadcrumbs (adica linkurile de genu "sunteti aici: categorie subcategorie produs") el le face cu :
    ul.path > li { content: "\00BB"; font-family: "Times New Roman", serif; font-size: 14px; padding-left: 6px; }
  • Initialele (prima litera din primu paragraf) le face cu :
    p.first:first-letter { font-family: "Imprint MT Shadow", "Times", "Times New Roman", serif; font-size: 3.6em; color: #222; }
  • Si ca poti folosi fisiere CSS pentru browsere diferite
    <!--[if lt IE 7]><script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE7.js" type="text/javascript"></script><![endif]-->
    <!--[if lt IE 8]><script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script><![endif]-->

23 octombrie 2008

Cica asta e "Google Gadget"

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="Titlul gadgetului" />
<Content type="url" href="http://www.pagina.ro/ccare_se_afiseaza.htm" />
</Module>

Nota: fisierul HTM nu trebuie sa contina decat codul din tagul BODY


21 octombrie 2008

Geo localizare a IP-urilor

O baza de date cu locatiile (tarile) de provenienta ale IP-urilor (geolocalizare) se poate gasi, in format CSV, aici. Baza de date se updateaza lunar. Pentru a determina IP-ul vizitatorului, in PHP se foloseste $_SERVER['REMOTE_ADDR']

20 octombrie 2008

Conectare MySQL

<?php
 mysql_connect('localhost', 'user', 'pass') or die('Not connected : '.mysql_error());
 mysql_select_db('db');
?>

17 octombrie 2008

Utilizare display_startup_errors

Pentru a nu mai afisa erorile / warning-urile pe un site se editeaza fisierul .htaccess astfel
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off

Cum se foloseste PHPMailer

De obicei nu folosesc (nu foloseam) scripturi deja facute, dar a trebuit sa updatez un site care folosea PHPMailer, asa ca am invatat cum se foloseste
$mail = new PHPMailer();
$mail->From = $r['from'];
$mail->FromName = $r['fromname'];
$mail->Subject = $r['subject'];
$mail->IsHTML(true);
$mail->Body = $mesaj;
$mail->AddAddress($r['email'], $r['name']);
if(!$mail->Send()) {
echo 'Eroare la trimitere mail ('.$r['email'].')';
} else {
echo 'Mail trimis ('.$r['email'].')';
}
======================================================================================
$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';
======================================================================================

MySQL : Stergere articole duplicat

Pentru a sterge articolele duplicat dintr-o tabela MySQL se foloseste DISTINCT astfel :
DELETE FROM table1 USING table1, table1 AS vtable WHERE (table1.id > vtable.id) AND (table1.field_name=vtable.field_name)