hieuvo

Simple template engine for backend

When I try to implement automatically sending email system for my current project. I thought it would be much easier if I can apply templates to sending email, just bind different variables and send it, no more complicated logics. Tried googling around, but it seems there isn’t simple enough template engine for backend while there are many javascript template engine for frontend such as HandleBar, Mustache, etc. So I tried to make new one to suit my needs.

I chose regex as main tool to parse/ bind variables to template because I want to make it as simple as possible. I have little experience using Handlebar, so I’ll apply its expression to my template engine: {{variablesName}}. To make it more robust, I added more “if” and “loop” expressions. This template engine is written in ColdFusion, because my project uses ColdFusion. But I think it is easy to port the engine to other programming languages, cos its logics are rather simple.

function cleanUpTemplate(templateString) {
	templateString = REReplaceNoCase(templateString, "\{\{(\w+) (\w+)\}\}((?!\{\{\1 \2\}\})[.\s\S])*\{\{end\1 \2\}\}", '', 'all');
	templateString = REReplaceNoCase(templateString, "\{\{(\w+)\}\}", '', 'all');
	return templateString;
}

function parseTemplate(templateString, parameterName, parameter) {
	parameterName = lcase(parameterName);

	if (!isArray(parameter)) {

		var tmp = REMatchNoCase("\{\{if (#parameterName#)\}\}((?!\{\{if \1\}\})[.\s\S])*\{\{endif \1\}\}", templateString);

		for (var i=1; i<=ArrayLen(tmp); i++) {
			var newTmp = tmp[i];

			if (parameter eq '') {
				checkElse = REMatchNoCase(newTmp, "\{\{if #parameterName#\}\}((?!\{\{if #parameterName#\}\})[.\s\S])*\{\{else #parameterName#\}\}");

				if (ArrayLen(checkElse) >0 ) {
					newTmp = REReplaceNoCase(newTmp, "\{\{if #parameterName#\}\}((?!\{\{if #parameterName#\}\})[.\s\S])*\{\{else #parameterName#\}\}", '', 'all');
					newTmp = replace(newTmp, '{{endif #parameterName#}}', '', 'all');
				}
				else
					newTmp = REReplaceNoCase(newTmp, "\{\{if #parameterName#\}\}((?!\{\{if #parameterName#\}\})[.\s\S])*\{\{endif #parameterName#\}\}", '', 'all');
			}
			else {
				newTmp = REReplaceNoCase(newTmp, "(\{\{else #parameterName#\}\}((?!\{\{if #parameterName#\}\})[.\s\S])*)?\{\{endif #parameterName#\}\}", '', 'all');
				newTmp = replace(newTmp, '{{if #parameterName#}}', '', 'all');
			}

			templateString = replace(templateString, tmp[i], newTmp);
		}

		templateString = replace(templateString, '{{#parameterName#}}', parameter);
	}
	else {

		var tmp = REMatchNoCase("\{\{loop (#parameterName#)\}\}((?!\{\{loop \1\}\})[.\s\S])*\{\{endloop \1\}\}", templateString);

		for (var i=1; i<=ArrayLen(tmp); i++) {

			var tmpList = ArrayNew(1);

			// start to parse
			for (var j=1; j<=ArrayLen(parameter); j++) {
				var newTmp = tmp[i];

				var keys =  StructKeyArray(parameter[j]);

				for (var k=1; k<=ArrayLen(keys); k++) {
					newTmp = parseTemplate(newTmp, keys[k], parameter[j][keys[k]]);
				}

				newTmp = replace(newTmp, '{{loop #parameterName#}}', '', 'all');
				newTmp = replace(newTmp, '{{endloop #parameterName#}}', '', 'all');
				ArrayAppend(tmpList, newTmp);
			}

			templateString = replace(templateString, tmp[i], ArrayToList(tmpList, ''));
		}
	}

	return templateString;
}



a sample template

■ Customer's information
○{{lastname}} {{firstname}}
○{{lastkana}} {{firstkana}}{{if sex}}
○{{sex}}{{endif sex}}
○{{birthday}}
○{{zipcode}}{{if prefname}}
○{{prefname}}{{endif prefname}}
○{{addr1}}{{if addr2}}
○{{addr2}}{{endif addr2}}
○{{tel}}{{if fax}}
○{{fax}}{{endif fax}}
○{{mail}}{{if transportid}}
○{{transportid}}{{endif transportid}}



