20231231

Post resum 2023


Kms patinats: 

- 612


Gadgets of the year (comprats o regalats):

- iphone15 pro

- carregador inalambric iniu

- un munt de cables usb-c


Samarretes de l’any:

- Easypromos

- Palorder

- Be Stack Overflow be with you

- Pixies

- Eres tan feria de Abril, Ojete Calor

- The last sofas

- Los pollos hermanos

- Heissenberg

- Morrisey is Murder

- Homer Simpson

- Where’s Jessica Hyde


Friky coses guays:

- osv.dev

- lands.php.earth

- https://laraveldaily.com/roadmap-learning-path

- manticoresearch

- Muvon/yoda

- libsql/sqld

- hyperf

- SingleStore

- laravel-grapes

- Wazuh

- Elastic Security

- Laravel Pennant

- airops

- endoflife.date

- https://proxify.io/worlds/php

- crontab.guru

- saloon

- tauri.app

- PixiJS

- Edge|DB

- SurrealDB

- fixie.ai

- Ballerina

- bref.sh

- SudoLang

- suphle

- databricks dolly2

- https://developer.fermyon.com/spin/index

- https://laravel-package-ocean.com/

- phind.com

- sanity.io

- croquet.io

- https://pxplang.org/

- https://8values.github.io/quiz.html

- vector.dev

- https://python.langchain.com/en/latest/index.html

- LaraDumps

- Jolt

- coolbackgrounds.io

- Anker Solix

- sonnen batteries

- AI.jsx

- amigalive.com

- weezevent.com

- HTMX https://www.sitepoint.com/htmx-introduction/

- qwick.builder.io

- https://it-tools.tech/

- herd.laravel.com

- nativephp.com

- tldraw.com

- https://falconwatertech.com/

- idx.dev

- caddyserver.com

- nue.js

- Kamal

- signoz.io

- codewithrockstar.com

- wg/wrk

- rpgjs.dev

- appwrite.io

- https://resonance.distantmagic.com

- https://radapp.io/

- lychee.cli.rs

- turbineui.com

- vapor.codes

- frankenphp.dev

- PHP2JS

- QuickRequest

- Octoparse

- Fedora Asahi Remix

- dragonflydb.io

- idb-keyval


Jocs als que m'he viciat aquest any:

- Quake 2 remastered

- Warcraft Rumble

- Suika game


Grups guays que he descobert aquest any:

- Launder

- Alexanderplatz

- Muro María

- Fotos de la novia

- Bark Psychosis

- The honey buzzards

- Diavol Strain

- Minami Deutsch

- Moon Duo

- Singapore Sling

- CFM

- Acid dad

- Ringo Deathstarr

- Junip

- Sloan

- Davila 666

- The Sandwitches

- shego

- The Limiñanas

- BRONCHO

- Lucille Dupin

- Smashing Orange

- Blushing

- Píldora letal

- The Beths

- The Jaws of Brooklyn

- La Culpa

- Pencil Legs

- Dead Sullivan

- Foxes in Fiction

- Modern Baseball


Concerts:

- Sr. Chinarro, sala Wolf

- Los Punsetes + Grushenka, Salamandra

- Pixies, Sant Jordi Club

- Los Toreros Muertos, Sarau

- Ojete Calor, Sant Jordi Club

- El último vecino + Fotos de la novia, Upload

- Pantocrator, Jardins de la Sedeta

- Triàngulo de amor bizarro, Apolo

- Triàngulo de amor bizarro, Zero Tarragona

- Biznaga + Los Yolos + Enemic Interior, RAZZ2


i al Primavera:


Dimarts:

- La Paloma + Just Mustard + Far Caspian a l’Apolo 2


Dijous:

- Heather

- Terno Rei

- Alex G

- Turnstile

- OFF!

- New Order

- Le Tigre


Divendres:

- Niña Coyote eta Chico Tornado

- Bala

- Los Hacheros

- The wedding present

- Depeche Mode

- Bad Religion

- Lebanon Hanover


Dissabte:

- Grupo de expertos sol y nieve

- My morning jacket

- The Voidz

- The war on drugs

- Liturgy

- Maneskin


I al Cruïlla, Divendres:

- Menta

- Ciudad Jara

- Sexy Zebras

- Calavento

- Pinpilimpusssies

- Carolina Durante

- Franz Ferdinand

- Sexy Zebras

- The Offspring

- Ladilla Rusa


Pelis:

- Más allá de los dos minutos infinitos, filmin

- Topgun Maverick, amazon

- The Batman, HBO

- White noise, Netflix

- Willow, Disney+

- Decision to leave, cine

- Wonder Woman 1984, hbo

- Everything Everywhere At all once, cine

- John Wick 4, cine

- Dungeons and Dragons, Honor among thiefs, cine

- Evil Dead Rise, cine

- Licorice Pizza, Amazon Prime

- What lies below, Amazon Prime

- Ant-man and Wasp Quantum-mania, Disney+

- Spider-man Across the Spiderverse, cine

- Too big to fail, HBO

- Matrix resurrections, HBO

- Oppenheimer, cine

- Babylon, Amazon Prime

- Avatar, the way of water, Disney+

- Flamin Hot, la historia de los Doritos picantes, Disney+

- Broker, Filmin

- Kids, Filmin

- The Flash, HBO

- Tokyo Revengers

- Turbo Kid

- Benny loves you

- Awareness

- Jojo rabbit

- The good the bad and the weird

- Escape from Mogadicio

