Missing code to include staticfiles

If you are reading Writing your first Django app, part 6, the code won’t work until you put in the following code from https://docs.djangoproject.com/en/1.8/howto/static-files/ (in the section named Serving static files during development) to the urls.py file.

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Basically your urls.py needs to know where to route the static file requests. =)

Django using TIME_ZONE to display local time

It took me a while to figure out how to do this correctly. There is too much noise from google search… Here are my settings for everything to display correctly in my admin site w/ Django 1.8.

settings.py

USE_TZ = True
TIME_ZONE = 'US/Pacific'
HUMAN_TIME_FMT = '%Y-%m-%d %H:%M:%S %p'

HUMAN_TIME_FMT is optional, I put it there for my own usage.

models.py

from django.conf import settings
from django.db import models
from django.utils import timezone

class Sync(models.Model):

    sync_start = models.DateTimeField('sync starts')
    sync_end = models.DateTimeField('sync ends')
    
    def __str__(self):
        fmt = settings.HUMAN_TIME_FMT
        my_dt1 = timezone.localtime(self.sync_start).strftime(fmt)
        my_dt2 = timezone.localtime(self.sync_end).strftime(fmt)
        return 'From ' + my_dt1 + ' => ' + my_dt2

More to read:
# https://docs.djangoproject.com/en/1.8/ref/settings/#std:setting-TIME_ZONE
# http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
# http://strftime.org/

iphone 6 and google voice

If after switching to iphone 6 your google voice mail all of a sudden stops working, keep reading.

This may have something to do with the new internal settings in iphone 6 with iOS 8. To the general public, simply need to know that the instructions from google voice to dial **004*1[GV-Number]# is not going to work. You would see error messages Setting Registration Failed.

I tried it on my iphone 6 and it works now. Assuming your number is 1-650-789-1234. Simple do this:

  1. Dial *#61#
  2. Dial *#62#
  3. Dial *#67#
  4. Dial *61*16507891234# – Call Forward if Unanswered
  5. Dial *62*16507891234# – Call Forward if Unreachable
  6. Dial *67*16507891234# – Call Forward if Busy

If this is still not working, double check your google voice website and make sure your iphone 6 setting is correct.

Hope this helps!

Ref: http://www.macobserver.com/tmo/cool_stuff_found/post/how-to-make-ios-8-and-iphone-6-work-with-google-voice
http://marcelbrown.com/2014/09/22/ios-8-iphone-6-conditional-call-forwarding/
https://productforums.google.com/forum/#!topic/voice/XJt1i0rlm7A

Git push asks for username and password

If git push keeps asking you for user/pass, chances are that you did a git clone using HTTPS. Fix that by going to your repo page on github, then click on the SSH link below the clone URL field, then copy that URL over (something like git@github.your_username/your_repo_name.git). Then update your local git repo with something like the following command

git remote set-url origin git@github.your_username/your_repo_name.git

ref: http://stackoverflow.com/questions/6565357/git-push-requires-username-and-password

Install MongoDB on OSX


If you are reading this, chances are that you need to deal with unstructured data. =)

First, install mongodb using homebrew!

brew install mongodb

Now we need to set up a dir for mongodb to keep its data. For simplicity, we will just use its default db path /data/db. We will need to change the permission of that dir to your username and your group. Run ls -ld ~ to get that info.

sudo mkdir -p /data/db
sudo chown -R your_user_name /data
sudo chgrp -R your_group_name /data

At this point, we are ready to run/start mongod. We could run mongod directly (the log info will come into your terminal…). My preference is to run mongod in the background.

First install this. It will enable you to handle the launchctl on osx a lot easier.

brew tap gapple/services

Then you can now make the following calls whenever. brew services basically calls launchctl under the hood.

brew services start mongodb
brew services stop mongodb

While mongodb has been started with brew services, if you take a look at /Users/[your_user_name]/Library/LaunchAgents/, you will see the homebrew.mxcl.mongodb.plist file sitting there. Take a peek at the file inside, you will see that the conf file is at /usr/local/etc/mongod.conf, and stdout/stderr gets forwarded to /usr/local/var/log/mongodb/output.log (not so useful…).

In the mongod.conf file, we see that the log goes to /usr/local/var/log/mongodb/mongo.log. That would be where you look for the server pid, port, dbpath, etc.

Now start up mongod, and then call mongo to run some commands!

brew services start mongodb
mongo

Run a few of these below to play around

show dbs     -- just admin and local
use my_db    -- at this point, we haven't created my_db yet
db           -- showing the current selected db, which is my_db
db.books.insert({'name': 'Harry Potter', 'Vol': 1}) 
             -- "db" refers to my_db, "books" is our "collection"
show collections     -- you will see "books" there, kinda like a db table
db.books.find()      -- you will see our newly inserted data row
db.books.find({"Vol":1})  -- with condition
show dbs             -- you will see our newly created db "my_db"
exit

See the documentation on db.dollection.find here.

To exit the mongo shell, just type exit. To stop mongod, issue brew services stop mongodb.

You may wonder how to create users and set up authentication. brew services doesn’t do this, so we will need to ditch brew services and do the following instead.

First make a copy of the default plist conf file.

brew services start mongodb
cp /Users/[your_user_name]/Library/LaunchAgents/homebrew.mxcl.mongodb.plist ~
brew services stop mongodb