way to use

var emailContent = template;
emailContent = parseTemplate(emailContent, 'FirstName', FirstName);
emailContent = parseTemplate(emailContent, 'LastName', LastName);
...

// remove all expressions which aren't binded
emailContent = cleanUpTemplate(emailContent);



Notices:
- Variables in template must be lowerCase
- if and loop expressions must be well-formed

Otherwise the template engine couldn’t work correctly.

Use Mamp Pro to build a server through local network

While building website for blueup.vn, I came up with an idea to how to test website through local network. After quickly searching by google, I got an easy solution with Mamp Pro. Fortunately I have already used Mamp Pro for localhost. You just simply start Apache server by Mamp Pro then other computers in your local network can access to the server with your pc’s local ip address and port used by Apache, eg: 192.168.1.12:80.

What an easy tip!

My first app on Android Market, check it out friends!

Here it is

 

Now this website is powered by Linode’s vps service

Wow, I successfully migrated this website to Linode.com from prgmr.com. Linode vps is much more flexible and easy to control. No more lagging, no more sudden down-time…

 

I’m currently building a football-style website for 5giosang, just a little bit of research review about football.

Football is a sport and it is also known as American Football involving two opposing teams of players competing for territory on a football field using a ball and set play with the objective being to get the ball to the goal line of the opposing team by either scoring a running touchdown or kicking the ball over the post and between the uprights of the goal. Football does not have a goal defender like soccer instead it is much similar to Rugby and Australian Rules Football where all team members play a defensive and offensive role during the game.

The Rugby sport which is the predecessor to Football was invented in England during the 1860s although its background is common to soccer and dates back to at least the middle ages when groups of rival villages would compete to score a goal using filled or inflated pigs bladders that were held and run with until the player was tackled and lost control of the ball, a goal was scored when the ball was picked or carried thru to a designated point like the a post erected in the village square.

Football A Brief History of Football

In England during the 1860s a number of public schools, universities and working mens clubs got together to form a set of rules that would allow teams from different schools or districts to play against each other. The rules ultimately published were the forerunner of modern soccer but were not accepted by all teams who refused to join the new association and instead chose to create their own code known as rugby that allowed picking up the ball and tackling of opponents.

While the rules of football can be traced back to English parent games, American Football is in fact also indigenous to North America and older versions of the sport were played at Princeton in the early 1800s. The game was called ballown which involved passing and punching the ball along the field and past the opposing team to score. Eventually the game became known as football but the rules changed from time to time as new students took it up.

At Harvard University, a similar game was played on the first Monday of academic year by freshman and sophomore students which was a source of enjoyment for senior students, this game was called Bloody Monday and was considered a good ice breaker for letting new students get to know each other. The name Bloody Monday was no accident but was not a free for all, there was an objective to be met by scoring goals to win.

Shortly after the rules of soccer and rugby had been agreed in England, the US entered a new period of prosperity brought about by the end of the civil war. Rutgers and Princeton independently created their own rules of play and played the very first intercollegiate game of football on 6th November 1869. Princeton lost by two goals scoring only four goals to Rutger’s six goals and college football was born as a result of this.

Not long after intercollegiate games became popular and in 1873 representatives from Rutgers, Princeton, Yale and Columbia met to formulate a set of rules that would be used for future intercollegiate games. They established the intercollegiate Football Association and adopted many of the rules used in rugby, reducing the number of players per team from twenty to fifteen and setting the length of the field to 140 yards.

Football is very similar to rugby and in America had its dissenters namely Walter Camp of Yale who wanted a shorter playing field and less players fielded down to just eleven at any one time. As a senior member of the IFA rules committee Camp was influential and not long after the first rules were drawn up, Camp and Yale got their wish, the field was reduced to 110 yards and the number of players reduced to eleven.

American style football is proved more popular with American players and audiences than the older rugby styled game. Colleges all over the US adopted Camps new rules establishing American Football as the leading football code within a very short time. In 1882 Camp and the rules committee brought in the new system of three downs, it was a further change from rugby that allowed the team with possession of the ball to retain possession until the completion of their set play.