- Zombieland

- The first purgue

- Mad Heidi, Amazon Prime

- Otra ronda, filmin

- Venus, Amazon Prime

- Indiana Jones y el dial del destino, Disney+

- The Northman, Amazon Prime


I a les nits de cinema de Vic:

- Duelo del Dragón y el Tigre (1980)

- Next Sohee

- Baby Assasins 2 - Two babies

- KBKJ

- Ninja vs Shark

- Restart the earth

- Mutant Ghost Wargirl

- The great arms robbery


I a Sitges:

Dijous 5

8:30 - Tokyo Revengers 2 - Part 1 - 6.5

10:00 - Tokyo Revengers 2 - Part 2 - 6.5

12:00 - Project Silence - 7.5

14:45 - Suitable Flesh - 4

17:00 - Blackout - 2

19:15 - Let it Ghost - 6


Divendres 6

8:30 - Onyx the Fortuitous and the talisman of souls - 7.5

11:00 - Last Straw - 5.5

13:15 - Los Ojos de la Noche - 7Dissabte 7

10:45 - Apéndice - 6

12:45 - Sleep - 6.5

20:00 - Propriedade - 7

22:15 - Vive Dentro - 6

Diumenge 8

8:30 - The Sacrifice Game - 7

10:30 - There’s Something in the Barn - 7.5

12:30 - Acción mutante - 7

16:00 - Brooklyn 45 - 7.5

22:00 - El Chico y la Garza - 7.5

00:45 - Wake Up - 7.5


Dilluns 9

8:30 - El Exorcismo de Eastfield - 6

10:45 - You’ll Never Find Me - 7

13:00 - Robot Dreams - 5

20:00 - Diabolik - Ginko All’Attacco - 6

22:30 - Vincent Debe Morir - 8

01:00 - Late Night With the Devil - 8


Dimarts 10

8:30 - Hood Witch - 7

11:30 - Sand Land - 8

13:30 - Tiger Stripes - 4.5


Dimecres 11

10:45 - Nina Dei Lupi - 6


Dijous 12

17:30 - The Primevals - 5

19:45 - Smugglers - 8

22:15 - Pobres Criaturas - 9.5


Divendres 13

10:30 - Superposition - 5.5

12:45 - Where the Wind Blows - 3.5

15:45 - Rabia - 4

17:45 - Juego Prohibido - 5.5

20:15 - Concrete Utopia - 7.5

23:00 - Vermin: La Plaga - 7.5


Dissabte 14

08:45 - Riddle of Fire - 6.5

11:15 - Sorcery - 5

13:30 - Jericho Ridge - 7.5

22:30 - Lumberjack The Monster - 6.5

01:00 - We are Zombies - 7.5


Sitges Top 11:

Pobres Criaturas - 9.5

Smugglers - 8

Sand Land - 8

Vincent Debe Morir - 8

Late Night With the Devil - 8

Onyx the Fortuitous and the talisman of souls - 7.5

Project Silence - 7.5

We are Zombies - 7.5

Jericho Ridge - 7.5

Concrete Utopia - 7.5

Vermin: La Plaga - 7.5


Sitges Bottom 11:

Blackout - 2

Where the Wind Blows - 3.5

Rabia - 4

Suitable Flesh - 4

Tiger Stripes - 4.5

Sorcery - 5

The Primevals - 5

Robot Dreams - 5

Juego Prohibido - 5.5

Last Straw - 5.5

Superposition - 5.5


Series:

- The Crown s5, s6, netflix

- Apagón s1, movistar+

- Shadow and bone, netflix

- Esterno notte, filmin

- Three-Body, youtube

- Willow, disney+

- Northern Exposure, filmin

- The Last of Us, HBO

- The Consultant, Amazon prime

- Swarm, Amazon prime

- The office (BBC), Filmin

- Attack on Titan, s1, s2, s3, s4, special1, Amazon Prime

- Invincible, Atom Eve, Amazon Prime

- From, HBO s1, s2

- Invasion, AppleTV+ s1, s2

- Winning time, la dinastía de los Lakers, HBO, s2

- El cuerpo en llamas, Netflix

- GenV, Amazon Prime

- El peor de los males, Disney+

- Utopia (US), Amazon Prime

- El otro lado, Movistar+

- Poquita fé, Movistar+


Llibres:

- The pragmatic programmer

- Boom and bust, a Global history of financial bubbles

- The Haçienda, cómo no dirigir un club, Peter Hook

- Fingers crossed, Miki Berenyi

- Macro Festivales, Nando Cruz

- La fábrica de cretinos digitales, Michael Desmurget


Comics:

- El mercenario, V. Segrelles

- Querida Becky, Garth Ennis

- Crossed vol1, Garth Ennis

- Guardianes de la galaxia 3, El vórtice negro

- Ironman, demon in the bottle

- Hellboy vol1

- Crossed vol2, vol3, vol4

- Atac als titans vol1

- Molts a Marvel Unlimited


Teatre:

- Las Ruinas, Blas Infante

- Berto Romero, Lo nunca visto, Coliseum

- Faemino y Cansado, 17 veces reloaded


Documentals:

- Good night Oppy

- Todo y nada: Ciencia asombrosa de espacio vacío

- Arny, historia de una infámia (HBO)

- La gran distracció, TV3

- Cowspiracy

- Girl Gang: El preu de ser influencer, TV3

- Taxme if you can, filmin

- Carl Icahn, el millonario incansable, HBO

- Becoming Warren Buffet, HBO

