Simple JavaScript templating with jquery-tmpl


When writing applications where you fetch data asynchronously from the server and render it to the user using AJAX you would have to deal with building DOM elements that would markup(v) the data. One way to avoid writing ugly looking strings of HTML in your JavaScript is to fetch the markup(n) directly from the server. But that would mean blurring the lines of separation of concerns. It would be nice if you had some kind of template HTML with placeholders for data where you could drop in the data fetched from your server and render it to the user. Well, JavaScript templating engines provide just that!

I said templating engines. Yes there are several engines that would cater to such needs of yours. But in this post we are going to look at a very basic yet powerful but relatively old engine, the JQuery Template or simply JQuery Tmpl. Its pretty easy to use. This post will be a small tutorial to using JavaScript templates for people who haven’t tried templating before. We will go through the basics of JQuery templates and then see an example usage.

Continue reading

Making a comeback!


Its been over 10 or so months since I wrote a blog. I love the blogging culture. Its something everyone should try. We get so much out of blogs written by others but we never think about returning the favor. Well, I am actually talking about what I was doing these past 10 months. After I started developing Rails applications all I have been doing was reading article after article, several pages of documentation and tons of code. I learned so much from other people. I’ve faced hundreds of day to day problems from authentication to real time updates. But I never cared to write even a single blog about any of this. A friend of mine told me that he was going to try Rails and asked if I had good tutorials written in my blog. That question made me think. I’m not the greatest Rails developer on earth. And I’m not a bad one either. But I love Rails and Ruby. And if I truly love Rails then I shouldn’t just sit tight and keep churning out code. I should rather be spreading the love! So I started asking myself whether I truly love Rails or if it’s just a crush that’s going to fade away after few months like the ones I’ve had with C# and .Net, Java, Android etc. (I really don’t like the direction this blog is taking!). But I also knew that if I did not love Rails truly I would not have let go of two huge opportunities to work at large corporations and joined a totally unstable startup that was formed over a cup of coffee and few handshakes. BTW, that startup went south after few months and now I am in another awesome company. Ill talk more about this in the coming blog.

Alright. Now I know for sure that I love Rails. But the only problem is that I’m not doing anything about it. I haven’t contributed to Rails or other open source projects except to a couple of gems. So basically I haven’t done anything. That is why I’ve decided to start writing again. What I write might be very trivial for some but may make the day for others! Who cares as long as atleast one person gets benefited. That’s what the blogging culture is all about. Right? I’ve promised myself that I would post four blogs in a week. Don’t know if its too ambitious. But lets see. I wish the buses in our country had enough space to use a laptop comfortably. Funny thing is I think about this while I’m standing in the bus without a place to sit! Anyway lets see how it goes. And I realized today that my theme is so boring. Need to find a good minimalist design. That’s the way way I like it.

Id like to conclude this blog by telling you folks about the beta release of www.changebadtogood.com! Its a platform where you can share the various street level issues you face in your day to day life. It can be anything from broken roads to stagnant water and from voltage fluctuation issues to garbage disposal problems. You can locate the issue on a map and provide a rating for it. You could also attach a photograph to help describe the issue you are sharing. Its currently in beta and lacks few features. We are working hard on it whenever we get spare time and will have a decent release by the end of next week. We think and hope that this application will help start a revolution that would eventually help the government take note and cleanup our streets and roads.

That’s all for now. Cya folks!

Generate Entity-Relationship diagrams from Rails ActiveModels


Hey people! Documenting your code is really crucial for projects regardless of the size of the project. There are a lot of stuff that must be documented in a project. You have various tools to generate documentation for your code. I am going to show you a tool, a gem, that allows you to document your database models. When I was doing my Pacman (github.com/steverob/student-marks) I used an online uml tool called “dbdsgnr” to document my database. But I had to make many chances to my database schema and updating the Entity Relationship diagram I had on that website was getting tedious. At one point I dropped the whole idea of maintaining that piece of documentation. When I completed my project (pending testing), I wanted to document my database and I was searching for a tool that would document my rails project by reading the ActiveRecord models that I have. That was when I found this really cool gem called ‘rails-erd’.