Many colleges banned the game for being too rough and brutal with horrific injuries being reported during the 1890s and despite enlarged rules committee representing over 60 colleges things didn’t improve much until President Roosevelt who was a keen follower of the game called on the National Collegiate Athletic Association (NCAA) which was the successor to the IFA to eliminate brutality from the game.

The forward pass rule for the game was instituted that almost immediately eliminated the mass scrums that had been the cause of so many injuries and opened up the game to wide running play that is the hallmark of American Football even today. The number of downs was increased to four and the distance of play between downs increased from five to ten yards.

The new changes to American Football were so successful that non college teams based around community athletic clubs formed and began to compete against each other, often players were paid their time and in 1920 the National Football League (NFL) was formed. The rules of play were the same as for college football with the noted difference that players became professional and no longer had to do a separate job.

Professional football and the NFL franchise had begun to dominate with ever increasing viewer numbers and network television broadcasting most major games by the 1950s. A rival association, the American Football League (AFL) started in areas not already serviced by NFL teams and quickly started to compete for the best players, network broadcasting contracts and viewing numbers.

Football

The merger of the AFL and NFL in 1970 into a 26 team franchise was described as a defining moment in American Football history. A stronger league emerged and created the Super Bowl as its defining championship game but most importantly the revenue sharing model in place has meant that every team has a chance of competing in the Super Bowl, this is in stark contrast to other codes where major teams manage to dominate their league.

Source: http://www.bighistory.net/a-brief-history-of-football/

Ethical Issues of E-commerce in Vietnam

Ambiguous Online Trading Of C2C Model In Vietnam And Its Social & Ethical Issues

Introduction

These days, along with Internet, electronic commerce has been developing very quickly including B2C, B2B and C2C. Consumer-to-Consumer (C2C) electronic commerce, the main objective of this article, involves the electronically facilitated transactions between consumers through some third parties, for example: 5giay.vn, enbac.com, rongbay.com, etc. The sites are only intermediaries and they’re just places to match consumers. Most of C2C websites in Vietnam don’t check the quality of products being offered. If any problems happen, the punishment is simply banning the account of sellers while the buyers receive the consequences. Besides this article will analyze the social and ethical problems caused by the seller’s intentional ambiguous description of items during online trading.

Common characteristics of C2Cmodel in Vietnam

Before discussing about the problems of the C2C model in Vietnam, we should learn few common characteristics of the C2C model in Vietnam.

Firstly, if something wrong happens after trading, buyers cannot undo it. Within the properties of the C2C trading, both buyers and sellers are individuals. They tend not to reveal their real contact information may not even meet face to face. As a result, they have no clues about each other. Therefore, there is no chance for the buyers to ask the sellers for new items or a refund if the products do not meet the buyer’s expectations

Second, unless someone reports a classified, there isn’t anyone to check information given by the seller of that classified. The sellers can freely use attractive words to describe and not state the full condition of the items. The buyers only discover it after a period time of use. Even experienced buyers could be confused.

Finally, although the C2C websites in Vietnam have been developed over many years (since 200?), weaknesses still exist. The most vulnerable issue is that they cannot manage and assure the personal information given by users is real. Many websites are forum-based, so users can freely and anonymously create accounts and sell items. So it’s definitely an ideal condition for scammers to “work”.

Ambiguous selling

What is an ambiguous description of items? It isn’t that sellers tell illegal information about items which they are selling. The sellers will tell the truth but not the full truth, it means they only state “good” details and hide “bad” ones. For example, if someone is selling a cellphone, the description will only state that the phone is really nice, has no scratches, has 3G and Wi-Fi works perfectly, etc. But after taking it home, the buyer finds out the microphone is malfunctioning. Consequently, the buyer gets angry and wants to give the item back immediately, but it’s not that easy. Later, the behaviors of both the seller and buyer can be grounds for potential crimes.

The source of crimes

When the buyer finds out the item is not as good as its description, he will try to give it back to seller, but in most cases they cannot (we consider the case happens in Vietnam). There are a lot of ways the buyer can react, but here are four common behaviors:

