Skip to main content

NETWORK BASICS

Network A system of interconnected computers and computerized peripherals such as printers is called computer network. This interconnection among computers facilitates information sharing among them. Computers may connect to each other by either wired or wireless media. A computer network consists of a collection of computers, printers and other equipment that is connected together so that they can communicate with each other.  


Network application
A Network application is any application running on one host and provides a communication to another application running on a different host, the application may use an existing application layer protocols such as: HTTP(e.g. the Browser and web server), SMTP(e.g. the email-client). And may be the application does not use any existing protocols and depends on the socket programming to communicate to another application. So the web application is a type of the network applications. 
There are lots of advantages from build up a network, but the th…

JavaScript Coding for the Touch Interface, Device and Operating System Resources, and More

Responding to the Touch Interface
JavaScript Coding for the Touch Interface

Touch screens have become the most popular form of smartphone interface, and there are a fair number of desktop touch screen monitors in use. A touch-enabled device has a specially developed screen that senses touch data (called points), which begin in the form of pressure or electrical signals. There are two primary types of touch screens: • A resistive touch screen is made up of several layers, the topmost of which flexes when pressed and pushes into the layer underneath. Sensors detect the pressure, which is how the system knows which part of the screen has been pressed. The touch screens used in hospitals and restaurants are often resistive. • Capacitive touch screens use electrodes to sense objects touching the screen. Because the object must have conductive properties, a finger works but something like a stylus does not. Most touch-screen smartphones and computer monitors are capacitive. A touch screen processor gathers the touch data and interprets them as gestures. Depending on the hardware involved, the data is sent from the processor directly to the user application, or from the processor to the operating system to the application, where the application uses the data to perform tasks. A gesture is a technique using one or more fingers, or a pointing device like a stylus, over a control or object on the screen to provide input to a touch-enabled application. Tapping selects an object or presses a button, swiping a finger scrolls a set of photos or a list of contacts on the screen, and a pinchopen action increases the size of the screen display (zooms in). Microsoft defines gestures as shown in Table 10-1. 

JavaScript Coding for the Touch Interface, Device and Operating System Resources, and More | 245
You use the addEventListener method to attach an event handler to an HTML e lement, which can be a div, link, or anything you want. Using addEventListener lets you do something useful when an event is triggered. The following is general syntax for addEventListener:
object.addEventListener(event, eventListenerFunction);
For example, in the following code for a canvas drawing program, the startup function is called when the Web page loads. The program listens for a user touching the screen (the touchstart event), moving a finger (touchmove), and so on:
function startup() {    var el = document.getElementsByTagName("cdraw")[0];    el.addEventListener("touchstart", handleStart, false);    el.addEventListener("touchmove", handleMove, false);    el.addEventListener("touchend", handleEnd, false);    el.addEventListener("touchcancel", handleCancel, false); }  
Let’s look more closely at the handleStart function. It’s declared in the following code, the same way other functions are declared in JavaScript except that the listener function must have one argument to represent the event. You can use any identifier as the event argument, but developers often use the letter “e” or an identifier that starts with the letter “e.” 
function handleStart(evt) {    evt.preventDefault();    var el = document.getElementsByTagName("cdraw")[0];    var context = el.getContext("2d");    var touches = evt.changedTouches;  for (var i=0; i<touches.length; i++) {      ongoingTouches.push(touches[i]);      var color = colorForTouch(touches[i]);      context.fillStyle = color;      context.fillRect(touches[i].pageX, touches[i].pageY, 4, 4);    }  }  
The evt.preventDefault method stops the browser from continuing to process the touch event, which prevents it from scrolling in this instance. After getting the context (e1.getContext), the list of changed touch points is pulled from the event’s changedTouches property. Then, the program deals with the touch objects in the touchlist. PageX and pageY give the X and Y coordinates of the finger. Gesture events are triggered for multi-finger gestures. The main gesture events are: • gesturestart: Every new two-finger gesture triggers a gesturestart event. • gesturechange: When both fingers move around the screen, a gesturechange event occurs. • gestureend: Lifting both fingers from the screen triggers a gestureend event. Gesture events are types of touch events, so they receive event objects that contain touch properties. In addition, gesture events may include these properties: • scale: Indicates the amount of two-finger pinch zooming that occurred. The decimal value of the property starts at 1.0; the value is less than 1.0 when the fingers move toward each other, and the value is more than 1.0 when the fingers move apart.Now that you understand the different types of touch gestures, let’s see how they’re captured and used in applications.

