Jaye Tan's Octopress Blog

Just Blogs

Ftp Info on Uploading Themes in Wordpress on Localhost

Today I tried uploading underscore theme to my computer’s localhost server, I tried to unzipped it and paste it directly on my wordpress theme directory, but does’t shows up on wordpress theme dashboard, so I decided to install it via worpress theme installation, but came across in this wierd ftp connection info that I need to provide, it is bizzar because I’m only working on my localhost so ftp info is not necessary. by the way I’m using ubuntu, this might not show if you are using windows machine. I fixed it by adding define(‘FS_METHOD’, ‘direct’); on wordpress wp-config.php which can be found on the root folder of wordpress.

Wordpress Permalinks 404 Not Found

Wordpress Permalinks 404 not found

This is mainly a problems for Ubuntu users after installing the Wordpress on their localhost. to solve this problem follow this instructions:

Using Terminal

first allow overides on your apache sudo gedit /etc/apache2/apache2.conf and find all <Directory /> </Directory> and paste this code in between in all of that tag

Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all

ex. <Directory />

Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all

</Directory>

then go to your wordpress folder usually you can find it on /var/www/html/wordpress then create an htaccess by typing:

sudo touch .htaccess then change the access permission by typing: sudo chmod 664 /var/www/html/wordpress/.htaccess then change the ownership by typing: sudo chown www-data:www-data /var/www/html/wordpress.htaccess take note of the path you may need to change it depending on where you wordpress is installed.

Then change the grant access to the www folder:

sudo chmod -R 777 /var/www
sudo chown -R **yourusername** /var/www

then type this in your terminal sudo a2enmod setenvif headers deflate filter expires rewrite include

then refresh the apache by: sudo service apache2 restart

you can now change your wordpress permalinks to Post name without an 404 error not found.

Up and Running With Django

What is Django?

Django is a free and open source web application framework, written in Python, which follows the model–view–controller architectural pattern. Django’s primary goal is to ease the creation of complex, database-driven websites. Django emphasizes reusability and “pluggability” of components, rapid development, and the principle of don’t repeat yourself. Python is used throughout, even for settings, files, and data models. Django also provides an optional administrative create, read, update and delete interface that is generated dynamically through introspection and configured via admin models.

How to install

first download the tarball of django at https://www.djangoproject.com/download/ extract it and via terminal go to the extracted folder of django, then type

sudo python setup.py install

if it didn’t work you can read the README.rst which can be found at the extracted django folder and read the instruction on how to install it.

Listing all available commands

to list all available Django commands just type

django-admin.py

Creating django project

just type

django-admin.py startproject django_test

where in django_test is the name of your project, after installing, a folder with name django_test will be created it will also contains django files.

Running django server

python manage.py runserver

this will run the django server on localhost:8000, just view it on you browser and you will able to see this line “It worked! Congratulations on your first Django-powered page.”

Changing the Django default page using templates

in settings.py add these lines

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)

then on urls.py add this line in the top page

from django.views.generic import TemplateView

then include this on urlpatterns inside urls.py

url(r'^$', TemplateView.as_view(template_name="index.html")),

then make a folder name templates inside your project, inside that templates folder create an index.html and add you html codes.

Creating an App

python manage.py startapp article

where article is the name of the app

Make views.py in apps use template

put this on top of the page to be able to pass variables and use template

from django.template.loader import get_template
from django.template import Context

then on views define a function

def article(request):
    name = "Jaye"
    template = get_template('article.html')
    html = template.render(Context({'name': name}))
    return HttpResponse(html)

The simpliest way rendering template

from django.shortcuts import render_to_response

then define a function

def article(request):
    name = "Jaye"
    return render_to_response("article.html", {"name": name})

Rendering template via class definition (can also be used in changing django default page)

assuming you have already imported TemplateView

class articleTemplate(TemplateView):
    template_name = "article.html"
    def get_context_data(self, **kwargs):
        context = super(articleTemplate, self).get_context_data(**kwargs)
        context["name"] = "Jaye"
        context["test"] = "Admin"
        return context

Creating template that includes external header and footer or anything you want.

this is usefull if you have multiple pages that has the same header and footer.

first we create our html files, index.html, _header.html, and _footer.html now open up index.html, then use {% include %} to include the other html files

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
{% include "_header.html" %}
<body>
    
    BODY CONTENTS HERE

{% include "_footer.html" %}
</body>
</html>

while the _header and _footer.html can contain any html tags except for <html></html> and <body></body>

