Notes: Reset Expired root Password for MySQL 5.7 on Mac OS X

I installed MySQL 5.7 from a .dmg package installer for Mac OS X. I followed the installer taking note of the temporary root password given. After the installation, I cannot login as root because the password expired. Here’s what I did.


I stopped MySQL in System Preferences.

MySQL in System Preferences

MySQL in System Preferences


Switched user to root.

$ sudo su


Started MySQL in safe mode.

$ sudo mysqld_safe --skip-grant-tables


I opened another terminal tab/window and lauched mysql shell there.

sh-3.2# mysql -u root

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.12 MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.



Changed root password.

mysql> UPDATE mysql.user SET authentication_string=PASSWORD('password') WHERE user='root';
Query OK, 0 rows affected, 1 warning (0.01 sec)
Rows matched: 1  Changed: 0  Warnings: 1



And then,

Query OK, 0 rows affected (0.02 sec)




mysql> \q
sh-3.2# exit



Now try logging in with the new password.

$ mysql -u root -p
Enter password:


It works!

Snippets: Test Email Sending in Django

This is what I do when I want to test if sending of emails from a Django web app works.

First, in the project directory, I launched a manage shell session.

$ python shell

Then I entered the following commands.

Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.core.mail.message import EmailMessage
>>> e = EmailMessage('S', 'M', '', [''])
>>> e.send()

A return of 1 means it’s working. A second later, the email came.

It works!

Notes: Using MySQL


Replace everything that starts with “a_”.


Login to MySQL console.

$ mysql -u root -p

Backup a MySQL database.

$ mysqldump -u a_username a_database > a_file.sql

Restore from backup.

$ mysql -u a_username -p a_database < a_file.sql

Update MySQL user password.

mysql> UPDATE USER.master SET PASSWORD = AES_ENCRYPT('a_password', 
'a_passkey') WHERE username = 'a_username'

It works!

Notes: Using PostgreSQL


Bash v4.2
PostgreSQL v9.5


Replace everything that starts with “a_”.


launch psql.

$ sudo su postgres
bash-4.2$ psql


postgres=# \q

List databases.

postgres=# \l

Create user.

postgres=# CREATE ROLE a_username LOGIN PASSWORD 'a_password';

Change user password.

postgres=# ALTER ROLE postgres WITH PASSWORD 'a_password';

Create database.

postgres=# CREATE DATABASE a_database WITH OWNER a_username;

Drop database.

postgres=# DROP DATABASE a_database;

Drop user.

postgres=# DROP ROLE a_username;

Adding PostGIS extension.

$ sudo su postgres
$ psql -d a_database
a_database=> CREATE EXTENSION postgis;


Backup as dump file (tested to work in migrating servers).

$ pg_dump -Fc -h localhost -U a_username -f a_file.dump a_database

To create a non-compressed backup.

$ pg_dump -h localhost -U a_username -f a_file.sql a_database

To create a schema-only database backup.

$ pg_dump -s -h localhost -U a_username -f a_file.sql a_database


To restore a database from a dump (works with backups as dump only). The database should already exist. If an error occurs for some reason, use postgres as the username.

$ pg_restore -c -h localhost -U a_username -d a_database a_file.dump

To restore a database from a non-compressed backup.

$ psql -h localhost -U a_username a_database < a_file.sql


To recreate a fresh initdb’d PostgreSQL instance.

$ pg_dropcluster


Database management commands.

$ psql -h localhost -U a_username -d a_database
sampledb=> select * from a_tablename where id=168;

It works!

Notes: Install Python 2.7 on Cent OS 7 from Source

I enabled the EPEL repository.
Enable EPEL repository.

I upgraded setuptools.

$ sudo yum update python-setuptools

I installed python-pip.

$ sudo yum -y install python-pip

I installed pre-requisites.

$ yum groupinstall "Development tools"
$ yum install zlib-devel bzip2-devel openssl-devel ncurses-devel 
$ yum install sqlite-devel readline-devel tk-devel gdbm-devel 
$ yum install db4-devel libpcap-devel xz-devel

I could have actually issued the above yum install commands in one-line but..

I downloaded Python 2.7.10.

$ mkdir -p ~/Downloads
$ cd ~/Downloads
$ wget

I extracted the compressed file.

$ tar -xzf Python-2.7.10.tgz

I installed Python 2.7.10 from source.

$ cd Python-2.7.10
$ ./configure
$ make
$ sudo make altinstall

I created a symlink to Python 2.7 in /usr/local/bin which is on my PATH environment variable. (optional)

$ cd /usr/local/bin
$ sudo ln -s python2.7 python

It works!!

Notes: Cron Jobs (Scheduled Tasks) in Mac OS X

These are my notes on how to create cron jobs in Mac OS X. Linux users are already familiar with cron. Cron jobs in Windows are called Scheduled Tasks.

First, I set the default editor to be nano. I like the simplicity of nano compared to the default vim editor. It is more humane!!

Edit the .bash_profile script

$ nano ~/.bash_profile

Add the following line

export EDITOR=”nano”

Save, exit and reload the bash script

$ source ~/.bash_profile

Open the cron table

$ crontab -e

Add the following lines (for example)

*/5 9-15 * * *  <command>

Save and exit

That will run <command> every 5 minutes, from 9am to 3:55pm, daily. Of course you should change <command> with a real Mac OS X command that you need to run.

Watch out for mails in:


If you wish to receive emails every time the cron job executes, change the MAILTO line to:


It worked!

Django: Generic Class Based Views with Object Level Permissions Checking

