Category Archives: Development

newlogo-repro

Template engine – Why it’s better to use two of them at once?

Template engine

In the following post I’ll try to show and explain how and why I am using two template engines in every application I’m working on. Also, why and how I am choosing my template engine(s) I’m working with.

 

Intro (about me)

Developing in: .NET / Python / Java / Go / PHP and more,

  • New exciting and better tools are important to me!
  • Performance (server & client) are very important to me!
  • The ability to arrange and split the code smartly exact as I want is very important to me!
  • The ability to comment as I like inside the code and the client not to receive it is very important to me! (especially in web HTML/JS)

Who using Template engine

Probably every web developer is using a template engine. You can find it as integral part of most decent modern web development frameworks and environments. Many exist standalone and not as part of any framework. although, Templates Engines are not sole exist for Web development and are used in large variety of tasks. This post is dedicated to web development Template Engines which are called specifically – “Web Template System”

If you’re a web developer and you don’t know or use any Template Engine: You better run some self-tests(!). If you don’t know what is template engine and how to use it, you better read before you continue…

Note about PHP. as I call PHP a bad language but a great Template engine by itself, so in many cases Template engine doesn’t needed or not used (although there are many PHP templates engines).

 

So, Why one template engine? Why not 2?

All configurations of template engine I saw are using one template engine per application. The scenario is simple; The web developer creates a template for an HTML page.. process it on the server and send the results to the browser. for example:

<html>
<head>
   <title>$title</title>
</head>
<body></body>
</html>

In the above example, the server will fill the $title variable as needed and result with the following to the client:

<html>
<head>
   <title>Using My Template Engine</title>
</head>
<body></body>
</html>

…..

Now.. for my suggestion.

I’ve changed the way I am using template engine in my development. I am using two separate template engines in the app. One for creating minified html files with embedded JS and CSS, the other for filling the variables and send to the client.

I call the first TE(Template Engine) – The ‘First layer’, and second ‘Second layer’.

 

Example of 2-Layers-TE

Maybe It’s the best to show an example of how I am using my Templates engines together.

In this example I am rendering at first HTML using Tenjin (Python) and the second template engine as the web server is the basic Golang Template engine.

First Template Engine

<!-- all comments will be removed at the minify process -->
<html>
<head>
   <style><?py include('index.css') ?></style>
   <script type="text/javascript"><?py include('index.js') ?></script>
   <title>{{ .Title }}</title>
</head>
<body></body>
</html>

In the above example with Tenjin, you can see it includes two files: index.css and index.js which I I’ll show below. Also note the {{ .Title }} annotation which is NOT tenjin syntax but it’s golang template engine syntax, which means the first template engine (Tenjin) will just output this into the final html result.

The Styles are saved in another file (index.css):

// All comments will be removed at the minify process
body { background-color: blue }

Actually, I am using SCSS (SASS) for my CSS development, and then I compile and minify them (in the same script as part of the whole website compile) into index.min.css file. then, the above Tenjin imports index.min.css and not index.css. Also, I’m adding one more global.css which is embedded into all htmls.

And the JS are saved in another file (index.js):

$(function () {
 // also, those comments will be removed on minify
});

As with the CSS, sometimes I use CoffeeScript or IcedCoffeeScript and then compile it into JS.
Also, as part of the compile process, I am minifying the JS to index.min.js and Tenjin imports the minified file and not the source. If I use JS (and not CS or ICS) I minifyjs it before too, and in the process doing a syntax check.

Then, Using script I made – I minify all the templates (with inline CSS and JS) onto:

<html><head><style>body{background-color:blue}</style><script type="text/javascript">$(function(){});</script><title>{{ .Title }}</title></head><body></body></html>

You can see that the {{ .Title }}, which is Golang template engine syntax is still here. The first template engine (which in our case is Tenjin) isn’t processing the variables and just minify them with everything else.

Now, its ready to use from the Golang environment Template Engine. comment-less, minified and as one document, even if it’s built from 10 CSS files, 10 JS files and hierarchical templating.

In this way the actual logic designing of the hierarchy of the templates are done in the first layer and the second layer is only responsible to fill in the variables and pass to the client.

How I choose the templates engines?

The equation I use is simple:

FOR THE FIRST LAYER I use for the strongest template engine I can find. I like features like inheritance, raw, import, widgets …… ! I need everything! Performance isn’t needed at all at the first layer. It’s compiled after work has done in the code and then that’s it!. I want to be able to arrange my website htmls into preety smart structure. To split the JS files into many logic files… same with CSS. After it will be rendered for the second layer it will be fully minified as one document. then the performance matters…

FOR THE SECOND LAYER I use the fastest template engine I can find. Caching of templates is a must feature! Here the performance matters!. The template engine could be Logic-Free or not, It’s design decision, but no need here for hierarchy or any other expert feature in the TE as it using the full minified htmls. only to read the html from file into memory and then fill it now and then with data and pass to client.

REMEMBER You need to choose two TE with different syntax(!). You can’t use two of them that has the same snytax (like {{ var }}). Tenjing is using <% %> and Golang is using {{ }}.

If you’ll later use client side TE you better take that into account. AngularJS is using {{}}. Angular Syntax must be changed or another TE must be chosen for the second layer.

 

So, Why it’s good for?

So, Why I am doing this complex structure? Those are the advantages of this method:

  • Performance – Golang caches into memory the minified html with css, js embedded. it’s better for server side and for client side performance!!. It’s PRO! and minification doesn’t need to be done in real time!
  • You can create a complex inheritance for your files in the first layer WHILE you preserve performance in the second layer. You get to write and split code (html, css and js) in many files as you like. you know it will be all be merged and minified later….
  • You can put comments wherever you want freely!! (in the html as well as in the css/js) and they will be removed later by the minify process.
  • You can use Placeholders as usual in the webserver template engine (second layer), as well in the first layer.  application name, for example will be suited for the first layer as It doesn’t supposed to be changed but user name can be filled as usually in the second layer.
  • JS files are verified in the process!!. you will know about bad syntax before you’ll even open the browser!
  • If you use SASS you’ll find it’s so sweet… at last! you can manage your CSS as you’ve always dreamed of!