Capturing and Responding to Gestures

The action an application takes in response to a gesture is called a touch event. You can use JavaScript to create touch events in touch-enabled apps. Developers can draw from a large set of input application programming interfaces (APIs) that work with touch screen data. The primary JavaScript touch events are: • touchstart: Every new finger touch triggers a touchstart event. • touchmove: When a finger moves around the surface of the screen, a touchmove event occurs, which tracks the finger movement. • touchend: Lifting the finger from the screen triggers a touchend event. • touchcancel: The touchcancel event is triggered when the device launches another application.

The touchcancel event helps the browser keep track of active touch objects in the touchlist. It can also reset variables used during touchstart and touchmove events. However, developers seldom use the touchcancel event, so you won’t see it very often in scripts.

In JavaScript, the touch object detects input from touch-enabled devices. You reference touch objects in the touchlist, which includes all of the points of contact with a touch screen. A single tap has one entry in the touchlist, whereas a three-finger gesture would have a total of three entries. Touch objects are read-only and have the following properties: • identifier: A unique identifier for the touch • target: The HTML element that the touch affected • clientx: Horizontal position, relative to browser window • clienty: Vertical position, relative to browser window • pagex: Horizontal position, relative to HTML document • pagey: Vertical position, relative to HTML document • screenx: Horizontal position, relative to the screen • screeny: Vertical position, relative to the screen Each touch event includes three different touchlists: • touches: A list of all touch points currently in contact with the screen • targetTouches: A list of touch points currently in contact with the screen and whose touchstart event occurred within the same node (inside the same target element as the current target element) • changedTouches: A list of touch points that caused the current event to be fired; for example, in a touchend event, this is the finger that was removed• rotation: Indicates the amount of two-finger rotation that occurred. The value of the rotation is in degrees; positive values are clockwise, and negative values are counterclockwise. You can combine gesture events with CSS visual effects to enable scaling and rotation. For example, the following code implements the gesturechange event handler with scaling and rotation: document.addEventListener('gesturechange', function(event) {        event.preventDefault();    console.log("Scale: " + event.scale + ", Rotation: " + event.rotation); }, false);
An implied listener function is being created in this example. The event handler passes the event object as an implied argument called “event” to get specific information about the event. Screens that can display in portrait or landscape trigger an orientation-changed event when the user changes the orientation of the screen. You can use orientation-changed to test for the rotation of the device. Each event has a numeric value representing the scale and rotation values.

DETECT TOUCH SCREEN CAPABILITY GET READY. 

To check whether a user’s device is touch-enabled, perform the following steps: 1. In an editing or app development tool, create a file named L10-touch.html with the following content:
<!doctype html>
<html>  <head>    <title>Detect Touch Screen</title>    <meta charset="utf-8" />
    <style type="text/css"> #canvas{background-color: dodgerblue;}    </style>
    <script type="text/javascript">
