Agregar una tabla al PDF removiendo aquellas columnas donde no existen
datos en la columna para todas las filas
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
@version 2016-10-06
554594
public function addTableWithoutEmptyCols($titles, $data, $options = [], $html = true)
    {
        $cols_empty = [];
        foreach ($data as $row) {
            foreach ($row as $col => $value) {
                if (empty($value)) {
                    if (!array_key_exists($col, $cols_empty))
                        $cols_empty[$col] = 0;
                    $cols_empty[$col]++;
                }
            }
        }
        $n_rows = count($data);
        $titles_keys = array_flip(array_keys($titles));
        foreach ($cols_empty as $col => $rows) {
            if ($rows==$n_rows) {
                unset($titles[$col]);
                foreach ($data as &$row) {
                    unset($row[$col]);
                }
                if (isset($options['width']))
                    unset($options['width'][$titles_keys[$col]]);
                if (isset($options['align']))
                    unset($options['align'][$titles_keys[$col]]);
            }
        }
        if (isset($options['width'])) {
            $options['width'] = array_slice($options['width'], 0);
            $key_0 = null;
            $suma = 0;
            foreach ($options['width'] as $key => $val) {
                if ($val===0)
                    $key_0 = $key;
                $suma += $val;
            }
            if ($key_0!==null) {
                $options['width'][$key_0] = 190 - $suma;
            }
        }
        if (isset($options['align']))
            $options['align'] = array_slice($options['align'], 0);
        $this->addTable($titles, $data, $options, $html);
    }
640475
protected function _getLastAbsoluteX()
    {
        for ($k=count($this->table)-1; $k>=0; $k--) {
            if ($this->table[$k]['x'] && $this->table[$k]['position']) return $this->table[$k]['x'];
        }
        return $this->_pdf->getlMargin();
    }
1177548
def dar_nombre_campo_dbf(clave, claves):
    ""
    # achico el nombre del campo para que quepa en la tabla:
    nombre = clave.replace("_","")[:10]
    # si el campo esta repetido, le agrego un número
    i = 0
    while nombre in claves:
        i += 1    
        nombre = nombre[:9] + str(i)
    return nombre.lower()
247164
public function getColumnPackedCopy()
    {
        $P = [];
        for ($i = 0; $i < $this->m; $i++) {
            for ($j = 0; $j < $this->n; $j++) {
                array_push($P, $this->A[$j][$i]);
            }
        }
        return $P;
    }
216464
public function getColumns()
    {
        $columns = [];

        foreach ($this->columns as $field => $fieldTitle) {
            if (in_array($field, $this->model->getFillable())) {
                if (!$field) {
                    $field = $fieldTitle;
                    $fieldTitle = Str::title($fieldTitle);
                }
                $columns[$field] = $fieldTitle;
                continue;
            }

            // We can replace this with data_get() I believe.
            if (($methodBreaker = strpos($field, '.')) !== false) {
                $method = substr($field, 0, $methodBreaker);
                if (method_exists($this->model, $method)) {
                    if (method_exists($this->model->$method(), $submethod = str_replace($method.'.', '', $field))) {
                        $this->model->$method()->$submethod();

                        $columns[$field] = $fieldTitle;
                        continue;
                    }
                }
            }

            if (is_numeric($field)) {
                $field = $fieldTitle;
                $fieldTitle = Str::title($fieldTitle);
            }

            $columns[$field] = $fieldTitle;
        }

        if (count($columns)) {
            return $columns;
        }

        return [$this->model->getKeyName() => $this->model->getKeyName()];
    }
