Entradas

Load SASS and Bulma to your Vue JS project

Imagen
Introduction According to docs Bulma is highly customizable thanks to 419 Sass variables living across 28 files. These variables exist at 4 levels: initial variables: global variables with literal values derived variables: global variables with values that reference other variables, or are computed generic variables: for the HTML elements which carry no CSS class element/component variables: variables that are specific to a Bulma element/component In this case we are gonna add SCSS files to our existing project made with the webpack template via vue-cli, so maybe if you create your project in different way this may not work. Strategy To customize Bulma, you will need to: vue create my-awesome-project npm install bulma After that let's install the SASS dependencies: npm install --save-dev node-sass sass-loader If you have a vue.config.js you will add a few lines, otherwise you need to create this file in the root of you...

Why does this Nginx config result in “rewrite or internal redirection cycle”

Imagen
API REST: Flask APP: Vue Js made with vue-cli NGINX as web server Fast note of what happened with the error  “rewrite or internal redirection cycle”. I have to say that I've been dealing with this for hours. THE STORY My vue-router export const router = new Router({ base: '/myapp/', mode: 'history', routes: [   { path: '/', name: 'home', component: Login   },   { path: '/login', name: 'login', component: Login   },   { path: '/foo', name: 'foo', component: Foo   },   { path: '*', component: NotFound   }, ]   }); So I built my app with the command npm run build  Then i copy and paste the files of dist in a subdirectory let's say "myapp" in my ngnix folder /var/www/html/myapp  after that I went to file /etc/nginx/sites-enabled/default and edited with this lines server {     listen 0.0.0.0:80;        index...

Laravel y MercadoPago SDK

Imagen
Hola a todos, escribo esta pequeña nota sobre como implementar el SDK que MercadoPago México ofrece, decidí hacerla porque no hay mucha información sobre esto en internet y también para no olvidar lo que yo misma hice. Quizá (y siempre lo he dicho) existan mejores maneras de hacerlo pero a mi me funcionó y por la urgencia de entregar el proyecto para ayer lo hice de esta manera. De igual forma existe un API que a mi parecer es lo ideal puesto que puedes manipular mucho mejor la información pero esa guía la publicaré después. En este punto podríamos considerar que ya tenemos un proyecto entonces solo detallaré lo que precisa. En la documentación de MercadoPago en la sección de guías - checkout mercado pago  como requisito dice que debemos descargar el sdk  por medio de composer, entonces ejecutamos esto en nuestra terminal situándonos por supuesto en la carpeta de nuestro proyecto: php composer require "mercadopago/dx-php:dev-master" Afortunadamente composer ...

Creating views to show specific spatial data [POSGIS POSTGRES QGIS VIEWS]

Imagen
Hello everyone, Sometimes as database managers we need to show only specific data for security or for whetever reason . In this case we are talking about showing geometry that are stored in two (relational) tables the problem remains in not showing the area , descripcion and id_user fields of state table . Fig 1. Tables Solution:  1) Create view,  2) Create role, 3)Setup in QGIS First thing is to create a view, note that is important to add the objectid column otherwise QGIS is going to get an error. CREATE VIEW view_state AS         SELECT   sg.id_state_geom AS objectid,         COALESCE(s.name, 'NO NAME'::character varying) AS name,    FROM (state_geom sg        LEFT JOIN state s ON ((sg.id_state = s.id_state)))        ORDER BY sg.id_state Second step is create a role wich be attached to the view and only to the view. CREATE ROLE xxx WITH L...

Entrust Migration Error Solved

