Today I learned
Inspired from Github Repo / Reddit, this will be a listing what I learned if it's short I will be listing it here but if it's long I'll make it a post.
Laravel
Voyager
Overwriting certain piece of function
Go to vendor file and copy the exact same file from the same directory, if its controller then copy the controller then put it in your controller if model then do the same.
Don't forget to change the namespace and extend it to \TCG\Voyager\Http\Controllers\Controller then in route copy the same specific route then modify the url.
Default Folder and Permission Laravel
cd [..LARAVEL PROJECT ROOT]
sudo find . -type f -exec chmod 644 {} \;
sudo find . -type d -exec chmod 755 {} \;
sudo chmod -R 777 ./storage
sudo chmod -R 777 ./bootstrap/cache/
Difference between Job and Event
Job
A Job is doing something.
- RegisterUser
- UpdateProfile
- PublishArticle
- SendReminderEmail
Event
An Event occurs when something happens/happened.
You can think of it as an Event occurs throughout different stages of a Job. In this case, and in most cases, an Event is defined in the past tense.
- UserHasRegistered
- ProfileWasUpdated
- ArticleWasPublished
- RemiderEmailWasSent
Adding custom redirect login and register
Find where the LoginController and RegisterController, I use breeze so login is in AuthenticatedSessionController and register is in RegisteredUserController.
Learn that can't use mutators and accessors when using mass assignment
Example of mass assignment:
$user = new User(Input::all());
$user->save();
Example of not mass assignment:
$user = new User();
$user->name = 'steve';
$user->email = '[email protected]';
$user->password = Hash::make('123');
$user->save();
when using mass assignment, then you can't use mutators and accessors
/** ACCESSOR
* Get the post title.
*
* @param string $value
* @return string
*/
public function getNameAttribute($value)
{
return ucfirst($value);
}
/** MUTATOR
* Set the post title.
*
* @param string $value
* @return string
*/
public function setNameAttribute($value)
{
$this->attributes['name'] = strtolower($value);
}
To show error in test
$this->withoutExceptionHandling()
Laravel Policy
php artisan make:policy PostPolicy --model=Post
in AuthServiceProvider
protected $policies = [
Post::class => PostPolicy::class,
];
in PostPolicy
public function update(User $user, Post $post)
{
if (Auth::user()->hasRole('admin')) {
return true;
}
return $user->id === $post-> user_id;
}
implement in controller
$post = Post::find($id);
$this->authorize('update', $post);
Migration Down - Integrity constraint violation: 1062 Duplicate entry '' for key
upon down - usually can't be set to unique because it's already dropped unique on up then after sometime data it stuffed with duplicates, the only way is to empty out the data from duplicates
Migration Down - Syntax error or access violation: 1091 Can't DROP ''; check that column/key exists
Schema::table('tables', function (Blueprint $table) {
$table->dropIndex(['column']);
$table->dropColumn('column');
});
the above is wrong it needs to be dropped index first then drop column
Schema::table('tables', function (Blueprint $table) {
$table->dropIndex(['column']);
});
Schema::table('tables', function (Blueprint $table) {
$table->dropColumn('column');
});
Proxies
I have a case where the traffic is proxied by Cloudflare and when uploading a file to Digitalocean Spaces it keeps on returning 401
// in app/bootstrap in middleware add
->withMiddleware(function (Middleware $middleware) {
$middleware->trustProxies(at: '*');
})
Laravel 8
laravel 8 class controller not found
App/Providers/RouteServiceProvider.php
protected $namespace = 'App\Http\Controllers';
Laravel 5
The one on the top shows the right result but it shows gives null results in logs and the one on the bottom doesn't.
Alpine
This is when a dom is showing to your browser and it fires, I think in the past I tried to make this on jquery and it was hell.
Ngrok
ngrok http 8000
url is not showing https
I use url() but when using ngrok it reads as http, add this forceScheme to boot in appserviceprovider to fix all url() to https
// AppServiceProvider.php
public function boot()
{
if($this->app->environment('development')) {
\URL::forceScheme('https');
}
}
Postman
The GET method is not supported for this route - All method is always either GET or POST, Update in file - settings
Mailgun
Sending from laravel 8, it has different settings from previous mailgun... you need to make smtp email from the mailgun, the default in laravel using smtp.
In mailgun - Dashboard -> click on the your domain -> domain settings -> smtp credential -> add new smtp user
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=2525
[email protected]
MAIL_PASSWORD=insert_password_smtp
MAIL_ENCRYPTION=TLS
[email protected]
MAIL_FROM_NAME="${APP_NAME}"
Mandrill
After making template in mandrill, turns out to make it available on development is to send template from mandrill, the button should say `Send to mandrill`. Then in mandrillapp, turn on test mode go to template find the template it should be there.
Another way debugging
This is another nice way to see in different angle, other than laravel-debugbar
https://underground.works/clockwork/
https://chrome.google.com/webstore/detail/clockwork/dmggabnehkmmfmdffgajcflpdjlnoemp
composer require itsgoingd/clockwork
Rails
ActiveAdmin
Add a Custom filter with custom select2
ActiveAdmin comes with a default filter with all fields in it but sometimes I need to custom it a bit and when it comes to a larger database and need to find the specific filter I need some custom select2 to populate and when searching through the dropdown it will find the keyword. this comes with a cost of slowness when it comes to larger databases so be careful.
In the Model
filter :campaign_id, as: :searchable_select, collection: -> { Campaign.pluck(:name, :id) }
Don't forget to install this gem for select2
gem 'activeadmin-searchable_select'
NGINX
Add Trailing Slash
I've found out there's 2 way to do this, the first one is to add in the server block section and somehow it works, but there are times when there's a blog on the public block which will messup the blog (wordpress), The other way is to put in the \.php$ block, I've seen it work but when it doesn't work try the solution 2.
Solution 1:
rewrite ^/(.*)/$ /$1 permanent;
Solution 2:
location ~ ^([^.\?]*[^/])$ {
try_files $uri @addslash;
}
location @addslash {
return 301 $uri/;
}
Removing Trailing Slash
I learned that in try_files has a role on redirecting too so in below if the second $uri is $uri/ that means you want to redirect that to trailing slash.
location / {
rewrite ^/(.*)/$ /$1 permanent;
try_files $uri $uri /index.php?$query_string;
}
Client intended to send too large body
http {
. . .
client_max_body_size 64M;
. . .
}
Nuxt Nginx Config
Was new to this, then I found out how to serve the server that points to localhost:3000
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
Install PM2 to make yarn start as daemon
sudo npm install pm2 -g
# to start yarn start
pm2 start yarn --interpreter bash --name api -- start
Setting Max-Age Expiry Header
location ~* \.(jpg|jpeg|gif|css|png|js|ico|html)$ {
expires max;
}
Gzip Pre-Compression
./configure --with-http_gzip_static_module
make && make install
http {
. . .
gzip_static on;
gzip_http_version 1.1;
..
}
Removing Whitespace
location / {
strip on;
}
Etags for Static Content
location / {
etag on;
...
}
Location for nginx in macOS
/opt/homebrew/etc/nginx/nginx.conf -> nginx config
SEO
Schema Org
I never knew what breadcrump for until I saw the documentation and understood a bit about schema. What I learned was every page need an organization, SiteNavigationElement and BreadCrumpList schema.
Rendering Smartphone
Sometimes we just put css/style.css or js/script.js, to remind myself this need to be fullpath with the domain so the bot crawler see what user see. To test this just copy paste your html to html generator what does it looks like.
Android
cannot fit requested classes in a single dex file
implementation 'com.android.support:multidex:1.0.3
Then in defaultConfig()
multiDexEnabled true
Upload APK to android store
After creating and subscribing to your account to play store, there are steps that are sometimes confusing, even thought this isn't my first time but somehow I don't remember what to do.
- First, create a new app, just put some required fields and check all the necessary checkboxes.
- Skip tasks for Release your app early for internal testing without review.
- Complete tasks for Provide information about your app and set up your store listing.
Set privacy policy -> On your website make a page that has a privacy policy
App access -> Give 1 tester credential for google to test out.
Ads -> Pick whether the app uses ads
Content rating -> Questionnaire
Target audience -> Questionnaire
News apps -> so easy...
COVID-19 contact tracing and status apps -> just follow the steps
Data safety -> just follow the steps
Select an app category and provide contact details -> just go through one by one for which category is the right one.
Set up your store listing ->
1. App icon 512x512
2. Upload 2-8 phone screenshots. Screenshots must be PNG or JPEG, up to 8 MB each, 16:9 or 9:16 aspect ratio, with each side between 320 px and 3,840 px
3. Upload up to eight 7-inch tablet screenshots. Screenshots must be PNG or JPEG, up to 8 MB each, 16:9 or 9:16 aspect ratio, with each side between 320 px and 3,840 px
4. Upload up to eight 10-inch tablet screenshots. Screenshots must be PNG or JPEG, up to 8 MB each, 16:9 or 9:16 aspect ratio, with each side between 320 px and 3,840 px
MYSQL
Incorrect string value: '\xC2\x80\xC2\x9355
ALTER TABLE
table_name
CONVERT TO CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
Export mysql using gzip
mysqldump -u root -p databasename | gzip -9 > database.sql.gz
Import mysql using zcat
I thought this would be using mysqldump too but nope...
zcat database.sql.gz | mysql -u username -p databasename
Unknown collation: ‘utf8mb4_unicode_520_ci’
sed -i 's/utf8mb4_unicode_520_ci/utf8mb4_unicode_ci/g' file.sql
Fatal error: Can't open and lock privilege tables: Table 'mysql.db' doesn't exist
sudo mysql_install_db --user=mysql --ldata=/var/lib/mysql
can't login to workbench because need sudo
create a user
CREATE USER 'madindo'@'localhost' IDENTIFIED BY 'madindo123';
GRANT ALL PRIVILEGES ON *.* TO 'madindo'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;
can't connect to database server workbench ubuntu 20.04
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
Downgrade from mysql 8 to 5.5 in ubuntu 20.04
Say no more, I've tried many ways and failed but the last one worked out.
# backup
mysqldump -u root -p --add-drop-table --routines --events --all-databases --force > mysql80.sql
sudo apt-get remove --purge mysql-\* -y
sudo apt-get autoremove -y
wget http://repo.mysql.com/mysql-apt-config_0.8.10-1_all.deb
sudo dpkg -i mysql-apt-config_0.8.10-1_all.deb
configure to bionic and mysql5.7
sudo apt-get update
sudo apt install -f mysql-client=5.7.32-1ubuntu18.04
sudo apt install -f mysql-community-server=5.7.32-1ubuntu18.04
sudo apt install -f mysql-client=5.7.32-1ubuntu18.04 mysql-community-server=5.7.32-1ubuntu18.04 mysql-server=5.7.32-1ubuntu18.04
The steps above failed, I think I was close but failed at install mysql-community-server, but below doesn't fail me
https://gist.github.com/ahmadhasankhan/48fc9fc9a19807daef1622751a56884b
Update (25 nov 2020) : don't even think on using 5.5 on modern application... hell breaks lose
Ubuntu 24.04 - The repository 'https://ppa.launchpadcontent.net/ondrej/php/ubuntu oracular Release' does not have a Release file.
sudo add-apt-repository --remove ppa:ondrej/php
sudo add-apt-repository ppa:ondrej/php
sudo sed -i 's/oracular/noble/g' /etc/apt/sources.list.d/ondrej-ubuntu-php-oracular.sources
sudo apt update
Make auto restart php if it's down
If you prefer a script-based solution, create a cron job or use a monitoring tool:
Example Script:
#!/bin/bash
if ! systemctl is-active --quiet php7.4-fpm; then
echo "PHP-FPM is down! Restarting..."
systemctl restart php7.4-fpm
fi
Set up a cron job to run the script every minute:
crontab -e
Add this line:
* * * * * /path/to/script.sh
Postgres / PSQL
failed: FATAL: role "postgres" does not exist
In this case I have another role as superuser but don't have postgres, just add new roles in pgadmin and add roles superuser
error: connection to server on socket "/tmp/.s.PGSQL.5432" failed (m1)
Just happened to see https://stackoverflow.com/questions/70908116/psql-error-connection-to-server-on-socket-tmp-s-pgsql-5432-failed-fatal where macs don't create username databases after installing PostgreSQL
createdb
Purging Binary Log
When I failed to import some big imports because there's no more storage, turns out when importing it saves the imports to mysql-bin
MariaDB [(none)]> SHOW BINARY LOGS;
+------------------+------------+
| Log_name | File_size |
+------------------+------------+
| mysql-bin.000077 | 2815113 |
| mysql-bin.000078 | 365 |
| mysql-bin.000079 | 296244824 |
| mysql-bin.000080 | 1074274682 |
| mysql-bin.000081 | 127711613 |
| mysql-bin.000082 | 365 |
| mysql-bin.000083 | 342 |
+------------------+------------+
7 rows in set (0.000 sec)
MariaDB [(none)]> PURGE BINARY LOGS BEFORE '2021-03-12 23:00:00';
Mysql Workbench - now() is not working
Use \func in the field
\func now()
Use where on update
db=# UPDATE users SET email = lower(email);
UPDATE 1010000
Time: 1583.935 ms (00:01.584)
db=# UPDATE users SET email = lower(email)
db-# WHERE email != lower(email);
UPDATE 10000
Time: 299.470 ms
there are 3 other sessions using the database.
SELECT
pg_terminate_backend(pid)
FROM
pg_stat_activity
WHERE
-- don't kill my own connection!
pid <> pg_backend_pid()
-- don't kill the connections to other databases
AND datname = 'database_name'
;
Ubuntu 20.04
an apparmor policy prevents this sender
- Go to Ubuntu Software
- Search for the app throwing the error
- Click Permissions
- Turn
ON
Read, add, change, or remove saved passwords
After install workbench my text is all squared
So I updated my ubuntu from 18.14 to 20.04, I noticed that my workbench is gone so I installed it from snap after installing all the query and rows is squared
sudo apt --fix-broken install
Wifi adapter is not found in ubuntu 20.04
This is so weird i happened to stumble this incident where the wifi isn't there, just out of the blue. After look around this post helped me
https://askubuntu.com/questions/1249907/ubuntu-20-04-no-wifi-adapter-found-dell
Well my machine is ASUS but still works, just followed all the steps
lspci -knn | grep Net -A3; rfkill list
# shows the specs hard and soft
sudo modprobe wl
# modprobe: FATAL: Module wl not found in directory /lib/modules/5.4.0-37-generic
sudo apt install --reinstall bcmwl-kernel-source
# now this is the solution and dont forget to restart
Main setting for Ubuntu 20.04 not working after upgrade
sudo apt-get update
sudo apt-get install --reinstall gnome-control-center
AWS
IAM User Accessing to Billing
Had trouble on accessing billing as an IAM, Already added an admin group with full access and Billing permission still won't work.
Solution :
Lighthouse And EC2 are different parts
I have lighthouse server and was wondering if the server I used in lighthouse were actually ec2 but packed, turns out it's NOT.
Configuring CORS AWS
I working on livewire upload, where it saves the upload on a temporary file but it shows error.
Go to the bucket permission -> Cross-origin resource sharing (CORS)
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"PUT",
"POST",
"DELETE"
],
"AllowedOrigins": [
"http://www.example1.com"
],
"ExposeHeaders": []
},
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"PUT",
"POST",
"DELETE"
],
"AllowedOrigins": [
"http://www.example2.com"
],
"ExposeHeaders": []
},
{
"AllowedHeaders": [],
"AllowedMethods": [
"GET"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": []
}
]
Cloudflare
Redirecting the right way using Page Rule
if matches url always use * because if you don't add it it will only match the domain url not the path.
https://www.domain.com/*
when using 301 permanent redirect use $1 to pass the asterisk
https://www.domain.com/$1
Nuxt
Create our own global js
Use plugins, below is example of custom function
import Vue from 'vue'
Vue.mixin({
methods: {
truncate (str, noWords) {
return str.split(' ').splice(0, noWords).join(' ')
}
}
})
then add to plugins
plugins: [
'~/plugins/script',
],
Server
Cron - automatically renew certbot
15 1 * * * /usr/bin/certbot renew --noninteractive --quiet --renew-hook "/bin/systemctl reload nginx"
Find folder / file that takes too much space
Add this to your alias
alias ducks='du -cks * | sort -rn | head'
Running Composer install to specific version of PHP
lets say you have php version of 7.0 7.1 7.2 7.3 but the composer but default is 7.3 and can't run composer using 7.2
#find where is php
which php
#find if there's another version php
/usr/bin/php7.2 -v
#use this to run composer
/usr/bin/php7.2 composer install
The phar signature did not match the file you downloaded, this means your public keys are outdated or that the phar file is corrupt/has been modified
composer self-update --update-keys
// Open https://composer.github.io/pubkeys.html to find the latest keys
// copy paste as requested
Make the default PHP version
sudo update-alternatives --set php /usr/bin/php7.4
The uploaded file exceeds the upload_max_filesize directive in php.ini.
upload_max_filesize = 256MB
post_max_size = 256M
memory_limit = 512M
max_execution_time = 180
Yarn
Yarn install command error No such file or directory: 'install'
At first I downloaded the main repo and it shows error -
sudo apt remove cmdtest
sudo apt remove yarn
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt-get update
sudo apt-get install yarn
Node Sass
(25 nov 2020)
Installing node-sass in ubuntu 20.04
I don't know why unsafe-perm but it'll install...
sudo npm install -g --unsafe-perm node-sass
Example of using Node-sass
node-sass --watch public/frontend/stylesheets/sass/main.scss -o public/frontend/stylesheets/css
GIT
How to reset master to empty commit
git checkout -b my-feature-1 master
git branch -D master
git checkout --orphan master
git reset --hard
git commit --allow-empty -m "Initial commit"
git push origin master:master --force-with-lease
Set password remember for 1 day
git config --global credential.helper "cache --timeout=86400
Set git branch like ls
git config --global pager.branch false
Go
Gorm
Count
var count int64
query := p.db.Model(&model.Product{})
query.Count(&count)
Pluck
var productIds []int
query := p.db.Model(&model.Product{})
query.Pluck("ID", &productIds)
missing go.sum entry for module providing package
go mod tidy
Go not recognizing Goose installed
the installation states only for $PATH, but it also needs $GOPATH also need to set if you have another directory.
export GOPATH=$HOME/codespace/go
export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin
Wordpress
Custom post type
Custom Post Type With prefix blog
If you are using custom post types on your site, you need to make sure that ‘rewrite with front’ is disabled for each of your post types. Otherwise your custom post type URLs will also get/blog/
in front of them.
If you use a plugin to register your post types, look for the ‘Rewrite‘ option, and make sure that ‘With Front‘ is unchecked. After saving your settings, go back to the Permalinks Settings and click ‘Save Changes’ (this is necessary so that the new links are generated).
Adding Breadcrumbs
<?php
if ( function_exists('yoast_breadcrumb') ) {
yoast_breadcrumb( '<p id="breadcrumbs">','</p>' );
}
?>
Getting a post by slug
<?php
$args = array(
'name' => $uri_segments[2]
);
$my_posts = get_posts($args);
?>
Spotify
Stuck in fullscreen
wmctrl -l
wmctrl -r "Spotify" -b toggle,minimize
Udemy
Black screen on the screenshot
I just notice this recently when I want to screenshot the video on a course that I PAID, well I don't want to mess up my chrome settings by disabling the hardware accelerator but instead just use firefox.
Cpanel
To Connect
ssh -p 22 [email protected]
SSH
Could not open a connection to your authentication agent
ssh-agent /bin/sh
ssh-add ~/.ssh/id_rsa
Error connecting to agent: No such file or directory (windows)
I thought the terminal and linux terminal share the same ssh but it doesn't.
// start the service
Start-Service ssh-agent
// to get all the keys available
Get-Service ssh-agent
I already have a key registered from linux so I copied the file to windows then
// to add
ssh-add {path of the key}
// to check if key added
ssh-add -l
Office-related
What Is a Brown Bag Meeting?
A brown bag meeting is an informal meeting or training that generally occurs in the workplace around lunchtime. This type of meeting is referred to as a brown bag meeting or a brown bag seminar because participants typically bring their lunches, which are associated with being packed in brown paper bags.
Python (mac)
brew install pyenv
pyenv install $(pyenv install --list | grep --extended-regexp "^\s*[0-9][0-9.]*[0-9]\s*$" | tail -1)
pyenv versions // check the version downloaded
pyenv local {{ check version downloaded }}
Google Cloud SDK
Gsutil
brew install google-cloud-sdk
Interview
Step1: get the premium subscription
Step2: start with the top 100 questions
Step3: focus on questions topic by topic
Step4: practice with a plan
Step5: Solve company-specific questions
CSS
Adding CSS overlay when Javascript is disabled
HTML
<noscript>
<div>
<h1 style="padding: auto; color : #fff;margin : 261px auto; width : 500px;height: 300px">Your Browser JavaScript is not enabled. Please enable to continue</h1>
</div>
</noscript>
CSS
.noscript_overlay {
position:fixed;
top:0px;
text-align: center;
left:0px;
z-index:3000;
height:100%;
width:100%;
background: rgb(0, 0, 0) transparent;
background: rgba(0, 0, 0, 0.6);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
}
Java
Springboot
Unable to get spring boot to automatically create database schema/table
spring.jpa.hibernate.dll-auto=create
solution before adding the dll-auto add this
spring.jpa.generate-ddl=true
Flutter
Error: The "instance" getter on the ServicesBinding binding mixin is only available once that binding has been initialized.
When trying to run on an Android emulator this error shows but not in the browser.