450091
public function makeTableMapDTO()
    {
        $data = [];
        $data['table_id'] = $this->binaryDataReader->readTableId();
        $this->binaryDataReader->advance(2);
        $data['schema_length'] = $this->binaryDataReader->readUInt8();
        $data['schema_name'] = $this->binaryDataReader->read($data['schema_length']);

        if (Config::checkDataBasesOnly($data['schema_name'])) {
            return null;
        }

        $this->binaryDataReader->advance(1);
        $data['table_length'] = $this->binaryDataReader->readUInt8();
        $data['table_name'] = $this->binaryDataReader->read($data['table_length']);

        if (Config::checkTablesOnly($data['table_name'])) {
            return null;
        }

        $this->binaryDataReader->advance(1);
        $data['columns_amount'] = $this->binaryDataReader->readCodedBinary();
        $data['column_types'] = $this->binaryDataReader->read($data['columns_amount']);

        if ($this->cache->has($data['table_id'])) {
            return new TableMapDTO($this->eventInfo, $this->cache->get($data['table_id']));
        }

        $this->binaryDataReader->readCodedBinary();

        $columns = $this->repository->getFields($data['schema_name'], $data['table_name']);

        $fields = [];
        // if you drop tables and parse of logs you will get empty scheme
        if (!empty($columns)) {
            $columnLength = strlen($data['column_types']);
            for ($i = 0; $i < $columnLength; ++$i) {
                // this a dirty hack to prevent row events containing columns which have been dropped
                if (!isset($columns[$i])) {
                    $columns[$i] = [
                        'COLUMN_NAME' => 'DROPPED_COLUMN_' . $i,
                        'COLLATION_NAME' => null,
                        'CHARACTER_SET_NAME' => null,
                        'COLUMN_COMMENT' => null,
                        'COLUMN_TYPE' => 'BLOB',
                        'COLUMN_KEY' => ''
                    ];

                    $type = ConstFieldType::IGNORE;
                } else {
                    $type = ord($data['column_types'][$i]);
                }

                $fields[$i] = Columns::parse($type, $columns[$i], $this->binaryDataReader);
            }
        }

        $tableMap = new TableMap(
            $data['schema_name'],
            $data['table_name'],
            $data['table_id'],
            $data['columns_amount'],
            $fields
        );

        $this->cache->set($data['table_id'], $tableMap);

        return new TableMapDTO($this->eventInfo, $tableMap);
    }
285599
def CrearPlantillaPDF(self, papel="A4", orientacion="portrait"):
        ""
        
        # genero el renderizador con propiedades del PDF
        t = Template(
                 format=papel, orientation=orientacion,
                 title="F 1116 B/C %s" % (self.NroOrden),
                 author="CUIT %s" % self.Cuit,
                 subject="COE %s" % self.params_out.get('coe'),
                 keywords="AFIP Liquidacion Electronica Primaria de Granos", 
                 creator='wslpg.py %s (http://www.PyAfipWs.com.ar)' % __version__,)
        self.template = t
        return True
557824
public function CreateIndexTables()
    {
        $aIndexTableNames = TdbShopSearchIndexer::GetAllIndexTableNames();
        $aTmpIndex = array();
        foreach ($aIndexTableNames as $sTableName => $length) {
            $aTmpIndex['_tmp'.$sTableName] = $length;
        }
        $aIndexTableNames = $aTmpIndex;
        foreach ($aIndexTableNames as $sTableName => $iLength) {
            if (TCMSRecord::TableExists($sTableName)) {
                $query = "DROP TABLE `{$sTableName}`";
                MySqlLegacySupport::getInstance()->query($query);
            }
            $sPrimaryKey = '';
            $query = 'CREATE TABLE `'.MySqlLegacySupport::getInstance()->real_escape_string($sTableName)."` (
                    `shop_article_id` CHAR(36) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL COMMENT 'the shop article',
                    `substring` CHAR( {$iLength} ) NOT NULL COMMENT 'the substring',
                    `cms_language_id` CHAR(36) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL COMMENT 'language of substring',
                    `occurrences` INT NOT NULL COMMENT 'Number of times the substring occured in the field for that article',
                    `weight` FLOAT NOT NULL COMMENT 'calculated weight for the substring',
                    `shop_search_field_weight_id` CHAR(36) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL COMMENT 'field for which the search term was made'
                    {$sPrimaryKey}
                  )";
            MySqlLegacySupport::getInstance()->query($query);
        }

        // drop index fields not needed
        $sBaseName = '_tmp'.self::INDEX_TBL_PREFIX;
        $query = "SHOW TABLES LIKE '".MySqlLegacySupport::getInstance()->real_escape_string($sBaseName)."%'";
        $rTableRes = MySqlLegacySupport::getInstance()->query($query);
        while ($aTableData = MySqlLegacySupport::getInstance()->fetch_row($rTableRes)) {
            if (!array_key_exists($aTableData[0], $aIndexTableNames)) {
                $query = 'DROP TABLE `'.MySqlLegacySupport::getInstance()->real_escape_string($aTableData[0]).'`';
                MySqlLegacySupport::getInstance()->query($query);
            }
        }
    }