Imagen
Working with JWT and Entrust packages on mi brand new Laravel App I got these errors right after run the command php artisan entrust:migration I know you want the solution right away so... Error: Method Zizaco\Entrust\MigrationCommand::handle() does not exist Solution: Go to the file vendor/zizaco/entrust/src/commands/MigrationCommand.php find the method called "fire" and rename it with "handle" and after the command "php artisan entrust: migration" will be generate. But... If your scenario is identical as mine the next error will be raised... Error: Symfony\Component\Debug\Exception\FatalThrowableError  : Class name must be a valid object or a string Solution: Go to the file vendor/zizaco/entrust/src/commands/MigrationCommand.php (same file we edit before) and change these lines: $usersTable = Config::get('auth.table'); $userModel = Config::get('auth.model'); To: $usersTable = Config::get('auth.providers.user...

Pentaho Data Integration and GIS Plugin

Imagen
Para la manipulación de datos GIS y operaciones con geometría existe un plugin muy interesante el cual es gratuito y puede ser descargado de aquí . La instalación del plugin es de lo más sencillo, primeramente hay que descargar el archivo y el contenido pegarlo dentro de la carpeta plugins en el directorio de pentaho, en mi caso es  D:\data-integration\plugins después de esto   se reinicia Pentaho y para ese momento si todo va bien la barra de herramientas nos mostrará la carpeta Geospatial Barra de herramientas Ahora lo importante, un ejemplo del uso de este plugin. El problema: Tenemos dos capas de datos una capa es de sectores y otra capa con terrenos. Cada terreno debe tener el dato del sector al que pertenece, en este momento los terrenos no poseen información alguna del sector al que pertenecen, hay que realizar la transformación y el resultado debe arrojar cada terreno con su num de sector correspondiente. Capa de sectores Capa de terrenos ...

proc_open(): fork failed - Cannot allocate memory in phar

Today I got an error while I was making updates to my laravel app because of a lack of memory in my digitalocean droplet. I was reading some documentation and the solution was set up a swap file: "Swap is an area on a hard drive that has been designated as a place where the operating system can temporarily store data that it can no longer hold in RAM. Basically, this gives you the ability to increase the amount of information that your server can keep in its working "memory", with some caveats. The swap space on the hard drive will be used mainly when there is no longer sufficient space in RAM to hold in-use application data." as the documentation says we need to configurate the swap area so that composer can do it's thing. The solution sudo dd if=/dev/zero of=/swapfile bs=1024 count=512k sudo mkswap /swapfile sudo swapon /swapfile composer update Regards!

Data Integration

Next posts are related with extraction, transformation and load massive data. Stay tuned.

Título y Fechas Error FullCalendar

Anteriormente tuve un detalle con el calendario de FullCalendar versión minificada, ya que la fecha se mostraba de forma extraña: 1st — 7th June 2018 Si a alguien por ahi le ocurre lo mismo la solución es buscar entre las líneas del archivo minificado fullcalendar.min.js la siguiente variable  titleRangeSeparator y sustituir su valor por un " - ".  Después de esto la fecha debería mostrarse correctamente: 1st - 7th June 2018 ¡Saludos!

Filezilla, DigitalOcean MAC OS

Imagen
Hola, guía rapidísima de como usar Digital Ocean y Filezilla. PRERREQUISITOS: Filezilla Cliente SSH Keys Ok requisito esencial es generar un par de llaves SSH ( si no sabes de que estoy hablando checate esto ) Primero instalamos el cliente de Filezilla, abrimos el programa y nos vamos a Edición>Opciones y dentro de este menú seleccionamos SFTP y veremos algo como esto: Presionamos el botón de ADD KEY FILE el cual nos abrirá una ventana para seleccionar nuestra id_rsa,  en el caso de OS si dejamos la ubicación por default podemos encontrarlas en usuario>.ssh>id_rsa recuerda que para ver archivos ocultos puedes presionar "shit + command + . " luego de presionarlo es probable que nos pida convertir el archivo a un archivo ppk, seleccionamos un nombre distinto con el que podamos identificar esta llave y guardamos. Posteriormente nos dirigimos a Archivo>Gestor de Sitios Añadimos un nuevo sitio con las siguiente características: PROTOCOLO: SFTP - ...

Manejo de errores en Laravel UX

Algo muy sencillo realmente de hacer pero que a veces no sabemos como realizar es el manejo de errores en Laravel, es decir como retornar al cliente una pantalla de 404, 405, 503, 500... etcetera. La configuración es la siguiente: Dentro del archivo . env setea lo siguiente, recuerda que esto es para un ambiente de producción. APP_ENV=production APP_DEBUG=false y en tus plantillas blade crea los archivos resources/views/errors/400.blade.php resources/views/errors/405.blade.php resources/views/errors/503.blade.php Esto va a renderizar tus plantillas cada que un error ocurra. Ademas dentro de la plantilla puedes añadir lo siguiente para que el usuario sea dirigido a una ruta específica después de determinado tiempo. setTimeout(function(){ window.location.href='{{ route('mihome')}}'; },10000); Espero te ayude. Saludos.

Números a Letras Laravel 5.6

Hola, guía rápida de como agregar un helper en laravel que nos ayude a convertir letras a números (pesos mexicanos). Agregar una carpeta llamada helpers dentro de App Añadir un archivo llamado Convertidor.php dentro de la carpeta helpers Dentro de este archivo agregar el namespace namespace App\Helpers; Esto porque estamos usando una clase y los métodos son nuestros helpers. Además es importante ya que si no utilizamos un namespace esas funciones pueden ser utilizadas globalmente, así prevenimos cualquier error. Queda un archivo como el siguiente: <?php namespace App\Helpers; class Convertidor { public static function numtoletras($xcifra) {     $xarray = array(0 => "Cero",         1 => "UN", "DOS", "TRES", "CUATRO", "CINCO", "SEIS", "SIETE", "OCHO", "NUEVE",         "DIEZ", "ONCE", "DOCE", "TRECE", "CATORCE", ...

Obtener primer día del mes apartir de una fecha MYSQL

Para obtener el primer día del mes apartir de una fecha en mysql podemos realizar lo siguiente: SET @FechaFin="2018-05-08"; SELECT CAST(DATE_FORMAT( @FechaFin ,'%Y-%m-01') as DATE) INTO @FechaInicio ; SELECT  @FechaFin, @FechaInicio; ¡Saludos!

To enable extensions, verify that they are enabled in your .ini files LARAVEL COMPOSER

Para cuando tratas de hacer un Composer Update y cmd te da el error " To enable extensions, verify that they are enabled in your .ini files" esto ocurre porque faltan paquetes php en nuestro localhost. Para solucionar ejecutamos en el siguiente orden las siguientes instrucciones: Primeramente sudo apt - get install php7.1 - gd luego sudo apt - get install php7.1 - intl finalmente sudo apt - get install php7.1 - xsl Asegurate de instalar correctamente de acuerdo a la version de php que tengas instalada. Probado en  Ubuntu 14.04 PHP 7 Laravel 5.7

EventSource AKA Server-Sent Events (EventSource o mejor conocido como Server-Sent Events) + VUE JS + LARAVEL

Ok voy a escribir una nota breve sobre el server-sent event API , el cual está contenido en la interfaz EventSource; su función es abrir una conexión al servidor para recibir eventos de él. Se crea un nuevo objeto EventSource , especificando el URI de un script que genera los eventos, ejemplo gráfico y rápido a continuación: El código Primeramente el controlador ejemplo desde Laravel, use Symfony\Component\HttpFoundation\StreamedResponse;     public function micontroladordivertido(){   $start = time(); $maxExecution = ini_get('max_execution_time'); $response = new StreamedResponse(function() use ($start, $maxExecution) { while(true) { if(time() >= $start + $maxExecution) { exit(); } echo 'data: ' . json_encode(Compras::all()) . "\n\n"; ob_flush(); flush(); usleep(20000000); } }); $response->headers->set('Content-Type', 'text/event-stream'); $response->headers...

Error 419 en el envío de JSON a una funcion vía AJAX - Laravel

El error 419 unknow es un error que puede surgir al momento de realizar una llamada vía AJAX a algún metodo en un controlador, esto pasa porque no estamos incluyendo el CSRF token en nuestra petición POST entonces el Middleware no puede validar que hay un X-CSRF-TOKEN request. La solución es muy sencilla, añadimos al header de nuestra plantilla blade la siguiente línea, esto para almacenar el token. < meta name = " csrf-token " content = " {{ csrf_token() }} " > Y a nuestra petición AJAX añadimos los headers , como se muestra a continuación: $.ajax({ method: 'POST', url: '/miURL', data: {'id' : id}, headers: { 'X-CSRF-TOKEN' : $ ( 'meta[name="csrf-token"]' ) . attr ( 'content' ) }, success: function(response){ console.log(response); }, error: function(jqXHR, textStatus, errorThrown) { console.log("...