Run mongod –noauth to start up the server (without authentication!!!). Then run mongo to connect.

use test     -- this is our test db
db.createUser({user: "testUserAdmin", pwd: "password", roles: [{role: "readWrite", db: "test"}]})
exit

Notice you get the Successfully added user response from the createUser call. If you need to drop a user do something like db.dropUser(“testUserAdmin”).

The above createUser command created a testUserAdmin user with password being the secret password… See all the built-in roles.

Then Ctrl-C to quit server, and run mongod –auth to start up the server, this time with authentication. Then run mongo -u testUserAdmin -p password to login to the test db.

If you made a copy of homebrew.mxcl.mongodb.plist, you could look at the settings and run the server with something like the following. Then you can read the log with tail -f /usr/local/var/log/mongodb/mongo.log

mongod --auth --config /usr/local/etc/mongod.conf >>/usr/local/var/log/mongodb/output.log 2>>/usr/local/var/log/mongodb/output.log &
[Now your shell is freed up]

See more info at http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/ and http://docs.mongodb.org/manual/tutorial/add-user-administrator/

Error establishing a database connection

For some reasons my blog has been getting this error every now and then. I knew it had something to do with my recent setup of a new server, even though I copied over all my old settings. After digging around in my ubuntu 14, I found that it was a lack-of-memory issue.

My ubuntu 14 box is running the standard lamp stack: apache, mysql and php5, btw.

So first you wanna see if you can simply restart your apache:

sudo service apache restart

If your website comes back alive, then lucky you. You are done. cough cough…

If it complains about mysql, then try to restart your mysql:

sudo service mysql restart

If it lets you, then ah… luck you. What that means is, the problem “goes away”.

If my case, I had to dig deeper. The restart failed, so I opened up the mysql log file.

sudo tail /var/log/mysql/error.log

You may see something like this:

141229 7:03:52 [Warning] Using unique option prefix myisam-recover instead of myisam-recover-options is deprecated and will be removed in a future release. Please use the full name instead.
141229 7:03:52 [Note] Plugin ‘FEDERATED’ is disabled.
141229 7:03:52 InnoDB: The InnoDB memory heap is disabled
141229 7:03:52 InnoDB: Mutexes and rw_locks use GCC atomic builtins
141229 7:03:52 InnoDB: Compressed tables use zlib 1.2.8
141229 7:03:52 InnoDB: Using Linux native AIO
141229 7:03:52 InnoDB: Initializing buffer pool, size = 128.0M
InnoDB: mmap(137363456 bytes) failed; errno 12
141229 7:03:52 InnoDB: Completed initialization of buffer pool
141229 7:03:52 InnoDB: Fatal error: cannot allocate memory for the buffer pool
141229 7:03:52 [ERROR] Plugin ‘InnoDB’ init function returned error.
141229 7:03:52 [ERROR] Plugin ‘InnoDB’ registration as a STORAGE ENGINE failed.
141229 7:03:52 [ERROR] Unknown/unsupported storage engine: InnoDB
141229 7:03:52 [ERROR] Aborting

141229 7:03:52 [Note] /usr/sbin/mysqld: Shutdown complete

See that error line? InnoDB: mmap(137363456 bytes) failed; errno 12. Um… it turns out while trying to allocate memory for InnoDB, the process failed. So that means, my box doesn’t have that much RAM to do so. Yea… I signed up for a small plan.

birdchan@birdhome-ubuntu14:/etc/mysql$ free -h
             total       used       free     shared    buffers     cached
Mem:          484M       452M        31M        55M       6.0M       109M
-/+ buffers/cache:       337M       147M
Swap:           0B         0B         0B

You see how I only got 31M free RAM? Upping the RAM surely is an option, but I want to stay cheap, haha. So… let’s try the swap file? You may want to double check and see you’ve got the space needed in your file system. I only allowed myself to use 1Gb space for the swap file.

df -h

You will need root access for the following steps. Do a sudo su or add sudo before all the following commands.

The following command creates a swap file swap.dat at the root directory path. Each block size is 1024 bytes, which is 1Kb. I am creating 1 million blocks, so that makes 1Gb. Feel free to play with the count parameter to create the right size for your swap file.

dd if=/dev/zero of=/swap.dat bs=1024 count=1M

Double check you have your swap file with ls -lh /swap.dat. Then we will need to enable the swap file.

mkswap /swap.dat
swapon /swap.dat

Lastly, edit /etc/fstab and add the following line to the file.

/swap.dat      none    swap    sw      0       0 

Now when you run free -h, you should see your swap file being recognized by the OS.

root@birdhome-ubuntu14:/# free -h
             total       used       free     shared    buffers     cached
Mem:          484M       478M       6.2M        56M       1.0M        86M
-/+ buffers/cache:       390M        93M
Swap:         1.0G         0B       1.0G

One more thing. Open up your /etc/mysql/my.cnf and reduce the default InnoDB buffer pool size from 128Mb to 64Mb. Why 64Mb? Um… well, it could be anything you want. =)

So look for [mysqld], then add the following line.

innodb_buffer_pool_size=64M

Then restart mysql, you should be good to go.

root@birdhome-ubuntu14:/# sudo service mysql restart
stop: Unknown instance: 
mysql start/running, process 14156

Remember to exit out from your root shell!!! =)