A common design pattern in Django Class Based Views (CBVs) is checking whether the user is logged-in (authenticated) or not. If the user is authenticated, the view proceeds. If not, the view throws a permission denied exception. A common security feature in web sites.

For example, take a look at this code:

from django.contrib.auth.models import User
from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=255)
    user = models.ForeignKey(User)

from django.views.generic.edit import UpdateView

from models import Blog

class BlogUpdateView(UpdateView):
    model = Blog

from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required

from views import BlogUpdateView

urlpatterns = patterns("views",

The is a common place to put these constraints. In here, only logged-in users are allowed to edit blog entries. Great!

But consider this scenario. Darwin logs-in, creates his blog, and then saves it. Mel happens to log-in, creates her blog, and saves it. Now two blog objects exist with IDs let’s say 1 for Darwin and 2 for Mel. Darwin tries to hack Mel’s blog and types the following address in his browser.

Remember that the codes above allow any logged-in user access to the view BlogUpdateView. Darwin could actually edit Mel’s blog entry and save his changes. Terrible!

Enter dslibpy.views.restricted

As a solution to the problem, I have rolled-out dslibpy.views.restricted. A set of “secure” Class Based Views that subclass each of the view classes in django.views.generic. I compiled the modules as part of a larger library of Python reusable codes. You can subclass these views in your projects to add restrictions to your views.

Here is the full documentation for dslibpy.views.restricted.

Installing dslibpy

dslibpy is absolutely free! You may use it, modify it, and redistribute it. The dslibpy documentation contains instructions on how to install dslibpy.


It worked!

Using: SyntaxHighlighter Evolved Shortcode Parameters

I used SyntaxHighlighter Evolved for pasting codes in my blog site. Here’s a quick guide on how I used it.

Sample Usage

In my article:
[python light="false"]print 'Hello, World!'[/python]

The Output:

 print 'Hello, World!' 

Shortcode Parameters

These are the parameters you can pass to the shortcode and what they do. For the booleans (i.e. on/off), pass true/1 or false/0.

lang or language The language syntax to highlight with. You can alternately just use that as the tag, such as [php]code[/php]. Click here for a list of valid tags.
autolinks Toggle automatic URL linking.
classname Add an additional CSS class to the code box.
collapse Toggle collapsing the code box by default, requiring a click to expand it. Good for large code posts.
firstline An interger specifying what number the first line should be (for the line numbering).
gutter Toggle the left-side line numbering.
highlight A comma-sperated list of line numbers to highlight. You can also specify a range. Example: 2,5-10,12
htmlscript Toggle highlighting any extra HTML/XML. Good for when you’re mixing HTML/XML with another language, such as having PHP inside an HTML web page. The above preview has it enabled for example. This only works with certain languages.
light Toggle light mode which disables the gutter and toolbar all at once.
padlinenumbers Controls line number padding. Valid values are false (no padding), true (automatic padding), or an integer (forced padding).
title (v3 only) Sets some text to show up before the code. Very useful when combined with the collapse parameter.
toolbar Toggle the toolbar (buttons in v2, the about question mark in v3)
wraplines (v2 only) Toggle line wrapping.

Some more example shortcodes

[php]<?php phpinfo(); ?>[/php]

[css autolinks="false" classname="myclass" collapse="false" firstline="1" gutter="true" highlight="1-3,6,9" htmlscript="false" light="false" padlinenumbers="false" smarttabs="true" tabsize="4" toolbar="true" title="example-filename.php"]your code here[/css]

[code lang="js"]your javascript code here[/code]

[sourcecode language="plain"]your code here[/sourcecode]

As of this time, SyntaxHighlighter Evolved is the most popular WordPress plugin for syntax highlighting based on the download count. However, I found it quite funny that I had a hard time looking for an article on how to use it. What I needed was the list of syntax parameters so I could control how my codes look when rendered in a browser. I found it inconvenient having to click my way to the Settings page for the plugin in the WordPress admin panel just to get this list up front. Well, there goes the list for my convenience.

Notes: Connect PHP5 to MySql in Mac OS X

I came across this error in my Apache error log file found in /var/log/apache2/error_log.

PHP Warning:  mysql_connect(): [2002] No such file or directory
(trying to connect via unix:///var/mysql/mysql.sock)

I figured out that this is due to PHP not being able to find the MySql socket to connect to the MySql database server. To be exact, PHP is looking for a file named mysql.sock.

I turned to look for mysql.sock in the MySql configuration file found in /usr/local/bin/mysql_config.

if [ -f "$basedir/include/mysql/mysql.h" ]; then
elif [ -f "$basedir/include/mysql.h" ]; then


if [ 0 -eq 0 ]; then

# Create options

PHP was looking for the file /var/mysql/mysql.sock but the file exists in /tmp/mysql.sock.

So what I did was to simply create a symlink for the mysql.sock file in the /var/mysql/ folder.

$ sudo mkdir /var/mysql
$ ln -s /tmp/mysql.sock /var/mysql/mysql.sock

I could have modified the line in the mysql_config file to point to /var/mysql/mysql.sock but this is not good for other applications in Mac OS X that need the mysql.sock file in /tmp/mysql.sock.


To test if indeed PHP can connect to MySql, I created a file named ~/Sites/test-php-mysql.php with the following contents.

    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = 'password';
    $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error: Could not connect to MySql.');

    if ($conn) {
        echo 'Successfully connected to MySql.';

    $dbname = 'mysql';

Then I launched Safari and typed http://localhost/~darwin/test-php-mysql.php in the address bar. It showed that the connection was established.

Successfully connected to MySql.

It worked!