Derniers snippets latest snippets

Symfony, trier aléatoirement les résultat avec Propel et MySQL

Attention, cela ne fonctionnera probablement qu'avec MySQL :

<?php
$c = new criteria;
$c->addAscendingOrderByColumn('rand()');
$results = TotoPeer::doSelect($c);
by Nicolas Perriault on 2008-03-30, tagged order  propel  rand  symfony 

Enbarquer un objet QuickTime en XHTML

Parfois, on a besoin d'inclure une vidéo QuickTime (.MOV) dans une page XHTML :

<!--[if IE]>
<object id="ieqt" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="640" height="415">
  <param name="src" value="toto.mov">
  <param name="autoplay" value="false"/>
  <param name="controller" value="true"/>
  <param name="loop" value="false"/>
  <p><a href="toto.mov">Télécharger la vidéo</a>.</p>
</object>
<![endif]-->
 
<!--[if !IE]><-->
<object id="nonieqt" data="toto.mov" type="video/quicktime" width="640" height="415">
  <param name="autoplay" value="false"/>
  <param name="controller" value="true"/>
  <param name="loop" value="false"/>
  <p><a href="toto.mov">Télécharger la vidéo</a>.</p>
</object>
<!--><![endif]-->
by Nicolas Perriault on 2008-03-26, tagged html  quicktime  video  xhtml 

Ajouter la coloration dans le terminal Mac OS X

Pour avoir de belles couleurs au chargement d'une session dans le terminal OS X (ou iTerm), il faut éditer son fichier ~/.profile et y ajouter cette ligne :

export CLICOLOR=true

Et recharger le profil :

$ . ~/.profile
by Nicolas Perriault on 2008-03-23, tagged cli  colors  mac  osx 

Comparer les différences entre deux répertoires

C'est tout con, mais encore faut-il le savoir :)

$ diff -rq rep1/ rep2/
by Nicolas Perriault on 2008-03-22, tagged bash  cli  filesystem  linux 

[Symfony 1.1 beta] Créer un test unitaire et initialiser Propel

Depuis l'apparition du nouveau système de configuration de Symfony 1.1, voici un boostrap type pour vos tests unitaires nécessitant l'accès à l'environnement Propel :

<?php
require_once(dirname(__FILE__).'/../../config/ProjectConfiguration.class.php');
$configuration = ProjectConfiguration::getApplicationConfiguration('main', 'test', true);
include($configuration->getSymfonyLibDir().'/vendor/lime/lime.php');
sfContext::createInstance($configuration);

Pensez cependant à remplacer main par le nom de votre application courante (par ex. frontend).

by Nicolas Perriault on 2008-03-19, tagged lime  propel  symfony  unittest 

Une progress bar mise à jour à partir d'un thread

Dans le cadre d'une application graphique, un traitement long peut être déporté dans un thread à part. Si l'on veut afficher une progress bar, elle doit être mise-à-jour à partir de ce thread.

En PyQt, on utilise un mécanisme de SIGNAL/SLOT pour faire cela.

#!/usr/bin/python
# use a progress dialog from a thread
 
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import time,sys
 
STEPS=5
 
class MyThread(QThread):
   def __init__(self,parent):
      super(MyThread,self).__init__(parent)
      self.cancel = False
 
   def run (self):
      for i in range(STEPS):
         if self.cancel: break
         time.sleep(1)
         self.emit(SIGNAL("increment"))
         print "%d "%(i),
 
   @pyqtSignature("")
   def cancel(self):
      """SLOT to cancel treatment"""
      self.cancel = True
 
class MyAppli(QWidget):
   def __init__(self,parent=None):
      QWidget.__init__(self, parent)
      # create button to start the thread
      self.btnStart = QPushButton("Start",self)
      self.connect(self.btnStart, SIGNAL("clicked()"),
                   self,          SLOT("on_btnStart_clicked()"))
 
   @pyqtSignature("")
   def on_btnStart_clicked(self):
      """Start the treatment in the thread"""
      self.p = QProgressDialog("Running...","Stop",0,STEPS-1,self)
      self.th = MyThread(self)
      self.th.connect(self.th,SIGNAL("increment"),
                              self.incProgress)
      self.p.connect (self.p, SIGNAL("canceled()"),
                      self.th,SLOT("cancel()"))
      self.p.show()
      self.th.start()
 
   def incProgress(self):
      """Increment the progress dialog"""
      self.p.setValue(self.p.value()+1)
 
if __name__ == "__main__":
   app = QApplication(sys.argv)
   widget = MyAppli()
   widget.show()
   sys.exit(app.exec_())

On commence par créer un simple bouton pour lancer le thread. Lorsqu'il est cliqué, une boite de progression est créée et l'on connecte deux signaux :

  • increment pour déclencher la maj de la progressdialog dans le thread principal
  • canceled pour annuler le traitement

