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.

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

class BlogUpdateView(UpdateView):
    model = Blog

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

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!

The problem

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 access 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. Not cool!

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.



No need for @login_required and @permission_required decorators. These reusable Django class-based-views will provide object-level permissions to its subclasses more than what those two can offer. These views take a step ahead by giving an option to make views accessible only to the owner of the object (via the usual model attributes .user, .owner, or .creator).


  • RestrictedCreateView – subclass of django.views.generic.CreateView
  • RestrictedDetailView – subclass of django.views.generic.DetailView
  • RestrictedListView – subclass of django.views.generic.ListView
  • RestrictedUpdateView – subclass of django.views.generic.UpdateView
  • RestrictedDeleteView – subclass of django.views.generic.DeleteView
  • RestrictedMixin – for use with views that inherit from other classes


.restriction attribute

There are 8 restriction levels that you can assign to your class-based-views:

  • 0 – Nobody has access (not even you? aw!)
  • 1 – Only super users have access.
  • 2 – Any staff with permissions has access.
  • 3 – The owner of the object has access (request.user == object.user, object.owner, etc.)
  • 4 – Any logged-in user with model-level permissions has access.
  • 5 – Any staff has access (request.user.is_staff == True).
  • 6 – Any logged-in user has access (request.user.is_authenticated() == True).
  • 7 – Anybody have access.

You set the restriction through the restriction attribute of the view class. This attribute is an integer (not string).

For example:

class MyClass(RestrictedDeleteView):
    model = Blog
    restriction = 1

will only allow superusers (admins) to delete Blog objects.

The restrictions filter-through, meaning a user is evaluated from the top (level 1) downwards until the user qualifies on a level which grants him/her access. When a user fails to pass the restriction level set for the view, a PermissionDenied() exception is thrown.

.owner_field attribute

For models in which objects belong to a user (i.e. owned by a user). set the owner_field attribute to the name of the field that is a ForeignKey to django.contrib.auth.models.User. This attribute is a string. It is mainly used in views that have restriction = 3.

You do not have to declare an owner_field attribute if you don’t need restriction level 3. It will simply be ignored in other restriction levels.

For example:

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

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

from dslibpy.views.restricted import RestrictedUpdateView
from myproject.blogs.models import Blog
from myproject.blogs.forms import BlogModelForm

class BlogRestrictedUpdateView(RestrictedUpdateView):
    model = Blog
    form_class = BlogModelForm
    restriction = 3

will grant access to the owner of the Blog object (level 3). It will also grant access to any staff (is_staff == True) provided that they have “change” permission for Blog objects (level 2). It will also grant access to all superusers (level 1). Users who belong to level 4 and below are NOT granted access to this view.

Note here that the view does not have the owner_field attribute. You can also do this and the view will safely ignore objects that do not have owners in the first place. To be exact, this view will grant access to levels 1 and 2 users only although it indicates level 3.

More Examples

The following usage examples are based on the Blog model above.

Using RestrictedCreateView

This code:

from dslibpy.views.restricted import RestrictedCreateView
from myproject.blogs.models import Blog

class BlogRestrictedCreateView(RestrictedCreateView):
    model = Blog
    owner_field = 'user'
    restriction = 5

will make BlogRestrictedCreateView automatically save the logged-in user into the field user of the Blog object (i.e. object.user == request.user). Also it grants access not only to the owner and the admins but also to any authenticated user who is a staff (is_staff == True) and to any authenticated user who has “add” permissions on the Blog model.

Using RestrictedDetailView

This code:

from dslibpy.views.restricted import RestrictedDetailView
from myproject.blogs.models import Blog

class BlogRestrictedDetailView(RestrictedDetailView):
    model = Blog
    owner_field = "user"
    restriction = 2

will only allow admins, and staff users (is_staff == True) who have “view” permissions on the Blog model.

Using RestrictedListView

This code:

from dslibpy.views.restricted import RestrictedListView
from myproject.blogs.models import Blog

class BlogRestrictedListView(RestrictedListView):
    model = Blog
    template_name = "blogs/blog_list.html"
    owner_field = 'user'
    restriction = 7

    def get_queryset_perm(self, user):
        queryset = super(Blog, self).get_queryset_perm(user)
        # one-million-lines-of-code-here

will allow all users including guests and visitors who are not logged in to view the list of blog entries.

RestrictedListView deserves special mention here. The default get_queryset() method now is wrapped in get_queryset_perm() which requires passing of the user object (request.user). Aside from that, the usual attributes like template_name, success_url, etc. retain their default behaviors.

Using RestrictedUpdateView

from dslibpy.views.restricted import RestrictedUpdateView
from myproject.blogs.models import Blog
from myproject.blogs.forms import BlogModelForm

class BlogRestrictedUpdateView(RestrictedUpdateView):
    model = Blog
    form_class = BlogModelForm
    restriction = 3

Using RestrictedDeleteView

I will leave the usage of this view as an exercise for you. If you have reached this far, you can definitely nail it.

Using RestrictedMixin

This code:

from dslibpy.views.restricted import RestrictedMixin
from dslibpy.profiles.models import CustomerProfile, VendorProfile
from myproject.profiles.views import ProfileUpdateView

class CustomerProfileUpdateView(RestrictedMixin, ProfileUpdateView):
    model = CustomerProfile
    user = 'customer'
    restriction = 3

class VendorProfileUpdateView(RestrictedMixin, ProfileUpdateView):
    model = VendorProfile
    user = "vendor"
    restriction = 3

will allow you to have all the security features of dslibpy.views.restricted alongside the reusable features of your existing class-based-views. Just make sure that RestrictedMixin is the first in the list of base classes so that its methods are called first in the command chain.


You can download the Python library from my GitHub repository:
Darwinian Software Library for Python.


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!