- Icónica Chamorro, rtve play

- Eduard Punset, la urgencia del tiempo, rtve play

- La gran estafa de los teleoperadores, HBO

- Las cintas de Rosa Peral, Netflix

- El curioso caso de Natalia Grace

- Generació Porno, 3cat

- Surviving Utoya, 3cat

- La industria de lligar, 3cat

- No me llames Ternera, Netflix

- Running with the Devil: The Wild World of John McAfee, Netflix

- Fantastic Machine, Filmin

- Plastic Disasters, HBO

- Los años de la transición, HBO

- Nuñez, 3cat


Podcasts:

- Nadie sabe nada

- Quieto todo el mundo


Hotels als que he anat:

Cid, Sitges

Estació del Nord, Vic

Casa Boumort

Lauria, Tarragona

Ultonia, Girona


Restaurants:

- Can Recasens

- San Kil

- Little Korea

- Shangai Stories

- Da Emanuele

- Dolsotbap

- La Forquilla

- Els Pescadors

- Pocha

- Os familia

- Shifu ramen

- Casa Lupe

- La barraca del Delta

- El racó del port

- Puerto Escondido

- Can Calopa

- L’Aliança d’Artés

- El Raier


Sortides al Extranjer:

Desert


Curts:

Desert


Exits:

Desert


20230203

How to change the internal links of all the posts in wordpress

 When you change the url pattern of a Wordpress installation some internal links can still be pointing to the old pattern of urls.

To mitigate this problem you can use a plugin like redirection in order to redirect old pattern urls to the new ones. With this solution you can solve the problem of internal links and of external links too (that you don't have control).

However, it's recommended to change all the internal links inside your content to avoid innecessary redirections.

For this reason we've created a procedure to update the content of all the posts, looking for urls that already are redirected and replacing them for the new ones.

IMPORTANT: This procedure assume that you have already installed and configured the redirection plugin and you have good knowledge of Linux commands and MySQL.

The procedure is as follows:

- Dump the wp_posts table using mysqldump

- Backup this dump just in case

- Launch a query to get all the replacement commands

- Launch replacement commands to replace all the strings in the dump

- Upload the modified dump into mysql


1) Dump the wp_posts table to a file

mysqldump -u <user> -p<password> -h <host> <db> wp_posts > wp_posts.sql

2) Make a backup of the file, just in case...

cp wp_posts.sql wp_posts.bk.sql

3) Then launch this select using your favorite MySQL client or PHPMyAdmin.

The idea of the sql query is to get all the redirection redirects that are enabled in the Wordpress database (table wp_redirection_items) and generate a Linux command (sed) that substitute all the urls in the content from the original ones to the new ones.

select 
concat("sed -i 's/"
,replace(url,'/','\\/'),"/"
,replace(action_data,'/','\\/'),"/g' wp_posts.sql") cmd
from (
	select substr(url,1,length(url)-1) url
	, if(substr(action_data,length(action_data))='/', substr(action_data,1,length(action_data)-1), action_data) action_data
	, action_type, status, action_code
	, url original_url, action_data original_action_data
	from wp_redirection_items
	where url like '%/'
	union all
	select url
	, if(substr(action_data,length(action_data))='/', substr(action_data,1,length(action_data)-1), action_data) action_data
	, action_type, status, action_code
	, url original_url, action_data original_action_data
	from wp_redirection_items
	where url not like '%/'
) t 
where status='enabled'
and action_type='url'
and action_code=301
group by cmd;


A sample line that are returned by the sql query above is:

sed -i 's/\/blog\/2013\/03\/prepare-your-promotions-xxx/\/blog\/prepare-your-promotions-xxx/g' wp_posts.sql

4) Then execute all the lines in your Linux box it will replace all the urls that match /blog/2013/03/prepare-your-promotions-xxx by /blog\/prepare-your-promotions-xxx
because in my case I've changed the url pattern to avoid the date in the url.

Copy the results of all the lines into your Linux box in the same folder where you have generated the backup of the table wp_posts 
(you must have the utility sed installed (available in 99% of Linux installations)).

5) Upload the dump again

mysql -u <user> -p<password> -h <host> <db> < wp_posts.sql
Hope this help you.

20230113

Adding percentages to labels in amcharts5

 Amcharts5 is a very powerful graphics library, however the documentation is really scarce.


If you want to add the percentage of a value in some label you must use the undocumented valuePercentTotal attribute in the desired text label, for example.

legendValueText: "[bold {fill}]{value} {valuePercentTotal.formatNumber('0.00p')}[/]"
Generates a label like this:


This value can be used in different labels and can be formatted as the other attributes like "value".

Hope this helps








 









20230101

Post resum 2022

Com cada any deixo aquí un resum del meu any 2022 sense editar molt. Un any marcat pel meu canvi  de feina d'Omatech (després de gairebé 16 anys) cap a Easypromos, on em sento molt ben acollit.

Kilòmetres patinats: 238, cal millorar!

Exits:

- Adsmurai x15

Gadgets of the year (comprats o regalats):

- LG Gram

- Airpods Pro Max

- Navalla suïssa

Samarretes del any:

DESERT