518022
public function &buildColumnList()
    {

        $str = "";
        $ct = 0;

        // Build Select Column List
        foreach ($this->columns as $k => $col) {
            if ($col->in_select) {
                if ($ct > 0) {
                    $str .= ",";
                }

                $str .= " ";

                if ($col->table_name) {
                    $str .= $col->table_name . ".";
                }

                $str .= $col->column_name;

                if (($col->query_name)) {
                    $str .= " " . $col->query_name;
                }

                $ct++;
            }
        }
        //die;
        return $str;
    }
110708
public function ColumnsList()
    {
        $list = new ArrayList();

        foreach ($this->columns as $key => $column) {
            $header     = $this->array_get($column, self::KEY_HEADER);
            $required   = $this->array_get($column, self::KEY_REQUIRED);
            $type       = $this->array_get($column, self::KEY_TYPE,
                self::TYPE_TEXT);
            $values     = $this->array_get($column, self::KEY_OPTIONS);
            $valuesList = null;

            $size = null;

            if ($type == self::TYPE_CURRENCY) {
                $type = 'text';
                $size = 7;
            }

            if ($values && is_array($values)) {
                $valuesList = new ArrayList();
                foreach ($values as $k => $v) {
                    $valuesList->push(new ArrayData(array('Name' => $k, 'Value' => $v)));
                }
            }

            $rowData = array(
                'Key' => $key,
                'Size' => $size,
                'Header' => $header,
                'Values' => $valuesList,
                'Type' => $type,
                'Required' => $required ? 'true' : 'false'
            );
            $list->push(new ArrayData($rowData));
        }
        return $list;
    }
260834
public function pdf()
    {
        if ('snappy' == config('datatables-buttons.pdf_generator', 'snappy')) {
            return $this->snappyPdf();
        }

        return $this->buildExcelFile()->download($this->getFilename() . '.pdf', $this->pdfWriter);
    }
649300
public function snappyPdf()
    {
        /** @var \Barryvdh\Snappy\PdfWrapper $snappy */
        $snappy      = resolve('snappy.pdf.wrapper');
        $options     = config('datatables-buttons.snappy.options');
        $orientation = config('datatables-buttons.snappy.orientation');

        $snappy->setOptions($options)->setOrientation($orientation);

        return $snappy->loadHTML($this->printPreview())->download($this->getFilename() . '.pdf');
    }
387311
public function main()
    {
        // cargar XML y extraer arreglo con datos de carátula y DTEs
        $EnvioDte = new \sasco\LibreDTE\Sii\EnvioDte();
        $EnvioDte->loadXML(file_get_contents($this->args['xml']));
        $Caratula = $EnvioDte->getCaratula();
        $Documentos = $EnvioDte->getDocumentos();
        // procesar cada DTEs e ir creando los archivos PDF
        foreach ($Documentos as $DTE) {
            if (!$DTE->getDatos())
                $this->error('No se pudieron obtener los datos de uno de los DTE del XML');
            $this->out('Generando PDF para DTE '.$DTE->getID());
            $pdf = new \sasco\LibreDTE\Sii\Dte\PDF\Dte($this->args['papel']);
            $pdf->setFooterText();
            if ($this->args['logo'])
                $pdf->setLogo($this->args['logo']);
            $pdf->setResolucion(['FchResol'=>$Caratula['FchResol'], 'NroResol'=>$Caratula['NroResol']]);
            $pdf->setWebVerificacion($this->args['web']);
            $pdf->agregar($DTE->getDatos(), $DTE->getTED());
            if (isset($this->args['cedible'])) {
                $pdf->setCedible(true);
                $pdf->agregar($DTE->getDatos(), $DTE->getTED());
            }
            $pdf->Output($this->args['dir'].'/dte_'.$Caratula['RutEmisor'].'_'.$DTE->getID().'.pdf', 'F');
        }
        return 0;
    }