This gem is maintained at github/voormedia/rails-rd and the project website is rails-erd.rubyforge.org. Installation of this gem is pretty easy. It depends upon a graphics tool called Graphviz.

You can install graphviz on Ubuntu using the command,

sudo apt-get install graphviz

Now add ‘rails-erd’ to your project’s Gemfile under the development group. So it would look like,
group :development do
gem "rails-erd"
end

Now run ‘bundle install’. This will enable your project to use the rails-erd gem.

We have installed the gem and its dependency. All we have to do now is to run a simple rake task to generate the ERD. The command is,

rake erd

This will generate “ERD.pdf” file in the application root. Neat huh? The best thing about this is that you can customize the way the output is generated by passing in many options. The various customizations are clearly explained in the project’s website. But mostly you wouldn’t need much customization. And I can tell you, the output is quite awesome. The entities are spaced well and the overall alignment of the diagram is quite brilliant. It looks like as though someone had manually aligned the entire thing. Okay, you’ll know what I am saying when you see the output pdf that I got for my project. Here it is. Click the image to get a better view.

See? Its just awesome. For more information regarding the gem visit rails-erd.rubyforge.org.

Steve

Installing Ruby, Rails, MySQL and Apache on a fresh Ubuntu 12.04 installation


The first challenge I faced when I started using Ubuntu was moving my Wubi installation inside Windows to a separate partition. Thats when I understood how one should find his/her way around the problems they face using Linux. Linux has one of the biggest support base on the internet. You can find solutions to almost all problems you face in the web. The only thing you need to do is a simple and proper Google search and you’ll fix whatever problem you have in not time at all! But unfortunately many who are new to this whole idea find it really difficult using Linux. This is because they are completed immersed in and used to the way Windows works. And so whenever they face some problem in Linux, like a dependency issue, they call you or text you and ask you to fix their problems. Unlike in windows where you get generic error messages with an error code, Linux provides verbose details about the kind of error that has occurred. People must make use of this information to find solutions to their problems.

Okay enough said! When I started learning Ruby I wanted to install Ruby on my Ubuntu 11.10 installation. But I really didnt know that I already Ruby pre-installed! Not knowing this I started installing Ruby and I faced a lotta issues. I had no idea what was happening. Then I tried removing Ruby. Then after my failed attempts to remove Ruby completely I installed RVM. Then I installed a Ruby version via RVM. But then gems like rails etc just wouldn’t install. Me being a Linux beginner back then found it really irritating and annoying to the extent that I considered dumping the whole idea of learning Ruby. But the pure elegance of Ruby and the thirst to learn Rails made me keep pushing. Finally after two days I got Ruby and Rails working on my PC without re-installing Ubuntu :P. Since then I’ve made several Ruby and Rails installations on many computers. I faced a lotta issues, especially dependency problems when installing Ruby, Rails, MySQL etc. So I decided to write this post to tell those beginners out there, the stuff they would need to properly install Rails etc.
Continue reading

A handy tool for our college staff


Hello people!! Its been a really long while since I posted anything here. Its been a really good 6 or 7 months for me both academically and personally. Been through a lot of changes, learnt new stuff, decided on my main field of interest etc! Well… the main thing is, Im Back! Ive jumped over to the Ruby on Rails platform now. And I think I love this platform. Its a joy to write code in Ruby and extra joy to use the goodies provided by Rails.

I also have undertaken a project for my college to manage marks and attendance which is almost complete. I will write an exclusive post about that in coming days.

Ok. Before I begin this post I cant help mentioning how good Chelsea are performing this season! πŸ˜€ We’re on course for a Title win! πŸ™‚

Ok okay… My college’s management is very demanding. When our university results come, the staff are required to get the results from the results websites, analyse the results and generate reports on the very same day which can be a really challenging and tiresome task given the large number of students in each batch.