- They give in and use the item reluctantly
- They sell the item to other people at lower prices and give full the description.
- They use force to make the seller refund the item.
- They try to sell the item exactly the same the way they bought it, with the hope of getting money back!

The third way seems a violent solution, but it’s an efficient one. In the cases I have known, if the buyer uses force to deal with the seller, he is always successful. Fortunately there aren’t many people react in this way.

The first and second solutions are the nice ones. Most of people choose these ways. They may not cause serious crimes, but they will make the buyers lose their belief in online trading and probably avoid buying online in future. It would affect the overall growth of e-commerce in Vietnam in a certain extent.

But it’s a serious problem when the buyer chooses the 4th way.

Social and ethical impacts

The problem becomes serious when the buyers choose the fourth solution. As an experienced online buyer, I know that the number of those kinds of people is not small. It’s considerable. And the number will grow quickly when cheated people try to cheat other ones. New generations of cheaters will appear recursively. How horrible it is.

Legally, the sellers aren’t wrong; they do not tell lies or give wrong information. The sellers just hide “bad” information. However, ethically they are completely wrong. Instead of helping buyers choose the best and most suitable items, sellers just want to sell items as quickly and at high price as possible, without caring about what matters could happen to the buyers. Sellers also use the reason “I’m not wrong” as a way to eliminate guilt and justify their cheating. Without the feeling of shame when selling items people will have more encouragement to do higher-level violent issues.

One side effect of this problem is it will seriously affect and slow down the growth of e-commerce in Vietnam. People will lose belief in e-commerce and set a self-guard against any kinds of online trading. According to a survey “Why are you afraid of online trading?” on Facebook, 46% of people vote for “the items don’t match their descriptions” and 12% of people vote for “the buyers are anonymous”. Ambiguous online trading surely has great affect on the overall growth e-commerce in Vietnam.

Moreover, the Government will also have a strict outlook on commerce. The more social issues it causes, the more strictly government treat it. Consequently e- commerce in Vietnam falls behind.

It’s just a small ethical issue in C2C, but causes such incredible effects.

————————————————————

 

Great thanks to Xuan Phuong and Alexa McDonald for review and revise

20 things I learned

When I search around to find flip book effect library, I found this. It’s really inspirable.

http://www.20thingsilearned.com/

 

The most interesting news today

Bing Tops Google in Search Accuracy

Both Microsoft’s search engine and Yahoo’s Bing-powered search outscored Google at getting users to visit websites.

By Pete BabbInfoworld Feb 10, 2011 10:27 pm

Here’s a line of defense Microsoft could use against accusations that Bing steals Google’s search results: Bing doesn’t rip off Google because Bing is more accurate than Google. Ouch!

According to research by Experian Hitwise, Bing (and Yahoo Search powered by Bing) achieved a success rate of 81 percent for January 2011; Google, meanwhile, managed only a 65 percent success rate. Both of those figures are unchanged from December 2010.

Experian defines “success rate” as inducing a user to click on one of the search results, which does leave Google with some possible excuses. For example, perhaps users are finding the information they’re looking for right there on Google’s results page and don’t need to click on any of the links. After all, lots of people like to use Google as a spelling checker these days.

On the bright side for Google, it is still the heavyweight champion when it comes to overall usage, pulling 68 percent of all U.S. searches. However, it can’t rest on those laurels. That 68 percent figure for January is down from 70 percent in December 2010, while Bing jumped from 10.6 percent to nearly 13 percent, an increase of 21 percent month over month.

There’s still a big gap between Google and Bing when it comes to usage, but if Bing proves itself to be more accurate and more useful, Google could be looking at the first serious challenge to its search dominance.

Source

5gio sang’s logo

My work for 5gio sang (a non-profit charity organization who supports kids in shelters)

Smush.it™

I have just found this, it’s very useful tool for web developers.

http://www.smushit.com/

Smush.it uses optimization techniques specific to image format to remove unnecessary bytes from image files. It is a “lossless” tool, which means it optimizes the images without changing their look or visual quality. After Smush.it runs on a web page it reports how many bytes would be saved by optimizing the page’s images and provides a downloadable zip file with the minimized image files.

Do not link to the smushed images on Smushit.com since they will only be available there temporarily. Instead, download the zip file containing the smushed images for your web page and replace your image files with those files.