Friky coses guays:
- n8n.io
- parceljs
- mermaid
- sidecar
- browsershot
- lando.dev
- bitsy
- Xata
- Redox
- Stackblitz
- loom
- matomo
- facebook/lexical
- redpanda
- mattermost
- loadforge
- filamentphp
- bun.sh
- zig
- orchid
- remix
- prisma.io
- sveltekit
- baserow.io
- plausible.io
- fresh.deno.dev
- railway.app
- astro
- openai and Dall-e
- simplemvc
- squirephp https://github.com/squirephp/squire
- sushi php
- https://laravel.initializer.dev/
- ponylang.io
- https://github.com/JuliaLang/julia
- VemtoApp
- jsoncrack
- qwick.builder.io
- NocoDB
- FrankenPHP
- glitch.com
- locust.io
- https://whatthediff.ai
- https://turbo.build/
- rectorphp
- twill
- bref.sh
- spiral.dev
- ulid https://github.com/ulid/spec
- Mitosis
- sulu.io
- alpine.js
- blitz.js
- synthesia
- Nanocrazor

Jocs als que m'he viciat aquest any:
- PUBG New State
- Plants vs zombies 2
- Tetris99
- Katamari

Grups guays que he descobert aquest any:
- Desenterradas
- Dry Cleaning
- Grasias
- Dan Romer
- Clise to Modern
- Robot Emilio
- Ovlov
- Big Thief
- Dexist
- Wet Leg
- Pillow Queens
- Nation of Language
- Yawners
- Ezekiel
- Mitski
- Just Mustard
- Portico quartet
- Lund quartet
- Whatever, Dad
- Cuchillas
- Radiator Hospital
- Secundaria
- High Vis
- Policias y Ladrones
- Videoclub
- El diablo de Shangai
- Indian Summer
- Porridge Radio
- La Paloma
- Childbirth

Concerts als que he anat:
- Ojete Calor al Sant Jordi Club
- Los Punsetes + Marcelo Criminal a l’Apolo
- Just Mustard + Calibra al Sidecar
- Menta + El Diablo de Shangai a la sala VOL.
- The Cure al Palau Sant Jordi
- McEnroe + El verbo odiado a l’Apolo2

Pelis que he vist:
- Spiderman no way home
- La mano de Dios
- Don’t look up
- While we’re young 
- Marriage Story
- Attack the block
- Sputnik
- Ad Astra
- O que arde
- Gone Girl
- The French Dispatch
- The Adam Project
- Driven
- El método Williams
- All eyes off me
- Déjame caer
- Los Cronocrimenes
- Monster
- Lizzie
- Tourists
- Utoya
- Dr. Strange en el multiverso de la locura
- Moonfall
- Eternals
- Iron Sky
- Heat
- Peninsula
- Dredd
- Oranges Sanguines
- Apnee
- Prey
- Day shift
- To your last death
- Incendies
- El reino de la belleza
- Softie
- Yo, Cristina F
- Satan’s Slave
- Blonde
- X
- Sissy
- Deep Water
- Host
- Planeta rojo
- As Bestas
- Barbarian
- Captive State
- Troll
- Mantícora
- Your Lost Memories

Series a les que m’he enganxat:
- The book of Bobba Fett
- Curb your enthusiasm s4, s5, s6, s7, s8, s9, s10, s11
- Celebrity Bake Off España
- Station Eleven
- Curb your entusiashm
- All of us are dead
- Peacemaker
- Euphoria s2
- Mai neva a ciutat s1, s2, s3
- The Dropout
- Winning time
- The Boys s3
- Locomia
- Crims s1, s2, s3
- Love, Death + Robots s1, s2
- Maricon perdido
- Stranger Things s4
- Children of Dune
- Narco Saints
- Dahmer
- La liga de los hombres extraordinarios
- Antidisturbios
- The Bear
- Autodefensa s1, s2

Curts:
- Cerdita

Llibres que he llegit:
- Conversaciones con Ana Curra
- Domain Driven Design in PHP
- Radical Candor
- Astrofísica para gente con prisas
- From zero to sold

Comics:
- Dinastia de X / Potencias de X
- Dawn of X
- Hierba
- The Hellfire gala
- X lives of Wolverine / X deaths of Wolverine
- The trial of Magneto
- Destiny of X
- La patrulla X y los Nuevos titanes
- X-Factor
- DUNE I
- I molts més amb Marvel Unlimited

Teatre:
- Faemino y Cansado. Quien tuvo, retuvo

Documentals:
- Autosuficientes
- Warning: This drug may kill you
- 4 hours at the Capitol
- Devastados por el cristal
- Arcadeology
- Almost Ghosts
- Jimmy Savile, a British Horror Story
- The push
- Tell me who I am
- Natalie Wood, entre bambalinas
- Val
- Jane Fonda en cinco actos
- We were once Kids
- The John Wayne Gacy Tapes
- Los Anarquistas
- Keep sweet pray and obey
- Wall Street: David contra Goliat
- Swiped
- Orgasm Inc.
- Ummo, La España alienígena
- Entre la terra i el cel: Guerra
- Criptomonedas: guía para principiantes
- La Sagrada Família
- Osel
- Salvar al Rey

Podcasts:
- itnig
- X-Rey s1, s2
- Le llamaban Padre

Sortides al Extranjer:
DESERT

Hotels als que he anat:
- Granados 83
- Hotel Petit Mirador
- Ultonia, Girona

Restaurants:
- Ikoya
- Kanada Ya
- La Nansa, Sitges
- Els pescadors
- Lluerna, Santa Coloma
- La barraca del Delta, Amposta
- El Racó del Port, Les cases d’Alcanar
- Draps, Girona

Sitges 2022:

38 pelis, 800kms, 16 peatges

Pelis vistes:

Dijous 6:

- Hunt

- King of screen

- The breach

- Blood flower

- Carnifex

- Deep fear

Divendres 7:

- Polaris

- After Yang

- Satan’s Slave Communion

- [REC] Terror sin pausa

- Flesheater

Dissabte 8:

- Kids vs Aliens

- Saloum

- Mal de ojo

- Flux gourmet

- The Lair

Diumenge 9:

- Tales from the Occult

- Resurrection

Dilluns 10:

- Family Dinner

- Rubikon

- Occhiali neri

Dimarts 11:

- Megalomaniac

- Slash back

- Incroyable mais vrai

- Emergency declaration

- The Knocking

- Christmas bloody Christmas

Dimecres 12:

- Shepherd

- Fumer fait tousser

Dijous 13:

- Glorious

- Social Distancing

- Pearl

Divendres 14:

- Harbinger

- Viejos

Dissabte 15:

- Wolfkin

- La exorcista

- Sisu

- Alienoid

Ranking millors pelis (de millor a pitjor):

- Sisu

- Fumer fait tousser

- Pearl

- Glorious

- Incroyable mais vrai

- Satan’s Slave Communion

- Resurrection

- Mal de ojo

- Megalomaniac

- Deep Fear

- (menció especial al documental de [REC])

Ranking pitjors pelis (de pitjor a… bé):

- Occhiali neri

- Social Distancing

- Tales from the Occult

- Carnifex

- Polaris


Grups vistos al Primavera Sound 2022:

Dijous:

Aiko el grupo - 18:15 - Ouigo

Les Savy Fav - 18:55 - Binance

Richard Dawson - 19:05 - Plenitude

Dinosaur Jr. - 20:00 - Cupra

Sharon Van Etten - 21:05 - Binance

Yo la tengo - 22:20 - Cupra

Tame Impala - 22:55 - Estrella Damm

Pavement - 00:40 - Pull & Bear


Divendres:

Pinpilinpussies - 16:30 - Ouigo

Cariño - 17:15 - Binance

Beach Bunny - 18:00 - Cupra

Manel - 19:00 - Pull & Bear

Fontaines DC - 20:05 - Estrella Damm

Shellac - 20:50 - Plenitude

Beck - 21:20 - Pull & Bear

Parquet Tours - 22:35 - Plenitude

Jehnny Beth - 23:30 - Ouigo


Dissabte:

Die Katapult - 18:45 - Tous

Automatic - 19:55 - Ouigo

Black Country New Road - 20:40 - Binance

Nick Cave and the bad seeds - 22:00 - Pull & Bear

Bauhaus - 22:55 - Binance

Gorillaz - 00:15 - Estrella Damm


Que tingueu un molt bon any 2023!
Agustí

20221208

Query to get drop and create foreign keys pointing to a table

When making DB scripts that massively manipulate big tables in MySQL sometimes you want do disable all foreign keys pointing to a particular table, make some operations and then enable the foreign keys again.

You can query the mysql information schema to get the metainformation of the foreign keys and generate the appropiate statements.

Just change the $db-schema-name and $table-name in this query and you can use the drop_cmd column that contains all the drop foreign keys statements and the create_cmd column that contains the add constraint statements to enable them again

SELECT r.CONSTRAINT_SCHEMA db, r.REFERENCED_TABLE_NAME referenced_table_name
, r.CONSTRAINT_NAME, r.TABLE_NAME
, c.COLUMN_NAME, c.REFERENCED_COLUMN_NAME
, r.UPDATE_RULE, r.DELETE_RULE
, CONCAT ('alter table `',r.CONSTRAINT_SCHEMA,'`.', r.TABLE_NAME, ' drop foreign key ',r.CONSTRAINT_NAME,';') drop_cmd 
, CONCAT ('alter table `',r.CONSTRAINT_SCHEMA,'`.', r.TABLE_NAME
, ' add constraint ', r.CONSTRAINT_NAME
,' foreign key (',c.COLUMN_NAME,')'
,' references ', r.REFERENCED_TABLE_NAME, '(',c.REFERENCED_COLUMN_NAME,')'
,' on delete ', r.delete_rule
,' on update ', r.update_rule
,';') create_cmd 
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS r
, INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE r.CONSTRAINT_SCHEMA = '$db-schema-name'
AND r.REFERENCED_TABLE_NAME = '$table-name'
AND c.REFERENCED_TABLE_SCHEMA = r.CONSTRAINT_SCHEMA
AND c.REFERENCED_TABLE_NAME = r.REFERENCED_TABLE_NAME
AND c.CONSTRAINT_NAME = r.CONSTRAINT_NAME
ORDER BY r.CONSTRAINT_NAME
Hope this will help you!

20221206

Beware of accumulating expired Octane cached items

When using swoole tables as Octane cache in Laravel, be aware that the expired cached items are never really deleted. 


The get method of the cache ignores the expired items but they are never flushed if you don't explicitly delete them. 

To avoid the Swoole Cache table to grow ad aeternum you must do some cleanup from time to time.
Define a new class that will do the clean up every minute using the Tick functionality of the Swoole extension. 

<?php

namespace xxxxxx;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Laravel\Octane\Facades\Octane;
use Illuminate\Support\Facades\App;