I always wanted to help then out by giving them an easy way around this cumbersome job. Ive tried finding loopholes and vulnerabilities in the University Server but hit dead ends all the time. Finally I decided that the only way (atleast for me) to get the results was to parse the results from the website directly from the HTML page. I had this idea in mind but did not implement it until the results came for my 6th semester!

That night I was reading stuff when one of my friends texted me saying that the results have come. I opened the results website without any sorta excitement or expectations πŸ˜‰ coz I already know that Anna University (the uni to which my college is affiliated to) is known for throwing big surprises. And they did not dissapoint! An average result once again (for me). Well I had to do something to divert my mind. So I thought of writing the app to download the results! πŸ˜€ And my word! It was a brilliant idea πŸ™‚
Continue reading


creativentechno

Why this topic Foreign Author vs Local Author ?

If you WERE , ARE or WILL take up Engineering or any Professional Course then this topic is sure to hit your mind at some point of time.

Everyone loves to be the best Engineer hoping to work on some creative stuff and do great innovations. But the point is β€œDoes the education system of today teaches us to be creative?”

I felt i would become a notable Engineer who will be recognised for some great works one day, when i first entered my college. But they were nothing different from my school.The Whole System was focused on Marks.Education systems of today are trying to achieve marks rather than knowledge.Its so strange where some colleges even provide notes for the students to prepare for exams ! :-/ OMG Why would they do that ? We are not school kids…

View original post 618 more words

Java TicTacToe


Hello people! Wow its been a while since I posted something here…! I must say I really miss writing stuff and I promise I wont get into a ‘writer’s block’ again. Hopefully :).. A helluva lot of things happened in the last two months and I’ve got loads to say. But in this post Im just gonna publish a small application that I wrote sometime ago. Its a TicTacToe game application. There’s not much to be learnt from this particular program but I really want to get outta this impasse and hence Im posting this today.

I actually wrote this code to show off some of the really cool features of Java to one of my friends who also wrote the same application in a “C++”-esque style. And btw that friend of mine even developed code for the computer player. But after completing his code he sadly realized the basic fact that you cannot win in TicTacToe if you play perfectly!! Hehe πŸ˜€ So I did not venture into that area. Well to be honest, Im not really interested in writing AI apps. But I thought of adding Network Multiplayer functionality to this application since I love network programming. But unfortunately I havent had the time to do so.

Anywaiz the application works like this – the game is autostarted once launched and the status bar indicates which player’s turn its now and rest is just simple tictactoe! And at the end of the game the app is automatically reset.

Onto the code..


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Logger;

/**
* TicTacToe Application
* @author Steve Robinson
* @version 1.0
*/

class TicTacToeFrame extends JFrame
{

	JButton [][] buttons= new JButton[3][3];
	JTextField statusBar;
	GamePanel panel;
	Integer turn;
	GameListener listener=new GameListener();
	Integer count;

	public TicTacToeFrame()
	{
		setLayout(new BorderLayout());

		panel=new GamePanel();
		add(panel,BorderLayout.CENTER);

		statusBar=new JTextField("Player1's Turn");
		statusBar.setEditable(false);
		add(statusBar,BorderLayout.SOUTH);

		setTitle("Tic Tac Toe!");
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(400,400,300,300);
	}

	class GamePanel extends JPanel
	{

		public GamePanel()
		{
			setLayout(new GridLayout(3,3));
			turn =1;
			count=0;
			for(int i=0;i<3;i++)
				for(int j=0;j<3;j++)			{
					buttons[i][j]=new JButton();
					buttons[i][j].putClientProperty("INDEX", new Integer[]{i,j});
					buttons[i][j].putClientProperty("OWNER", null);
					buttons[i][j].addActionListener(listener);
					add(buttons[i][j]);
				}
		}
	}

	class GameListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			count++;
			JButton b=(JButton)e.getSource();
			Integer[]index=(Integer[]) b.getClientProperty("INDEX");

