Author - Web Developer - Educator
Found 5 results for tag "java"
RSS Feed

HTML API: Intro to Web Notifications API

After taking some time to get back into my craft, I realized that I had missed a lot of advancements in the HTML world, especially the evolution of the HTML API. Yes, there actually is an HTML API.

While researching some of the "new" API, I came across a bunch of articles by Aurelio De Rosa via SitePoint (a lot of good stuff there), and one of the items that caught my attention was the "Web Notifications API." Now, I will say that this stuff is still experimental (see the W3C's Working Draft for Notifications, so it's not widely supported and may even disappear. But for now, it's pretty awesome!)

Anyway, I'm sure you're not here to hear read about my day, so let's get to the point of the matter: HTML API - specifically, the Web Notifications API.

I know a lot of you just want to get to the demo and play with it, so here's a Working Demo (Chrome, Firefox, and Safari 7+ only)


What are "Web Notifications"?


If you use an email system like Gmail or Outlook, chances are you've already seen something like this:
Web Notification in the wild!

Well, those are technically desktop notifications and are usually controlled by software, not browsers. (Prior to HTML5, in order to get Desktop Notifications for Gmail, you had to download the "Gmail Notifier" application, and Outlook is already a software program to begin with).

The main difference is that these notifications (like the one above) are controlled by the browser - yes, the browser can control (certain) desktop notifications, and it's actually quite simple.

How to Use It


In an HTML file, add this bit of Javascript:
var notification = new Notification("New Email Received", { icon: "mail.png" })
That's pretty much it. No external libraries to load, no frameworks to bend around your whim - it's automatically built in to most modern browsers. Now, I know what you're asking: "What? That seems too simple! There has to be more." Don't worry, that was just the extremely core concept (provided by W3C). Technically, there is one more step to do: your application must first ask for permission before doing anything with the visitor's computer. (Yes, I know this seems a bit backwards, but for privacy, I can understand - especially with all of the ActiveX IE vaulnerabilities out there). This seems that the W3C wants to get rid of, but for now, it stays. (W3C says: Warning: In designing the platform notifications are the one instance thus far where asking the user upfront makes sense. Specifications for other APIs should not use this pattern and instead employ one of the many more suitable alternatives. [ref])
Notification.requestPermission(function(){
 
    //we're declaring a new object here
 
    var notification = new Notification(title, options);
 
});
There are 3 states to the "Permission" request: default (equivilant to "denied", because a choice has not been made yet), denied (the user denied the access, and therefore the request cannot proceed), or granted (the green light). This is similiar to when a browser (and/or application) asks to automatically use your physical location to determine items near you, like so:

Geolocation API in use

If you haven't already allowed a site to display desktop notifications (or allowed for geolocation, as the above image), then it will ask you for permission before proceeding:

Asking Permission

Overall, in accordance with "best practices", here's what I have learned/uncovered/researched:

First, you need to check to see if the API is supported. As this is still in the works, it isn't fully supported everywhere (for example, only Chrome, Firefox, and Safari 7+ support this - see http://caniuse.com/#feat=notifications for the full supported range).

In order to detect if the API is supported, add this bit of JS before you go calling Notifications.
//check to see if the API is supported
 
if (!('Notification' in window)){
 
    //API not supported. Show a message or something
 
    ....
 
} else {
 
    // API is supported. Do things
 
    ....
 
}
Therefore, if you have any buttons, links, or other items that make the notifications appear based on calling them, then you can disable them safely (or, if you are basing it off of automatic notifications, like emails, scores, or calendars, you can safety defer the notifications instead of having an error thrown).

Let's get fancy


The above sample is pretty much all you need to know for calling Notifications. If you want to get a little fancy with things, try this:
title = 'Email Received';
 
options = {
 
    body: 'You have a total of 3 unread emails',
 
    tag: 'preset', //The UID of the notification
 
    icon: 'https://mail.google.com/mail/u/0/images/favicon2.ico'
 
};
Before we go into detail about this, let's break it down:

  • title: This is the title of the Notification (duh)

  • options: This outlines a few of the Instance options available in the API
    (technically, everything is optional)

    • dir: This determines the text direction that the notification will be displayed (options are auto, ltr (left to right), or rtl (right to left) (default: auto)

    • lang: The language that the notification should be displayed in (example: 'en' for 'english') - (default: default language for computer)

    • body: The message that is displayed in the notification, like the body of a letter (default: blank)

    • tag: I like to think of this as the UID (Unique IDentifier) of the notification. Examples in the W3C Draft Documentation show usage of multiple instances of notification windows, so if you want one for your Email, Calendar, Reminders, etc, you can name each appropriately instead of just having to fall back on just 1. (default: blank)

    • icon: If you have a jpg, png, ico, or any other image file to show with the notification, you can list it here (I'd recommend the full absolute path of a web file instead of locally) (default: blank)

Those are all of the options available for the Notification API right now. Maybe more will come in the future - it just depends on what the official word is on the development.

FAQ


Can the notification automatically close after a few seconds?

I'd like to say 'yes', but the answer is unfortunately, no - at least, not completely.

I've tested my demo in Chrome and Firefox and had different results. I set up a setTimeout right after the notification is shown and tested it.
notification.onshow = function() { setTimeout(notification.close, 15000) }
However, Firefox displays the notification and automatically dismisses it after 5 seconds, regardless of the timeout, and Chrome will display the notification until you close it. Apparently, the problem is that the drafted Event Handlers don't register in the browsers, yet. I've tried to implement a calling feature of event.type == 'onshow', then call the setTimeout function, but to no avail. I've also tried to match up the event.type prior to the forEach function, but yet again, nothing.

Demo

In case you missed it above, here's the live demo again. It provides a call button that calls the notification on demand. I'm sure you can play around with it and figure out how it works.

References

Mozilla Dev Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Notification W3C Draft: w3.org/TR/notifications/ Articles by Aurelio De Rosa: sitepoint.com/author/aderosa/ Aurelio's Notifications API Demo: http://aurelio.audero.it/demo/web-notifications-api-demo.html "Can I Use" browser feature comparison: http://caniuse.com/#feat=notifications


Tags:#html #api #javascript #w3c #mozilla #demos #tutorials

RSS Feed

Java Progress

XKCD
Lost on the concept? This may help explain it

As per the request of many a-people, I have started studying Java.

Personally, it's because I started an Android application course that apparently was a lot harder than I anticipated. I expected the course to be "Here's what you need to know in order to develop an Android program." Instead, it was "We're expecting you to know Java. Knowing that, create this program with these Android specifics."

Let's just say that I easily zoomed through the video lectures (it was via Coursera) and the quizzes, but the first assignment really handed me my rear end. I thought I was alone in the fact that I had absolutely no idea what to do.

The Assignment

	// Create counter variables for onCreate(), onRestart(), onStart() and
 
	// onResume(), called mCreate, etc.
 
	// You will need to increment these variables' values when their
 
	// corresponding lifecycle methods get called
Okay, no biggie. I just need to create incremental variables in Java. How do I do that? In PHP, it's just $counter = 0. How does Java do it?
	// TODO: Create variables for each of the TextViews, called
 
        // mTvCreate, etc. 
Okay, creating variables. In PHP, it's $variable = 'string';. So, is there any difference than the above step?
		// TODO: Assign the appropriate TextViews to the TextView variables
 
		// Hint: Access the TextView by calling Activity's findViewById()
 
		// textView1 = (TextView) findViewById(R.id.textView1);
Wait, what? So do I write textView1 = (TextView) findViewById(R.id.textView1);?

And that's about as far as I got before I spent hours on Google searching on how to do these specific things (yes, they are extremely specific), and combed through the Course's forums.

Apparently, I was not alone. A lot of people were complaining about "I'm a Java beginner. I don't understand any of this stuff!" Even some people were saying "I've been studying Java for about 2 years, and even the first assignment took me about 7 hours to complete." WHAT? The first assignment of courses is supposed to be progressive. "Here's how you output 'Hello World'." and "Here's how you add color." and "Here's how you add a button." - you know, progressive

At this point, I said "I need to study Java more." So much for trying to "dive" into Android. I need to backtrack a bit.

Kilobolt to the Rescue!


So I followed some links in the forum and found many, many Java tutorials and found one that I really liked: Kilobolt, a student at Duke, has a lot of tutorials of basic Java (like understanding public vs. private methods, classes, and variables, actually declaring variable types like string, int, long, boolean, and even ArrayTypes, referencing outside classes, expanding classes, inheriting classes, and more. Overall, all of these items helps you develop a 2-D game to put all of these items to use: as in "Application Learning," which is what my Python course did last year.

Kilobolt has really saved me and helped me understand Java better. I don't think I'll be an expert by the end of the week, but I'll know more than I did a few days ago. And hopefully, by knowing this, I should be able to give Android a crack again.

Fruit of my Labor


Also, in the 8 (or so) hours that I have been going through Kilobolt's tutorials, I completed 2 out of the 4 Units for Java, and completed this nice little number:

It's not much to look at, but given the fact that as of 12PM on Wednesday, I had absolutely no idea how to do that, and, as of 3AM this morning, I created that, I think it's pretty awesome. I can't wait until the full project is done!

Wait a sec - you're studying Java, NOW? Why not in College?


I'm sure some of my programmer friends are asking "Why did you wait so long to study Java? Why didn't you go into Computer Science when you were in colleg?" Personally, I never really saw the appeal of "Desktop Software" (Software that only operated on your computer and nowhere else). I always saw potential in languages like HTML, PHP, MySQL, etc, because you could post it to the web and let the whole world see, without having to do any major marketing ("Here, try my software!"). Visual Basic and C++ gave me a taste of desktop programming back in high school, and although those were building blocks for what I know today, I had more fun with PHP and the like. When I entered into college, I saw that the CS department was teaching Java, and I thought "Why study something that was current 20 years ago?" and never thought twice about it (and seeing all of these "Applet Rich" programs on the web that took at least 10 minutes to download and run on a dial-up connection steered me away from learning a "pointless, single-purpose" language). However, now since Keat is going through a CIS 250 course and learning HTML 4.01 (ok, 13 years ago - yes, HTML 4.01 came out officially in 2000), I'm re-thinking my priorities. Entrepreneurship has its advantages, and it was fun while it lasted, but I love to code. I love to learn new languages. I love to push my potential. When I entered college, "Smart Phones" hadn't even been thought of. "Android" and "iPhone" programming was something completely foreign. I never thought "By learning Java, I can learn to program phones!" Never crossed my mind.

Looking back on it, I think I would have joined my friends in the CS department and been able to accelerate my programming knowledge further than today. Aside from 1 formal HTML course, a VB course, and a C++ course (and a Python course, if you count Coursera), I've always been self-tought in languages I learn. Maybe that's a problem with me - since I've never really had any advanced formal programming training, that's a flaw I have and didn't seek it out, thinking "I can learn all of this from the web." However, while trying to apply to jobs, I think a lot of people are saying "He has a degree in Entrepr-something. We want a Programmer!" and turning me down. Instead of saying "Ha! Their loss!", maybe I should look at myself and re-examine the priorities, emphasizing my experience in difference languages. Yes, I may have a degree in Entrepreneurship, but I studied and practiced web technologies, web strategies, web marketing tactics, PHP algorithims, code-based studies, SEO methods, and more while trying to build up my business.

Last Notes


I will say that I was against learning Java for the longest time. I always saw it as "slow, decrepit software". I always told people that it's like "learning Japanese when you know Spanish," which is technically true. However, the logic planning and orientation of the language is fairly similiar to PHP. The only main differences being that:
  1. Java (from what I've seen), like Python, is heavy on the "Object Oriented" portion of OOP.
  2. You must declare all of your variables at the top and specify their types, whereas PHP can just declare variables.
  3. You must have an IDE to complile Java, where as PHP you just need a text editor and a PHP-based web server.
  4. Changing variable types is not easy whereas in PHP, it doesn't really matter (example: integer to string to float and back).

I'm sure there are a few more, but that's the basics that I've seen so far. It's certainly more structured than PHP is, but I hope I can learn more about PHP through Java, just like I learned more about PHP Objects from Python.

Day 2


After completing Unit 3 and starting Unit 4, this is what I have so far:



Tags:#java #android #coursera #kilobolt

RSS Feed

HTML5 Canvas - Bouncing Ball Example

At this point, I'm trying to stay up with HTML5 programming, and I feel like I'm a little behind the times.

So, because I'm in a Python class (via Coursera by Rice University) learning about interactive programming (more specifically, "Pong" was this week's project) and seeing Google's anniversary edition of Breakout, I felt inspired to learn how innovative HTML5 could be, so I looked up some HTML5 references and thought I'd try my hand at it.

Well, I combined by Python experiences and some HTML5 canvas examples and created some ball-bouncing joy. Want a demo? Here's a demo!

Here's a screenshot of it:
Bouncing Ball
I've taken out the clear() function to show it in motion


Even though this is very simple (as compared to some more advanced HTML5 stuff), I thought I'd go ahead and put this here for others to view/use/learn from.

Here's the HTML:
 
<!DOCTYPE html>
 
<html>
 
	<head>
 
		<meta charset='utf-8'/>
 
		<title>Ball Canvas Test</title>
 
		<link href='main.css' rel='stylesheet'/>
 
		<!--[if lt IE 9]>
 
			<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
 
		<![endif]-->
 
		<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js'></script>
 
		<script src='main.js'></script>
 
	</head>
 

 
	<body>
 
		<div id='debug'></div>
 
		<div id='container'>
 
			<canvas id='scene'></canvas>
 
		</div>
 

 
		<footer>
 
			© 2013 - Kyle Perkins
 
		</footer>
 
	</body>
 
</html>
 


Here's the CSS: (this uses a standard Reset CSS, started by Eric Meyers)
 
@import url("//dev.shadowdev.com/reset.css");
 
html, body{
 
	display: block;
 
	text-align: center;
 
}
 
#debug{
 
	position: absolute;
 
	top: 50px;
 
	right: 50px;
 
}
 
canvas{
 
	margin: auto;
 
	display: block;
 
	border: 5px #000 solid;
 
	background-color: #efefef;
 
}
 


And here's the fancy-smancy Javascript:
var canvas, ctx;
 
var circles = [];
 
var circleCount = 4; 
 
var velocity_set = 2;
 

 
function oneorzero(num){
 
	// simple function to randomly get 0 or 1
 
	if (Math.round(Math.random())==1) num *= -1;
 
	return num;}
 

 
function Circle(x,y,radius, color){
 
	// get the information stored for eac ball
 
	this.x = x;
 
	this.y = y;
 
	this.radius = radius;
 
	this.color = color;
 
	var V1 = oneorzero(velocity_set);
 
	var V2 = oneorzero(velocity_set);
 
	// velocity is set as an array so we can have the [x,y] values
 
	// [5,5] means ^,>
 
	// [-5, -5] means V,<
 
	this.velocity = new Array(V1, V2);
 
}
 

 
function clear(){
 
	// clear the screen (prevent "dirty canvas")
 
	ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height);
 
}
 

 
function getrand(){
 
	// function to randomly get a value between 0-255 (one value for R, G, and B each)
 
	return Math.floor((Math.random()*255)+1);
 
}
 

 
function drawCircle(ctx, x, y, radius, color) { // draw circle function
 
//	$('#debug').html("X:"+x+" Y:"+y);
 
//    ctx.fillStyle = 'rgba('+r+', '+g+', '+b+', 1.0)';
 
	ctx.beginPath();
 
	ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
 
	ctx.fillStyle = "rgb("+color+")";
 
	ctx.fill();
 
	ctx.stroke();
 
//    ctx.closePath();
 
}
 

 
function drawScene(){ //main draw function
 
	clear(); //clear the canvas
 
	// this is only for additional draw functionality (testing only)
 
/*	ctx.beginPath();
 
      ctx.arc(canvas.width/2, canvas.height/2, 70, 0, 2 * Math.PI, false);
 
      ctx.fillStyle = 'blue';
 
      ctx.fill();
 
      ctx.lineWidth = 5;
 
      ctx.strokeStyle = '#fc0';
 
      ctx.stroke();
 
*/
 
	
 
	var ball_info ="";
 
	for (var i=0; i 0)
 
		$('#debug').html(ball_info);
 
}
 

 
////////////////////////////////////////
 

 
$(function(){
 
	// call these setup properties upon load
 
	canvas = document.getElementById("scene");
 
	ctx = canvas.getContext('2d');
 

 
	// this is to make sure the canvas spreads across the screen
 
	ctx.canvas.width = window.innerWidth-10; // the canvas has a 5px border
 
	ctx.canvas.height = window.innerHeight-50; // 50 is only for the footer info
 

 
	var circleRadius = 25;
 
	var width = canvas.width;
 
	var height = canvas.height;
 

 
	for (var i = 0; i < circleCount; i++){
 
		// start at random position
 
		var x = Math.random()*(width*.9);
 
		var y = Math.random()*(height*.9);
 
		var r = getrand();
 
		var g = getrand();
 
		var b = getrand();
 
		ballColor = r+","+g+","+b;
 
		// add circle to array
 
		circles.push(new Circle(x,y,circleRadius, ballColor));
 
	}
 
	setInterval(drawScene, 1); // loop drawScene - aka: "draw handler"
 
});
 

 
function animate(ball, canvas, context) {
 
	// this is for adding (aka: "move") the ball based on the velocity increase/decrease
 
	// velocity is an array
 
        ball.x += ball.velocity[0];
 
	ball.y += ball.velocity[1];
 
	
 
        if( (ball.x > (canvas.width - ball.radius)) || (ball.x < (0 + ball.radius))) {
 
		// bounce off left or right wall
 
		ball.velocity[0] *= -1;
 
        }
 
	if ( (ball.y > (canvas.height - ball.radius)) || (ball.y < (0 + ball.radius))){
 
		// bounce off top or bottom wall
 
		ball.velocity[1] *= -1;
 
	}
 

 
	// draw the circles with on the (canvas, x position, y position, radius, color)
 
        drawCircle(ctx, ball.x, ball.y, ball.radius, ball.color);
 
      }


I hope this works for some people learning how to use HTML5 and the "velocity effect"


Tags:#html5 #css #javascript #python #tutorials

RSS Feed

Bachelor for a Week 2013: Day 2

I did not report in yesterday because I was in immense pain, almost flu-like symptoms. Needless to say, I spent most of the day in bed, surrounded by cats.

Today, however, was much better. For me, but not for the weather.
Garfield

(Seriously: a major downpour of rain today, snow last Thursday, great short-sleeve weather on previous weekends, then heavy gusts throughout the month....all that we're missing is hail)

I moved the Wii into the guest room/office so I could have some entertainment while I coded away. Let's just say that if I had a fridge and a toilet in this room, I'd never leave.

I watched a good chunk of Enterprise today. Now, I'm only 6 episodes away from the end. What's on my "To Watch" list next?

I also wrote 3 articles for Shadow Dev, which will be premiering over the course of the following week.

I worked on the small blurbs and larger fancyboxes of our new pricing page, which should also be premiering sometime soon.

I lastly worked on the Portal 2.0. I made some great stride with window.location.hash when trying to reload pages based on post-hash URI's. jQuery just became a lot better now.

Here's what I am happy about today:
 
$(function(){
 
	$('#db_menu').find('a').live('click', function(){
 
		var link_id = $(this).attr('id');
 
		$.ajax({
 
			type: "GET",
 
			url: "/get_box.php",
 
			data: { q: link_id },
 
			success: function(data){
 
				$('#db_box').html(data);
 
			}
 
		});
 
	});
 

 
	var path = window.location.hash;
 
	if (path==""){
 
		$('#main').click();
 
		window.location.hash = "#main";
 
	}
 
	else
 
		$(path).click();
 
});
 


I basically had to scrap the whole project and start from almost square 1. I kept the original login scripts along with the database structures in tact. My main starting point was from the Dashboard and so on.

My plan over the following week is to improve the new Portal to a point that it is ready to launch. The plan to launch Portal 1.0 with the new site launch had a small...drawback. It didn't convert with the new CSS well, and had a few delayed bugs in it, along with a good chunk missing for the Clients. My goal is for Portal 2.0 to fix that.

I don't usually like scrapping projects during development, but the pro is that the revamp comes out much cleaner than originally expected. Only time (and late nights) will tell if my feats become useful.

On a some-what related note, I was told by Keat (I don't recall if it was today or yesterday, as both days are a bit of a blur) that it is 4° out in Frisco right now. I would have been okay (that's a joke) with 4° Celsius, but we're in America, and that's 4° Fahrenheit. I do wish her the best in that frigid temperature. I'll stick with the rainy 40° here.

XKCD


Also, I used a gift code from StateFarm to order the next Star Trek/Doctor Who Crossover Vol. 2 comic book today. It only cost me $5.71 (and that was with shipping and tax). It would have cost me somewhere around $18 in a shop. Although I do support local shops, I had a gift code that I had to use or it would have expired.


Tags:#jquery #javascript #enterprise #startrek #projects #garfield #keat #articles #xkcd #doctorwho #comics

RSS Feed

A Brief History of Programming

Saw this via @GeeksAreSexy - it's amazing how the Java vs PHP and Ruby duels have progress

History of Programming


Tags:#programming #java #php #ruby #javascript #fortran #cobol #basic #c #pascal #c++ #python #perl #ruby #rails