Puis on affiche la boite et on lance le thread.

by JJL on 2008-03-19, tagged progressbar  pyqt  python  thread 

[Symfony] Utiliser sqlite pour stocker le cache des templates

D'abord, s'assurer d'avoir le module sqlite de php5 chargé et activé :

$ sudo apt-get install php5-sqlite
$ sudo /etc/init.d/apache2 restart

Dans le fichier factories.yml de l'application concernée :

view_cache:
    class:                     sfSQLiteCache
    param:
      automaticCleaningFactor: 0
      database:                %SF_ROOT_DIR%/cache/cache.db

Et voilà, maintenant les symfony cc se feront en un éclair.

by Nicolas Perriault on 2008-03-17, tagged cache  sqlite  symfony 

[Symfony] Un validateur de date qu'il est bien

Quelques fonctionnalités en plus par rapport à sfDateValidator (qu'il étend), notamment l'interdiction de date futures ou passées et l'évitement du traitement de la langue courante utilisateur (utile pour les formats de date figés).

/**
 * Custom date validator
 *
 */
class myDateValidator extends sfDateValidator
{
  /**
   * Execute this validator.
   *
   * @param mixed A file or parameter value/array
   * @param error An error message reference
   *
   * @return bool true, if this validator executes successfully, otherwise false
   */
  public function execute(&$value, &$error)
  {
    $culture = $this->getContext()->getUser()->getCulture();
 
    // Validate the given date
    if ($this->getParameter('with_culture'))
    {
      $value1 = $this->getValidDate($value, $culture);
    }
    else
    {
      $value1 = strtotime($value);
    }
 
    if (!$value1 || -1 == $value1) // Before php 5.1, strtotime() returns -1 on fail
    {
      $error = $this->getParameter('date_error');
      return false;
    }
 
    // Is there a compare to do?
    $compareDateParam = $this->getParameter('compare');
    $compareDate = $this->getContext()->getRequest()->getParameter($compareDateParam);
 
    // If the compare date is given
    if ($compareDate)
    {
      $operator = trim($this->getParameter('operator', '=='), '\'" ');
      $value2 = $this->getValidDate($compareDate, $culture);
 
      // If the check date is valid, compare it. Otherwise ignore the comparison
      if ($value2)
      {
        $valid = false;
        switch ($operator)
        {
          case '>':
            $valid = $value1 >  $value2;
            break;
          case '>=':
            $valid = $value1 >= $value2;
            break;
          case '==':
            $valid = $value1 == $value2;
            break;
          case '<=':
            $valid = $value1 <= $value2;
            break;
          case '<':
            $valid = $value1 <  $value2;
            break;
 
          default:
            throw new sfValidatorException(sprintf('Invalid date comparison operator "%s"', $operator));
        }
 
        if (!$valid)
        {
          $error = $this->getParameter('compare_error');
 
          return false;
        }
      }
    }
 
    if (!$this->getParameter('allow_future') && $value1 > time())
    {
      $error = $this->getParameter('future_error');
      return false;
    }
 
    if (!$this->getParameter('allow_past') && $value1 < time())
    {
      $error = $this->getParameter('past_error');
      return false;
    }
 
    return true;
  }
 
  /**
   * Initializes the validator.
   *
   * @param sfContext The current application context
   * @param array   An associative array of initialization parameters
   *
   * @return bool true, if initialization completes successfully, otherwise false
   */
  public function initialize($context, $parameters = null)
  {
    // Initialize parent
    parent::initialize($context, $parameters);
 
    // Set defaults
    $this->getParameterHolder()->set('with_culture', true);
    $this->getParameterHolder()->set('allow_future', true);
    $this->getParameterHolder()->set('future_error', 'Future dates not allowed');
    $this->getParameterHolder()->set('allow_past', true);
    $this->getParameterHolder()->set('past_error', 'Past dates not allowed');
    $this->getParameterHolder()->add($parameters);
 
    return true;
  }
}
by Nicolas Perriault on 2008-03-16, tagged date  php  symfony  validator 

Compiler tous les fichiers PHP en un seul

Pour faire un gros fichier comportant l'intégralité d'un projet par exemple :

$ find . -name "*.php" |xargs php -w > mongrosprojet.php
by Nicolas Perriault on 2008-03-15, tagged php 

Export/Import d'une base MySQL utf8

C'est pas facile, mais c'est possible.

I. Exportation de la base :

$ mysqldump -uuser -p --opt --default-character-set=utf8 mabase > mabase.sql

II. Reconversion :

$ iconv -f iso-8859-1 -t utf-8 mabase.sql > mabase_utf8.sql

III. Reimport :

$ mysql -uuser -p mabase < mabase_utf8.sql
by Nicolas Perriault on 2008-02-27, tagged mysql  utf8