be the change you want to see in the world
Uncategorized
[rb]Custom doctrine count query
May 7th
Sometimes you may need to use count with the index column rather than *, because of some dark corners of sql driven databases. Though this is somehow rare, this is how you could do it with Doctrine … this example is part of a symfony 1.4 project(place the file in any of the /lib dirs … app ones or global one):
<?php
class Custom_Doctrine_Query extends Doctrine_Query {
public static function create($conn = null, $class = null)
{
if ( ! $class) {
$class = 'Custom_Doctrine_Query';
}
return new $class($conn);
}
public function getCustomCountSqlQuery()
{
// triggers dql parsing/processing
$this->getSqlQuery(array(), false); // this is ugly
// initialize temporary variables
$where = $this->_sqlParts['where'];
$having = $this->_sqlParts['having'];
$groupby = $this->_sqlParts['groupby'];
$rootAlias = $this->getRootAlias();
$tableAlias = $this->getSqlTableAlias($rootAlias);
$primaryKey = $tableAlias . '.' . $this->_queryComponents[$rootAlias]['table']->getColumnName( $this->_queryComponents[$rootAlias]['table']->getIdentifier());
// Build the query base
$q = 'SELECT COUNT(' . $primaryKey . ') AS ' . $this->_conn->quoteIdentifier('num_results') . ' FROM ';
// Build the from clause
$from = $this->_buildSqlFromPart(true);
// Build the where clause
$where = ( ! empty($where)) ? ' WHERE ' . implode(' ', $where) : '';
// Build the group by clause
$groupby = ( ! empty($groupby)) ? ' GROUP BY ' . implode(', ', $groupby) : '';
// Build the having clause
$having = ( ! empty($having)) ? ' HAVING ' . implode(' AND ', $having) : '';
// Building the from clause and finishing query
if (count($this->_queryComponents) == 1 && empty($having)) {
$q .= $from . $where . $groupby . $having;
} else {
// Subselect fields will contain only the pk of root entity
$ta = $this->_conn->quoteIdentifier($tableAlias);
$map = $this->getRootDeclaration();
$idColumnNames = $map['table']->getIdentifierColumnNames();
$pkFields = $ta . '.' . implode(', ' . $ta . '.', $this->_conn->quoteMultipleIdentifier($idColumnNames));
// We need to do some magic in select fields if the query contain anything in having clause
$selectFields = $pkFields;
if ( ! empty($having)) {
// For each field defined in select clause
foreach ($this->_sqlParts['select'] as $field) {
// We only include aggregate expressions to count query
// This is needed because HAVING clause will use field aliases
if (strpos($field, '(') !== false) {
$selectFields .= ', ' . $field;
}
}
// Add having fields that got stripped out of select
preg_match_all('/`[a-z0-9_]+`\.`[a-z0-9_]+`/i', $having, $matches, PREG_PATTERN_ORDER);
if (count($matches[0]) > 0) {
$selectFields .= ', ' . implode(', ', array_unique($matches[0]));
}
}
// If we do not have a custom group by, apply the default one
if (empty($groupby)) {
$groupby = ' GROUP BY ' . $pkFields;
}
$q .= '(SELECT ' . $selectFields . ' FROM ' . $from . $where . $groupby . $having . ') '
. $this->_conn->quoteIdentifier('dctrn_count_query');
}
return $q;
}
public function count($params = array())
{
$q = $this->getCustomCountSqlQuery();
$params = $this->getCountQueryParams($params);
$params = $this->_conn->convertBooleans($params);
if ($this->_resultCache) {
$conn = $this->getConnection();
$cacheDriver = $this->getResultCacheDriver();
$hash = $this->getResultCacheHash($params).'_count';
$cached = ($this->_expireResultCache) ? false : $cacheDriver->fetch($hash);
if ($cached === false) {
// cache miss
$results = $this->getConnection()->fetchAll($q, $params);
$cacheDriver->save($hash, serialize($results), $this->getResultCacheLifeSpan());
} else {
$results = unserialize($cached);
}
} else {
$results = $this->getConnection()->fetchAll($q, $params);
}
if (count($results) > 1) {
$count = count($results);
} else {
if (isset($results[0])) {
$results[0] = array_change_key_case($results[0], CASE_LOWER);
$count = $results[0]['num_results'];
} else {
$count = 0;
}
}
return (int) $count;
}
}
The usage of the above class should be something like this:
$query = Custom_Doctrine_Query::create()->from('TargetTable t');
$count = $query->count();
or the bulky way omitting the static create method:
$query = Doctrine_Query::create(null, 'Custom_Doctrine_Query')->from('TargetTable t');
$count = $query->count();
The result of the above queries should be something like “SELECT COUNT(index_field) from target_table”.
Intel reinvents the micro-chip design
May 7th
Intel presented 2 days ago at San Francisco, one of the biggest breakthroughs of the last decade regarding the design of microchips, on which the new 22nm processor generations will be based. More information about it can be found here:
Transistors go 3D as Intel re-invents the microchip
and here
[snip] Doctrine update enum field
Feb 5th
$query = Doctrine_Query::create()->update('table')->set('field',Doctrine_Manager::connection()->quote('some_value', 'text'))->where('id = ?', $id);
Batch convert .ai files as pdf compatible
Nov 23rd
The title should be self explaining:
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
//should we overwrite our files? i strongly recommend that you DON'T or if you do, have a backup
var OVERWRITE = false;
function main() {
var initDir = Folder.selectDialog();
if(initDir == null) return;
var dlg = prompt("Would you like to overwrite existing?(Strongly suggested that you don't)", "NO", "Overwrite?");
if(dlg == null) return;
else if(dlg.toLowerCase() == "yes") {
var cdlg = confirm("Are you really sure that you want to overwrite all files?");
if(cdlg) OVERWRITE = true;
}
recurseDirs(initDir);
}
function isValidFile(file) {
var os = (file.creator == "????") 'win' : 'unix';
if(os == 'win') {
if(file.name.indexOf(".ai") > -1 || file.name.indexOf(".eps") > -1) return true;
} else if( os == 'unix') {
if(file.creator.substring(0,3) == 'ART') return true;
}
return false;
}
function recurseDirs(dir){
var files = dir.getFiles(isFile);
var dirs = dir.getFiles(isDir);
if(files.length>0) recurseFiles(files);
if(dirs.length>0) dirs.forEach(recurseDirs);
}
function recurseFiles(files){
for(j = files.length - 1; j>=0; j--) {
if(files[j].hidden || files[j].name.substring(0,1) == '.') continue;
var _doc = app.open(files[j]);
var name = '', ext = '';
if(files[j].name.indexOf(".ai") > -1) {
name = files[j].name.substring(0, files[j].name.indexOf(".ai"));
ext = ".ai";
} else if(files[j].name.indexOf(".eps") > -1) {
name = files[j].name.substring(0, files[j].name.indexOf(".eps"));
ext = ".eps";
} else {
name = files[j].name;
ext = '';
}
var path = '';
if(!OVERWRITE) {
path = files[j].path + "/" + name + "_CS3" + ext;
} else {
path = files[j];
}
exportFileToAI(path);
_doc.close(SaveOptions.DONOTSAVECHANGES);
//app.redraw();
}
}
function isDir(fileObj) {
if(fileObj instanceof File) return false;
else if(fileObj instanceof Folder) return true;
return false;
}
function isFile(fileObj) {
if(fileObj instanceof File) return true;
else if(fileObj instanceof Folder) return false;
return false;
}
function exportFileToAI (dest) {
if ( app.documents.length > 0 ) {
var saveOptions = new IllustratorSaveOptions();
var ai13Doc = (dest instanceof File) ? dest : new File(dest);
saveOptions.pdfCompatible = true;
saveOptions.compatibility = Compatibility.ILLUSTRATOR13;
saveOptions.flattenOutput = OutputFlattening.PRESERVEAPPEARANCE;
app.activeDocument.saveAs( ai13Doc, saveOptions );
}
}
main();
JQuery true background changer
Nov 21st
While looking for a background changer, i couldn’t find one that would fit my needs … that’s when i realize that it would take less to make one myself … while it might not work just perfect yet, it was just enough for what i needed … damn laziness …
Test case: http://www.insightmed.eu/showcase.html
JScript plugin: http://www.insightmed.eu/media/interactive/vendor.jquery.js
Usage: $(‘selector’).bgChange({ images: ['image 1', 'image 2', 'image 3', 'etc.'], dir: ‘images dir’, apply_classes: ['apply these classes to the helper used for the effect'] });