class CacheHouseKeeping {

public static function clean () {
  $table=App::make('octane.cacheTable');
    $i=$deleted=0;
    Log::info("** Current date=".date('Y-m-d H:i:s')." expiring old cached items");
    foreach ($table as $key => $record) {
    if ($record['expiration']<time()) {
Log::debug("EXPIRING key=$key value=".$record['value'].' expiration='.date('Y-m-d H:i:s', $record['expiration']));
        $table->del($key);
        $deleted++;
      }
      $i++;
    }
    Log::info("** Total keys scanned $i, deleted=$deleted remaining=".($i-$deleted)." finished ".date('Y-m-d H:i:s'));
  }
public static function boot() {
  Octane::tick('cache-housekeeping-ticker', fn () => self::getAndReport())
    ->seconds(60);
  }
}


And in the file app/Providers/RouteServiceProvider.php call the boot method of the class in order to set the Ticker. 
if ($record['expiration']<time()) {

20221127

How to detect real client ip in swoole laravel octane without nginx but behind a reverse proxy

 

When using Laravel Octane without nginx and you're behind a load balancer like Google Cloud Platform's or Amazon AWS or other reverse proxy that sets X-FORWARDED-FOR header, you must check this header to get the real client IP.

I've tried setting TrustedProxies etc. with no succes. And Laravel Octane didn't get it right when you call request()->ip()

Finally I've found the solution getting the server parameter HTTP_X_FORWARDED_FOR from the request and getting the first IP from a comma separated list. 


Check in your particular case if maybe the client IP is set in other header like HTTP_REAL_IP or similar using dd(request()->server) to get all the parameters bag.

You can use this sample class (adjust your namespace):

<?php

namespace YourOrg\Helpers;

class Ip {
    public static function get () {
        $XFFip=request()->server->get('HTTP_X_FORWARDED_FOR');
        if ($XFFip) {
            $ips = explode(',', $XFFip);
            $ips = array_map('trim', $ips);
            $ip = $ips[0];        
        } else {
            $ip=request()->ip();
        }
        return $ip;
    }
}


Then anywhere in your code you can use:

use YourOrg\Helpers\Ip;

...

echo Ip::get();


Have fun


20220101

Post resum 2021

Gadgets of the year (comprats o regalats):

desert

Kilòmetres patinats: 930

Samarretes del any:

sadako gameboy

sushi kill bill

starters friends

scarlet witch, no more mornings


Friky coses guays:

craftcms

workerman

newman

wrk

swoole

roadrunner

meilisearch

rasa

krakend.io (lura)

Utopia

phpinsights v2

hotwire turbo

phpsandbox.io

getporter.dev

neatnik.net/view-source

SvelteKit

Frontity

https://laravel-news.com/rich-text-for-laravel

pixijs.io

Astro

solid.js

asyncapi

monaco-editor

gather.town

api platform

react-admin

lean-admin.dev

builderio/qwik

builderio/partytown

lighthouse-php

locust.io


Jocs als que m'he viciat aquest any:

Sparkle 2

Puyo puyo tetris

PUBG New State


Grups guays que he descobert aquest any:

Alcest

Pantocrator

Melenas

Martes Niebla

Marta Movidas

Nueve desconocidos

Patio Rosemary

The Goon Sax

L.A. Exes

Menta

Margaritas podridas

Disco Las Palmeras!

Maw

Beladrone

Airiel

shane

Dharmacide

Cruz de Navajas

Ciudad lineal

Depresión sonora

Último día

Plataforma

Chill Mafia Records

Sofia

Luz Futuro

Mausoleo

Somos la herencia

Cruhda

Nunca Nada

VVV

Margarita quebeada

Viuda

Paralelo

El destello

Quiets

Galería interior


Concerts als que he anat:

desert


Pelis que he vist:

La autopsia de Jane Doe

Hellboy (2019)

JT Leroy: Engañando a Hollywood

Mank

Primos

Widows

Wonder Woman

The Big Short

El escándalo

Deadpool 2

Odio por Dani Rovira

The assistant

Las ventajas de ser un marginado

Cherry

Space Sweepers

Zach Snyder’s Justice League

Capa caída

Josep

Die Hard 4.0

Hangover

Hangover 2

Hangover 3

Robocop 2014

Spiderman far from home

Lego Movie 2

Los juicios de Nuremberg

Don Jon

The Circle

Army of dead

Sucker Punch

Shiva baby

Mitchells vs the machines

Jay and Silent Bob: The reboot

Midsommar

The night eats the world

The eight night

War of tomorrow

Terminator: Genisys

Man on the moon

A quiet place

Heavy Metal

It follows

Reindeerspoting

The lost boys

1987

John Wick 3, Parabellum

Night in Paradise

El padrino

El padrino 2

Cruella DeVil

El padrino 3

Dune

Wyrmwood

The last of wolves

Ali G indahouse

Destello bravio

Tesla

Crash

Sound of violence

The thing

The lighthouse

Veteran

Kenshin

My hero academia, hero’s world mission

Dolores. La verdad sobre el caso Wanninkhof

Greetings from Tromaville

Zombies en el cañaveral

Holiday

Red State

Bohemian Rapshody

Joker

Green room

Freud: The secret passion

The Show

Atrapado en el túnel

Free guy

Frances Ha

Venom

A scanner darkly

Black Widow

Ron da error


Pelis vistes a Sitges:

Hunter Hunter

Alien on stage

Caveat

Werewolves wihin

La Pasajera

Witch hunt

Censor

Le calendrier

Mona Lisa and the blood moon

Wyrmwood apocalypse

Broadcasting signal intrussion

Realidad virtual

Cliff Walkers

The amusement park

The deep house

The Sadness

The boy behind the door

Llanto Maldito

The trip

The knocking

Lamb

in the earth

the exorcism of god

Superhost

The power

El páramo

Hand rolled cigarrete

Limbo

Barbarians

Antlers

Eight for silver

The medium

The Samejima incident

She will

Nitram

Demonic

Last night in soho

The great yokai wars, Guardians

Son

Tides

Dashcam


Top 5 i bottom 5 Sitges:


Top 10 (de millor a pitjor):

The Sadness

Last night in soho

Dashcam

Alien on stage

Censor

The trip

Limbo

Lamb

Son

The deep house


Bottom 5 (de millor a pitjor):

Caveat

Broadcasting signal intrussion

The boy behind the door

Llanto Maldito

The knocking


Curts:

desert


Llibres que he llegit:

The mythical man-month

Object Oriented Programming, Timothy Budd

Clean Code, Robert C. Martin

It doesn’t have to be crazy at work, Jason Fried, David Heinemeier

Ready player two, Ernest Cline

Dune (rellegit)


Comics:

molts, he perdut el compte


Series a les que m'he enganxat (sense ordre particular):

La casa de papel s1,s2,s3,s4,s5

Squid game

The Soprano s1-s6

Seinfield s1-s9

Sweet Home

The morning show s1

Unorthodox

High Score

Servant s1,s2

It’s a sin

Wandavision

The Boys s2

Raised by wolves

Calls

Snowpiercer s2

Invincible

Mrs. Fletcher

The Crown s4

Ted Lasso

The royal house of windsor

Falcon and the winter Soldier

Snabba Cash

Queen’s Gambit

Jupiter’s Legacy

El vecino s1, s2

Loki

Sweet Tooth

Inside Job

The billion dollar code

Borat’s American Lockdown

Black Summer s1,s2

Todo lo otro s1

black Mirror s1,s2,s3

Station Eleven

The Silent sea

Hellbound

Hawkeye

Curb your enthusiasm s1,s2,s3


Teatre:

Faemino y Cansado. Quien tuvo, retuvo


Documentals:

High Score

El Pepe a supreme life

Brexit at closed doors

Pobreza en Estados Unidos

Power of Grayskull

Allen vs. Farrow

Billie Eilish, the world is little blurry

Wrinkles the clown

El Víbora, Solo para supervivientes

El Terrat, los primeros 30

Lolo Rico, la mirada no inventada

The Reagan show

El culo del mundo

Friends: The reunion

Barça Dreams

Dirty Money s1, s2

Becoming Warren Buffet

Heroin, Cape Cod, USA

Spielberg

Q into the storm

La Familia

Lo and behold: el inicio de Internet

Los bots del dinero

El arma perfecta

Galácticos

El chico más bello del mundo

Jodorosky’s dune

La dura cerdad sobre la dictadura de Franco

El fin de ETA

Story of plastic

Cryptopia: Bitcoin, Blockchains and the future of the Internet

San Julian: el poder de la ilustración

What happenes to Brittany Murphy?

Springboard

NYC Epicenters 9/11 -> 2021


Sortides al Extranjer:

desert


Millors Hotels als que he anat:

Hostal Sa Tuna


Millors restaurants:

Yatai

La forquilla (2)

Dolsotbap

Devil’s Kitchen

Hostal Sa Tuna


20210212

The ultimate purge logs bash script for Laravel

Let's assume that you have a very large log table that can grow up to millions of records.

 In this example the table is named activity_logs and VERY IMPORTANT it should have an index in created_at to allow us to remove records by date.

If you put this shell script in the root folder of your Laravel project it will take the database credentials from your .env file and purgue the log table day by day, from an starting date to an end date (in the example from 6 months ago to 2 months ago)

#### Contents of purge_logs.sh

dbhost=$(grep -oP '^DB_HOST=\K.*' .env)
dbpass=$(grep -oP '^DB_PASSWORD=\K.*' .env)
dbname=$(grep -oP '^DB_DATABASE=\K.*' .env)
dbusername=$(grep -oP '^DB_USERNAME=\K.*' .env)

i=$(date --date="6 months ago" +"%Y-%m-%d")
limit=$(date --date="2 months ago" +"%Y-%m-%d")
while [ "$i" != "$limit" ]; do
    echo $i limit $limit
    tomorrow=$(date -I -d "$i + 1 day")

    mysql -u $dbusername -p$dbpass -h $dbhost --default-character-set=utf8 $dbname << EOF
delete from activity_logs
where
created_at>='$i'
and created_at<'$tomorrow'
EOF

    sleep 5
    i=$tomorrow
done

#### end of purge_logs.sh

Explanation

Those lines take the db parameters from the .env file and make them available to the script.

dbhost=$(grep -oP '^DB_HOST=\K.*' .env)
dbpass=$(grep -oP '^DB_PASSWORD=\K.*' .env)
dbname=$(grep -oP '^DB_DATABASE=\K.*' .env)
dbusername=$(grep -oP '^DB_USERNAME=\K.*' .env)

Then configure the starting date and the limit

i=$(date --date="6 months ago" +"%Y-%m-%d")
limit=$(date --date="2 months ago" +"%Y-%m-%d")

You can change the parameters as long as they are valid date params, for example you can use "today", "tomorrow", "2 weeks ago", ...

In the next two lines we'll start the loop and echo the dates for debug purposes, and guess the next day in the variable "tomorrow", beware, the limit should be greater than the start date, if you don't want an infinite loop :)