Example

I made an example @ Github (https://github.com/ET-CS/2TE). I used Cheetah(Python) as the first layer, as it have lot more features then Tenjin, and I’ve used Golang as the webserver (second layer). although Golang is not the fastest TE I know, it’s fast enough and I really like Golang as a web server.

I made another example @ https://github.com/ET-CS/2TE-Bootstrap which is essentially the same idea as 2TE, but it is ready packed with Bootstrap HTML on either Jinja2 or Cheetah as the First layer. Great boilerplate for amazing fast web application!!

 

Always think performance…… and always MInified is better!!!

Development Specialist, Artist and Activist
Personal Website
Android_Robot_200

Android Context in non-activity Class – The Secret of ContextWrapper

Android Context in non-activity Class – The Secret of ContextWrapper

Android Context in non-activity Class

One of most frustrating issues I had to figure out when I’ve started to develop for Android was the Context.

Why there are several kind of Context? and more important – How can I call to system API method from a Class when all the important functions are available only from a Context class??

The problem

Let’s take this function inside activity for example (test for AirPlane Mode),
Where isAirPlaneModeOn() is using the getContentResolver() which is Context.method:

public class MyActivity extends Activity {
 
   ...
 
   public boolean isAirplaneModeOn() {
      return Settings.System.getInt(getContentResolver(),
         Settings.System.AIRPLANE_MODE_ON, 0) != 0;
    }
 
}

Or inside a service:

public class MyService extends Service {
 
   ...
 
   public boolean isAirplaneModeOn() {
      return Settings.System.getInt(getContentResolver(),
         Settings.System.AIRPLANE_MODE_ON, 0) != 0;
   }
 
}

P.S: The isAirplaneModeOn() function is using depreceated method (pre API 17) just for the purpose of simple example and backward compatibility.

Now… lets say you want to create some other class, and move the function to that class:

import android.provider.Settings;

public class MyOtherClass {
   ...
   public boolean isAirplaneModeOn() {
      return Settings.System.getInt(<span style="text-decoration: underline;">getContentResolver</span>(),
         Settings.System.AIRPLANE_MODE_ON, 0) != 0;
   }
}

HEY?!!? Why Eclipse telling me: The method getContentResolver() is undefined for the type MyOtherClass

????? ….. Because getContentResolver() is a context method – Soon you realize you must have access to Context.. so What the solution?

 

Some solutions

I’ve read a lot about context(s). Maybe, most of the valuable stuff out there in the internet…

Some are saying to pass the context to the class and save a reference to that context like:

class YourNonContextClass {
   private Context context;

   public YourNonContextClass(Context context){
      this.context=context;
   }

   public boolean isAirplaneModeOn() {
      return Settings.System.getInt(context.getContentResolver(),
         Settings.System.AIRPLANE_MODE_ON, 0) != 0;
   }
}

Some are saying to pass the context to your static function like:

public class MyOtherClass { 
   public static boolean isAirplaneModeOn(Context context) {
      return Settings.System.getInt(context.getContentResolver(),
         Settings.System.AIRPLANE_MODE_ON, 0) != 0;
   }
}

Both solutions works. Both have their Pros and Cons. both require you to alter the code inside the function.

 

Solution – The Secret of ContextWrapper

Finally … After a fashion… With lot of experimentation, I’ve found a great solution that I really like! :

CONTEXTWRAPPER!

So What is ContextWrapper?

Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context.

In other simple words: It’s a class that inherits another Context.

 

So, How to use the ContextWrapper?

Let’s talk about the function we discussed above and create a ContextWrapper class for it:

public class MyContextWrapper extends ContextWrapper {

    public MyContextWrapper(Context base) {
      super(base);
   }

   public boolean isAirplaneModeOn() {
      return Settings.System.getInt(getContentResolver(),
         Settings.System.AIRPLANE_MODE_ON, 0) != 0;
   }
}

Note that nothing need to be changed in the isAirplaneModeOn() function as the class itself inherits the wrapper you’ve called from (Activity, Service, IntentService, etc).

To call the function just use:

boolean isAir = (new MyContextWrapper(this)).isAirplaneModeOn();

Where ‘this’ could be any context you’d like to. applicationContext, Service or Activity.

 

That’s it.  Easy haa!

And choose what fits you best…

 

Development Specialist, Artist and Activist
Personal Website
android

Android Get Mobile IP Address code example

Android Get Mobile IP Address

Android Get Mobile IP Address Code Example

Android Get Mobile IP Address :

Getting the android IP address for Wi-Fi connection using the API is very simple:

/**
 * Get the IP of current Wi-Fi connection
 * @return IP as string
 */
private String getIP() {
 try {
   WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
   WifiInfo wifiInfo = wifiManager.getConnectionInfo();
   int ipAddress = wifiInfo.getIpAddress();
   return String.format(Locale.getDefault(), "%d.%d.%d.%d",
   (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
   (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
 } catch (Exception ex) {
   Log.e(TAG, ex.getMessage());
   return null;
 }
}

But what if you need to get the Mobile connection IP?

The answer is to check the NetWorkInterface like this:

/** Get IP For mobile */
public static String getMobileIP() {
  try {
    for (Enumeration<NetworkInterface> en = NetworkInterface
    .getNetworkInterfaces(); en.hasMoreElements();) {
       NetworkInterface intf = (NetworkInterface) en.nextElement();
       for (Enumeration<InetAddress> enumIpAddr = intf
          .getInetAddresses(); enumIpAddr.hasMoreElements();) {
          InetAddress inetAddress = enumIpAddr.nextElement();
          if (!inetAddress.isLoopbackAddress()) {
             String ipaddress = inetAddress .getHostAddress().toString();
             return ipaddress;
          }
       }
    }
  } catch (SocketException ex) {
     Log.e(TAG, "Exception in Get IP Address: " + ex.toString());
  }
  return null;
}

And if you want to get the IP as IPV4 just replace the line:

          if (!inetAddress.isLoopbackAddress()) {

With:

 if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
Development Specialist, Artist and Activist
Personal Website
grails-logo

CentOS Grails installation tutorial for newbs – CentOS 6.x

centos grails

centos grails installation tutorial for newbs. for CentOS 6.x (And probably for older/later)

 

Prerequisities

You have to install Groovy (which require JDK). If you don’t have Groovy (And JDK) installed follow those instructions.

  • Java SDK 1.4+ for Grails 1.0.x and 1.1.x
  • Java SDK 1.5+ for Grails 1.2 or greater (For this tutorial make sure you have JDK 1.5+ installed)

 

Install Grails

Option 1: Using GVM (Recommended)

If you’ve installed groovy using GVM, you can use the GVM to install grails too. use:

gvm install grails
centos grails

centos grails

Option 2: Manual Installation

We’d go by the official Grails manual:

The folder we’ll install Grails is: /usr/grails, but you can choose any other as you like.

Init Folder

cd /usr
mkdir grails
cd grails

Here we’ll put the grails files by version.

Visit the download page to get the latest version. as for now it’s 2.3.7

wget http://dist.springframework.org.s3.amazonaws.com/release/GRAILS/grails-2.3.7.zip
unzip grails-2.3.7.zip
rm grails-2.3.7.zip

Install wget & unzip if you don’t yet have them install by: yum install wget unzip

add the following to your ~/.bash_profile or ~/.bash_rc (or wherever you init your user environment):

# grails
export GRAILS_HOME=/usr/grails/grails-2.3.7
export PATH=$PATH:$GRAILS_HOME/bin

That’s it

Option 3: Using GIT

If you want to be updated with latest patches (and bugs) you can clone the git repo.

Prerequisities: you should have JDK installed, your JAVA_HOME set and GIT installed (yum install git).

For the 2.0.x and the ‘master’ branch:

cd /usr
git clone https://github.com/grails/grails-core
cd grails-core && ./gradlew install

and set your GRAILS_HOME in the ~/.bash_profile (or ~.bash_rc):

# grails
export GRAILS_HOME=/usr/grails-core
export PATH=$PATH:$GRAILS_HOME/bin

If you want to install older branch read here.

 

Testing grails

Type at command:

grails --version

You should get something like this output (depend on version)

grails-version

 

That’s It! you have centos grails installed.

Cheers!

Development Specialist, Artist and Activist
Personal Website
groovy-logo

CentOS Groovy installation tutorial for newbs – CentOS 6.x

CentOS Groovy

CentOS Groovy installation instruction for newbs.

 

Prerequisities

JDK

To install Groovy you have to install the JDK. If you don’t have JDK installed yet follow those instructions by RaveMaker.

 

Groovy Installation

There are several mothods (as always) to install groovy into your CentOS box.

 

Option 1: GVM

The simplest is using the GVM, tool for managing parallel Versions of multiple Software Development Kits on most Unix based systems. It provides a convenient command line interface for installing, switching, removing and listing Candidates.

GVM is a powerful tool to install Candidates and switch between them (on current terminal, or by default). reading the full intro to GVM is recommended.

to install GVM use the command:

curl -s get.gvmtool.net | bash

This will quickly install GVM into your system

gvm-install

Run the following command as required or log again to the system, as GVM is adding this line to your ~/.bash_profile file:

source "/root/.gvm/bin/gvm-init.sh"

which should return nothing. now you are ready to install groovy by:

gvm install groovy
centos groovy install

centos groovy install

Notes:

  • This will installed groovy version 2.2.2. you can use GVM to install specific groovy version, or multiple versions (read the manual).
  • GVM will create the ~/.gvm directory with all the assets inside (~/.gvm/groovy/2.2.2).

that’s it.

 

Option 2: Manual Installation

It’s always recommended to manually install every peace of code to fully understand what going on there. Following the official installation guide,

Download binary

Download binary for groovy from the download page (check if there is newer version, or specific version you need other then 2.3.0-beta-2 shown here):

cd /usr
mkdir groovy
cd groovy
wget http://dl.bintray.com/groovy/maven/groovy-binary-2.3.0-beta-2.zip
unzip groovy-binary-2.3.0-beta-2.zip
rm groovy-binary-2.3.0-beta-2.zip

This will create a /usr/groovy/groovy-2.3.0-beta-2 folder with the files packed inside.

* If you don’t have wget installed use then ‘yum install wget’ command to install it.
* If you don’t have unzip installed use then ‘yum install unzip’ command to install it. 

TIP

Create a symlink to that folder named ‘latest’ which you can change later when you’ll update your groovy installation without the need to update the environment variables.

ln -s groovy-2.3.0-beta-2 ./latest

Set-up environment

Last thing you need is to:

  • set your GROOVY_HOME environment variable to the directory you unpacked the distribution
  • add GROOVY_HOME/bin to your PATH environment variable

Edit your ~/.bash_profile file and append the following lines:

# Groovy
export GROOVY_HOME=/usr/groovy/latest
export PATH=$PATH:$GROOVY_HOME/bin

or, if you didn’t created the latest symlink, use:

# Groovy
export GROOVY_HOME=/usr/groovy/groovy-2.3.0-beta-2
export PATH=$PATH:$GROOVY_HOME/bin

 

Test Groovy

groovy -e ‘println(“Hello, World!”)’

centos groovy

centos groovy

 

And that’s it! You have Groovy Installed.

Cheers!,

 

grails-logo    Do you need Grails framework for Groove? Read my walkthrough tutorial.

 

Development Specialist, Artist and Activist
Personal Website
Golang

CentOS golang Installation Instructions – for CentOS 6.x

CentOS golang

CentOS golang Installation Instructions – for CentOS 6.x.
In the following tutorial I’ll show how to install and run “Hello, world!” script with golang on CentOS 6.x

 

CentOS golang Installation Instructions – for CentOS 6.x

Install EPEL

If you haven’t install EPEL repository yet, you’ll need it now. follow those instructions.
If you want newer versions of golang you might want to try the hop5.in repository but I haven’t tried.

 

Install golang

Simple as:

yum install golang

you may want to install hg also, you’ll probably will need it later for the ‘go get’ command:

yum install hg

 

Hello, World!

create a file named ‘hello.go’ and fill it with:

package main
import "fmt"
func main() {
     fmt.Println("Hello, World!")
}

run the script using:

go run hello.go
centos-golang

centos-golang

You can first build to a binary executible with:

<div class="codecolorer-container text railscasts" style="overflow:auto;white-space:nowrap;width:555px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td class="line-numbers"><div>1<br /></div></td><td><div class="text codecolorer">go build hello.go</div></td></tr></tbody></table></div>

and then run with:

<div class="codecolorer-container text railscasts" style="overflow:auto;white-space:nowrap;width:555px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td class="line-numbers"><div>1<br /></div></td><td><div class="text codecolorer">./hello</div></td></tr></tbody></table></div>

 

$GOPATH

The ‘Hello, World!’ is a very basic example, but in real-world you may need to install packages and libraries for more complex applications.

The $GOPATH environment variable specifies the location of your workspace. It is likely the only environment variable you’ll need to set when developing Go code.

If your project for example is located at $HOME/go, you should create a variable like:

export GOPATH=$HOME/go

For convenience, add the workspace’s bin subdirectory to your path:

export PATH=$PATH:$GOPATH/bin

Now, your project environment variables are set and you can download packages with the simple command: (for example – the Google OAuth 2.0 library)

go get code.google.com/p/goauth2/oauth

 

What’s next

Web Applications using Go

  • Writing Web Applications tutorial.
  • Bones – A project template for Go webapps.
  • Gorilla web toolkit.
  • Revel – A high-productivity web framework for the Go language. Deploy Revel.
  • Martini – Classy web framework for Go.
  • sawsij – lightweight, open-source web framework for building high-performance, data-driven web applications.

Template Engines for Go

Web Applications in Production

 

 

That’s it!, Cheers!

Development Specialist, Artist and Activist
Personal Website
clojure-logo

CentOS Clojure / Leiningen / Luminus / http-kit Installation and sample tutorial

CentOS Clojure

CentOS Clojure installation and sample tutorial.
In the following post I’ll show how to install and configure Clojure on you CentOS box with sample web server example.

Also,, weI’ll use leiningen for manage the Clojure app and http-kit for deployment.

 

CentOS Clojure Installation

First, Clojure requires only Java 1.5 or greater, if you don’t have the JDK installed yet on your CentOS box please follow this instructions by ItekBlog writer – Adam to install Oracle Java on your CentOS box.

Download Clojure

Before you continue, check the Downloads page to install the latest version.

To download Clojure use:

# if you don't have wget installed - use: yum install wget
# if you don't have unzip installed - use: yum install unzip
cd /opt
wget http://repo1.maven.org/maven2/org/clojure/clojure/1.5.1/clojure-1.5.1.zip
unzip clojure-1.5.1.zip
rm clojure-1.5.1.zip

to bring up a simple read-eval-print loop (REPL) use:

cd clojure-1.5.1
java -cp clojure-1.5.1.jar clojure.main

try:

user=> (+ 1 2 3)
6
user=> (javax.swing.JOptionPane/showMessageDialog nil "Hello World")

Try Clojure Online

  • TryClojure provides a brower-based Clojure REPL
  • Himera provides a browser-baed ClojureScript REPL

Community Resources

Community volunteers maintain Getting Started documentation for a number of different tools and approaches.

 

Leiningen

Leiningen is the easiest way to use Clojure. With a focus on project automation and declarative configuration, it gets out of your way and lets you focus on your code.

Installing Lieningen

to install Lieningen you need to download the lein script place it on your $PATH (eg. ~/bin) and set it to be executable:

cd ~/bin
wget https://raw.github.com/technomancy/leiningen/stable/bin/lein
chmod a+x ~/bin/lein

you can read the tutorial by running lein help tutorial.

The tutorial is the best place to start. It does not cover learning the language itself; good Clojure documentation can be found.

Running lein help faq will get you the FAQ. Documentation for each individual task is available via lein help $TASK. You can also see the sample project.clj file containing a reference of most project settings by running lein help sample.

 

Creating a Project

Creating a new project is easy:

cd ~/
lein new app my_first_app
cd my_first_app
find .

In this example we’re using the 

1
app

 template, which is intended for an application project rather than a library. Omitting the app argument will use the default template, which is suitable for libraries.

Directory Layout

The output of the find command is:

leiningen_find

Here you’ve got your project’s README.md file, .gitignore file for you all GIT users, a src/ directory containing the code, a test/ directory, and a project.clj file which describes your project to Leiningen. The src/my_stuff/core.clj file corresponds to the my-stuff.core namespace.

Running Code

let’s start our code running:

lein run

 

centos clojure

centos clojure

 

For extended information and documentation about Leiningen and the REPL Read here.

 

FAQ: Set LEIN_ROOT to disable this warning.

leiningen_error

 

If you want to run LEIN using root, you should add to your ~/.bash_profile :

export LEIN_ROOT="Something"

rem

ember to touch the file:

. ~/.bash_profile

 

Frameworks

Luminus

Luminus is a micro-framework based on a set of lightweight libraries. It aims to provide a robust, scalable, and easy to use platform. With Luminus you can focus on developing your app the way you want without any distractions.

create a new project:

    lein new luminus myapp
    cd myapp
    lein ring server

the app is now available at 

1
localhost:3000

luminus-welcome

 

Clojure Deployment

When you’re ready to deploy your app, you have many web servers such as: nginx, http-kitimmutant, tomcat, JBossPallet, GlassFish, Jetty, Netty, Grizzly, etc.

 

using nginx

You can use nginx-clojure to run your clojure project inside of nginx server.

In Clojure web server benchmarks, this server achieved the highest performance.

20140121-14-30

read this tutorial for more information about nginx/clojure implementation.

 

using Tomcat

To install Tomcat server follow those steps.

You need to package the application as a WAR archive, to do that run:

lein ring uberwar

then simply copy the resulting myapp-0.1.0-SNAPSHOT-standalone.war to the webapps folder on Tomcat, eg:

cp target/myapp-0.1.0-SNAPSHOT-standalone.war ~/tomcat/webapps/myapp.war

Your app will now be avaliable at the context /myapp when Tomcat starts. To deploy the app at root context, simply copy it to webapp as ROOT.war.

 

HTTP Kit – HTTP client/server for Clojure

HTTP Kit is a minimalistefficientRing-compatible HTTP client/server for Clojure. It uses a event-driven architecture to support highly concurrent a/synchronous web applications. Feature a unified API for WebSocket and HTTP long polling/streaming

<div class="codecolorer-container text railscasts" style="overflow:auto;white-space:nowrap;width:555px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td class="line-numbers"><div>1<br /></div></td><td><div class="text codecolorer">          [http-kit "2.1.16"] ; Add to your project.clj.</div></td></tr></tbody></table></div>

Check this great example of a websockets app with Clojure and http-kit.

 

That’s It!

 

Cheers!,

Development Specialist, Artist and Activist
Personal Website
LuaJIT

CentOS LuaJIT Installation instructions

centos luajit installation instructions

centos luajit

centos luajit installation instructions – In the following tutorial I will show you how to install and use the LuaJIT Compiler on your CentOS box.

Before you continue you should already know what is Lua and JIT Compiler.

 

What is LuaJIT?

LuaJIT is a Just-In-Time Compiler (JIT) for the Lua programming language.

LuaJIT has been successfully used as a scripting middleware in games, appliances, network and graphics apps, numerical simulations, trading platforms and many other specialty applications. It scales from embedded devices, smartphones, desktops up to server farms. It combines high flexibility with high performance and an unmatched low memory footprint.

LuaJIT has been in continuous development since 2005. It’s widely considered to be one of the fastest dynamic language implementations. It has outperformed other dynamic languages on many cross-language benchmarks since its first release — often by a substantial margin.

LuaJIT is Copyright © 2005-2014 Mike Pall, released under the MIT open source license.

from LuaJIT website

 

Prerequisities

you need to install a package for GCC before compiling LuaJIT, you can do that by:

yum install gcc

or better, install the development tools:

yum groupinstall “Development Tools”

 

centos luajit installation instructions

Check the LuaJIT download page to check if newer version available. The next insructions are for the latest stable version currently available – LuaJIT-2.0.2

cd /opt
wget http://luajit.org/download/LuaJIT-2.0.2.tar.gz
tar -zxvf LuaJIT-2.0.2.tar.gz
cd LuaJIT-2.0.2
make && make install
# or sudo make install if you are not 'root'

Option 2: using git

OPTIONALLY, you can install LuaJIT using GIT. choose this method only if you want to be updated with the latests patches and updates and your don’t care about the risk of bugs. (NOT FOR PRODUCTION) 

cd /opt
git clone http://luajit.org/git/luajit-2.0.git
cd luajit-2.0
make && make install 
# or sudo make install if you are not 'root'
centos luajit

centos luajit

Running LuaJIT

That’s it. you have luajit installed.

consider the file ‘test.lua’:

print ("Hello, world!")

You can run (interpret) the file using

luajit test.lua

Save bytecode to test.out

luajit -b test.lua test.out
luajit test.out

more information about running luajit here.

 

 

That’s it! you have centos luajit installed.

Cheers!.

Development Specialist, Artist and Activist
Personal Website
VMWare Workstation start on boot CentOS

CentOS Gunicorn installation instructions for newbies

centos gunicorn installation instructions

centos gunicorn

centos gunicorn : In this simple tutorial I’ll explain how to install and run Gunicorn python server on your CentOS machine.

This tutorial is meant for Centos 6.4 and above but it should work on any CentOS 6.x release.

 

What is gunicorn?

From: Gunicorn – Python WSGI HTTP Server for UNIX:

Gunicorn ‘Green Unicorn’ is a Python WSGI HTTP Server for UNIX. It’s a pre-fork worker model ported from Ruby’s Unicorn project. The Gunicorn server is broadly compatible with various web frameworks, simply implemented, light on server resources, and fairly speedy.

 

Installation

Python

before you going to install the centos gunicorn server you need to insure you have the python interperter installed (it should be, as it’s installed by default on the latest CentOS releases). to check that you have python use the command:

python

command not found of course means you need to install python now.

 

Install python

first make sure your have python installed. Simple as:

yum install python

test python by typing: “python” and you should see something similar to:

python

(Ctrl+D to exit)

 

Gunicorn

Next we need to install gunicorn. for this we have (as always) several choices.

1) Using YUM. I personally don’t recommend it. I know some are happy to use the system packaging management wherever possible, but as for python I don’t think it’s the way to go.

To install gunicorn using yum:

yum install python-gunicorn

2) Using easy_install. using easy_install is a better choice for my taste to install python packages. this is how you install gunicorn using easy_install, but I recommend installing gunicorn using PIP as I will show next…

yum install python-setuptools
easy_install gunicorn

3) Using PIP: This is my RECOMMENDED way of installing gunicorn. to install PIP you actually need easy_install so the commands are:

yum install python-setuptools
easy_install pip
pip install gunicorn

Virtualenv

I can’t recommend enough to start working with virtualenv from beginning. At some point in the future, if you are going to consist with python coding, you are going to use the ‘pip update’ command to update some or all your libraries and then expect your python application to stop working.

Python libraries, as any open source library, have the freedom to sacrifice backward compatibility for new features, performance or redesign.

Virtualenv is a python virtual environment tool to ensure that your python applications will work as expected as long you don’t deliberately update some or all of the dependency libraries for that virtual environment specifically.

To install virtualenv (and virtualenvwrapper) and learn the basics read this tutorial. then create your virtual environment and install gunicorn to that environment.

# after you've install pip, virtualenv and virtualenvwrapper
mkproject myapp
workon myapp
pip install gunicorn

 

Running Gunicorn

Basic usage:

$ gunicorn [OPTIONS] APP_MODULE

so for the following myapp.py file:

# -*- coding: utf-8 -

def app(environ, start_response):
    data = 'Hello, World!\n'
    status = '200 OK'
    response_headers = [
        ('Content-type','text/plain'),
        ('Content-Length', str(len(data)))
    ]
    start_response(status, response_headers)
    return iter([data])

just run:

gunicorn -w 4 myapp:app
# Sample output
[INFO] Arbiter booted
[INFO] Listening at: http://127.0.0.1:8000
[INFO] Worker spawned (pid: 16801)
[INFO] Worker spawned (pid: 16802)
[INFO] Worker spawned (pid: 16803)
[INFO] Worker spawned (pid: 16804)
centos gunicorn

centos gunicorn

This command starts gunicorn with 4 workers on port 8000. feel free to experiment and customize the command with additional parameters.

There also command line for using Django <1.4 and Paster. read more here.

Read more about configuring Gunicorn and configuration files.

 

Deploying Gunicorn

on deployment, It’s strongly recommended to use Gunicorn behind a proxy server.

nginx

I personally prefer nginx but it’s not your only choice.

If you want to install nginx on your CentOS machine follow this installation instructions.
use this script (at github) to configure your nginx to pass request to the gunicorn process

 

Monitoring and Logging

Usally you’d want the gunicorn to be run in the background, load on boot and restart on errors. you want also the ability to monitor that process.

There are several tools for that.job, including: Supervisord, Gafferd, runit and many more…  choose what fits you best. here you have examples for monitoring gunicorn using those tools.

 

That it. enjoy playing with your centos gunicorn setup.

 

Development Specialist, Artist and Activist
Personal Website
cento tomcat

CentOS Tomcat server installation is easy!

CentOS Tomcat installation

CentOS Tomcat

centos tomcat

“Apache Tomcat is an open source software implementation of the Java Servlet and JavaServer Pages technologies. The Java Servlet and JavaServer Pages specifications are developed under the Java Community Process.” from Tomcat homepage.

 

Prerequisities

  • CentOS 6.x (I haven’t tested this on older versions but it should probably work as well) 

Check your Java installation

before we’ll continue the installation of Tomcat, the JDK (Java Development Kit) should be installed on your CentOS machine. to check for Java support use the command:

java -version

javanotfound

if bash returns ‘command not found‘ then continue to the next step and install the JDK, else skip the step and continue to Tomcat server installation.

 

Install Java Development Kit (JDK)

To install the jdk we have 2 options:

  1. Install OpenJDK – Using YUM.
  2. Install Oracle JDK – Install manually.

I’ll explore both:

Option 1: Install Open-JDK using YUM

For beginners and testing purposes you should go with this option.

Why should I use the Oracle JDK over the OpenJDK, or vice-versa? [closed]

The command to install JDK using YUM is very simple:

yum install java

yuminstall java

  • Note: use sudo if you are not logged-in with root.
  • the command will install the latest jdk (1.7 as for this date). If you want to install older version use the full name (search using: $ yum search jdk)yum-search-jdk
    You can see you can install the 1.6 version by typing: yum install java-1.6.0

Check you have installed it right:

javafound

 

Option 2: Install JDK manually

Download your required JDK here.

Note: I can’t give you an WGET command to download, because you need to Accept License Agreement before downloading any file.

You can download and install using the RPM or the tar.gz (both with x86 or x64) on your CentOS machine:

downloadjava

 

 

In case of our CentOS we can download and install the .rpm file or the .tar.gz file.

RPM can be installed ONLY by the root.
TAR.GZ can be installed be any user on the computer.

 

Option A: Install using .rpm

make sure to uninstall older installations (if any):

rpm –e <package name>

To install the jdk using the downloaded rpm use the rpm command:

rpm –ivh jdk-7u45-linux-x64.rpm

If you just want to upgrade a package you’ve already installed use the -Uvh parameter.

rpm –Uvh jdk-7u45-linux-x64.rpm

Delete the .rpm file if you want to save disk space.

Read more about installation of Oracle Java on Centos here on ItekBlog

 

Use alternatives :

alternatives –install /usr/bin/java java /usr/java/latest/jre/bin/java 20000
alternatives –install /usr/bin/javaws javaws /usr/java/latest/jre/bin/javaws 20000

alternatives

and config your default jdk (if you have more then one) using:

using:

alternatives –config java

alternatives-config

 

Test your environment

Just as in the first step: type java -version to see if your have jdk installed.

oraclejavaversion

 

Option B: Install using tar.gz

The advantage of tar.gz installation of the JDK is that we can able to install multiple version of java if required.

The archive can be installed by anyone (not only root users), in any location that you can write to. However, only the root user can install the JDK into the system location.

You need to unpack the .tar.gz file (using tar -xzf) into the  the location where you would like the JDK to be installed.

Unpack the tarball and install the jdk:

tar zxvf jdk-7u<version>-linux-i586.tar.gz

Delete the .tar.gz file if you want to save disk space.

 

Use alternatives :

alternatives –install /usr/bin/java java /path/to/jdk1.7.0_45/bin/java 2
alternatives –config java

read more about installation of jdk in the oracle documentation.

for extended installation tutorial read this post by adam in this blog.

 

JDK 1.6 vs JDK 1.7

read more on What is the difference between jdk 1.6 and 1.7 ?

 

Environment Variables

1
JAVA_HOME

 is a 

1
environment

 variable (in Unix terminologies), or a PATH variable (in Windows terminology) you need to create to point to where Java is installed. ($JAVA_HOME/bin/java should execute the Java runtime).

Why doesn’t the Java SDK installer set JAVA_HOME?

To set it for your current session type at bash:

export JAVA_HOME=/usr/java/jdk1.7.0_05
export PATH=$PATH:$JAVA_HOME/bin

To set the JAVA_HOME permanently we need to add the commands to the ~/.bash_profile file of the user.
We can also add it /etc/profile and then source it to give to all users.

 

Test Environment Variables

use the echo command to check you’ve configured the variables:

echo $JAVA_HOME
echo $PATH

echovars

 

Installing Tomcat

After we have java installed and tested we can continue to the installation of the Tomcat server.

Download Tomcat

Since Apache Tomcat is distributed as binaries, all you have to do is to download it and start it.

Download apache-tomcat-x.x.xx.tar.gz (latest version or any) from Apache Tomcat Homepage

I’ll go with the tomcat 8 – tar.gz package.

centos tomcat

centos tomcat

and using command:

cd /usr/share
wget http://apache.spd.co.il/tomcat/tomcat-8/v8.0.0-RC10/bin/apache-tomcat-8.0.0-RC10.tar.gz

tomcat-wget

verify and extract the download using::

md5sum apache-tomcat-8.0.0-RC10.tar.gz
tar xvzf apache-tomcat-8.0.0-RC10.tar.gz

and I have a /usr/share/apache-tomcat-8.0.0-RC10 folder now.

 

Test Tomcat server

Tomcat by default start on port 8080 you can start the server now by typing at bash:

cd apache-tomcat-8.0.0-RC10
./bin/startup.sh

tomcat-start

 

Now Access the tomcat by connecting your server with a web browser on port 8080.

http://localhost:8080

tomcat

If you cannot access the above Tomcat page, make sure to stop iptables (since CentOS has iptables on by default set to block the Tomcat’s default listening port 8080).

service iptables stop

to permanently disable iptables (NOT RECOMMENDED AT ALL) use:

chkconfig iptables off

Change the Tomcat server port

Locate server.xml in {Tomcat installation folder}/conf/ which is at /usr/share/apache-tomcat-8.0.0-RC10/conf in our case

Find the following:

 <!-- Define a non-SSL HTTP/1.1 Connector on port 8180 -->
    <Connector port="8080" maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="8443" acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true" />

and change the 8080 port to your required port.

 

Start on boot

To start the tomcat service on system boot create the file /etc/init.d/tomcat8 (I am using vi /etc/init.d/tomcat8) and fill it with:

#!/bin/bash 
# description: Tomcat Start Stop Restart 
# processname: tomcat 
# chkconfig: 234 20 80 
JAVA_HOME=/usr/java/jdk1.7.0_05 
export JAVA_HOME 
PATH=$JAVA_HOME/bin:$PATH 
export PATH 
CATALINA_HOME=/usr/share/apache-tomcat-8.0.0-RC10
 
case $1 in 
start) 
sh $CATALINA_HOME/bin/startup.sh 
;; 
stop) 
sh $CATALINA_HOME/bin/shutdown.sh 
;; 
restart) 
sh $CATALINA_HOME/bin/shutdown.sh 
sh $CATALINA_HOME/bin/startup.sh 
;; 
esac 
exit 0