671211
private function copyCustomSystem()
    {
        //Para cada biblioteca
        foreach (Helper::listFolder(PATH_HOME . VENDOR) as $lib) {

            // copia tema caso não exista no projeto mas exista nas libs
            if (!file_exists(PATH_HOME . "public/assets/theme.min.css") && file_exists(PATH_HOME . VENDOR . $lib . "/public/assets/theme.min.css"))
                copy(PATH_HOME . VENDOR . $lib . "/public/assets/theme.min.css", PATH_HOME . "public/assets/theme.min.css");

            $libNot = Config::getMenuNotAllow();

            //Remove index caso alguma biblioteca já possua
            if (file_exists(PATH_HOME . VENDOR . $lib . "/public/view/index.php") && file_exists(PATH_HOME . "public/view/index.php")) {
                if (preg_match("/<h1>Parabéns, tudo funcionando de acordo!<\/h1>/i", file_get_contents(PATH_HOME . "public/view/index.php")) && (!isset($libNot) || !in_array($lib, $libNot))) {
                    unlink(PATH_HOME . "public/view/index.php");
                    unlink(PATH_HOME . "public/param/index.json");
                }
            }
        }
    }
713231
protected function buildColumns() {
		$select = [];
		$params = [];
		if(!$this->columns)
			return ['*', []];
		else {
			foreach($this->columns as $alias=>$column) {
				if($column instanceof static) {
					$sql = $column->buildSQL();
					$params = array_merge($params, $column->getParameters());
					$select[] = '('.$sql.') AS '.$this->identifierQuotes($alias);
				}
				elseif($column instanceof Raw) {
					$sql = $column->getSQL();
					$params = array_merge($params, $column->getParameters());
					$select[] = $sql.' AS '.$this->identifierQuotes($alias);
				}
				elseif((string)$alias !== (string)$column)
					$select[] = $this->identifierQuotes($column).' AS '.$this->identifierQuotes($alias);
				else
					$select[] = $this->identifierQuotes($column);
			}
		}
		return [implode(', ', $select), $params];
	}