while [ "$i" != "$limit" ]; do
    echo $i limit $limit
    tomorrow=$(date -I -d "$i + 1 day")

 Then launch mysql with the script to delete the records between $i and $tomorrow

     mysql -u $dbusername -p$dbpass -h $dbhost --default-character-set=utf8 $dbname << EOF
delete from activity_logs
where
created_at>='$i'
and created_at<'$tomorrow'
EOF

 In the last lines we'll sleep for a while to avoid stressing our server and recalculate the $i date

    sleep 5
    i=$tomorrow
done

Finally you can add a line in your crontab to run the script once a day for example:

10 0 * * * cd root_folder; ./purge_logs.sh

Hope this help

 

20210101

Post resum 2020

Gadgets of the year (comprats o regalats):
Cap

Samarretes del any:
Ink Snorlax
Dark Star Summer Camp
LeChuck Grog
Offline Park
2020 bad review
psycho star wars
raise spirits up
I don’t always test my code but when I do, I do it in production
I am an engineer to save time, just assume I’m aleays right


Friky coses guays:
Stimulus
Sails.js
nedb
Redox
Tactician
inertia.js
svelte.dev
structurizr.com
strapi.io
dgraph.io
deno.land
https://www.biotech-foods.com
beekeeperstudio.io


Jocs als que m'he viciat aquest any:
Fallout Shellter
PUBG mobile
COD mobile