Now set the permissions on the file and the catalina.sh file:

chmod a+x /etc/init.d/tomcat8
chmod a+x /usr/share/apache-tomcat-8.0.0-RC10/bin/catalina.sh

to start/stop/restart the service use:

service tomcat8 start
service tomcat8 restart
service tomcat8 stop

to start the service on boot use:

chkconfig --add tomcat8
chkconfig tomcat8 on

to disable it later you can use off instead of on:

chkconfig tomcat8 off

 

 

That’s it! you have your CentOS Tomcat server working and runing… 

Development Specialist, Artist and Activist
Personal Website
how to speed website

How to speed up website load time

How to speed up website load time

How to speed up website load time is important question for those that performance matters to them.

Nobody Likes a Slow Website!

 

Overview

How to speed up website?

Website optimization is a required step for production, and when is automated when possible correctly it can help you deliver your website as fastest as possible without compromising on development comfortability and code readability.

 

Test your website load time speed

How to speed up website question could be answered for your case better if you’ll use a website speed test tools. There several good websites load time speed tests available online for free. check out pingdom website speed test, Google PageSpeed tools. this are very good tools which also gives you important and valuable information and tips to speed up your website.

 

pingdom

You can also check: WebPagetest, GTmetrix or PageScoring Website Speed Test.