Enabling Django Admin

go to settings.py and uncomment these lines

'django.contrib.admin',
'django.contrib.auth',

and

go to urls.py and uncomment these lines

from django.contrib import admin
admin.autodiscover()
url(r'^admin/', include(admin.site.urls)),

after this you will now able to log in the admin page of django http://localhost:8000/admin

Detect Mobile - Tablet Orientation Using Jquery

This Javascript / Jquery code can detect mobile or tablet orientation.

    window.addEventListener("orientationchange", function() {
        var orientation = window.orientation;
      }, false);

a portrait orientation will result of a value of “0” while landscape orientation will yield a result of “90” you can now use this value to create a conditional statements, this is helpful if you are creating a realtime orientation query.

tags: javascript mobile orientation, javascript tablet orientation, device orientation jquery, jquery window orientation

Learning Python

What is Python?

Python is a modern object-oriented programming language that’s well-suited for a variety of uses, from simple scripts to complex web applications. Using third-party tools, such as Py2exe or Pyinstaller, Python code can be packaged into standalone executable programs.

This Blog will be updated during my free time to share all the knowledge I learned in studing this powerful programming language.

Before we start make sure that you have the python installed in your computer, If you are using linux or mac chances are that you already have python preinstalled in your computer.

In this blog I’ll be using python 3, and sublime as my text editor. you can use what ever text editor you like such as eclipse to help you in you coding and compiling in one development application, but I prefer the traditional way of doing it using a separate text editor and command line it running python.

I will be starting this blog by creating the traditional hello world program.

#!/usr/bin/python3
print("Hello, World!")

to run python, save the file first with .py extension ex. helloWorld.py then you should compile it by typing in the terminal cat helloWorld.py then to run the program type in ./helloWorld.py if you got an Permission denied error type chmod 755 helloWorld.py to make it executable.

looking in the helloWorld.py the line #!/usr/bin/python3 is called shebang line, in unix based operating system such as linux and mackintosh, this is the path to the python interpreter which tells the computer to use it to run the program. while the print(“Hello, World”) is use to display the a text.

Assigning Values

a, b = 1, 2

1 will be assigned in “a”, and 2 will be assigned in “b”, so “a” will hold the value of 1 and “b” will hold the value of 2.

Conditional Statement

a, b = 1, 2

if a < b:
    print("a ({}) is less than b ({})".format(a, b))
else:
    print("a ({}) is not less than b ({})".format(a, b))

In creating conditional statement in python, you type the condition followed by colon then the indented code, this is how you create a block of codes in python, blocks are called “suites” in python. you can see this kind of syntax in loops, functions and classes. If you notice the curly braces inside the print statement, it will be replaced by the value inside the format. This format is a method of string object.

Conditional Expression

a, b = 1, 2

print("foo" if a < b else "bar")

This is the other way of creating conditionals in python

Working with loops There are two kinds of loops in python, the while loop and for loop.

While Loop

b = 1
while b < 50:
    print(b)
    b += 1

In creating while loop we type while followed by the condition then a colon, then underneath it we place the code we want to be done in this case print the value of b then followed by the incrementing value, in python the is no “++” e.g “b++” to increment the value by one, instead we can use “+=” sign to increment a value. In this example the print(b) will continue to execute until it reach 50, if we run the program we will see numbers 1 to 49, it will shows only up to 49 since the the increment happens after the print().

For Loop

fruits = ['banana', 'apple',  'mango']
for fruit in fruits:
    print('Current fruit :', fruit)

For loop works with iterator when the loop runs, it goes to each list inside the fruits variable and put it on the fruit variable one by one for each loop, it breaks out if it has no longer has a list to print.

Function

def loopValue(n):
    for num in range(1, n):
        print(num)

loopValue(20)
loopValue(30)

def is the keyword that we are defining a function and loopValue is the name of the function, a function can hold multiple parameter separated by commas, in this example (n) this holds the value that has been passed by calling the function “loopValue(20), loopValue(20)” this is a great way to reuse code preventing you to type them repeatedly.

<— TO BE CONTINUED —>

Creating Multiple Github Account

Creating Multiple Github Account on a Single Machine
(don’t change your default github if you have octopress site in your personal github)

In case you already have a personal Github account and want to create a new one for your projects or your client on a single machine (computer) follow this easy steps.

Create a new ssh key by typing in the terminal ssh-keygen -t rsa -C “email address” a prompt will show asking where to save the generated key, be carefull not to overwrite your existing key, just save it as ex. ~/.ssh/id_rsa_clientName