Grups guays que he descobert aquest any:
Bigott
Lisasinson
Crushed Beacks
Pet Shimmers
Alvvays
Comando Suzie
Soviet Soviet
Anabel lee
Topographies
Automatic
Chelsea Wolfe
Somos la herencia
Ambros Chapel
Luna y panorama de los insectos
Marcelo Criminal
Ela Minus
Décima víctima

Concerts als que he anat:
RIDE + Crushed Beaks
Sandy (Alex G) + Pet shimmers

Pelis que he vist:
Girl
The drug king
I’m not a serial killer
Toy Story 4
Captain Marvel
Thor el reino oscuro
Thor Ragnarok
Guardians of the galaxy
Guardians of the galaxy vol 2
Ant-man
Captain America winter soldier
Captain America Civil War
Time to hunt
Avengers Age of Ultron
Dr. Strange
Avengers Infinity War
Guns Akimbo
Grabbers
I love you, stupid
Rampant
The Clobberfield Paradox
Da 5 Bloods
Dolor y gloria
Velvet buzzsaw
Shin Godzilla
You were never really here
Mortal engines
Canino
The rules of attraction
Jupiter’s moon
1984
Greyhound
The old guard
Snowpiercer
Tiempo después
1917
System error
Extraterrestre
Outbreak
American Pickle
Illang la brigada del lobo
The wandering earth
#Alive
Aquaman
Take shelter
Showgirls
Borat 2
The Purge: Anarchy
Padre no hay más que uno
La caída del imperio Americano
La edad de la ignorancia
Please stand by
De Pollos y hombres
Old boy
On the rocks
Blade runner 2049
Dans la brume
Under the skin

Pelis vistes a Sitges:
The night
Vicious fun
La funeraria
Blackwater: Abyss
The pale door
Archenemy
Kubrick by Kubrick
Bumperkleef
Malnazidos
Lucky
Spirit walk
La vampira de Barcelona
Mandibules
The queen of black magic
Boys from country hell
No matarás
The old ways
Mosquito state
May the devil take you 2
She dies tomorrow
Tin Can
A perfect enemy
Le Nuee
Soul
Ghost in the shell
Snowden

Top 5 i bottom 5 Sitges:

Top 5 (de millor a pitjor):
Mandibules
Bumperkleef
Le Nuee
The queen of black magic
A perfect enemy

Bottom 5 (de millor a pitjor):
She dies tomorrow
Lucky
The pale door
La funeraria
Tin Can

Curts:
Cap

Llibres que he llegit:
Open, Andre Agassi
Sapiens
Historias de terror, Liz Phair
El consentimiento, Vanessa Sprinzora

Comics:
The Boys, tomos 1,2,3
Guardians of the galaxy vol1, vol2
Raven
Snowpiercer
X-Men la saga Messiah Complex


Series a les que m'he enganxat (per ordre d'adiccio):
Dracula
Watchmen
Star Trek TNG s5,s6,s7
Picard
Kingdom s2
The Mandalorian
Upload
The Last Dance
La conjura contra America
Silicon Valley s6
See
The Purge s1, s2
Snowpiercer
Community
Dietland
Utopia s1, s2
El colapso
Watchmen
El fin de la comedia
Seinfeld
Little Britain USA
Norsemen s1, s2
Pure
Dragonslayer666
Días de mierda
Patria
Utopia 2020 us
Star Trek Discovery s3
Euphoria
Parlement
The Terror s1
30 monedas

Teatre:
Berto, cuanta tontería

Documentals:
McMillions
One child nation
Jeffrey Epstein: Filthy rich
Polansky, se busca
Garbo, the spy
Catalunya Barcelona: La historia catalana de Barcelona
Deep water
Eugenio
Sesión Salvaje
El Palmar de Troya
You don’t Nomi
The forum
Too funny to fail
El desafio ETA
Banksters
Oeconomia
James May, our man in Japan
This giant beast that is global economy

Sortides al Extranjer:

Cap

Millors Hotels als que he anat:
Sa Tuna

Millors restaurants:
Gorria (2)
Xerta
Lluerna
Ferran Cerro
Direkte