Some of them rates your website and/or explain what could be done to make your site faster. you can learn also a lot from loading time graphs.collect information from all the above to optimize your website to maximum.

  • If it takes more then 10 seconds for your website to load. you are doing a very bad job optimizing your website (if at all).
  • If your page load time takes several seconds then you’re ok (but you can do better then that!).
  • if your page load time takes up to two seconds then your site is in very good shape!
  • if your page load time takes less then a second then your site is sooooo fast!! and you are doing a excellent job!

if your score is bad.. continue reading How to speed up website

 

How to speed up website load time

So, how to speed up your website load time?

You can do that using several tweaks.. one at a time…

 

1. learn the waterfall. where are your bottom neck ?

Use the mentioned websites speed test graphs to learn what are the slowest parts of your website and start with them. does the problem is with your webserver or maybe the infrastructure?

How to speed up website ? Does your static files load time is the problem?

And maybe it is the dns? processing request? loading the images? loading the scripts? maybe you have bad requests?

This extreme powerfull tool will help you learn your weaks and strongs.

how to speed website

how to speed website

2. Minimize redirects

If your website on load check if it’s mobile or not, then it redirect to another page when checks the language and then redirects to another page who check the cookies and then redirect… well you’ve got the idea. Bad design pattern!

Minimize redirects!

 