			//System.out.println(turn);	//turn       											//			//System.out.println("["+index[0]+"]"+"["+index[1]+"]");  							//
			b.putClientProperty("OWNER", turn);
			Icon ico=new ImageIcon(turn.toString()+".gif");
			b.setIcon(ico);
			b.setEnabled(false);
			boolean result=checkVictoryCondition(index);
			if(result)
			{
				JOptionPane.showMessageDialog(null, "Player "+turn.toString()+" Wins");
				initComponents();
			}
			else
			{
				if(turn==1)
				{
					turn=2;
					statusBar.setText("Player2's Turn");
				}
				else
				{
					turn=1;
					statusBar.setText("Player1's Turn");
				}
			}
			if(count==9)
			{
				JOptionPane.showMessageDialog(null, "Match is a draw!");
				initComponents();

			}

		}

		Integer getOwner(JButton b)
		{
			return (Integer)b.getClientProperty("OWNER");
		}

		//PrintButtonMap for Diagnostics
		void printbuttonMap(Integer [][]bMap)
		{
			for(int i=0;i				for(int j=0;j					System.out.print(bMap[i][j]+" ");
				System.out.println("");
			}
		}

		boolean checkVictoryCondition(Integer [] index)
		{
			/*Integer[][]buttonMap=new Integer[][] {
					{ getOwner(buttons[0][0]),getOwner(buttons[0][1]),getOwner(buttons[0][2])},
					{ getOwner(buttons[1][0]),getOwner(buttons[1][1]),getOwner(buttons[1][2])},
					{ getOwner(buttons[2][0]),getOwner(buttons[2][1]),getOwner(buttons[2][2])}
			};

			printbuttonMap(buttonMap); */

			Integer a=index[0];
			Integer b=index[1];
			int i;

			//check row
			for(i=0;i<3;i++)		{
				if(getOwner(buttons[a][i])!=getOwner(buttons[a][b]))
					break;
			}
			if(i==3)
				return true;

			//check column
			for(i=0;i<3;i++)		{
				if(getOwner(buttons[i][b])!=getOwner(buttons[a][b]))
					break;
			}
			if(i==3)
				return true;

			//check diagonal
			if((a==2&&b==2)||(a==0&&b==0)||(a==1&&b==1)||(a==0&&b==2)||(a==2&&b==0))
			{
				//left diagonal
				for(i=0;i					if(getOwner(buttons[i][i])!=getOwner(buttons[a][b]))
						break;
				if(i==3)
					return true;

				//right diagonal
				if((getOwner(buttons[0][2])==getOwner(buttons[a][b]))&&(getOwner(buttons[1][1])==getOwner(buttons[a][b]))&&(getOwner(buttons[2][0])==getOwner(buttons[a][b])))
					return true;

				}

			return false;

		}
	}

	void initComponents()
	{
		for(int i=0;i<3;i++)			
                         for(int j=0;j<3;j++)		{
				buttons[i][j].putClientProperty("INDEX", new Integer[]{i,j});
				buttons[i][j].putClientProperty("OWNER",null);
				buttons[i][j].setIcon(null);
				buttons[i][j].setEnabled(true);
				turn=1;
				count=0;
				statusBar.setText("Player1's Turn");

			}
	}

}

class TicTacToe {

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable(){
			public void run()
			{
				TicTacToeFrame frame=new TicTacToeFrame();
			}
		});

	}

}

The code is rather straightforward. Ive used two properties in the Buttons to store some information used for checking the winning condition. One is the “OWNER” property which indicates which user currently owns the square and the “INDEX” property which indicates the square’s index in the grid (ie [1,1], [1,2]… etc) Once any player clicks on a square, the OWNER property is updated and the victoryCondition is checked by using the OWNER properties of all the buttons. The rest of the code is self explanatory.

And adding keyboard support for the second player is a pretty easy job. As they say… “I leave that as an exercise”! Hahaha πŸ˜€ Well I really hope I get some time so that I can add network functionality to this application.
Cheers,
Steve.

—–

I forgot to attach the image icon files that will be used by the application. You can download it from here…

 http://www.mediafire.com/?d7d93v2342dxind

Just extract the contents to the folder that contains the code. Thanks to my friend “Gur Png” for telling me about this.Β 
-Steve