Then go to ~/.ssh using terminal, type gedit id_rsa_clientName.pub then copy the whole line then login your new github account, go to settings-account settings-ssh key click Add SSH key, give your ssh key a title and then paste your ssh key.

next thing you want to do is to identify the new ssh key by typing ssh-add ~/.ssh/id_rsa_clientName this will allow you to sign in to your github account using the new ssh key, it also tells the git which key should it use to access your github account, this will also fixed the error: Agent admitted failure to sign using the ssh key.

assuming your still on the .ssh folder, create a config file by typing touch config then type in gedit config then paste this line of text

#Default GitHub
Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa

Host github-clientName
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa_clientName

this is where we will specify the new github hostname notice the “Host github.com” that is our default github while the “Host github-clientName” is our new github account.

after this we can now push to our new github account, but we need first to create a new repository and copy the git repository url ex. git@github.com:clientName/projectName.git we will be copying only the “clientName/projectName.git” because we will specify the git remote origin by typing git remote add origin github-clientName:clientName/projectName.git (this is also applicable if you are pulling/cloning an existing repository)

Note: As I stated above if you wish to have an multiple github account but already have an personal github account with octopress in it, you should not make that as your secondary github account, you will able to push to source but you cannot use “rake deploy” to push a new blog.

If this error shows up:

ERROR: Repository not found.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

you need to type this on the terminal ssh-add ~/.ssh/id_rsa_clientName
tags: octopress rake deploy error on multiple github accounts, github multiple accounts, Agent admitted failure to sign using the ssh key

Installing Drupal Locally

Installing Drupal on Localhost

In order to run Drupal locally we must have a Server that runs Apache, Php and MySQL, for windows you can install software bundle called wamp for mac you can use mamp and for linux you can install lamp, but I recommend to install it individually, in my experience as a linux user installing a bundle package will cause you a lot of errors rather than installing it individually.

Installing Apache, PHP MySQL and PHPmyadmin for LINUX

Open terminal and type in these commands:

APACHE

sudo apt-get update sudo apt-get install apache2 to test if the apache is working browse http://localhost

MySQL sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql sudo mysql_install_db sudo /usr/bin/mysql_secure_installation prompt will appear asking for current password for root

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

for testing purposes I would recommend to not put password for root, a bunch of promt questions will follow along installation just type y to all.

PHP

sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt

PHPmyadmin

sudo apt-get install phpmyadmin

after you installed the Apache MySQL PHP and PHPmyadmin

download the drupal at https://drupal.org/download choose the .zip format and unzipped it after download to see the drupal folder use the terminal to move the drupal folder to var/www by typing sudo mv Downloads/Drupal-7.27 /var/www

Note: You may need to grant access to your /var/www folder to do this simply type the following:

sudo chmod -R 777 /var/www
sudo chown -R **yourusername** /var/www

Next thing you must do is to setup the database for your drupal, browse http://localhost/phpmyadmin and create a database for your drupal.

then browse http://localhost/drupal folder name ex. http://localhost/drupal-7.27 this will take you to the installation, just follow the instruction and you wil be able to install drupal.

Creating Grails App

Creating Grails App

Before we can create an Grails application, we need to install Java Development kit in our computer by typing sudo apt-get install oracle-java6-installer (this will also fixed the JAVA_HOME was NOT set error in your terminal, if you have installed the GVM first.)

after installation we can now create our grails application by typing grails create-app name ex. grails create-app sampleProject

then cd sampleProject then to run the grails project simply type grails run-app then browse to http://localhost:8080/sampleProject/ you will now able to see your first grails app.

Configuring Database to use mySQL as default Database

By default Grails uses H2 as its database but we can change this by simply going to your Grails Project then open grails-app/conf/ directory then open DataSource.groovy

change

dataSource {
    pooled = true
    driverClassName = "org.h2.Driver"
    username = "sa"
    password = ""
}

to

dataSource {
    pooled = true
    driverClassName = "com.mysql.jdbc.Driver"
    username = "root"
    password = ""
}

and change all

dbCreate = "update"
url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000"

to

dbCreate = "update"
url = "jdbc:mysql://localhost/testing"

Then open BuildConfig.groovy find and uncomment the line runtime ‘mysql:mysql-connector-java:5.1.16’

NOTE: dbCreate dictates what grails will do to the database, these are the following definition you can use:

create-drop – Drop and re-create the database when Grails is run
create – Create the database if it doesn’t exist, but don’t modify it if it does. Deletes existing data.
update – Create the database if it doesn’t exist, and modify it if it does exist

-Both create-drop and create will destroy all existing data-

MVC Model View Controll

Grails uses MVC architecture pattern to implement user interface

Syntax in creating Domain (Model)

grails create-domain-class className ex. grails create-domain-class book

Syntax in creating Controller

grails create-controller controllerName ex. grails create-controller bookController

For creating the View

we could simply create a file with .gsp extension name inside the “projectName”/Grails-app/views directory ex. books.gsp

Basic Grails/Groovy Syntax

just like html tags grails uses opening and closing tags

example of grails form

<g:form controller="Persons" action="save" class="grails-form">
            <label>First Name: 
            <g:textField name="firstName"/>
<label>Last Name: <g:textField name="lastName"/>
<label>Age: <g:textField name="age"/>
<g:actionSubmit value="Save"/> </g:form>

example of grails input field <g:textField name=“lastName”/>

example of grails submit button <g:actionSubmit value=“Save”/>

example of looping data to display database content

    <table border="1">
        <g:each in="${viewRecords}" status="i" var="thisRecord">
            <tr>
                <td>${thisRecord.id}
                <td>${thisRecord.firstName}
                <td>${thisRecord.lastName}
                <td>${thisRecord.age}
            </tr>
        </g:each>
    </table>

Basic Controller Functions

Inserting Data to MySQL Database

    def save() {
        def users = new Persons(params)
        users.save()
        render "Success!"
        redirect(action:"view")
    }

Pulling data from MySql database

    def view = {
        def viewUsers = Persons.list();
        [viewRecords: viewUsers];
    }

Deleteing data from MySql database with if else statement

    def delete = {
        def deleteUser = Persons.get(params.idNum)

        if(!deleteUser){
            render "User Id don't exist!"
        }else{
            deleteUser.delete()
            render "Deleted!"
        }
        
    }

Installing GVM

Installing GVM (Grails Version Manager)

To install GVM we need to install Curl first via terminal sudo apt-get install curl then we could follow the instructions in the http://gvmtool.net/

curl -s get.gvmtool.net | bash

after the GVM is installed type this in the terminal gvm help we should see the list of candidates: candidate : gaiden, gradle, grails, griffon, groovy, groovyserv, lazybones, springboot, vertx if you are not able to see the candidates list you need to uninstall the GVM and install it again

how to uninstall GVM

we need to delete this #THIS MUST BE AT THE END OF THE FILE FOR GVM TO WORK!!! [[ -s “~/.gvm/bin/gvm-init.sh” && ! $(which gvm-init.sh) ]] && source “~/.gvm/bin/gvm-init.sh” lines in the

~/.bash_profile (or ~/.profile) ~/.bashrc and ~/.zshrc

just use your text editor to open the file and delete it ex. sudo gedit ~/.bash_profile then delete the ~/.gvm directory rm -rf ~/.gvm

if your GVM installed properly you can now install Grails by typing gvm install grails [version] ex. gvm install grails 2.1.1 to see the list of available grails type gvm list grails if you see a note saying that your gvm is in offline mode just put it online by typing gvm offline disable

NOTE: you might think that the code I posted above is not working due to constant errors that you will receive, this is normal, I repeat the steps above numerous times before it installed perfectly, especially in installing the grails, you have to put you gvm in online mode repeatedly because it automatically turns offline when installation fails.

Parallax Scrolling

Today I created a Simple Parallax Scrolling that scrolls different elements with different speed upwards, at first it looks intimidating but its simple to create probably the most challenging part of the parallax is how you can make it scroll smoothly, but you can achieve it by using some plug-ins These are the part of my codes:

Html

<div class="small-clouds-layer">
    <img src="blue-clouds-1.png" class="small-1">
    <img src="blue-clouds-3.png" class="small-3">
</div>

Css

.small-clouds-layer{
    position: absolute;
    top: 600px;
    width: 100%;
}
.small-1{
    margin-left: 300px;
}
.small-3{
    margin-left: 300px;
}

Javascript

$(window).bind('scroll',function(e){
    parallaxScroll();
});

function parallaxScroll(){
    var scrolled = $(window).scrollTop();
    $('.small-clouds-layer').css('top',(600-(scrolled*.5))+'px');
}

the javascript code above is enough to make a parallax scrolling if you want to animate more elements just set it’s css rules and add that elements inside parallaxScroll function