3. Browser caching

Set up your server to return Expire and Cache-Control headers with static files. Setup you expire date to be within week or more is a very good timeframe (depend on how frequently you update your website static files you can setup the expire date as required).

 

4. use CDN (if possible)

Content Delivery Network (CDN) can be an important tool in achieving decent page load and web application speeds. Providers such as AkamaiEdgeCast, Amazon (CloudFront), Rackspace (CloudFiles), Google (PageSpeed) and Microsoft (Azure CDN) are providing the means to distribute your content to locations geographically closer to your customers/users, which improves the responsiveness of the application or website.

 

5. put cache server between your server and your client when possible

Although using a CDN can help with page load speeds, a CDN is not always the best solution in terms of Cost–benefit.

when configuring a cache server before your website server, and no matter if it’s apache, tomcat, gunicorn or any other html generator you can boost up clients page load dramatically.

 

caching the compiled html pages is very important speed tweak. if you have any static and/or low-rate updated pages with no problem if some users will not see the lastest updates of the html when it changes (until cache reloads).. check varnish-cache or squid-cache or nginx (with HttpProxy module) or Apache with mod_proxy.

You should think of your webapp as in several seperate layers. where one layer could answering html requests and other serving your static files. always try to find the suitable tool for this mission in terms of speed (and taste). consider serving your static files (those not on CDN) using the fastest web server for static files you can find.

 