435530
public function ajouter()
    {
        $authentifie = new archiAuthentification();
        $formulaire = new formGenerator();
        if ($authentifie->estConnecte()) {
            $tabForm=$this->getAdresseFields();
            $this->connexionBdd->getLock(array('historiqueAdresse'));
            $errors = $formulaire->getArrayFromPost($tabForm); // recupere les donnees POST suivant les champs de tabForm , tabForm est passé en référence, il contient donc les valeurs des champs a la sortie de la fonction
            $this->nettoieCoordonneesAdresse($tabForm); // permet de garder l'id de la rue, quartier, sousQuartier le plus bas dans la hierarchie , a partir duquel on peut retrouver le reste

            if (count($errors)==0) {
            // on regarde si l'adresse existe deja parmis les adresses valides (non "archivees")
                $sql = "SELECT ha1.idAdresse as idAdresse
						FROM historiqueAdresse ha1, historiqueAdresse ha2
						WHERE ha2.idAdresse = ha1.idAdresse
						AND ha1.idRue='".$tabForm['rue']['value']."'
								AND ha1.idSousQuartier='".$tabForm['sousQuartier']['value']."'
										AND ha1.idQuartier='".$tabForm['quartier']['value']."'
												AND ha1.idVille='".$tabForm['ville']['value']."'
														AND ha1.idPays='".$tabForm['pays']['value']."'
																AND ha1.numero = '".$tabForm['numero']['value']."'
																		AND ha1.date='".$tabForm['date']['value']."'
																				AND ha1.idIndicatif='".$tabForm['indicatif']['value']."'
																						GROUP BY ha1.idAdresse, ha1.idHistoriqueAdresse
																						HAVING ha1.idHistoriqueAdresse = max(ha2.idHistoriqueAdresse)";

                //debug($sql);

                $resCheckExist=$this->connexionBdd->requete($sql);

                if (mysql_num_rows($resCheckExist)>1) {
                    echo "plusieurs adresse existe concernant cette adresse, pas d'ajout, veuillez prevenir l'administrateur.<br>";
                } elseif (mysql_num_rows($resCheckExist)==1) {
                    echo "l'adresse existe deja dans la base";
                    // recuperation de l'id existant
                    $fetchAdresseExistante=mysql_fetch_array($resCheckExist);
                } else {
                    // ajout
                    // recherche du nouvel idAdresse
                    $resIdAdresse = $this->connexionBdd->requete("select max(idAdresse) as maxIdAdresse from historiqueAdresse");
                    $nouvelIdAdresse=0;
                    if (mysql_num_rows($resIdAdresse)>0) {
                        $fetchNouvelIdAdresse = mysql_fetch_array($resIdAdresse);
                        $nouvelIdAdresse = $fetchNouvelIdAdresse["maxIdAdresse"] + 1;
                    }

                    $sql = "INSERT INTO historiqueAdresse (idUtilisateur,idAdresse,date,description,nom,idRue,numero,idQuartier,idSousQuartier,idPays,idVille) VALUES (
							'".$authentifie->getIdUtilisateur()."',
							'".$nouvelIdAdresse."',
							\"".$this->date->toBdd($tabForm['date']['value'])."\",
							\"".$tabForm['description']['value']."\",
							\"".$tabForm['nom']['value']."\",
							'".$tabForm['rue']['value']."',
							'".$tabForm['numero']['value']."',
							'".$tabForm['quartier']['value']."',
							'".$tabForm['sousQuartier']['value']."',
							'".$tabForm['pays']['value']."',
							'".$tabForm['ville']['value']."'
							)";

                    $this->connexionBdd->requete($sql);

                    $cache = new cacheObject();
                    $cache->refreshCache();
                }
            } else {
                echo $this->afficheFormulaire($tabForm);
            }




            $this->connexionBdd->freeLock(array('historiqueAdresse'));
        } else {
            echo "erreur : Vous devez etre authentifié pour faire un ajout<br>";
        }
    }
984330
private function writeEndereco(
        $t, $l, $w, $titulo, $nomeDestinatario, $logradouro, $numero1, $complemento, $bairro,
        $cidade, $uf, $cep = null
    )
    {
        // Titulo do bloco: destinatario ou remetente
        $this->pdf->SetFont('', 'B');
        $this->setFillColor(60, 60, 60);
        $this->pdf->SetFontSize(7);
        $this->pdf->SetXY($l + 3, $t);
        $this->t($w, $titulo, 2, '');

        $addressPadding = 5;
        $w = $w - $addressPadding;
        $l = $l + $addressPadding;

        // Nome da pessoa
        $this->pdf->SetFont('', '');
        $this->setFillColor(190, 190, 190);
        $this->pdf->SetX($l);
        $this->multiLines($w, $nomeDestinatario, 'L');

        //Primeria parte do endereco
        $address1 = $logradouro;
        $numero = $numero1;
        if (!$numero || strtolower($numero) == 'sn') {
            $address1 .= ', s/ nº';
        } else {
            $address1 .= ', ' . $numero;
        }
        if ($complemento) {
            $address1 .= ' - ' . $complemento;
        }
        $this->setFillColor(100, 190, 190);
        $this->pdf->SetX($l);
        $this->multiLines($w, $address1, 'L');

        //Segunda parte do endereco
        $this->pdf->SetX($l);
        $this->setFillColor(100, 130, 190);
        $this->multiLines($w, '' . $bairro, 'L');
        $this->setFillColor(100, 30, 210);
        $this->pdf->SetX($l);
        $this->multiLines($w, ($cep ? $cep . ' - ' : '') . $cidade . ' - ' . $uf, 'L');

        return $this->pdf->GetY();
    }