document.addEventListener("DOMContentLoaded", init, false);
function init() { var canvas = document.getElementById("canvas");
if ("ontouchstart" in document.documentElement) { canvas.addEventListener("touchstart", detect, false); 

else { canvas.addEventListener("mousedown", detect, false); }     }
     function detect() { if ("ontouchstart" in document.documentElement) { alert("Touch screen device detected!"); } else { alert("No touch screen device detected."); } }
   </script>
  </head>
  <body>   <canvas id="canvas" width="100"   height="100"></canvas>  <br />  <p>Click the box to start touch screen detection.</p>  </body> </html> This code draws a canvas box on the screen, followed by a text line that states Click the box to start touch screen detection. The initial function assigns the canvas element, and then the event listener listens for a touch event or a mouse click. If the user has a touch screen and touches the box, the program displays a Touch screen device detected message. If a mouse click is 
 detected, the No touch screen detected message displays. 2. Open L10-touch.html in a Web browser. Your display should look like Figure 10-1.
3. Click the blue box. If you’re working on a computer with an ordinary monitor, the alert box shown in Figure 10-2 appears. Otherwise, an alert box appears that displays the text Touch screen device detected!
4. Click OK to close the alert box. 5. Close the file and Web browser but leave the editing tool open if you plan to
 complete the next exercise during this session.

Coding Additional HTML5 APIs

As you’ve learned throughout this book, there are many HTML5 APIs available that provide new and enhanced functionality while easing development of HTML documents. What hasn’t been specifically pointed out is that there are actually two versions of the HTML5 specification: one published by the W3C and another by WHATWG. The Web Hypertext Application Technology Working Group (WHATWG) was formed by Apple, the Mozilla Foundation, and Opera Software to define and document the HTML5 specification. The WHATWG Web site at http://developers.whatwg.org/ is a good resource for learning more about new HTML5 elements and how to use them. The living HTML specification maintained by WHATWG contains additional APIs to those described in the original W3C HTML5 specification. The applicable APIs covered in the following sections are Geolocation, Web Workers, WebSockets, and File API.
The Geolocation API defines an interface that provides a device’s location, usually using l atitude and longitude coordinates. The API exposes the latitude and longitude to JavaScript in a Web page using the geolocation object. The two primary geolocation functions are as follows: • getCurrentPosition: Gets the device’s current geographic position using the getCurrentPosition method. • watch-position: Watches the device’s position as it changes over time using the watch-position method, and generates an event if a change occurs. Calling clear-watch stops the watch.
The following is a simple example of a call to getCurrentPosition. The show-map callback function receives the latitude and longitude coordinates:
navigator.geolocation.getCurrentPosition(show-map); function show-map(position) {   var latitude = position.coords.latitude;  var longitude = position.coords.longitude;  // Code to display a map }
You can present location data to users in two ways: geodetic and civic. Geodetic data provides raw location data, such as longitude and latitude, or meters. Civic data is location data that’s more easily understood by humans, such as a map or an address like 637 Park Street. The Geolocation API returns geodetic data from the functions, which you can present in its raw form or combine with an online mapping service like Bing Maps to display a map with a pointer to the user’s location. Be aware that privacy is a major concern for many users. Therefore, the Geolocation API allows users to hide their location, and many implementations prompt the user for permission to return the user’s location coordinates. Geolocation is geared mainly for smartphones and other mobile devices, and doesn’t work consistently for desktop computers. When a device has no means of locating itself, the API generates a position unavailable error.

CREATE A GEOLOCATION APPLICATION GET READY.

 To create a geolocation application that displays the user’s current latitude and longitude, perform the following steps: 1. In an editing or app development tool, create a file named L10-geolocation.html with the following content:
<!doctype html> <html> <head>   <title>Geolocation Example</title>   <meta charset="utf-8" />   <script> var messageDiv =    document.getElementById('message');function initLocation() {
var geolocation = navigator.geolocation;
if (geolocation) { try {   navigator.geolocation.getCurrentPosition( successCallback, errorCallback );
} catch (err) { messageDiv.innerHTML = 'Error'; } } else { messageDiv.innerHTML = 'Your browser does not support geolocation.'; }
    }
function successCallback(location) { message.innerHTML = "<p>Latitude: " +    location.coords.latitude + "</p>"; message.innerHTML += "<p>Longitude: " +    location.coords.longitude + "</p>"; }
function errorCallback() { messageDiv.innerHTML = 'There was an error    looking up your position'; }   </script> </head> 
<body onload="initLocation()">    <div id="message">Looking Up Location</div> </body> </html>
This code is a good test of the HTML5 geolocation API. Here’s how the code works: navigator.geolocation.getCurrentPosition requests a position, which polls the hardware device’s GPS feature or a computer’s router for location information. If successful, the successCallback function displays the latitude and longitute coordinates onscreen. If the information is not available, the There was an error looking up your position message appears. 

2. Open L10-geolocation.html in a Web browser. If the browser supports geolocation, you should be asked for your permission for the browser to track your physical location, as shown in Figure 10-3. Click Allow once or a similar command, depending on the browser you’re using.

Understanding Web Workers

 Web Workers are APIs that allow scripts to run in the background as parallel threads. These background threads can connect to multiple Web pages, fetch real-time data like stock updates, make network requests, or access local storage while the main HTML document responds to the user input like tapping, scrolling, and typing. Web Workers help keep your user interface responsive for users. Web Workers objects run in isolated threads—they do not act directly on the main HTML document or the DOM. That means you don’t use document or getElementById in your script. (You can use setTimeout, setInterval, and XMLHttpRequest.) Instead, Web Workers pass information through messages, executing code from a JavaScript file separate from the main HTML document. To use a Web Worker, you first need to create a Worker object in your main HTML  document, as follows:
var worker = new Worker('worker.js');
When the browser interprets this line, it creates a new worker thread, and then starts it with the following method:
worker.postMessage();
The postMessage() method accepts a string or JSON object as its argument. All browsers support passing a string message, but only the latest versions of the major browsers support JSON object passing. As a simple example of message passing with a Web Worker, the following is a script in the main HTML document:
var worker = new Worker("doWork.js"); // Watch for messages from the worker worker.onmessage = function(e){  // The message from the worker e.data }; worker.postMessage("start");
The following code might appear in the doWork.js file:
onmessage = function(e){  if ( e.data === "start" ) {    // Perform an action or computation    done()  } }; function done(){  // Send results to main document  postMessage("Hello, I am done"); }
Instead of using the onmessage event handler, you could use addEventListener() in the main HTML document, like this: 
worker.addEventListener('message', function(e) { 

CREATE AND RUN A WEB WORKER GET READY. 

To create and run a Web Worker, perform the following steps: 1. In an editing or app development tool, create a file named L10-worker.html with the following content: <!doctype html> <html lang="en"> <head> <script> var worker = new Worker('doWork.js');
// Send a message to start the worker and pass a variable to it var info = 'Web Workers'; worker.postMessage(info);
// Receive a message from the worker worker.onmessage = function (event) {  // Do something  alert(event.data); }; </script> <title>Web Workers Example</title> </head> <body> </body> </html> 2. Create a JavaScript file named doWork.js in the same folder as worker.html, with the following content:
onmessage = function(event) {  var info = event.data;  var result = 'Hello ' + info + ' everywhere';  postMessage(result); }; 3. Open L10-worker.html in a Web browser. The alert box should display, as shown in Figure 10-5.
4. Click OK to accept the settings and close the alert box. 5. Close the files and Web browser but leave the editing tool open if you plan to
 complete the next exercise during this session.

Understanding WebSockets

WebSocket is an API that offers full-duplex communication, which is simultaneous two-way communication, through a single socket over the Internet. Developers use WebSockets mainly for real-time Web applications like chat, multiplayer online gaming, and stock quotes. To understand the power of WebSockets, you need a little background on what came before. Originally, when a user entered a URL in a Web browser or clicked a link on a Web page, the browser contacted the appropriate Web server for the page. Whenever the user wanted to update or refresh something on the page, the browser would fetch a whole new page from the Web server. You might still see this when clicking through a photo gallery. Each time you click to a new photo, the page refreshes and you sometimes have to scroll back to the gallery. Technologies such as AJAX made it possible to refresh only a portion of a Web page. Comet and similar “push” technologies introduced polling, in which a browser would contact the Web server periodically (sometimes constantly) to see if new information was available to present to the user. The problem with polling is that many requests are made to the server to check for new data, which can cause performance problems. WebSocket technology creates a persistent connection between a client and a Web server, so that either one can send data to the other at any time. The persistent connection greatly reduces the amount of overhead required for the communication channel. To establish a WebSocket connection, the client and server change from the HTTP protocol to the WebSocket (WS) protocol during their initial handshake. After a connection is established, the client and server can exchange both text and binary files in fullduplex mode. There are three primary events associated with WebSocket communications: • onopen: When a socket opens • onmessage: When a message has been received from the Web server • onclose: When a socket closes You’ll see each of these events in the code snippets in this section. First, let’s look at the JavaScript that opens a Web-socket connection: var host = 'ws://example.com'; Notice the use of ws rather than http in the URL. You can also use wss for secure WebSocket connections, just like you use https for secure HTTP connections. After initializing a Web connection, you should test it to make sure it was successful. You can test by using the onopen event handler to know when the connection is opened. Here’s one example that opens an alert box when the socket opens: socket.onopen = function(){      alert("Socket open");  }  

Here’s another onopen example that displays a message: socket.onopen = function (openEvent) { document.getElementById("serverStatus").innerHTML = 'Socket open'; }; Now you’re ready to send and receive data. To send text-based messages to the server, use the send ('message') method on the connection object. The code for sending a text-based message is: socket.send('message'); A simple way to send binary data is to use a binary large object (Blob). A Blob is simply a data type that can store binary data, like images or multimedia files. To send a file as a Blob, you can use this code: var file = document.querySelector('input[type="file"]').files[0]; socket.send(file); Then, to receive messages from the server, you can use the onmessage callback: socket.onmessage = function(msg){      alert(msg); //Received! } Finally, to close a connection, use the onclose event handler, like this: socket.onclose = function() {     alert("Connection closed."); }; The WebSockets API specification is still in draft format as of this writing, and WebSockets is not supported by all Web browsers. To get a feel for using WebSockets, complete the following exercise. 

CREATE A WEB-SOCKET TO TEST BROWSER COMPATIBILITY GET READY. 

To create a WebSocket that tests whether your browser supports WebSockets, perform the following steps: 1. In an editing or app development tool, create a file named L10-WebSocket.html with the following content:
<!doctype html> <html> <head> <script type="text/javascript">    function WebSocketTest() { if ("WebSocket" in window) { alert("Your browser supports    WebSockets."); // Open a WebSocket var socket = new   WebSocket("ws://localhost:9998/echo"); socket.onopen = function () { // Connected, send data socket.send("Connected"); alert("Connected."); };
socket.onmessage = function (e) { var received_msg = e.data; alert("Message received.");
};
socket.onclose = function () { // WebSocket closed alert("Connection closed."); };
} else { // Browser doesn't support WebSockets alert("Your browser does not support    WebSockets."); }    } </script> </head> <body> <div>   <a href="javascript:WebSocketTest()">Click to run    WebSocket demo</a> </div> </body> </html> 2. Open L10-WebSocket.html in a Web browser. 3. Follow the prompts displayed by the program. If your browser supports WebSockets, the first alert box that appears is shown in Figure 10-6.

Using File API for File Uploads

The File API allows a browser or application to upload files from local storage to a remote server without the need for a plug-in. For example, using File API, you can make an Open dialog box appear and allow the user to select an image file. When the user clicks OK, a thumbnail of the image file displays in the Web application. Developers use File API in games and applications that work with media files, in offline mail clients, photo editors, and video players. The File API uses several interfaces for accessing files from local storage. Some of the  interfaces are: • File: Includes read-only informational attributes about an individual file, such as its name and media type, and reads in the file as a URL • FileList: An array-like sequence of File objects; includes dragging a folder of files from local storage • Blob: Provides access to raw binary data • FileReader: Provides methods to read and display a file An easy way to load a file is to use the input type="file" element. Using the input type="file" element returns the list of selected File objects as a FileList. The code might look like this: <input type="file" id="input" onchange="handleFiles(this.files)">
To enable the user to load multiple files at once, add “multiple” before onchange, as follows: <input type="file" id="input" multiple onchange="handleFiles(this.files)">

CHECK BROWSERS FOR FILE API COMPATIBILITY GET READY. 

To check the major browsers for File API compatibility, perform the following steps: 1. In an editing or app development tool, create an HTML file with the following  content: <!doctype html> <html> <head>    <meta charset="utf-8" />    <title>File API Browser Support Check</title> <script> if (window.File && window.FileReader && window.FileList && 
 window.Blob) {    alert('Hurray! This browser supports File APIs.'); } else {  alert('This browser does not fully support File APIs.'); } </script> </head>
<body> </body> </html> The if statement checks for support of the File, FileReader, FileList, and Blob APIs. If the APIs are supported, the “Hurray” message appears. Otherwise the second message appears. 2. Save the files as L10-FileAPI-checkBrowser.html and open it in each of the major Web browsers. The display shown in Figure 10-8 appears when File APIs are not supported.

Accessing Device and Operating System Resources

As you learned in Lesson 1, the Windows Runtime (WinRT) is the operating system environment responsible for access to devices, media, networking, local and remote storage, and other items. This is the environment in which developers test their applications and where users run the apps. A developer can use APIs and the runtime environment to request access to user devices and memory within an application. The following sections walk you through in-memory resource access, and device and operating system access, which are functions of the WinRT.

Accessing In-Memory Resources

The Web Storage API provides a client-side method for saving session information locally within the browser or device memory. The localStorage method allows users to save larger amounts of data from session to session (persistent data), whereas the session-storage method keeps data only for one session (until the browser is closed). The data is stored in key/value pairs for both types of Web storage. Local storage is persistent data and is useful for things like online to-do lists, contact lists, calendars, and saved shopping cart data. You want this information to be available to the user after the browser closes and the user reopens it at some point. The information is held in persistent memory of Web applications and mobile devices. Session storage is temporary data that’s kept for only one session, until the browser is closed. All of the data in a session is saved in session storage and then erased from session storage when you close the browser tab or window. An example of the proper use of session storage is a ZIP code lookup program. In JavaScript, you use the localStorage and session-storage objects with the following methods to manage key/value pairs: • setItem(key,value): Adds a key/value pair to the storage object • getItem(key): Retrieves the value for a specific key • removeItem(key): Removes a key/value pair from the storage object • clear():Removes all key/value pairs from the storage object This is the generic code for adding a key/value pair to a session-storage object: sessionStorage.setItem('key', 'value'); var myVar = sessionStorage.getItem('key');

This is the generic code for local storage: localStorage.setItem('key', 'value'); var myVar = localStorage.getItem('key'); The getItem() and removeItem() methods use the same syntax. Using sessionStorage.clear() removes everything from the list. 

USE THE LOCALSTORAGE OBJECT GET READY. 

To save a value to local storage, perform the following steps: 1. In an editing or app development tool, create a file named L10-localStorage.html with the following content:
<!doctype> <html> <head> <title>localStorage Example</title>    <script type="text/javascript"> function load() { var value = localStorage.getItem("myKey");
if (!value) { alert("Item not found, adding to localStorage"); localStorage.setItem("myKey", "myValue"); } else { alert(value + " found!"); } } </script> </head> <body onload="load()"> </body> </html> 2. Open L10-localStorage.html in a Web browser. Because the value "myValue" has just been passed and the session is current, you should receive an alert box similar to Figure 10-9. Click OK to accept the settings and close the alert box.
3. Close the Web browser, and then reopen L10-localStorage.html. Now you should see the alert box shown in Figure 10-10. The value was saved in local storage and persisted between browser sessions.
4. Close the Web browser. 5. In the HTML document, change each instance of localStorage to session-storage. 6. Save the file as L10-sessionStorage.html and open it in a Web browser. Notice what displays in the alert box. 7. Close the Web browser, and then reopen L10-sessionStorage.html. 8. The alert box message should be the same—that the value was not found. This is because you closed the Web browser, which cleared the value from session memory. 9. Press Ctrl+R or click your browser’s refresh button. An alert box appears, confirming that the value is found. 10. Close the file and Web browser but leave the editing tool open if you plan to
 complete the next exercise during this session.

Accessing Hardware Capabilities

HTML5 is considered platform-independent. That means you can use the HTML5 family of technologies to create Web pages and apps that run on different desktop and mobile device operating systems, such as Microsoft Windows, Internet Explorer, and Windows Phone. You can also run them in Mac OS X, Android, iOS, and Blackberry OS. Because HTML5 is built on an open standard, users of HTML5 apps do not have to download a plug-in or use devices 
that have plug-in support. Instead, you can use any Web browser, whether on your PC or mobile device, and get the same rich Web experience. A program or interface that runs software that produces similar results on a wide variety of hardware is also called device-independent. With HTML5, along with CSS and JavaScript, you can easily create device-independent applications. Some of hardware capabilities you can access with device-independent applications are GPS, Accelerometer, and camera. In a nutshell, you use JavaScript to access the Windows Runtime APIs for hardware devices.

UNDERSTANDING GLOBAL POSITIONING SYSTEM (GPS) 

Global positioning system (GPS) hardware, which is usually a chip or circuit board, is a receiver that communicates with satellites to provide a device’s precise location in longitude and latitude coordinates. Most modern phones are now equipped with GPS functionality, as are laptops with WiFi and/or cellular broadband. The Geolocation API you learned about earlier in the lesson works with the GPS chip to gather raw geolocation data.

UNDERSTANDING ACCELEROMETER

 Many mobile devices include orientation and motion sensors, which detect the orientation and motion of the device and use that information as input. For example, as a user holds the device and swings his arm back and above his head, and then swings the arm forward as if executing a tennis stroke, the device recognizes and records the motion. An accelerometer is a device that measures acceleration, which is a change in speed or direction over a period of time. The Accelerometer sensor detects forces applied to the device, such as movement (up, down, sideways) and gravity. In Windows-related systems, specific APIs retrieve raw motion data from Accelerometer sensors, and then the Motion API combines the data from those sensors and crunches the numbers that result in easy-to-use values. The devicemotion event provides the acceleration of the device, in Cartesian coordinates, and the rotation rate. A snippet of JavaScript that receives devicemotion events is as follows: window.addEventListener("devicemotion", function(event) { // Process event.acceleration, event.accelerationIncludingGravity, // event.rotationRate and event.interval }, true);

Two related sensors are Compass and Gyroscope. The Compass sensor determines a device’s orientation relative to the Earth’s magnetic north pole. You can use the Compass sensor along with the appropriate APIs to create apps for geocaching and navigation, for example. The Gyroscope sensor uses motion (rotational forces) to detect the rotational velocity of the device along its three primary axes.

ACCESSING A CAMERA 

The W3C HTML Media Capture specification uses a capture attribute with the input element to capture data from cameras, camcorders, webcams, microphones, and so on. For example, the following generic code uploads an image from a device’s camera: <input type="file" accept="image/*" capture="camera">
However, this construct has limited support, working only with select mobile browsers. There is movement toward the getUserMedia() method along with the navigator object as an alternative, which accesses a device’s local camera and microphone stream. getUserMedia plays well with the new HTML5 audio and video elements. Here’s a code snippet that provides access to a device’s hardware: navigator.GetUserMedia('audio, video', function(localMediaStream) {  var video = document.querySelector('video');  video.src = window.createObjectURL(localMediaStream); }, onFailSoHard);
The specification is in flux, so you should expect changes over time as the specification is modified and browser vendors adopt the technology.  

EXPLORE HARDWARE CAPABILITIES GET READY. 

To explore hardware capabilities, perform the following steps: 1. Visit the “Quickstart: detecting location using HTML5” MSDN Web page at http://bit.ly/LerKIW. 2. Copy and paste the JavaScript sample code into an editing or app development tool, and save it as L10-geo-ms.html. 3. Open L10-geo-ms.html in a Web browser and test the application. 4. Compare the longitude and latitude coordinates with L10-geolocation.html, which you created in an earlier lesson. 5. Visit the Microsoft “Quickstart: Responding to user movement with the accelerometer” MSDN Web page at http://bit.ly/J7OA58. 6. Read through the JavaScript sample code and the HTML sample markup. 7. Answer the following questions, researching parts of the code and markup if necessary: a. Which function establishes a connection with the default accelerometer? b. Which function captures new accelerometer data? c. Which elements write new values to the screen? 8. Close all open files and programs.

ACCESSING A CAMERA 

The W3C HTML Media Capture specification uses a capture attribute with the input element to capture data from cameras, camcorders, webcams, microphones, and so on. For example, the following generic code uploads an image from a device’s camera: <input type="file" accept="image/*" capture="camera">
However, this construct has limited support, working only with select mobile browsers. There is movement toward the getUserMedia() method along with the navigator object as an alternative, which accesses a device’s local camera and microphone stream. getUserMedia plays well with the new HTML5 audio and video elements. Here’s a code snippet that provides access to a device’s hardware: navigator.GetUserMedia('audio, video', function(localMediaStream) {  var video = document.querySelector('video');  video.src = window.createObjectURL(localMediaStream); }, onFailSoHard);
The specification is in flux, so you should expect changes over time as the specification is modified and browser vendors adopt the technology. 

EXPLORE HARDWARE CAPABILITIES GET READY. 

To explore hardware capabilities, perform the following steps: 1. Visit the “Quickstart: detecting location using HTML5” MSDN Web page at http://bit.ly/LerKIW. 2. Copy and paste the JavaScript sample code into an editing or app development tool, and save it as L10-geo-ms.html. 3. Open L10-geo-ms.html in a Web browser and test the application. 4. Compare the longitude and latitude coordinates with L10-geolocation.html, which you created in an earlier lesson. 5. Visit the Microsoft “Quickstart: Responding to user movement with the accelerometer” MSDN Web page at http://bit.ly/J7OA58. 6. Read through the JavaScript sample code and the HTML sample markup. 7. Answer the following questions, researching parts of the code and markup if necessary: a. Which function establishes a connection with the default accelerometer? b. Which function captures new accelerometer data? c. Which elements write new values to the screen? 8. Close all open files and programs.


Comments

Popular posts from this blog

What if Analysis

What-If Analysis What-If Analysis in Excel allows you to try out different values (scenarios) for formulas. The following example helps you master what-if analysis quickly and easily.  Use scenarios to consider many different variables  A scenario is a set of values that Excel saves and can substitute automatically in cells on a worksheet. You can create and save different groups of values on a worksheet and then switch to any of these new scenarios to view different results. 
Create Different Scenarios 
Note: You can simply type in a different revenue and Cost into cell B2 and B3 respectively to see the corresponding result of a scenario in cell B4. However, what-if analysis enables you to easily compare the results of different scenarios.  
I. On the Data tab, click What-If Analysis and select Scenario Manager from the list. The Scenario Manager Dialog box appears  II. Add a scenario by clicking on Add.  III. Type a name (e.g. “First Case”), select cell B2 and B3 (represents “Revenue” and “…

PROFESSIONAL ENGLISH

Asking For and Giving Opinions on Likes and Dislikes

Words Meaning Sample Sentence Opinion A statement or judgment formed about some matter. Bhoomika gave her final opinion on the company’s matter. Dialogue A conversation between two or more people. Her dialogue stated her opinion about the company’s matter. Expression The action of making known one’s thought or feelings. Her expression was sad at the meeting. Frank An open, honest, and direct speech or writing Bhoomika is very frank with her friends. Recover Return to normal state of health, mind or strength. The company’s economic crisis will be recovered soon. Turmoil A state of great disturbance. The company is facing financial turmoil. Economics The branch of knowledge concerned with the production, consumption, and transfer of wealth. Bhoomika studied Economics at the State University. Betrayed Expose to danger by treacherously giving information to an enemy.

DAILY LIFE VOCABULARY

Apology Etiquette and Office Vocabulary 

Chapter Vocabulary

Word Meaning Sample Sentence Stressed A state of any mental or emotional tension. Ram seems much stressed after his poor exam. Launch An act of instance of starting something. The government launched a new scheme for the poor people. Error A mistake Ravi found a grammatical error in his new grammar book. Scold Blaming someone for any wrong doing Bhuvan scolded his employees for their poor performance. Accuse Claiming that someone has done something wrong. Bharati accuses her friend Chaya for stealing her necklace. Fair Good and honest Ravi got promoted for doing a fair job. Ashamed Embarrassed or guilty because of one’s action. <