6. Minify

A very important stage is to minify data.

  • Minify CSS files for production! there are many simple gui or command tools to do that..
    if you are using LESS, SASS or other, Never compile on client side! compiler only on server side and setup your compiler to minify results.
  • Minify your JS files. if possible, insert them as scripts into the html, or better, minify and join them inside when processing the html (But don’t forget to use Cache server!).
    If you’re using Coffee-script and template engine it should be easier as you can compile the ,coffee file to minified version and include it within your template.
  • Minify HTML. if you have static html files use command or gui tool. if you have more advanced server like python or ruby – minify them before sumbit.
  • If your template engine support preprocessors. use them to minify HTML (and everything other you can). if not – use a library (if possible).

 

7. GZip

Configure you webserver (nginx, apache,etc)  to GZip response.

Set the Vary header (Vary: Accept-Encoding header) correctly for Internet Explorer.

 

8. Caching data

If you have data you can cache in memory for your application server – DO IT.

Use Redis, memcached or any other tool you find is suitable.

It can be small data (like the number of your followers you’ve just counted from facebook, twitter and youtube JSON calls) or the Entire processed HTML.

Put expire time for each resource on your store as needed.

 

 

How to speed up website

‘ How to speed up website ‘ tutorial ends here.

hope you’ll have fun optimizing your website and now you now few important tips on How to speed up website

Using those steps I’ve managed to reduced my website load time from several seconds to only 1-2 seconds (and sometimes less then second). It’s was worth the effort!!

 

Good day (or night),

Development Specialist, Artist and Activist
Personal Website
googlelogo

Good SEO tips – Search engine optimization for your blog posts

Good SEO tips

Good SEO tips

Good SEO tips for your website / blog / posts /  etc.

Focus Keyword

The first thing you should do BEFORE writing your post is to choose a Focus Keyword.

  • A good Focus Keyword whould be the shortest and most common google search you would like to point to your post.
  • avoid using the same keyword in your website twice.

For example: The focus keyword of this post is “Good SEO“.

You can visit google and start typing “Good SEO” and you’ll see using the auto completion tool that this keyword search is the most common Keyword.

goodseosearch

Note: you can actually use other then the most common keyword (in our example, we could use the “Good SEO Tips” keyword, and It could be a great keyword too. It depends on you to choose what you think would fit best your post and is more related to the content of your post.

I could use also “Best SEO” keyword but as you can see below, is not so common used keyword:

bestseosearch

 

REMEMBER the keyword as you will need to use it in page title/url/content/etc.

 

Writing the article

Now you can start working on your article. Make sure you following:

 

Article Heading

In our example with the keyword “Good SEO“… our heading is:
“Good SEO tips – Search engine optimization for your blog posts

  • Your article heading should contain the keyword / Phrase. better when it at the beginning which is considered to improve rankings.
  • Remember that viewable limit of the heading in search engines is: 70 characters; some words will not be visible to users if it will be longer.
  • If you choose to set a longer heading, use a SEO Title

 

SEO Title

If you used title longer then 70 characters in your CMS (Like WordPress Page Title) use the HTML <title></title> to set a maximum of 70 chars title to your page.

this page title is:
<title>Good SEO tips – Search engine optimization for your blog posts</title>

 

Page titles

  • Your page title (<h1>) should contain the Keyword similar as the article heading.
  • Also make sure you have a sub header <h2> with the keyword.

 

Page URL

  • The keyword should appear in your page URL.

for example: this page URL is:
http://itekblog.com/good-seo-tips

 

Content

  • Make sure the keyword appears in your post content at least several times (at least 6+).
  • The keyword should appear in the first paragraph of the copy.
  • Write no less then 300 words in your copy.
  • run the Flesch Reading Ease test on your article. The copy scores 75.1 which is considered fairly easy to read.
  • add at least 1 outbound link(s). (<a href=””>)

 

Images

  • Add images to your article. at least 1 or 2. insert the keyword to the Alt=””. Adding the keyword as a caption for the images would be great too. look in this example:
Good SEO Tips. This is how it should be done!

Good SEO Tips. This is how it should be done!

 

Meta Description

  • Meta Description is the <meta> tag on your html. the preview on google (and other search engines) will show the meta when available instead of showing the first 156 chars of the article (including titles).
  • Use your keyword inside the meta. Preferably at the beginning. More then once will be better.
<meta name=”description” content=”Good SEO: what is the best description for my post with the keyword inside?.”/>

This article Meta is:

First thing you should do BEFORE writing your post is to think of a good SEO plan. good SEO will help your copy to reach more visitors from search engines!.

Which is exactly 156 chars!.

 

Twitter

Support Twitter too!! Using:

<meta name=”twitter:card” content=”summary”/>
<meta name=”twitter:site” content=”@ITekBlog”/>
<meta name=”twitter:domain” content=”ITek Blog”/>
<meta name=”twitter:creator” content=”@ITekBlog”/>
<meta name=”twitter:image:src” content=”http://itekblog.com/wp-content/uploads/2013/11/googlelogo-300×146.png”/>
<meta name=”twitter:image:src” content=”http://itekblog.com/wp-content/uploads/2013/11/goodseosearch.png”/>
<meta name=”twitter:image:src” content=”http://itekblog.com/wp-content/uploads/2013/11/bestseosearch.png”/>
<meta name=”twitter:description” content=”First thing you should do BEFORE writing your post is to think of a good SEO plan. good SEO will help your copy to reach more visitors from search engines!.”/>
<meta name=”twitter:title” content=”Good SEO tips – Search engine optimization for your blog posts”/>
<meta name=”twitter:url” content=”http://itekblog.com/good-seo-tips/”/>

Google+

Add link to your Google+ page. If authenticated right you will have your image near google searches.

<link rel=”author” href=”https://plus.google.com/109370438350838521961/“/>

 

For WordPress users

If you use WordPress: “WordPress SEO by Yoast” will help you do the job right!

Development Specialist, Artist and Activist
Personal Website