Opensourceforyou201504

Page 1

Make Your Own IVR With Asterisk

Manage Your Marketing Activities With CampaignChain

Volume: 03 | Issue: 07 | Pages: 108 | April 2015

Awesome Tools For

Web Development! Creating Great Web Experiences With Drupal Bootstrap: Building An Interactive Web Page Try Out The Eclipse Editor To Create Web Apps Developing Games For The Web

Android Lollipop: What’s In It For Enterprises?

An Interview With Sushanto Mitra, Founder And CEO, Lead Angels



www.unotechacademy.com

Industry is adopting

Open Source Are you adopting the skills? Open Doors to a career in Open Source

COURSES OFFERED RHCE RHC 77(120 (120 hours) hours)

PostgreSQL Postgres Admin Admin

Openldap (40 hours) OpenLDAP

JBoss PHP & Admin MYSql

PHP & Admin JBoss MySql

Jquery jQuery (40 hours)

Apache ApacheSpark Stack

Spring Hibernate Spring&Hibernate

RHEV (40 hours)

Ngnix (40 hours) Nginx

(40 Hours)

(40hours) hours) (40

(40Hours) Hours) (40

(40 Hours)

(40Hours) Hours) (40

For more details, contact Omar on (+91 887 968 5760) or write to omar@unotechsoft.in Unotech Academy, #139, DamjiShamji Bldg. Nr. BMW service Center, Mahakali Caves Rd, Andheri (E). Mumbai. 400093


Contents Developers 20

Talking to the Kernel through Sysfs

30

How to Install Moodle on a LAMP Server

32

Use Haskell to Access Two Popular Databases

37

Bootstrap: Building an Interactive Tourism Web Page

40

Writing a Basic Framebuffer Driver

45

Multi-device 43 Develop Web Based Games with HTML5

Popular Open Source IDEs for Web Development

47

Qt5: GUIs with QtQuick and QML

54

The Link+ Project for Linux Kernel Developers

59

Developing a Web-app Using the Eclipse Editor

68

Face-off with Sizeof()

73

Creating an Awesome Web Experience with Drupal

ADmin 79

FSlint: A ‘Laundromat’ for File Systems

87

An Overview of OpenShift

A Popular Software 63 Selenium: Testing Tool You Can Rely On

REGULAR FEATURES 07 08

Offers of the Month

10

FOSSBytes

You Said It...

4 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

24 104

Editorial Calendar Tips & Tricks



Contents

Editor

Rahul chopRa

Editorial, Subscriptions & Advertising Delhi (hQ) D-87/1, Okhla Industrial Area, Phase I, New Delhi 110020 Ph: (011) 26810602, 26810603; Fax: 26817563 E-mail: info@efy.in

Missing Issues E-mail: support@efy.in BeNGAlURU Ph: (080) 25260394, 25260023 E-mail: efyblr@efy.in

Customer Care

e-mail: support@efy.in

Back Issues Kits ‘n’ Spares New Delhi 110020 Ph: (011) 26371661, 26371662 E-mail: info@kitsnspares.com

Advertising CheNNAi Ph: (044) 42994363 E-mail: efyenq@efy.in hYDeRABAD Ph: (040) 67172633 E-mail: efyenq@efy.in KolKAtA Ph: (033) 22294788 E-mail: efyenq@efy.in

84

mUmBAi Ph: (022) 24950047, 24928520 E-mail: efymum@efy.in

Make Your Own IVR with Asterisk

PUNe Ph: (020) 40147882 E-mail: efypune@efy.in

For YoU & me 91

Ten Android Apps for Everyday Use on Your Smartphone

96

Manage Your Marketing Activities with CampaignChain

94

Android Lollipop: What’s in it for Enterprises?

open gUrUs 25 98

Using Scilab with the McCabe-Thiele Method Audio Video Bridging: Evolution of Multimedia Streaming Technology

ColUmns 16

CodeSport

18

Exploring Software: Spark: Exploring Big Data on a Desktop

GUJARAt Ph: (079) 61344948 E-mail: efyahd@efy.in JAPAN Tandem Inc., Ph: 81-3-3541-4166 E-mail: tandem@efy.in SiNGAPoRe Publicitas Singapore Pte Ltd Ph: +65-6836 2272 E-mail: publicitas@efy.in UNiteD StAteS E & Tech Media Ph: +1 860 536 6677 E-mail: veroniquelamarque@gmail.com ChiNA Power Pioneer Group Inc. Ph: (86 755) 83729797, (86) 13923802595 E-mail: powerpioneer@efy.in tAiwAN J.K. Media, Ph: 886-2-87726780 ext. 10 E-mail: jkmedia@efy.in

Exclusive News-stand Distributor (India) iBh BooKS AND mAGAziNeS DiStRiBUtoRS ltD Unit No.10, Bezzola Complex , Opp. Suman Nagar, Sion Trombay Road, Chembur, Mumbai – 400 071 Phones : 022 – 40497401 /02 E-mail: info@ibhworld.com Printed, published and owned by Ramesh Chopra. Printed at Tara Art Printers Pvt Ltd, A-46,47, Sec-5, Noida, on 28th of the previous month, and published from D-87/1, Okhla Industrial Area, Phase I, New Delhi 110020. Copyright © 2013. All articles in this issue, except for interviews, verbatim quotes, or unless otherwise explicitly mentioned, will be released under Creative Commons Attribution-NonCommercial 3.0 Unported License a month after the date of publication. Refer to http://creativecommons.org/licenses/by-nc/3.0/ for a copy of the licence. Although every effort is made to ensure accuracy, no responsibility whatsoever is taken for any loss due to publishing errors. Articles that cannot be used are returned to the authors if accompanied by a self-addressed and sufficiently stamped envelope. But no responsibility is taken for any loss or delay in returning the material. Disputes, if any, will be settled in a New Delhi court only.

SUBSCRIPTION RATES PeriodNews-stand price

don’t just require 101 “Start-ups funds. They need mentorship

and guidance as well!” —Sushanto Mitra, founder and CEO, Lead Angels

DVD Of The Month Try out something new and fresh

6 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

You Pay Year Five Three One

106

Overseas

(`) 6000 3600 1200

(`) 3600 2520 960

— — US$ 120

Kindly add ` 50/- for outside Delhi cheques. Please send payments only in favour of EFY Enterprises Pvt Ltd. Non-receipt of copies may be reported to support@efy.in—do mention your subscription number.


offe

rS

THE monTH 2000 Rupees Coupon

One month free

(Free Trial Coupon)

Free Dedicated Server Hosting for one month Subscribe for our Annual Package of Dedicated Server Hosting & enjoy one month free service

Hurry!till 30th alid Offer vril 2015! Ap

For more information, call us on 1800-209-3006/ +91-253-6636500

No condition attached for trial of our cloud platform Hurry!till 30th valid 5! r e ff O 01 April 2

Enjoy & Please share Feedback at sales@cloudoye.com

For more information, call us on 1800-212-2022 / +91-120-666-7718

www.cloudoye.com

www.esds.co.in

35%

Get 10% discount

off & more Reseller package special offer !

Hurry!till 30th alid Offer vril 2015! Ap

Free Dedicated hosting/VPS for one month. Subscribe for annual package of Dedicated hosting/VPS and get one month FREE Contact us at 09841073179 or Write to sales@space2host.com

Get 35% off on course fees and if you appear for two Red Hat exams, the second shot is free Hurry!till 30th alid Offer vril 2015! Ap

Hurry!till 30th alid Offer vril 2015! Ap

Get 25% Pay Annually & get 12 Month Free Services on Dedicated Server Hosting Subscribe for the Annual Packages of Dedicated Server Hosting & Enjoy Next 12 Months Free Services For more information, call us on 1800-212-2022 / +91-120-666-7777

Off

BIG DATA ANALYTICS using hadoop eco-system

Certificates Will Be Awarded

Venue: Malleshwaram, Bangalore Qualification: Degree / Diploma Trainging Contents: Introduction, HDFS Maoreduce, Administration, Hbase, Hive, Pig Sqoop, Flume, Oozie, Hadoop2.0 For more information, call us on Balajee. K.M, Asst, Director, Mob.: 9900226980, 080 41100557

www.msmedibangalore.gov.in

PACKWEB

PACK WEB HOSTING ProX

Time to go PRO now

Considering VPS or a Dedicated Server? Save Big !!! And go with our ProX Plans

Hurry!till 30th alid Offer vril 2015! Ap

www.goforhosting.com

Fees Rs. 15000/(SC/ST/PH-50% Concession)

Contact us @ 98409 82184/85 or Write to enquiry@vectratech.in

www.vectratech.in

www.space2host.com

Get 12 Months Free

“Do not wait! Be a part of the winning team”

25% Off on ProX Plans - Ideal for running High Traffic or E-Commerce Website Coupon Code : OSFY2014 Contact us at 98769-44977 or Write to support@packwebhosting.com

www.prox.packwebhosting.com

Register in Advance to receive a special discount

EMBEDDED SOFTWARE DEVELOPMENT COURSES AND WORKSHOPS

School of Embedded Software Development

Faculty - Babu Krishnamuthy Visiting Faculty/ CDAC/ACTS Porting Embedded RTOS to an ARM platform

School of embedded software, Bangalore Short-term Courses www.schoolofembedded.org Email: babu_krishnamurthy@schoolofembedded.org Contact : +91-98453-65845


YOU SAID IT The most informative magazine I am a regular reader of OSFY. I have tried many tech magazines but none of them are as informative and useful as yours. I liked the article ‘The Way FreeBSD Jails Work’ published in the February issue of OSFY. Could I request you to carry an article on tape drives in your ‘Buyer’s Guide’ section? And last of all, I would like to congratulate your team for such a tremendous effort in making this magazine so useful to us. I would also like to give a big thumbs up to your magazine’s distribution team for ensuring that I get my monthly issue on time. —Shivram Sharan, shivramsharan@gmail.com ED: Thanks a lot for the feedback. It feels great when readers tell us how they benefited from our magazine. We will convey your feedback to the author of the article on ‘The Way FreeBSD Jails Work’. We will surely try and implement your suggestion and come up with a ‘Buyer’s Guide’ on tape drives. Our magazine’s circulation and distribution team will be more than happy to get a pat on the back for their efforts. Keep sharing your feedback with us.

A request to feature Gridway I am a regular reader of OSFY (and earlier of LFY) for the past three years. I must tell you that LFY was the reason I made a complete switch to open source. I wish that you would have a special feature about how to implement grid computing in Gridway. I would also appreciate it if you could feature an article

Share Your

on how to configure the Globus toolkit . Thanks a lot and keep up the good work —Elisha Robinson, elisha.rob@gmail.com ED: Thanks a lot for the feedback. We cherish our readers' views and with every edition, we try to bring out a better product. It really makes us feel good to know that OSFY (or rather, LFY) was instrumental in your switching to open source. It’s true that we have not covered grid computing recently. Do keep reading the magazine, as we are trying to focus more on such topics. Feel free to continue sending us your feedback.

In appreciation of the article on Hadoop It's been an amazing experience following OSFY and I am very thankful to the OSFY team. Each and every topic published has its own advantages but the article on Hadoop (in the March 2015 edition of OSFY) truly enlightened me enough to be able to work on multinode Hadoop clusters. Keep posting more about Hadoop and HPC in forthcoming issues, too. Thanks and regards, —Tapas Sen, tapas.93028@gmail.com ED: We always value our readers and try to feature topics that interest them. Thanks a lot for the feedback. It really makes us feel good to know that you love most of the articles published in OSFY. So keep reading the magazine and writing in to us.

Please send your comments or suggestions to: The Editor, Open Source For You, D-87/1, Okhla Industrial Area, Phase I, New Delhi 110020, Phone: 011-26810601/02/03, Fax: 011-26817563, Email: osfyedit@efy.in

8 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com



FOSSBYTES Powered by www.efytimes.com

Google rolls out Android 5.1 Lollipop to improve stability and performance Google has announced that it is now rolling out Android 5.1 Lollipop, an update which improves stability and performance. It has several new features, including official support for multiple SIM cards, high definition voice calling on phones that support this feature, device protection and more. This would be the first major update to Android Lollipop since its release. Google made the announcement on its official Android blog, where it has been mentioned that 5.1 Lollipop will also provide enhancements such as the ability to join Wi-Fi networks and control paired Bluetooth devices directly from Quick Settings as well. With Android Lollipop 5.1, more than one SIM card can be used on a device with multiple SIM slots. Lollipop 5.1 will also come with high definition voice calling on mobile phones. Google has added an additional feature called ‘Device Protection’ which protects your phone when you lose it or if it gets stolen. It will remain locked until you sign in with your Google account, even if someone resets your device to factory settings.

Ubuntu MATE 15.04 to ship with Tilda terminal app

The Ubuntu MATE team, which is currently enjoying its official community flavour status, is busy providing details about the new features that are being shipped with Ubuntu MATE 15.04—the latest being the addition of Tilda. Tilda is a ‘dropdown’ terminal application which is quite similar to its popular alternatives like Guake. It is an important application for Ubuntu MATE. Dropdown terminals are necessary to some extent. You will not be required to open an app any more with this application, as you will now only have to hit a hot key (for example F12 in Ubuntu MATE) to open and then shut it down. Tilda has several customisation and configuration options, and it supports multiple tabs too. It is available for installation on most versions of Ubuntu and related flavours, directly from the repositories.

Latest Intel Linux graphics drivers now available

A new version of the latest Intel Linux graphics drivers installer is now available for download, which gives users an easy way to upgrade Intel graphics drivers on supported operating systems. ‘Intel Graphics Installer For Linux’ is a free utility that can be used to install the latest graphics and video drivers for Intel graphics hardware. It is developed and maintained by Intel Open Source Technology Center. It allows you to stay up to date 10 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

MakuluLinux Cinnamon upgraded to 64-bit version

MakuluLinux Cinnamon has been upgraded to a 64-bit version. This Linux distro is based on the Debian testing branch, Jessie, and it’s known to provide stability, speed and modern desktop features. Until now, MakuluLinux was a 32-bit distro only, but now it has an upgraded edition too. The Cinnamon flavour is quite popular because it is lightweight. It will not only be compatible with 64-bit machines, but it also integrates a new and interesting feature that allows users to save a snapshot of their current desktop, package it and install it on another computer. MakuluLinux is already very comfortable for new users. It’s based on Debian, and it directly competes with Linux Mint. The developer has posted, “This release is special for so many reasons. It is sure to mark a major milestone, not just for Makulu, but considering what is inside, the whole of the Linux world. Never before has Linux offered such options as we have done in this release, and what is more, we made it so easy to use. Makulu now offers a built-in constructor tool that lets you quickly and easily create a 100 per cent snapshot of your LIVE system as it is, and save it into an ISO that can be then re-installed on a new computer. It comes complete with a live mode, installer and full EFI/Secure boot.” As per the changelog, the Linux kernel is now at version 3.16, the Cinnamon desktop environment has been upgraded to version 2.2.16, EFI support has been integrated, and firewall and antivirus applications have also been added.


FOSSBYTES with the latest enhancements, optimisations and fixes released for Intel’s graphics hardware. The installer is currently available for Ubuntu and Fedora distributions. Deprecated status allows people to use the tool to remove or install an older version of the graphics stack. This time round, Ubuntu 14.10 and Fedora 21 are formally supported, with Ubuntu 14.04 LTS and Fedora 20 entering ‘deprecated’ status. The tool no longer performs major xserver-xorg upgrades as part of its update process. Utopic users can make full use of the tool to upgrade to the Intel 2014Q4 graphics stack. A number of improvements to the standard Intel Linux 2D and 3D drivers have been seen during the 2014 Q4. These include support for Broadwell and CherryView CPUs, preparations for Skylake processors, Backlight and power sequencer fixes and revamped Vblank handling.

Git 2.3.3 released with several bug fixes and performance improvements

The third maintenance release of the stable Git 2.3 branch has been released. The new release integrates several bug fixes and includes many performance improvements in the popular distributed revision control system. Git allows developers to interact with GitHub to upload the source code of programs. As per the changelog, in the newly released Git 2.3.3, corrupt input in the ‘git diff –M’ command has been fixed, which means it will no more cause a segfault. Description of the ‘grep-h’ command has been improved, too, and documentation for the ‘git remote add’ command has been modified so that information about ‘-tags’ and ‘-no-tags’ arguments is more clear. Now ‘unsigned char’ will be used to store values that range from 0-255, unnecessary dirstat based on lines have been removed from the ‘git diff --shortstat --dirstat=changes’ command, and some documentation has also been modified to make the interaction between the submodule.*.update configuration and the ‘git submodule update’ command more clear. An update has also been made to the ‘git apply’ command so that it correctly reads, creates, updates and removes paths from the directory or outside the working tree. In the new version, the ‘git daemon’ command will also not look for hostnames if the ‘%IP’ and ‘%CH’ interpolations are not sought for. The ‘interpolated-path’ option of the ‘git daemon’ command will also not insert any string client in the new release.

VMware to expand desktop virtualisation to Linux

VMware is expanding its Horizon desktop virtualisation solution. The software suite will soon deliver virtual Linux desktops over a network. VMware Horizon 6 is a comprehensive desktop and application virtualisation solution to deliver and manage any type of enterprise application and desktop, including physical desktops and laptops, virtual desktops and applications, and employee-owned PCs. The software is designed to allow administrators to control their organisation’s Linux virtual desktops with the same tools that they use to manage their Windows virtual desktops. The company has launched an early-access program for customers to test a

The first automotive bus with a Linux based design is out!

Germany based Technische Universität München (TUM) is unveiling a two-tier automotive service bus for car computers. This service will be available on a control unit running Linux on a PandaBoard. It is based on the Java based Open Service Gateway Initiative (OSGi). Technische Universität München (TUM) has open-sourced an automotive computer bus design developed as part of its ‘Visio.M’ (Visionary Mobility) electric car project. The automotive service bus is designed to handle today’s increasingly computerised cars, which often involve up to 80 different electronic systems. The system is controlled by a crossplatform central control unit built by IAV. A separate, Web-enabled control unit responsible for driver and Internet communications interacts wirelessly with a touchscreen, which in the case of the Visio.M, is an Apple iPad. Visio.M’s OSGi hardware platform is based on a hardware design that runs Linux on an open-spec PandaBoard, which in turn is equipped with a Texas Instruments 1GHz, dual-core, Cortex-A9 OMAP4430 system-on-chip. Although the bus uses a typical CAN network, it breaks away from traditional automotive bus designs, which are based on 100-year old technology. The new bus architecture resembles that of dual-layer smartphone architecture, securely isolating driving and safety functions from communications and Internet functions. All connected firmware components can be updated, appended or deleted over the Internet. The two-seat Visio.M has a range of 160km, and the 15kW motor supports a maximum speed of 120km/h. The lightweight car is powered by a 13.5kWh Li-Ion battery, which can be recharged in under four hours. The battery weighs 85kg, compared to 450kg for the car (without the battery).

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 11


FOSSBYTES

SUSE launches its own open source storage solution

SUSE has released its own storage solution for enterprise customers. The open source storage is powered by Ceph’s Firefly open source project and the solution is highly scalable. Nils Brauckmann, GM, SUSE, said that SUSE Enterprise Storage is a highly scalable and resilient software storage solution that lets small organisations and enterprises move from proprietary, hardware based storage to software based storage, which ensures great functionality at negligible cost. SUSE has designed this software based storage solution with easy back-up and archiving capabilities for enterprise customers. It has priced this solution well— charging $0.001 per GB for enterprise users. SUSE’s vision has been to bring cost-efficient and highly scalable storage solutions to enterprises. The companies can build their storage space using commodity off-the-self servers and disk drives. Enterprise customers can save a lot of the money being spent on expensive hardware with this solution. SUSE claims that this software based storage solution is 30 per cent less expensive than conventional NAS solutions and 50 per cent less expensive than average capacity optimised disk array systems. SUSE has designed this solution to be very flexible and scalable to serve an enterprise’s need for more storage as the company grows. Customers can rapidly boot new virtual machines with SUSE Enterprise Storage. The service offers fault-tolerant enterprise disk storage. SUSE has invested in OpenStack in the past so the company has no intentions of competing with it. Red Hat already has its own software based storage solution, so SUSE needed a cloud based storage solution to help serve the needs of its customers. It has integrated this new storage solution in SUSE OpenStack Cloud to provide flexible access. SUSE Enterprise Storage can also be used as a stand-alone storage solution.

version of Horizon 6 that can package server-based Red Hat and Ubuntu Linux desktops, so they can be accessed from remote computers and mobile devices. Customers can use VMware Horizon 6 to leverage the power of virtualisation, and transform their desktops into secure virtual workspaces to embrace business mobility. Virtual desktop infrastructure (VDI) software can be handy for organisations that have mobile workers who need to access applications and desktop environments from multiple devices. Virtual desktops can also simplify the large-scale management of software and operating systems. The company has updated Horizon 6 with additional capabilities for managing 3D images and for integrating into software defined networks (SDNs).

Google Code to close down!

The search giant is closing down Google Code because there are other alternatives available on the Web. Google Code was a competitive alternative to SourceForge for open source project hosting. Google launched the project in 2006 because it was unhappy with the ‘limited’ options available to the open source community. But since then, a “… wide variety of better project hosting services” such as GitHub and Bitbucket have moved to the forefront. In May 2013, Google also shut down Google Code Download services. In order to “…meet developers where they are,” Google itself has transferred nearly a thousand of its own open source projects to the popular coding repository GitHub. GitHub isn’t just a place to download, but it has become a fantastic and integral part of the development process in a way that neither Sourceforge nor Google Code ever were. The migration of developers to the new services has left Google Code dealing with a deluge of spam and abuse. The end of Google Code will be based on a timed approach. As of March 12, 2015, all new project creation has been disabled. On August 24, 2015, the site goes read-only and will effectively disappear on January 25, 2016.

Linux kernel 3.19.1 released

The first point release of Linux 3.19 kernel was announced with immediate availability for download. Linux kernel 3.19.1 is the current stable branch of the Linux kernel. As per the changelog, the first point release of Linux kernel 3.19 comes with a number of improvements to several architectures including ARM, x86, PowerPC, MIPS, ARM64 as well as s390. The release also includes updates to drivers, file systems, networking, sound and security. Developer Greg Kroah-Hartman said in the mailing list announcement, “I’m announcing the release of the 3.19.1 kernel. All users of the 3.19 kernel series must upgrade.” The 3.19.1 version brings updated

12 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com


FOSSBYTES drivers for wireless, USB, ACPI, Bluetooth (ath3k), CPUFreq, HID, MD/ RAID, MMC, DVB, PCI, SCSI, TTY, and XEN. The XFS, UDF, NFS, JFFS2, OCFS2, EXT4 and Btrfs file systems have also received several improvements, and some Ceph, IPv4 and SunRPC issues have also been fixed. The upcoming Ubuntu 15.04 (Vivid Vervet) will be based on the Linux 3.19 kernel, and it already includes packages based on the Linux kernel 3.19.1.

VLC 2.2 launched for Windows, Mac, Linux and leading mobile platforms

The favourite media player of millions worldwide, VLC, has released its 2.2 ‘Weathermax’ version which integrates some new features for the desktop. This release includes a built-in extension gallery. New features can be easily added to VLC with just a few clicks through Tools > Plugins and Extensions. The new version has also added the playback resume feature, which has been requested for since a long time. When a video or audio file is reopened, a ‘Continue Playback’ pop-up appears and in this way the desktop version comes on par with its mobile counterpart. Another major reallife bug has been resolved too, which used to auto-rotate videos that are recorded on a smartphone or tablet. Some usual codec updates have also taken place like support for Ultra HD, VP9 and H.265, and ‘compatibility’ fixes for a series of obscure file formats. Some other changes include GPU zero-copy decoding, which will ensure faster performance levels, support for ‘Digital Cinema Package’ and support for interactive Blu-Ray menus too. If you are feeling bored, you can also play with its three new video filters: ‘old movie’, ‘VHS effect’ and ‘freeze effect’. VLC 2.2 can be downloaded and used for free on Windows, Mac, Linux and other mobile platforms including Windows Phones, Android and iOS. Ubuntu users can also upgrade or install it through the official VLC Personal Package Archives.

Mozilla Firefox 64-bit developer edition launched for Windows

Mozilla recently launched Firefox 36 for desktops and Android devices. And the 10th Firefox anniversary was celebrated by launching the 64-bit Firefox Developer Edition 38 for Windows. The version can be downloaded now from the Firefox Developer Edition page. The new version for Windows can run larger applications faster and it maintains a high security standard too. The browser is limited to 4GB of address space. In its blog post, Mozilla said that heap sizes in

Apple launches ResearchKit framework to help medical research

At the launch of Apple Watch, a new software framework was announced by the company. This is expected to turn 700 million iPhones into medical diagnostic tools. This is an open source framework, called ResearchKit. It will allow medical researchers to create diagnostic apps to tap into the screens and accelerometers on the iPhone, and also tap data from HealthKit apps. The first five apps built with the open source framework have been made available and will help diagnose several kinds of disorders. At the event, details of the special applications were provided by Apple’s senior VP of operations, Jeff Williams. These applications include the mPower app, which can gauge the effects of Parkinson’s disease. This app has been developed jointly by the University of Rochester, Xuanwu Hospital at Capital Medical University in Beijing, and Sage Bionetworks. On stage at the launch of Apple Watch, some tests within the app were demonstrated by Williams. These showed how the app could measure hand tremors by using an iPhone touchscreen, vocal trembling by using the microphone and also walking balance. The ResearchKit framework is expected to help several problems faced during medical research, and the apps are built to be quite interactive too. The other apps mentioned include a diabetes diagnostic app from Massachusetts General Hospital, a heart disease diagnostic app from Stanford and the University of Oxford, an asthma health app from Mount Sinai Hospital and Weill Cornell Medical College, and an app to help victims of breast cancer, made by the Dana-Farber Cancer Institute, UCLA School of Public Health, Penn Medicine and Sage Bionetworks. Williams also said that sensitive data will be visible only to medical researchers and that, “Apple will not see your data.”

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 13


FOSSBYTES

Mozilla Firefox 36 to support the HTTP/2 protocol

Mozilla has decided to support the HTTP/2 protocol in its upcoming Firefox 36.0. The technology has been finalised as the next-generation HTTP (Hypertext Transfer Protocol) network protocol. The Internet will adopt the new protocol in the near future. Mozilla had proposed to use HTTP/2.0 in upcoming Firefox releases a few weeks ago. The decision was finalised on February 17. OpenLiteSpeed Web server has decided to support HTTP/2 draft 16. Even Microsoft IIS Web server will support the HTTP/2 protocol in upcoming Windows 10 OS. We can expect more and more technologies to adopt the HTTP/2 protocol in the coming months. Mozilla Firefox 36.0 adds many innovative features to the browser like the pinned tiles sync function. The native HTML5 YouTube playback will be a much appreciated feature in the new browser. A newly designed Preferences interface is enabled in the new browser. The flash protected-mode sandbox is disabled on Windows to evaluate the stability impact of protected mode. Firefox will no longer accept the insecure RC4 ciphers, whenever possible. The support for ECMAScript 6 symbol data type has been added to the new version. Mozilla has implemented Unicode range CSS descriptor in the new browser version. Users can create a new stacking context to isolate groups of boxes, to control which to blend together in Firefox 36.0. You can expect more privacy features in this version of Firefox than ever before. The major addition of full support for HTTP/2.0 protocol enables a faster, more capable and more responsible Web browsing experience.

32-bit browsers are recommended to be 512MB and this can reach up to 2GB in the 64-bit browser. The post, which refers to a game built by Epic Games’ Unreal Engine, adds, “For some of the largest of these apps, a 64-bit browser means the difference between whether or not a game will run.” Mozilla launched Firefox Developer Edition in November last year, and the company has offered 64-bit versions of Firefox for Mac OS X and Linux since a long time. But it’s only now that it’s introduced this on the Windows platform too. Firefox 36 for Android has also included HTTP/2 support, just like its desktop counterpart. With the new protocol, pages can be loaded faster than before and the connections are longer lived too. The user interface is also completely revamped and more features are expected to be added in future. Firefox 36 for Android tablets has also added a full screen tab panel and a new search system. The new Android version also introduces the Maithili locale for Android Lollipop users, a number of changes in HTML codes for developers and several fixes in VPNs.

Arch Linux 2015.03.01 released with Linux kernel 3.18.6

A brand new ISO image has been released for the lightweight, highly customisable and powerful Arch Linux computer operating system. The new release is meant for those who want to deploy the acclaimed distro on new computers. In the Arch Linux distro, on the first day of each month, a new ISO image is released and March 1 was no exception. A new ISO image includes all the updates released during the previous month, including the core of the OS, the Linux kernel. Arch Linux 2015.03.01 is powered by Linux kernel 3.18.6, and it includes all the updates that were released on the software repository of the distribution throughout February 2015. It also includes all the improvements, new packages and bug fixes. If you are already using Arch Linux, then you don’t need to download the new ISO image to keep your system updated as Arch Linux is a rollingrelease distribution. The latest version can be installed on both 64- and 32-bit computer systems.

LibreOffice 4.4.1 released with more than 100 fixes

The Document Foundation has announced the first maintenance release of the stable LibreOffice 4.4, which is an open source and multi-platform suite. The new updated release is available for download too. LibreOffice 4.4.1 introduces some minor fixes so that the office suite stays stable and dependable on all platforms. According to the official announcement, LibreOffice 4.4.1 fixes more than 100 bugs, which were discovered by developers as well as users in the previous release, LibreOffice 4.4 ‘Fresh’. This was announced at the end of January 2015, and it was said to be the most beautiful LibreOffice ever.

KDE Plasma gets a new update with version 5.2.1

Plasma is the desktop for the KDE project and it has got a new update now with

14 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com


FOSSBYTES version 5.2.1. It’s a maintenance update that comes with some minor changes and improvements Plasma is the most noticed and talked about component of the KDE project. All the changes made to Plasma can be noticed immediately, though developers still need to make some more fixes. As mentioned in the official announcement, “Today KDE releases a bug fix update to Plasma 5, versioned 5.2.1. Plasma 5.2 was released in January with many feature refinements and new modules to complete the desktop experience. This release adds a month’s worth of new translations and fixes from KDE’s contributors.” The developers have explained that when videos are being watched in a Web browser, the screen or the suspend function will no more interrupt, Powerdevil will not use the entire CPU any more, and a crash that happened while switching to and from the Breeze widget style has been fixed too.

Android Ice Cream Sandwich will not get any major Chrome release

Android has moved way ahead from the era of Ice Cream Sandwich, and so has Google. The Android OS and Chrome browser maker has announced that it will not provide any major Chrome browser release for Android 4.0 (Ice Cream Sandwich). After the last major version of Chrome browser for Android KitKat, which is Chrome version 42, Google will freeze the development of the browser for the Android version. Google stated that the number of Chrome users on Android 4.0 have been decreasing constantly. In addition, the backward compatibility has been restricting the company from coming up with new features that will work well on older devices. Aurimas Lutikas, software engineer, Google, wrote in a blog post, “In the last year, we’ve seen the number of Chrome users running ICS drop by 30 per cent. Developing new features on older phones has become increasingly challenging, and supporting ICS takes time away from building new experiences on the devices owned by the vast majority of our users.” However, the company has promised regular security patches till Google releases version 43 of the Chrome browser. But the Ice Cream Sandwich users will not get anything after that from the Chrome development team. www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 15


CODE

SPORT

Sandya Mannarswamy

In this month’s column, we feature a list of interview questions on operating systems, algorithms and computer architecture.

O

ver the past few months, we have been discussing natural language processing and insight-centric storage systems. This month, we take a break from that discussion to explore a bunch of computer science interview questions. Let us start off on a light-hearted note. 1. What is the KISS Principle in computer science? 2. File systems and database systems both act as containers of user data, albeit in different ways. Can you differentiate the two in terms of the consistency guarantees they provide to the end user? 3. Consider a file ‘1.txt’ on the same file system, say ext4, on Linux, which is opened by two different processes. Both these processes modify overlapping regions of the file and close their individual file handles. While each process has its own file handle on which it operates, how many file descriptors are actually created for this file in the file system in the kernel? If both process1 and process2 write ‘a’ and ‘b’ as the value at logical offset ‘0’ of the file ‘1.txt’, what would actually be stored when these processes close their descriptive handles? 4. When the user invokes ‘ls’ on the root directory of your file system, can you explain what Linux system calls get invoked internally? 5. What is a FUSE file system? How is it different from a kernel level file system module? Can you reimplement the Linux ext4 file system as a FUSE module? If not, why not? 6. Instead of having local storage on a hard disk connected to the device, you are asked to design a file system which will store its data on a public cloud storage provider like Amazon S3, which has an object interface. The file system needs to provide normal file access semantics to local applications, but has to store its durable data in the cloud. What are the design considerations when

16 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

creating such a system? 7. We all know that databases support ACID semantics where the ‘A’ in ACID stands for atomicity. Atomicity means that either the transaction completes successfully in its entirety or it appears not to have started at all. For example, consider the simple example of transferring money from your account to your father’s account. Successful completion means that the money is debited from your account and credited to your father’s account. So if there is a failure while the transaction is in progress, say after the money has been debited from your account but before it is credited to your father’s account, then the transaction is aborted and the effect to the end user is as if the transaction never started at all. This means that it appears as if the money was never debited from your account. Can you explain the mechanism by which databases support such failure atomicity? Think of how it would be possible to roll back a partially completed transaction. 8. What is a gossip protocol? How would you implement it in a local network of computers? 9. The conventional wisdom with regard to traditional storage media is that interrupt based signalling of IO completion is more efficient than polling. Can you think of a situation where polling may be better than interrupt based IO completion signalling? There is an interesting research paper which discusses this issue in detail, available at https://www.usenix.org/legacy/events/fast/tech/ full_papers/Yang.pdf 10. What are content addressable memories as opposed to traditional random access memories? 11. You are asked to write a program which supports the following operations:


Guest Column (a) Encrypts the input data and stores it as a file (b) Decrypts the data it reads from a file and displays it Can you write a small code snippet to do the same? If you are told that your program will execute on a processor, which supports AES-NI instructions, how will you modify your code to take advantage of this functionality? 12. Given an array of N integers and a number ‘k’, write a function which returns true if the array has a contiguous sub-sequence, which sums up to exactly ‘k’? How would your code change if you are asked to return the start and end of the contiguous subsequence, if such a sub-sequence exists in the array. What is the time complexity of your solution? 13. You are given an array of N integers and asked to return a popular item in the array, if such a popular item exists in the array. A popular item is an element which repeats at least N/4 times in the array. How would you modify your code if you are asked to return all such popular elements? What is the time and space complexity of your solution? 14. You are given an array of N integers and asked to write a program to find the maximum difference between two array elements A[i] and A[j] such that i < j. How would your solution change if the condition that ‘i’ needs to be smaller than ‘j’ need not hold true for your program? 15. You are given an array of N elements, where each element is a task. Each task has a priority, which is marked as either High, Medium or Low. You are asked to rearrange the array such that all tasks which have the priority value ‘High’ appear first, followed by tasks whose priority is ‘Medium’, and then by tasks whose priority is ‘Low’. You are asked to do this in-place with constant additional storage. What is the time complexity of your solution? 16. You are given a text file, which contains C/C++ code. The code has comments in it. The comments can be either single line or multi-line. Single line comments begin with a ‘//’ character and do not span beyond a line. Multi-line comments are enclosed by ‘/*’ and ‘*/’ characters. Comments cannot nest inside each other. You are asked to write a code snippet which strips out the comments from the code in the input file. 17. You are given a binary search tree containing N integers. You are asked to return the ‘kth’ largest element in the binary search tree. Write a code snippet to do this. How would your solution change if you are asked to return the ‘largest’ element and the ‘smallest’ element in the binary search tree? What is the time and space complexity of your solution? 18. You are given a list of N users along with their login and logout times on the computer, over a period of one

CodeSport

week. You are asked to write a program to: a. Find the time when the number of users that were logged into the computer was the maximum b. Find the time when the number of users that were logged into the computer was the minimum c. Find the user who was online for the maximum cumulative time over the one week d. Find the user who was online for the longest single duration slot over that week What is the data structure you would use to represent the login, logout time intervals? 19. A string is said to be unique if no two characters in the given string are identical. Given a set of N strings, you are asked to find all unique strings present in the set. 20. Given a string, find all the sub-strings of that string which are palindromes. 21. You are given two binary trees and asked to determine whether the two trees are identical both in terms of structure and the elements contained in them. Write a program to do this. What is the time and space complexity of your solution? How would your code change if you are told that the binary trees are actually binary search trees? 22. If you are asked to write a sort routine to replace the sort utility in UNIX/Linux, which sorting algorithm would you use and why? 23. If you are asked to design a data structure which needs to support (a) insert, (b) delete, (c) search, (d) findminimum, and (e) find-maximum, which data structure would you use and why? 24. What is a lock-free data structure? Can you give an example of one? 25. The two terms ‘concurrency’ and ‘parallelism’ are often mistaken for each other in computer science. Can you differentiate between the two with appropriate examples of where concurrency exists and where parallelism does? If you have any favourite programming questions or software topics that you would like to discuss on this forum, please send them to me, along with your solutions and feedback, at sandyasm_AT_yahoo_DOT_com. Till we meet again next month, happy programming!

By: Sandya Mannarswamy The author is an expert in systems software and is currently working with Hewlett Packard India Ltd. Her interests include compilers, multi-core and storage systems. If you are preparing for systems software interviews, you may find it useful to visit Sandya’s LinkedIn group, Computer Science Interview Training India at http://www. linkedin.com/groups?home=HYPERLINK “http://www.linkedin.com/ groups?home=&gid=2339182”&HYPERLINK “http://www.linkedin. com/groups?home=&gid=2339182”gid=2339182

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 17


Exploring Software

Anil Seth

Guest Column

Spark: Exploring Big Data on a Desktop Here’s an introduction to Apache Spark, a very fast tool for large scale data processing. Spark is easy to use, and runs on Hadoop and Mesos as a standalone application or on the cloud. Applications can be quickly written in Java, Scala or Python. Developers boast that it can run programs 100 times faster than MapReduce in memory, or 10 times faster on disk.

M

y interest in Hadoop had been sparked a year ago by the following headline: “Up to 100x faster than Hadoop MapReduce.” Now, it’s finally time to explore Apache Spark. MapReduce expects you to write two programs, a mapper and a reducer. The MapReduce system will try to run the mapper programs on nodes close to the data. The output of various mapper programs will be key value pairs. The MapReduce system will forward the output to various reducer programs, based on the key. In the Spark environment, you write only one set of code containing both the mapper and reducer code. The framework will distribute and execute the code in a manner that will try to optimise the performance and minimise the movement of data over the network. Besides, the program could include additional mappers and reducers to process the intermediate results.

Installing Spark

You will need to download the code from the Apache Spark site (http://spark.apache.org/) based on the version of Hadoop on your system. Installation involves just unzipping the downloaded file. The documentation will guide you on how to configure it for a cluster, e.g., consisting of three nodes – h-mstr, h-slv1 and h-slv2.

Getting a taste of Spark with word count

Let’s suppose that you have already created and copied text files in the Hadoop Distributed File System (HDFS) in the directory /user/fedora/docs/. Start the Python Spark shell, as follows: $ bin/pyspark

Open the text files in HDFS and run the usual word count example: >>> data = sc.textFile('hdfs://h_mstr/user/fedora/docs')

18 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

>>> result = data.flatMap(lambda line:re.sub('[^a-z0-9]+',' ',line.lower()).split()) .map(lambda x:(x,1)) .reduceByKey(lambda a,b:a+b) >>> output=result.collect() >>> output.sort() >>> for w,c in output: >>> print('%s %d'%(w,c))

The shell creates a Spark context, sc. Use it to open the files contained in the HDFS docs directory for the user Fedora. You use flatMap to split each line into words. In this case, you have converted each line into lower case and replaced all non-alphanumeric characters by spaces, before splitting it into words. Next, map each word into a pair (word, 1). The mapping is now complete and you can reduce it by keyword, accumulating the count of each word. So far, the response would have been very fast. Spark is lazy and evaluates only when needed, which will be done when you run the collect function. It will return a list of word count pairs, which you may sort and print.

Finding out which files contain a particular word

Let’s assume that you have a large number of small text files and you would like to know how frequently a particular word occurs in various files. Spark has the option to process the whole file rather than one record at a time. Each file is treated as a pair of values – the file name and the content. from pyspark import SparkContext import re # input to wholeFile is a file name, file content pair def wholeFile(x): name=x[0] words = re.sub('[^a-z0-9]+',' ',x[1].lower()).split() return [(word,name) for word in set(words)]


Guest Column Exploring Software

sc = SparkContext(appName='WordsInFiles') data = sc.wholeTextFiles('hdfs://h_mstr/user/fedora/docs') word_index = data.flatMap(wholeFile).reduceByKey(lambda a,b:','.join((a,b))) word_index.persist() output=word_index.collect() output.sort() # print the first 10 values for i in range(10): print output[i] explore(word_index) sc.stop()

The function wholeFile returns a list of (word, file name) pairs for unique words. As earlier, the text has been converted to lower case and all special characters replaced by a space. The reduceByKey function joins all the file names with a comma as the separator. For verification, the first 10 results of the sorted output are printed. The persist method saves the result of word_index, which is useful if you want to use the same data set again. For example, in the explore method mentioned above, you may want to analyse a list of words and see how many of these words appear in a file. class filter_keys(): def __init__(self,keys): self.keys = keys def filter(self,x): return x[0] in self.keys def explore_keys(rdd,keys): example = filter_keys(keys) res = rdd.filter(example.filter) \ .flatMap(lambda x:x[1].split(',')) \ .map(lambda x:(x,1)) \ .reduceByKey(lambda a,b:a+b) out=res.collect() out.sort(lambda a,b:-a[1].__cmp__(b[1])) print keys,len(out) print out def explore(rdd): explore_keys(rdd,['linux','fedora','ubuntu']) explore_keys(rdd,['linux','fedora','ubuntu','python'])

The first step is to select only those records that pertain to the keywords. The Filter operation on the data set will do just that. However, we need to pass a list of words as a parameter and this can be achieved by creating the class filter_keys. The class is initialised with a list of keywords

and the filter method in the class can use this list. The next step is like the word count example. Each line is a word followed by a string of comma-separated file names. So, split the file names into a list and count the number of times each file is selected. Sort the results in descending order (of the frequency) and print them. You can repeat the exercise for various keywords and the intermediate data set will be reused without the need to save it in a file. This is one of the major advantages of Spark over MapReduce. From a developer’s perspective, the ability to code the entire analysis (which may consist of a sequence of MapReduce operations) in a single file makes it much easier to think through the problem and write better code.

By: Dr Anil Seth The author has earned the right to do what interests him. You can find him online at http://sethanil.com and http://sethanil.blogspot. com, or reach him via email at anil@sethanil.com.

EMBEDDED SOFTWARE

DEVELOPMENT

COURSES AND WORKSHOPS School of Embedded Software

www.schoolofembedded.org COURSES:

• Embedded System Programming on Arm-Cortex-M • ARM Cortex-M architecture, internals and Programming • Embedded OS internals and programming • BSP and drivers • Linux Internals for Driver Development - in April 2015 • Linux Device Drivers

VENUE:

School of Embedded Software Development Kalyan Nagar, HRBR Layout, Bangalore - 560043 Faculty : Babu Krishnamurthy Email : babu_krishnamurthy@schoolofembedded.org Phone : +91-98453-65845/080-41207855

COURSE DETAILS:

http://www.schoolofembedded.org/course_s http://www.schoolofembedded.org/events-default

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 19


Developers

How To

Talking to the Kernel through Sysfs The Linux kernel provides a virtual file system called sysfs. By providing virtual files, sysfs is able to export information about various kernel sub-systems, hardware devices and associated device drivers from the kernel’s device model to user space. To further explore sysfs, dive deep into this article.

T

here is a need to provide information related to each process, to the user space, which can then be used by programs such as ps. The /proc file system was created for this purpose. Through the proc file system, each process has its directory in the /proc folder. It was originally designed to provide process related information to user space. Adding directories and files to the /proc file system is easier; so, many kernel sub-systems started using this file system for displaying information to the user space. It is also used to take inputs from the user space to control settings inside the kernel modules. But the /proc file system is getting cluttered with lots of non-process related information. From the Linux 2.5 development cycle, a new interface called the /sys file system has been introduced. Sysfs is a

20 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

RAM based file system. It is designed to export the kernel data structures and their attributes from the kernel to the user space, which then avoids cluttering the /proc file system. The advantages of sysfs over procfs are as follows: A cleaner, well-documented programming interface Automatic clean-up of directories and files, when the device is removed from the system The enforced one item per file rule, which makes for a cleaner user interface The ‘one item per file’ rule mandates that in each file of sysfs, there will be only one value that can be put in or read from it. This feature really makes it a cleaner interface. Through sysfs, user space programs can get information from the kernel sub-system like device drivers. Programs


How To can also send values to the kernel sub-system and can control the internal settings. This is how programs talk to the Linux kernel.

Sysfs mounting

By default, sysfs is compiled in the Linux kernel. It is dependent on CONFIG_SYSFS being enabled in the kernel configuration. If sysfs is not already mounted, then you can do so by using the following command:

Developers

sysfs, the struct kobject pointer that is passed to sysfs_create_ dir should have the parent kobject pointer pointing to the kobject of the directory in which the current directory is to be created. Then the name parameter of the kobject should be filled, with the proper name representing the functionality for which the directory is being created. But the above interfaces are not directly used to create directories in sysfs when writing kernel modules; instead, the following interface is used:

mount -t sysfs sysfs /sys

struct kobject * kobject_create_and_add(const char *name, struct kobject *parent);

Linux Kernel objects

…where, name: is the name of the directory to be created in sysfs, and… parent: is the kobject of the parent directory in which the current directory is to be created. The return value of the kobject_create_and_add is the kobject pointer of the created directory, and if it fails to create a directory then a NULL pointer is returned. Kobject parent pointer: Since each folder in the sysfs file system is represented using a struct kobject, to create a new directory in sysfs, the parent pointer is to be initialised with the kobject of the directory in which the current directory is to be created. For example, to create a directory named example_dev in /sys/kernel, the following function call is used:

Folders in each sysfs directory are represented by kernel objects (kobjects) in Linux. These are represented in the kernel through the struct kobject (defined in include/linux/ kobject.h). The important members of the struct kobject are given below. char *name: This is the name of the kobject. Folders corresponding to the current kobject are created with this name in sysfs. Struct kobject *parent: This is the parent of the current kobject being created. When a folder is created in sysfs, if this field is present, then the current kobject folder is created inside the parent kobject folder. Struct kref: This is the reference counting mechanism for kobject. Whenever any kernel module refers to any kobject, its reference count is incremented, and whenever any kobject reference is released by any kernel module, then the reference count is decremented. When the reference count decrements to zero, memory related to the kobject is released.

Directory operations in sysfs

The following are the interfaces that are used for directory related operations in sysfs: int sysfs_create_dir(struct kobject *kobj);

struct kobject *example_dev_kob; example_dev_kobj = kobject_create_and_add(“example_dev”, kernel_kobj);

…where, kernel_kobj is the kobject pointer of the kernel directory in sysfs. So in order to create a directory in /sys/ firmware, the firmware_kobj pointer will be used. In order to create the directory named example_dev directly in /sys, the following function call is used:

void sysfs_remove_dir(struct kobject *kobj); kobject_create_and_add(“example_dev”, NULL); int sysfs_rename_dir(struct kobject *kobj. const char *new_ name);

Sysfs directory creation

The sysfs_create_dir interface is used to create a directory in sysfs. The struct kobject parameter passed to it has two fields in it. kobj->name: This is the name of the directory that is to be created in sysfs. kobj->parent: This is the kobject pointer of the parent directory in which the current directory is to be created. Since each directory in sysfs has a struct kobject associated with it, when the new directory is to be created in

…so if the parent pointer is kept NULL, then the example_dev directory will be created in the /sys folder.

Sysfs directory removal

The sysfs_remove_dir interface is used to remove the directory from the sysfs file system. The parameter that is passed to the sysfs_remove_dir is the kobject pointer of the directory which is to be removed. The kobject pointer should be used to create the directory. Here, too, the same concept applies. Instead of directly calling this interface to remove the directory, the following kernel kobject interface is used, which internally calls the sysfs remove interface: www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 21


Developers

How To

void kobject_del(struct kobject *kobj);

This interface will delete the directory of sysfs represented by the kobject pointer passed to it. For example, to delete the example_dev directory that was created as an example, the following function call is used: kobject_del(example_dev_kobj);

Sysfs directory renaming

In case there is a need to rename the directory created in sysfs, the following functions are available: int sysfs_rename_dir(struct kobject *kobj, const char *new_ name)

kobject_get increments the reference count of the kobject passed to it, whereas kobject_put decrements the reference count of the kobject passed to it. So while writing drivers or any kernel module, whenever any kobject of the other module is directly used, kobject_get should be called to increment the reference count of the kobject. When the use of the kobject is finished, kobject_put should be called to decrement its reference count. Whenever kobject_put is called, passing the kobject pointer to it, it decrements the reference count. When the reference count reaches zero, it frees the memory of the kobject pointer, and the kobject pointer can no longer be used.

Files in sysfs

…where, kobject: This is the kobject pointer of the directory to be renamed. new_name: This is the new name to be given to the directory.

In the above example, we have created the example_dev directory in the /sys/kernel folder. Suppose the example had some attribute called example_info which we want to expose to the user space using sysfs, then the feature used is called sysfs attributes. Attributes are represented as regular files in sysfs with one value per file. Attributes are of the type struct attribute (defined in include/linux/sysfs.h). Struct attribute has the following two important pieces of information. name: This is the name of the attribute(file) to be created. mode: This is the permission with which the file is to be created. A simple attribute has no means by which it can be read or written; it needs wrapper routines for reading and writing. For this purpose, kobject defines a special structure called struct kobj_attribute (defined in include/linux/ kobject.h) as follows:

Kobject reference counting

struct kobj_attribute {

…where, kobj is the kobject pointer corresponding to the directory that has to be renamed, and new_name is to be given to the directory. Since the sysfs interface is normally not directly called, the following kobject interface is called for the renaming purpose: int kobject_rename(struct kobject *kobj, const char *new_ name)

Each kobject has a member struct kref, which is a reference counter. Whenever any module wishes to use the kobject already created, this reference count is incremented, and whenever that module wishes to stop using kobject, the reference count is decremented to maintain the number of modules using the kobject or the sysfs directory represented by the kobject. Whenever the reference count reaches 0, the memory related to the kobject which was allotted by kobject_create_and_add is released, and whenever a kobject is created using kobject_create_and_add, it internally initialises the kref reference counter by one. This indicates the kobject is being used by the current module, and then kobject_create_and_add internally creates the directory for the kobject. Whenever any new module wishes to use the directory represented by that kobject, the reference counter has to be incremented. The reference count is maintained in the kobject using the following functions:

struct attribute attr; ssize_t (*show)(struct kobject *kobj, struct kobj_attribute *attr, char *buf); ssize_t (*store)(struct kobject *kobj, struct kobj_ attribute *attr, const char *buf, size_t count); };

…where, attr is the attribute representing the file to be created, show is the pointer to the function that will be called when the file is read in sysfs, and store is the pointer to the function which will be called when the file is written in sysfs. Suppose we need to create our example_info file in the /sysfs/ kernel/example_dev directory that was created as an example; then the following method is the way to define the attribute:

struct kobject* kobject_get(struct kobject *kobj);

struct kobj_attribute example_info_attr = __ATTR(example_info, 0666, example_show, example_store);

struct kobject* kobject_put(struct kobject *kobj);

…where __ATTR is the macro, as shown below:

22 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com


How To __ATTR(name, permission, show_ptr, store_ptr)

…where, name is the name with which the attribute is to be created, permission is file permission where 0666 is read and write permission, show_ptr is the function pointer called when the file is read, and store_ptr is the function pointer called when the file is written. The example_attr defined above is then grouped in the struct attribute group as follows: struct attribute *example_attrs[] = { &example_attr.attr, NULL, };

Note: In the struct attribute, multiple attributes can be grouped together and then be created in one single API call. Also, NULL termination is compulsory for the group. The above attributes are then given to the attribute group as follows: struct attribute_group example_attr_group = { .attrs = example_attrs, };

To create attributes, the following sysfs API is used: int sysfs_create_group(struct kobject *kobj, const struct attribute_group *grp);

…where, kobj: This is the pointer to the kobject of the directory in which the file is to be created. grp: This is the group of attributes to be created, which will be created as files in sysfs. To create the example_info file in our /sys/kernel/ example_dev directory, the following sysfs API is called: sysfs_create_group(example_dev_kobj,&example_attr_group);

After this function, a file named example_info will be created in the sys/kernel/example_dev directory. Now, whenever the file is read, the example_show function will be called and whenever the file is written, the example_store function will be called, which needs to be defined. The function prototype for the show and store function is as follows: ssize_t (*show)(struct kobject * kobj, struct attribute * attr, char * buff);

…where, kobj: This is the pointer to the kobject of the directory

Developers

which was passed when the file was created. attr: This is the attribute pointer of the file which was passed when file was created. buff: This is the buffer in which the output should be written, which will be displayed as the result in user space. The value written should not exceed the size defined by the PAGE_SIZE macro. ssize_t (*store)(struct kobject * kobj, struct attribute * attr, const char * buff, size_t size);

…where, kobject and attr are as described above. buff: This buffer contains the value that was written to the file from user space. size: This is the size of the data written to the file through user space. So our example_show function can be defined as follows: ssize_t example_show(struct kobject *kobj, struct kobj_ attribute *attr, char *buf) { return sprintf(buf, “example show”); /*Here any value of variable can be written and exposed to user space through this interface also return value is the size of data written to the buffer*/ }

…and an example store can be written as follows: static ssize_t example_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { //here the value from the buff can be read and //respective action can be taken by module return count; //return the number of bytes read, if all the //bytes are read the count parameter which //was received by store routine }

Driver sysfs interface

Drivers are modules written to interface user space with hardware devices. Hardware devices have information, which the user needs to know during their operation. So drivers generally create sysfs files for providing their information to user space. Drivers don’t explicitly create directories in sysfs. Whenever drivers register with their sub-system, directories are internally created for the driver. Each driver has access to the struct device pointer for the device for which the driver is being written. This device pointer is used to create files in the driver interface. www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 23


Developers

How To

Drivers create one file for each piece of device information that is to be exposed to the user space through sysfs. Drivers use a special API for file creation in the user space, and this is as follows: int device_create_file(struct device *dev, const struct device_attribute *attr);

…where, dev: This is the pointer to the device structure of the driver module. attr: This is the attribute which is to be created. For removal of the file from the sysfs directory, the following interface can be used: void device_remove_file (struct device *dev, const struct device_attribute *attr)

…where, kobj: This is the pointer to the kobject that represents the directory in which the link is to be created. target: This is the target directory to which the link is to be pointed. name: This is the name with which the link is to be created. For our example, the link is created as follows: sysfs_create_link(ex1_kobj, ex2_kobj, “ex2”);

To delete symbolic links, the following interface is available: void sysfs_remove_link(struct kobject *kobj, char *name);

In our example, to delete the link, the following function is called: sysfs_remove_link(ex2_kobj, “ex2”);

Sysfs object relationship

References Let’s suppose there is the directory /sys/kernel/example1, the kobject pointer of which is ex1_kobj and there is a need to create a link file in the /sys/kernel/example2 directory named ‘ex2’, which has to show the relationship with the example1 directory. This can be accomplished by symbolic links in sysfs. Also, the kobject pointer of the example2 directory is ex2_kobj. Symbolic links are created in sysfs through the following interface: int sysfs_create_link(struct kobject *kobj, struct kobject *target, char *name);

[1] https://www.kernel.org/doc/Documentation/ filesystems/sysfs.txt [2] http://lxr.missinglinkelectronics.com/linux/drivdri/ rtc/rtc-ds1343.c [3] https://www.kernel.org/pub/linux/kernel/pepepe/ mochel/doc/papers/ols-2005/mochel.pdf

By: Raghavendra Chandra Ganiga The author is an embedded firmware development engineer at K2 Technosoft Pvt Ltd, Pune. His interests are microcontrollers, networking firmware, RTOS development and Linux device drivers. You can contact him at ravi23ganiga@gmail.com

osFy Magazine Attractions during 2015-16 Month

theMe

buyers’ guide

March 2015

Open Source Firewall and Network security

SSD for Servers

April 2015

Web Development

Network Switches

May 2015

Virtualisation (containers)

Wireless Routers for SME

June 2015

Open source Databases

PaaS Solution

July 2015

Network Monitoring

MFD Printers for SMEs

August 2015

Mobile App Development

Hosting Solutions

September 2015

Backup and Data Storage

External HDD

October 2015

Mobile App Development

IaaS Solution

November 2015

Cloud Special

Firewall and UTMs

December 2015

Open Source on Windows

Online Backup solutions

January 2016

Android Special

Wifi Hotspot Devices

February 2016

Top 10 of Everything

External Storage

24 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com


How To

Open Gurus

Using Scilab with the McCabe-Thiele Method

Cross-platform, open source numerical computational package, Scilab, can be used for image enhancement, fluid dynamics simulations and numerical optimisation, among other things. When used with the McCabe-Thiele method, which is said to be the simplest and perhaps most instructive method for the analysis of binary distillation, the combination is formidable.

T

he McCabe-Thiele method was published 90 years ago by Warren L. McCabe and Ernest W. Thiele in an article titled ‘Graphical Design of Fractionating Columns’. To use their own words, “… the method consists essentially in drawing, on the same rectangular plot, the equilibrium curve for vapour and liquid compositions and straight lines representing the equations for enrichment from plate to plate, and passing from one to another in a series of steps.” Scilab is an open source software for numerical computation with a syntax similar to MathWorks’ MATLAB. The aim of this article is to show how Scilab can be used to plot the McCabe-Thiele diagram and simulate the distillation of a binary mixture. All the Scilab examples presented here are made under Linux Mint 17 Xfce.

The vapour-liquid equilibrium curve

First, it’s necessary to plot the vapour-liquid equilibrium (VLE) curve for the most volatile (lower-boiling) component in the mixture. For the two mixtures discussed here (ethanol/ water and chloroform/methanol), the data points (x,y) are taken from the third reference given at the end of this article. Note that the point at which the VLE curve cuts the diagram on the

diagonal is called the azeotrope. At this point, the vapour phase has the same composition as the liquid phase and the mixture cannot be separated by a simple distillation. The data points are now fitted with three different techniques to obtain the VLE curve equation: Cubic spline monotone Rational function 1 (with four coefficients) Rational function 2 (with six coefficients) // Rational function 1 deff(“[y]=f(a,b,c,d,x)”,”y=((a+b*x)./(1+c*x+d*x.^2))”); deff(“[e]=res(A,x,y)”,”e=f(A(1),A(2),A(3),A(4),x)-y”); Ainit=[1;1;1;1]; [S,coe]=leastsq(list(res,x,y),Ainit); yp1=f(coe(1),coe(2),coe(3),coe(4),xx); // Rational function 2 deff(“[y]=f(a,b,c,d,e,f,x)”,”y=((a+b*x+c*x.^2)./ (1+d*x+e*x.^2+f*x.^3))”); deff(“[e]=res(A,x,y)”,”e=f(A(1) ,A(2), A(3),A(4),A(5),A(6),x)-y”); Ainit=[1;1;1;1;1;1]; [S,coe]=leastsq(list(res,x,y),Ainit); yp2=f(coe(1),coe(2),coe(3),coe(4),coe(5),coe(6),xx); www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 25


Open Gurus

How To and fourth references at the end of this article. Then it’s possible to draw another line called the operating line for the enriching section (the section above the feed inlet, the yellow line in Figures 4 and 5). This second line starts on the diagonal at the xD value and cuts the y-axis at the value xD/(R+1). The last line is called the operating line for the exhausting section (the section below the feed inlet, the magenta line in Figures 4 and 5). This third line starts on the diagonal at the xB value and ends at the intersection (xi,yi) of the two previous lines.

Figure 1: The VLE curve for the ethanol/water mixture

Figure 2: The VLE curve for the chloroform/methanol mixture // Cubic spline monotone df=splin(x,y,”monotone”); [yyf,yy1f,yy2f]=interp(xx,x,y,df); plot([0,1],[0,1],”c-”,.. xx,yp1,”b-.”,.. xx,yp2,”g-”,.. xx,yyf,”k-.”,.. x,y,”ko”);

// // // // //

Diagonal Rational function 1 Rational function 2 Cubic spline monotone Data points

The Rational function 2 was chosen as the most interesting (see the green curve in Figures 1 and 2) and six coefficients will be used to define each VLE curve. A simple polynomial model was not chosen because of its instability.

The McCabe-Thiele method

The next step is to draw the q-line. This line starts on the diagonal at the xF value and has a slope which depends on the feed thermal conditions. In Figures 4 and 5, because we have a saturated-liquid feed, the q-line is vertical. For the other q-line types, see the third 26 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

xF=0.35; // Feed mole fraction xD=0.6; // Distillate mole fraction xB=0.05; // Bottom product mole fraction R=1.5; // Reflux ratio R=L/D q=1; // Feed thermal conditions xi=(-(q-1)*(1-R/(R+1))*xD-xF)/((q-1)*R/(R+1)-q); // Intersection x point yi=(xF+xD*q/R)/(1+q/R); // Intersection y point plot([0,1],[0,1],”c-”,.. // Diagonal xx,yp,”k-”,.. // Rational function 2 [xF,xi],[xF,yi],”k-”,.. // q-line [xD,xi],[xD,yi],”y-”,.. // Operating line enriching section [xB,xi],[xB,yi],”m-”); // Operating line exhausting section

Finally, it’s possible to draw the steps between the operating lines and the VLE curve and then count them (Figures 4 and 5). These steps represent the equilibrium stages (theoretical plates) required to carry out the distillation at the given conditions. The required number of theoretical plates is seven for the example in Figure 4, and six for the example in Figure 5. The Scilab code used to plot the operating lines and the equilibrium stages is adapted to Scilab from the MATLAB code written by Housam Binous, as reported in the fifth reference at the end of this article. // VLE curve equation function f=equilib(x) f=y-((coe(1)+coe(2)*x+coe(3)*x.^2)./(1+coe(4)*x+coe(5)*x. ^2+coe(6)*x.^3)); endfunction // Enriching section i=1; xp(1)=xD; yp(1)=xD; y=xD; while (xp(i)>xi), xp(i+1)=fsolve(0.01,equilib); // Steps x coordinates yp(i+1)=R/(R+1)*xp(i+1)+xD/(R+1); // Steps y coordinates y=yp(i+1); plot([xp(i),xp(i+1)],[yp(i),yp(i)],”r-”); // Steps plot if (xp(i+1)>xi) then plot([xp(i+1),xp(i+1)],[yp(i),yp(i+1)],”r-”); //


How To

Open Gurus

Figure 3: Very simplified schema for a generic distillation process Figure 5: Distillation of the chloroform/methanol mixture

Figure 4: Distillation of the ethanol/water mixture Vertical lines end i=i+1; end // Exhausting section SS=(yi-xB)/(xi-xB); yp(i)=SS*(xp(i)-xB)+xB; y=yp(i); plot([xp(i),xp(i)],[yp(i-1),yp(i)],”g-”); // Vertical line while (xp(i)>xB), xp(i+1)=fsolve(0.01,equilib); // Steps x coordinates yp(i+1)=SS*(xp(i+1)-xB)+xB; // Steps y coordinates y=yp(i+1); plot([xp(i),xp(i+1)],[yp(i),yp(i)],”b-”); // Steps plot if (xp(i+1)>xB) then plot([xp(i+1),xp(i+1)],[yp(i),yp(i+1)],”b-”); // Vertical lines end i=i+1; end

Figures

Notes

1

Reference 3 at the end of the article does not give the data beyond the azeotrope.

3

F, feed; L, liquid; D, distillate; R=L/D, reflux ratio; B, bottom product; C, distillation column; E1, condenser; E2, reboiler.

4

xF (feed composition)=0.4; xD (distillate composition)=0.75; xB (bottom product composition)=0.05; R=1.5; q=1.

5

xF=0.35; xD=0.6; xB=0.05; R=1.5; q=1.

With Scilab, it’s possible to calculate the equation of a vapour-liquid equilibrium curve with the use of a rational function, at least as a first guess. Probably, in the future, it will be necessary to improve this kind of rational function. Then it will be possible to simulate a distillation process to obtain the number of equilibrium stages. I hope this article will stimulate the reader’s curiosity about Scilab. References [1] McCabe, Thiele, Graphical Design of Fractionating Columns, Industrial and Engineering Chemistry, 1925, 17 (6), 605-611 [2] http://www.scilab.org, last visited on 26/12/2014 [3] Perry, Green, Maloney (editors), Perry’s Chemical Engineers Handbook, 7th edition, McGraw-Hill, New York, 1997 [4] Foust, Wenzel, Clump, Maus, Andersen, I principi delle operazioni unitarie (Principles of Unit Operations), Casa Editrice Ambrosiana, Milan, 1967 [5] http://www.mathworks.com/matlabcentral/fileexchange/ 4472-mccabe-thiele-method-for-an-ideal-binary-mixture, last visited on 26/12/2014.

By: Stefano Rizzi The author works in the analytical chemistry and textile chemistry areas. He has been a Linux user since 1998.

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 27




Developers

How To

How to Install Moodle on a LAMP Server

Moodle, the free and open source learning platform, can be used to create private websites for dynamic online courses. Moodle can be used in the academic as well as corporate world for e-learning projects. So let’s find out how to install it.

M

oodle is an open source learning management system (LMS) that can be used for academic as well as administrative tasks. It was founded by Martin Dougiamas and is an acronym for Modular Object Oriented Dynamic Learning Environment. This LMS acts as a powerful teaching-learning tool as it comes bundled with many features that can be used by teachers, students or administrative staff. In this article, we explore how to install Moodle on a LAMP server. The operating system used here is Linux Mint 17.1 ‘Rebecca’. The prerequisites for Moodle version 2.8 (the latest) are: PHP 5.4.4 MySQL 5.5.31 Mozilla Firefox 25.0 Apache 2, to host the site The following steps will help you install Moodle on your server in no time. 1. Download a stable version of Moodle from https:// download.moodle.org/releases/latest. 2. Extract the directory in the document root of the server 30 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

(e.g., /var/www/html/moodle). 3. Also create an empty directory with the name ‘moodledata’ in the directory, one level above the document root (e.g., /var/www/moodledata). 4. Set the permissions of Moodle and ‘moodledata’ as follows: chmod -R 777 /var/www/html/moodle chmod -R 777 /var/www/moodledata

The permissions are set to 777 so that the installation script can read/write contents from and to the files in the directories. 5. Create an empty directory using phpMyAdmin or the mySQL console. To use phpMyAdmin, type localhost/ phpmyadmin in the browser’s address bar. Log on, and select the Databases tab. Enter the name of the database and click on the Create button. 6. In a new tab in the browser, type localhost/moodle to begin the installation process. 7. Select the language and click on Next. The default language is English.


How To

Developers

Figure 3: Front page setting

Figure 4: Manage authentication

Figure 5: Server checks php.ini file Figure 1: Moodle installation

Figure 4: Step 11 a Figure 5: Step 11 b

12. The plugins being installed will be displayed. Click on Continue after all the plugins have been installed. 13. Enter the details of the admin user. Then click on Update profile. 14. Enter the site name and other details, and click on Save changes. Moodle has been installed successfully. You can now create categories and courses on the site. Moodle comes with a set of default features such as assignments, files, forums, quizzes. To add more features, you can download plugins from https://moodle. org/plugins/ and install them on your site.

Figure 2: Server check page

8. Enter the path of the data directory, that is, the moodledata directory (/var/www/moodledata). 9. Select Improved MySQL as the database driver and click on Next. 10. Read the copyright notice and click on Continue. 11. In the Server checks page, if the status of any PHP extension is ‘Not OK’, enable the appropriate PHP extension. The configuration for PHP can be found in the php.ini file (/etc/php5/apache2/php.ini). Click on Continue.

References [1] https://docs.moodle.org/25/en/History [2] https://docs.moodle.org/dev/Moodle_2.8_release_notes

By: Gayatri Venugopal The author is assistant professor at Symbiosis Institute of Computer Studies and Research (SICSR), Pune, and is involved in the development and maintenance of Moodle at SICSR. She can be contacted at gayatrivenugopal3@gmail.com.

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 31


Developers

How To

Access Redis and PostgreSQL Databases with Haskell

Named after logician Haskell Curry, Haskell is a standardised,general-purpose, purely functional programming language, with non-strict semantics and strong static typing. This tenth article on Haskell explores access to Redis and PostgreSQL databases using Haskell modules.

T

he Hackage website at https://hackage.haskell.org/ packages/#cat:Database provides a vast number of database packages that you can use, a couple of which will be covered here. You will need to install the cabal-install tool on Fedora, for example, using the following command:

$ cabal install hedis

$ sudo yum install cabal-install

You can then test connectivity to the Redis server using the redis-cli command by issuing the PING command as follows:

Connecting to the Redis database

Let’s use the hedis package to connect to the Redis server. Install the Fedora dependency package alex, and the Redis server as shown below:

This installs the latest hedis version 0.6.5. You can now start the Redis server on Fedora using the service command: $ sudo service redis start

$ redis-cli

$ sudo yum install alex redis

127.0.0.1:6379> PING PONG

You can then install the hedis package using the following commands:

You can also test the same using the hedis package inside the GHCi interpreter as illustrated below:

$ cabal update

$ ghci

32 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com


How To GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done.

Developers

ghci> :t conn conn :: Connection ghci> :t connect connect :: ConnectInfo -> IO Connection

ghci> :m Database.Redis ghci> :t runRedis runRedis :: Connection -> Redis a -> IO a

ghci> conn <- connect defaultConnectInfo Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading

package package package package package package package package package package package package package package package package package package package package package package package

array-0.4.0.1 ... linking ... done. base-unicode-symbols-0.2.2.4 ... linking ... done. deepseq-1.3.0.1 ... linking ... done. old-locale-1.0.0.5 ... linking ... done. time-1.4.0.1 ... linking ... done. transformers-0.3.0.0 ... linking ... done. bytestring-0.10.0.2 ... linking ... done. text-0.11.3.1 ... linking ... done. stm-2.4.2 ... linking ... done. primitive-0.5.0.1 ... linking ... done. vector-0.10.0.1 ... linking ... done. hashable-1.1.2.5 ... linking ... done. transformers-base-0.4.1 ... linking ... done. monad-control-0.3.2.1 ... linking ... done. containers-0.5.0.0 ... linking ... done. attoparsec-0.10.4.0 ... linking ... done. mtl-2.1.2 ... linking ... done. BoundedChan-1.0.3.0 ... linking ... done. bytestring-lexing-0.4.3.2 ... linking ... done. unix-2.6.0.1 ... linking ... done. network-2.6.0.2 ... linking ... done. resource-pool-0.2.3.2 ... linking ... done. hedis-0.6.5 ... linking ... done.

ghci> runRedis conn ping Right Pong

ghci> :t defaultConnectInfo defaultConnectInfo :: ConnectInfo

The different options that can be used in defaultConnectInfo are as follows: = = = = = =

“localhost� PortNumber 6379 Nothing 0 10 20

If the Redis server was not started, and you tried to issue the ping command, the following exception would be automatically thrown by the package: ghci> runRedis conn ping *** Exception: connect: does not exist (No route to host)

You can automate the above code snippets into Haskell code with a main function, as demonstrated below: {-# LANGUAGE OverloadedStrings #-} import Database.Redis main :: IO (Either Reply Status) main = do conn <- connect defaultConnectInfo runRedis conn ping

The OverloadedStrings extension allows string literals to be polymorphic for the IsString class. You can compile and run the above code inside GHCi, as follows: $ ghci ping.hs

I would recommend that you use defaultConnectInfo to connect to the database, and its type is ConnectInfo:

connectHost connectPort connectAuth connectDatabase connectMaxConnections connectMaxIdleTime

ghci> :t ping ping :: RedisCtx m f => m (f Status)

------

Redis port No authentication SELECT database 0 Up to 10 connections Keep connection open for 20 seconds

The types of conn, connect, runRedis and ping are given below:

GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. [1 of 1] Compiling Main ( ping.hs, interpreted ) Ok, modules loaded: Main. ghci> main ... Right Pong

The echo Redis command is used to print a message that is passed as an argument to it. The equivalent hedis echo command expects the message to be of type ByteString. For example: {-# LANGUAGE OverloadedStrings #-} import Database.Redis import qualified Data.ByteString as B www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 33


Developers

How To

bytes :: B.ByteString bytes = “Hello, World” :: B.ByteString

You can also retrieve the value of a key using the get function. For example:

main :: IO (Either Reply B.ByteString) main = do conn <- connect defaultConnectInfo runRedis conn $ echo bytes

{-# LANGUAGE OverloadedStrings #-} import Database.Redis import Control.Monad.IO.Class

Loading the above code in GHCi produces the following output: ghci> main Right “Hello, World”

The type signature of the echo function is as follows:

main :: IO () main = do conn <- connect defaultConnectInfo runRedis conn $ do result <- get “a” liftIO $ print result

Executing the above code in GHCi gives the expected result:

echo :: RedisCtx m f => Data.ByteString.Internal.ByteString -> m (f Data.ByteString.Internal.ByteString)

ghci> :l get.hs [1 of 1] Compiling Main Ok, modules loaded: Main.

You can set a value to a key using the set function in hedis. An example is shown below:

ghci> main Right (Just “apple”)

{-# LANGUAGE OverloadedStrings #-} import Database.Redis

The liftIO function transforms an IO action into a Monad. Its type signature is shown below:

main :: IO (Either Reply Status) main = do conn <- connect defaultConnectInfo runRedis conn $ set “a” “apple”

ghci> :t liftIO liftIO :: MonadIO m => IO a -> m a The type signature of the get function is as follows: ghci> :t get get :: RedisCtx m f => Data.ByteString.Internal.ByteString -> m (f (Maybe Data.ByteString.Internal.ByteString))

Loading the above set.hs code in GHCi and testing the same produces the following output: ghci> :l set.hs [1 of 1] Compiling Main Ok, modules loaded: Main.

( set.hs, interpreted )

ghci> main Right Ok

The type signature of the set function is shown below: ghci> :t set set :: RedisCtx m f => Data.ByteString.Internal.ByteString -> Data.ByteString.Internal.ByteString -> m (f Status)

( get.hs, interpreted )

You are encouraged to read the Database.Redis documentation page that contains a comprehensive list of commands and their usage at https://hackage.haskell.org/ package/hedis-0.6.5/docs/Database-Redis.html.

Accessing the PostgreSQL database

We shall now explore accessing a PostgreSQL database using the postgresql-simple (0.4.10.0) package. You will need to install and configure PostgreSQL for your GNU/Linux distribution. Please follow your distribution documentation to do so. On Fedora, for example, you can install the database server using the following command: $ sudo yum install postgresql-server postgresql-contrib

You can verify the value of the key ‘a’ from the redis-cli command, and it must return the value “apple”: 127.0.0.1:6379> get a “apple” 34 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

You can then start the database server using the following service command:


How To $ sudo service postgresql start

You can now install the postgresql-simple package using the cabal command: $ cabal install postgresql-simple

Let us first create a database and a schema using the Postgresql command-line utility psql: $ psql -U postgres Password for user postgres: psql (9.3.5) Type “help” for help. postgres=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -------------+----------+-------------+-------------+-------postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | template0| postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/ postgres + postgres=CTc/postgres template1 | postgres | UTF8| en_US.UTF-8 | en_US.UTF-8 | =c/postgres + postgres=CTc/postgres (3 rows) postgres=# CREATE DATABASE test; CREATE DATABASE postgres-# \c test

You are now connected to database ‘test’ as user ‘postgres’. test=# create schema social; CREATE SCHEMA test=# \dn public | postgres social | postgres

We can then create a users’ table with an ID, first name and last name using the postgresql-simple package: {-# LANGUAGE OverloadedStrings #-} import Database.PostgreSQL.Simple main :: IO () main = do conn <- connect defaultConnectInfo { connectUser = “postgres”

Developers

, connectPassword = “postgres123” , connectDatabase = “test” } execute conn “create table social.users (id INT, fname VARCHAR(80), lname VARCHAR(80))” () close conn

Loading the above code in GHCi creates the table social.users as shown below: $ ghci create.hs GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. [1 of 1] Compiling Main ( create.hs, interpreted ) Ok, modules loaded: Main. ghci> main Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading

package package package package package package package package package package package package package package package package package package package package package package package package package package package package package package package package

array-0.4.0.1 ... linking ... done. deepseq-1.3.0.1 ... linking ... done. bytestring-0.10.0.2 ... linking ... done. containers-0.5.0.0 ... linking ... done. text-0.11.3.1 ... linking ... done. attoparsec-0.10.4.0 ... linking ... done. blaze-builder-0.3.1.1 ... linking ... done. dlist-0.5 ... linking ... done. hashable-1.1.2.5 ... linking ... done. transformers-0.3.0.0 ... linking ... done. mtl-2.1.2 ... linking ... done. old-locale-1.0.0.5 ... linking ... done. syb-0.4.0 ... linking ... done. pretty-1.1.1.0 ... linking ... done. template-haskell ... linking ... done. time-1.4.0.1 ... linking ... done. unordered-containers-0.2.3.0 ... linking ... done. primitive-0.5.0.1 ... linking ... done. vector-0.10.0.1 ... linking ... done. aeson-0.6.2.1 ... linking ... done. random-1.0.1.1 ... linking ... done. scientific-0.2.0.2 ... linking ... done. case-insensitive-1.0.0.1 ... linking ... done. blaze-textual-0.2.0.8 ... linking ... done. postgresql-libpq-0.9.0.2 ... linking ... done. binary-0.7.4.0 ... linking ... done. cereal-0.3.5.2 ... linking ... done. entropy-0.2.2.1 ... linking ... done. tagged-0.6 ... linking ... done. crypto-api-0.11 ... linking ... done. cryptohash-0.9.0 ... linking ... done. network-info-0.2.0.5 ... linking ... done.

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 35


Developers

How To

Loading package uuid-1.3.8 ... linking ... done. Loading package postgresql-simple-0.4.10.0 ... linking ... done.

You can verify the created table from the psql prompt: test=# id fname lname

\d | | |

social.users integer | character varying(80) | character varying(80) |

You can also list the databases in the PostgreSQL server using the query_ function as illustrated below: {-# LANGUAGE OverloadedStrings #-} import Database.PostgreSQL.Simple main :: IO () main = do conn <- connect defaultConnectInfo { connectUser = “postgres” , connectPassword = “postgres123” , connectDatabase = “test” } databases <- query_ conn “SELECT datname FROM pg_database” print (databases :: [Only String]) close conn

Executing the above code in GHCi produces the following output: $ ghci show.hs GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. [1 of 1] Compiling Main ( show.hs, interpreted ) Ok, modules loaded: Main. ghci> main [Only {fromOnly = “template1”},Only {fromOnly = “template0”},Only {fromOnly = “postgres”},Only {fromOnly = “test”}]

You can now insert a record into the databases using the execute function: execute conn “insert into social.users (id, fname, lname) values (?, ?, ?)” [“1” :: String, “Edwin” :: String, “Brady” :: String]

After executing the above code, you can verify the database entry from the psql prompt: test=# select * from social.users; id | fname | lname 36 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

----+-------+------1 | Edwin | Brady (1 row)

You can also do batch inserts using the executeMany function. For example: executeMany conn “insert into social.users (id, fname, lname) values (?, ?, ?)” [(“2” :: String, “Simon” :: String, “Marlow” :: String), (“3” :: String, “Ulf” :: String, “Norell” :: String)]

After running the above code, you can check the newly added rows in the database from the psql command-line tool: test=# select * from social.users; id | fname | lname ----+-------+-------1 | Edwin | Brady 2 | Simon | Marlow 3 | Ulf | Norell (3 rows)

You can also change a record entry using the UPDATE statement as shown below: execute conn “update social.users SET lname = ‘Peyton Jones’ where fname = ‘Simon’” ()

The corresponding entry is updated as seen from the psql prompt: test=# select * from social.users; id | fname | lname ----+-------+-------------1 | Edwin | Brady 3 | Ulf | Norell 2 | Simon | Peyton Jones (3 rows)

It is recommended that you catch exceptions when running database commands. Consider the following example, where the number of arguments passed does not match with what is expected: {-# LANGUAGE OverloadedStrings #-} import Database.PostgreSQL.Simple import Control.Exception import GHC.Int main :: IO () main = do conn <- connect defaultConnectInfo { connectUser = “postgres”

Continued on page ...39


How To Developers

BOOTSTRAP: Building an Interactive Tourism Web Page A well designed, interactive Web page offers satisfaction to the client, user and, above all, to the developer. The authors of this tutorial present an interactive tourism Web page that was created using Bootstrap. The whole process is explained lucidly and the code is all there, so that enthusiasts can wade into it straight away!

B

ootstrap is a free and open source HTML5, JS and CSS framework for building well designed, responsive, mobile first websites and Web applications, at very short notice. Besides, the Twitter Bootstrap framework provides a standard and consistent way to render Web pages across browsers and devices (from phones and tablets to desktops). In this article, we explore the fundamentals of this very handy tool, and demonstrate how to create a simple yet interactive tourism Web page using Bootstrap as one of the templates.

Get started with Bootstrap

To get started, one can download the latest Bootstrap version from http://getbootstrap. com, copy it in a folder of your choice or include it from CDN. For the example below, we are going to use CDN, as many users have already downloaded Bootstrap

from MaxCDN when visiting other websites. It will be loaded from the cache when they visit our website, resulting in faster website access.

Designing the first page using Bootstrap

The first thing any Web developer needs to do is to create a design for the Web page. Bootstrap provides some predefined website templates, which can be extended, or websites can be built from scratch. The templates or examples can be found in http:// getbootstrap.com/getting-started/#examples. Our Web page is divided into four sections using the marketing template provided by Bootstrap: 1. Navigation bar 2. Navigation tab and slide show 3. Content section 4. Footer

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 37


Developers

How To

To get started, add HTML5 DOCTYPE. Bootstrap uses HTML5 elements and CSS properties, which require HTML5 DOCTYPE at the beginning of the page.

</form>

<!DOCTYPE html>

Adding the navbar-brand class gives the Web page’s name. Following that, there is the form-group div containing the placeholder for the username and password, followed by two form elements—Sign In and Register, which can be used to navigate to the required pages. Now, let us add a slide show of pictures as the background for our Web page. The Bootstrap carousel is an interactive slider that is both responsive and flexible enough to contain not just pictures but videos, divs, frames, etc. The code for the carousel is divided into three parts. The first part, which is the ‘DOT indicators’, aims at displaying simple dots in the bottom centre of the images or the content to be displayed. These are meant for manual sliding across the different slides. The second part contains the actual content in the form of div elements. In our case, we have collected a few images that will be shifting around in the background. The last part contains the controls in the form of left and right arrows, also meant for the user to slide across the content.

<html lang=”en”> Defining <head>:

To build a responsive, mobile first Web page and to ensure proper rendering in any device, add the following line: <meta name=”viewport” content=”width=device-width, initialscale=1”>

The next step is to add relevant style sheets and JavaScript files to the head section, as follows: <link href=”https://maxcdn.bootstrap.com/bootstrap/3.3.2/css/ bootstrap.min.css” rel=”stylesheet”> <link rel=”stylesheet” type=”text/css” href=”CSS/custom.css”> <link rel=”stylesheet” href=”http://maxcdn.bootstrapcdn.com/ bootstrap/3.3.2/css/bootstrap-theme.min.css”>

</div><!--/.navbar-collapse --> </div> <!-- container closed-->

<link href=”https://maxcdn.bootstrap.com/bootstrap/3.3.2/css/ bootstrap.min.css” rel=”stylesheet”>

<div id=”myCarousel” class=”carousel container slide”>

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/

<ol class=”carousel-indicators”> <!-- Dot Indicators -->

jquery.min.js”></script>

<li data-target=”#myCarousel” data-slide-to=”0”></li>

<script src=”http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/ bootstrap.min.js”></script>

<li data-target=”#myCarousel” data-slide-to=”1” class=”active”></li> <li data-target=”#myCarousel” data-slide-to=”2”></li></ol>

Let’s begin with the <Body> section. We need to first define a fixed navigation bar at the top of the Web page:

div>

<nav class=”navbar navbar-default”> <!—This will be fixed at the

alt=”” /></div>

<div class=”carousel-inner”> <!-- slides --> <div class=”item”><img src=”images/pic1.jpg” alt=”” /></ <div class=” active item”><img src=”images/pic2.jpg”

top --> <div class =”container”> <!—see everything as container--> <div class=”navbar-header”>

<div class=”item”><img src=”images/pic3.jpg” alt=”” /></ div></div> <!—Slide Navigation -->

<button type=”button” class=”navbar-toggle collapsed” data-

<a class=”left carousel-control” href=”#carousel-example-generic”

toggle=”collapse” data-target=”#navbar” aria-expanded=”false”

role=”button” data-slide=”prev”>

aria-controls=”navbar”>

<span class=”glyphicon glyphicon-chevron-left” aria-

<span class=”sr-only”>Toggle navigation</span></button>

hidden=”true”></span>

<a class=”navbar-brand” href=”#Home” style=”margin-top: 0”>

<span class=”sr-only”>Previous</span></a>

<h4><em><strong>Leisurely Getaways</strong></em></h4></a>

<a class=”right carousel-control” href=”#carousel-example-

</div>

generic” role=”button” data-slide=”next”>

<div id=”navbar” class=”navbar-collapse collapse”>

<span class=”glyphicon glyphicon-chevron-right” aria-

<form class=”navbar-form navbar-right”>

hidden=”true”></span>

<div class=”form-group”>

<span class=”sr-only”>Next</span></a></div>

<input type=”text” placeholder=”Email” class=”form-control”></ div> <div class=”form-group”> <input type=”password” placeholder=”Password” class=”formcontrol”></div>

Bootstrap offers multiple ways of customising the way the carousel is rendered on the browser. The small JavaScript code snippet shown below makes the carousel more interactive:

<button type=”submit” class=”btn btn-success”>Sign in</button> <button type=”submit” class=”btn btn-success”>Register</button>

38 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

<!-- Java Script to set interval timing for images-->


How To Developers <script type=”text/javascript”>

<p> Powered by Twitter Bootstrap 3.3.2</p></div>

$(document).ready(function() { $(‘.carousel’).carousel({interval: 4000}); }); </script>

Apart from this, the carousel plugin also offers several options like intervals, pauses and wraps to showcase your content, which makes the Web page even more dynamic, in terms of features.

Closing with the footer

The last section in our Web page, the footer, is going to contain Help and Terms and Conditions, with text aligned to the centre and the right side: <footer class=”footer”> <div class=”span4 text-center”> <p> <a href=”#”>Help</a> &nbsp <a href=”#”> Terms & Conditions</ a> &nbsp © Leisurely Getaways 2014</p> </div></footer> <div class=”span4 text-right”>

You can download the entire source code of this Web page from https://github.com/VinayPatkar/Tourist_Bootstrap.git. It contains custom.css and index.html files. As we are done creating a basic Web page using Bootstrap, it’s time to now dive deeper into it and explore its more advanced features. For more learning, refer to the links given under ‘References’. References [1] http://getbootstrap.com/examples/carousel/ [2] http://getbootstrap.com/components/#dropdowns [3] https://wrapbootstrap.com/

By: Shubhra Rana and Vinay Patkar Shubhra Rana is a software development engineer at Dell R&D, Bengaluru, and is interested in network security and cryptography. Vinay Patkar works as a software development engineer at Dell India R&D Centre, Bengaluru, and has close to two years’ experience in automation and Windows Server OS. He is interested in virtualisation and cloud computing technologies.

Continued from page ...36 , connectPassword = “postgres123”

main :: IO ()

, connectDatabase = “test”

main = do

}

conn <- connect defaultConnectInfo

result <- try (execute conn “insert into social.users (id,

{ connectUser = “postgres”

fname, lname) values (?, ?, ?)” [“4” :: String, “Laurel” ::

, connectPassword = “postgres123”

String]) :: IO (Either SomeException Int64)

, connectDatabase = “test”

case result of

}

Left ex -> putStrLn $ “Caught exception: “ ++ show ex

users <- query_ conn “SELECT fname, lname FROM social.users”

Right val -> putStrLn $ “The answer was: “ ++ show val

forM_ users $ \(fname, lname) ->

close conn

putStrLn $ Text.unpack fname ++ “ “ ++ Text.unpack lname close conn

The error is observed when the main function is executed as shown below:

The output after executing the above code in GHCi returns the actual data:

ghci> main Caught exception: FormatError {fmtMessage = “3 ‘?’ characters,

ghci> main

but 2 parameters”, fmtQuery = “insert into social.users (id,

Edwin Brady

fname, lname) values (?, ?, ?)”, fmtParams = [“4”,”Laurel”]}

Ulf Norell Simon Peyton Jones

You can also retrieve multiple records from the database and use the results, with the help of a map function. An example is illustrated below: {-# LANGUAGE OverloadedStrings #-} import Database.PostgreSQL.Simple import Control.Monad import Data.Text as Text

Please refer to the Database.PostgreSQL.Simple documentation for more examples and usage at https://hackage.haskell.org/package/postgresqlsimple-0.4.10. By: Shakthi Kannan The author is a free software enthusiast and blogs at shakthimaan.com

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 39


Developers

How To

Writing a Basic Framebuffer Driver

This article deals with the basic structure of a framebuffer and will interest those who know how to write a character device driver. The author has tried to simplify the topic as much as possible so as to make it accessible to more readers.

A

framebuffer driver is an intermediate layer in Linux, which hides the complexities of the underlying video device from the user space applications. From the point of view of the user space, if the display device needs to be accessed for reading or writing, then only the framebuffer device such as /dev/fb0 has to be accessed. If you have more than one video card in your computer, then each will be assigned separate device nodes like /dev/fb0.. /dev/fb1.. /dev/ fbX (X being the minor number of the device). We also have many different ways to access a framebuffer. To get a snapshot of your screen, you can just use the cp command, as follows:

ioctl commands include FBIOGET_VSCREENINFO and FBIOPUT_VSCREENINFO. As you may have guessed, the FBIOGET_VSCREENINFO call will ask the hardware about the screen information, and FBIOPUT_ VSCREENINFO will set the screen information. Some other ioctl commands include FBIOGETCMAP, FBIOPAN_ DISPLAY, etc. You can find the list of commands in the uapi/linux/fb.h file in the kernel source. Now, let’s look at how to write a module that will work as a very minimal framebuffer driver, with only the required components. We need a few header files in our module, and with the basic structure of a module our starting point becomes…

cp /dev/fb0 myscreen

From a programmer’s point of view, you can read and write to this device, the main use being mmap. You can map the video memory in the user space memory, and then you can control each and every pixel of your screen. We also have a set of ioctl calls to get and set different parameters of the video hardware. A few 40 | april 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

#include #include #include #include #include #include #include

<linux/module.h> <linux/kernel.h> <linux/errno.h> <linux/string.h> <linux/mm.h> <linux/slab.h> <linux/delay.h>


How To #include <linux/fb.h> #include <linux/init.h> #include <linux/pci.h> static int __init ourfb_init(void) { return pci_register_driver(&ourfb_driver); } static void __exit ourfb_exit(void) { pci_unregister_driver(&ourfb_driver); } module_init(ourfb_init); module_exit(ourfb_exit); MODULE_LICENSE(“GPL”);

So now we have a very basic module with the required init and exit function, but we have not yet defined ‘ourfb_driver’ which we are using in the code to register in the PCI subsystem. static struct pci_driver ourfb_driver = { .name = “ourfb”, .id_table = ourfb_pci_tbl, .probe = ourfb_pci_init, .remove = ourfb_pci_remove, };

In the driver structure, we have defined only the required part. If you want to use power management in your driver code and provide Suspend and Resume functionality to your hardware, then you can define that in the driver. But here we are leaving them out as they are optional. In ourfb_pci_tbl, we have to mention the vendor ID and the device ID of the hardware for which you are writing the driver. static struct pci_device_id ourfb_pci_tbl[] = { { PCI_VENDOR_ID_XXX, PCI_DEVICE_ID_XXX, PCI_ANY_ID, PCI_ ANY_ID }, { 0 } }; MODULE_DEVICE_TABLE(pci, ourfb_pci_tbl);

THE COMPLETE MAGAZINE ON OPEN SOURCE

Developers

We are assuming that PCI_VENDOR_ID_XXX and PCI_ DEVICE_ID_XXX are defined elsewhere with the correct vendor and device ID. This table should always be null terminated. To explain MODULE_DEVICE_TABLE in a very simple way –- it informs the kernel that this driver is to be used if it finds any PCI device with the mentioned vendor and device IDs. When the kernel finds the device, it calls the probe callback function; and if it sees that the device is removed, then it will call the remove callback function. A detailed discussion on PCI drivers is outside the scope of this article. static int ourfb_pci_init(struct pci_dev *dev, const struct pci_device_id *ent) { struct fb_info *info; struct ourfb_par *par; struct device *device = &dev->dev; int cmap_len, retval; info = framebuffer_alloc(sizeof(struct ourfb_par), device); if (!info) { return -ENOMEM; } par = info->par; info->screen_base = framebuffer_virtual_memory; info->fbops = &ourfb_ops; info->fix = ourfb_fix; info->pseudo_palette = pseudo_palette; info->flags = FBINFO_DEFAULT; if (fb_alloc_cmap(&info->cmap, cmap_len, 0)) return -ENOMEM; if (register_framebuffer(info) < 0) { fb_dealloc_cmap(&info->cmap); return -EINVAL; } pci_set_drvdata(dev, info); return 0; } static void ourfb_pci_remove(struct pci_dev *dp) { struct fb_info *p = pci_get_drvdata(dp); unregister_framebuffer(p); fb_dealloc_cmap(&p->cmap);

Your favourite Magazine on Open Source is now on the Web, too.

OpenSourceForU.com Follow us on Twitter@LinuxForYou

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | april 2015 | 41


Developers

How To

iounmap(p->screen_base); framebuffer_release(p); }

The above code is an example of a very simple probe function. Now, let’s talk a little about what we have used in our probe function. framebuffer_alloc: This creates a new framebuffer information structure. It also reserves the size for the driver’s private data (info->par). You might have guessed by now that ourfb_par is our private data. This function will return a pointer to struct fb_info or it returns NULL if it fails. ourfb_par: As already said, this is the private data of our driver. It is not a required component but it is recommended that you have it in your driver. At any point of time, this structure will have information about the hardware state of the graphics card. framebuffer_virtual_memory: This is not defined in our code, but it is actually the virtual memory address for the framebuffer. We get this address after remapping the resource address. The following code will show you how we get this address: unsigned long addr, size; addr = pci_resource_start(dev, 0); size = pci_resource_len(dev, 0); if (addr == 0) return -ENODEV; framebuffer_virtual_memory = ioremap(addr, 0x800000);

ourfb_ops: This structure will define the operations that we will allow on our framebuffer. We can have many operations here which are similar to any character device driver, like open, read, write, release, ioctl, etc. But the operations that we have to provide are fb_fillrect, fb_copyarea and fb_imageblit. Regarding the other operations, even if we do not mention them in our ops structure, they will be taken care of automatically by the framebuffer layer by default. If we need any customised functions for our driver, then we have to provide for them also. Fortunately, the framebuffer layer has three functions: cfb_fillrect, cfb_imageblit and cfb_copyarea. We can use these functions in our driver instead of writing our own fb_fillrect, fb_copyarea and fb_imageblit functions. But if you are writing a driver for hardware that supports hardware acceleration, then you have to write your own functions. static struct fb_ops ourfb_ops = { .owner = THIS_MODULE, .fb_fillrect = cfb_fillrect, .fb_imageblit = cfb_imageblit, .fb_copyarea = cfb_copyarea, };

ourfb_fix: This structure will contain fixed information about our hardware. The following is the structure as defined in the header file: 42 | april 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

struct fb_fix_screeninfo { char id[16]; /* identification string */ unsigned long smem_start; /* Start of frame buffer mem (physical address) */ __u32 smem_len; /* Length of frame buffer mem */ __u32 type; /* FB_TYPE_* */ __u32 type_aux; /* Interleave for interleaved Planes */ __u32 visual; /* FB_VISUAL_* */ __u16 xpanstep; /* zero if no hardware panning */ __u16 ypanstep; /* zero if no hardware panning */ __u16 ywrapstep; /* zero if no hardware ywrap */ __u32 line_length; /* length of a line in bytes */ unsigned long mmio_start; /* Start of Memory Mapped I/O (physical address) */ __u32 mmio_len; /* Length of Memory Mapped I/O */ __u32 accel; /* Indicate to driver which specific chip/card we have */ __u16 capabilities; /* FB_CAP_* */ __u16 reserved[2]; /* Reserved for future compatibility */ };

flags: This will indicate the type of hardware acceleration our driver is capable of. fb_alloc_cmap: This allocates memory for the colour map, which our driver is going to use. register_framebuffer: This is the most important function that will actually register our framebuffer with the framebuffer layer. This function is responsible for creating the device nodes /dev/fb*. Note: In the probe function, at any stage, if the initialisation fails, we have to undo whatever we have done before that, and then need to return an appropriate error value. In the ourfb_remove function, we are unwinding what we have done in the probe function in a reverse manner. We have just looked at how to create a very simple framebuffer device, though we have not touched upon any hardware related topics here. But when we work with an actual framebuffer driver that is responsible for video hardware, we need to give all the hardware initialisation routines in the probe function. If you want to see the code of any framebuffer device driver, you can find it in the drivers/ video/fbdev/ folder of the Linux source tree. Another complicated scenario: Some graphical hardware will have support for two monitors, where each display can have its own unique data. In this case, each display should have its own separate framebuffer device, which means separate struct fb_info. Some hardware will have the double-buffering capability. By: Sudip Mukherjee The author is the maintainer of the Silicon Motion SM712 framebuffer driver in the mainline kernel. He works as an embedded Linux developer at Vector India Pvt Ltd, a renowned embedded training institute. He can be reached at sudip@vectorindia.org


How To

Developers

Develop Multi-device Web Based Games with HTML5 The gaming design and development industry is growing exponentially. If you are interested in creating a Web based game, try out this HTML5 sample script.

W

ith the Internet’s capabilities evolving at a fast pace and browsers now available in almost every handheld device, Web based games are common these days. A study suggests that users spend more time on Web based games than on traditional console games. A Web game as the term suggests is an application that you can launch in your browser and play. There are several plugins available right now, which allow us to play these standard games and most popular Web browsers (like Chrome, Firefox and IE) support them. Currently, there has been an evolution from single player games to multi-player games across the Internet. A few examples are listed here: http://www.powersoccer.com http://www.miniclip.com/games/en/

How a Web based game is designed

There are three main stages in a Web based game: The presentation or UI Interpretation of the user’s actions Calculation of the results based on the above factors Any Web based game has to go through these stages to work well. These specifics may vary for a few games but are the important aspects to keep in mind before developing a game engine. In some games, users may be asked to repeat certain actions, so your script has to be made to interpret those actions to achieve specific results in the game. Several requirements are involved in the development of a Web based game, such as:

The game platform – HTML5, JavaScript, etc Plugins – ActiveX, Shockwave, etc Browser support – Internet Explorer, FireFox, Google Chrome, etc

HTML5

HTML5 has good support for lots of game frameworks, and with JavaScript support, it makes a great platform for game development. Table 1 specifies the function and technology used, along with the features.

EaselJS

EaselJS is a simple JavaScript library that makes working with HTML 5 Canvas very efficient. It provides solutions for working with graphics and interactivity with HTML5 Canvas. It also provides an API that is familiar to Flash developers, including a hierarchical display list and DOM Level 2 events. Source: http://www.createjs.com/EaselJS

Sample script

Let’s try to create a simple animation clip using EaselJS. The following is the code that will help to demonstrate the animation: <!DOCTYPE html> <html lang=”en”> <head> <title>TITLE</title> www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 43


Developers

How To

Table 1: HTML5/JavaScript features

Function

Technology

Features

Audio

Web audio API

API for processing and synthesising audio.

Graphics

WebGL (OpenGL ES 2.0)

API for rendering 3D and 2D images. Compatible with browsers supported by plugins. Note: Not supported on mobiles but can use OpenGL wrappers

Input

Touch events, gamepad API, device sensors, WebRTC, full screen API, pointer lock API

WebRTC – Getusermedia can get hardware access

Language

JavaScript (or C/C++ using Emscripten to compile to JavaScript)

JavaScript has support for lots of game engines/frameworks

Networking WebRTC and/or WebSockets

Allows interactive sessions between user’s browser and server

Storage

IndexedDB

Client side storage for data

Web

HTML, CSS, SVG, social API

Types of APIs and languages for development

Source: Mozilla Development Network and HTML5 Forum <style> #stageCanvas { background-color:#333333; } </style> <!-- import the Easel library. Downloaded from: http://easeljs.com/ --> <script src=”scripts/easel.js”></script> <script> //EaselJS Stage instance that wraps the Canvas element var stage; var circle; //radius of the circle Graphics that we will draw. var CIRCLE_RADIUS = 10; var circleXReset; var bounds; //initialize function, called when page loads. function init() { //check and see if the canvas element is supported in //the current browser if(!(!!document.createElement(‘canvas’).getContext)) { var wrapper = document.getElementById(“canva sWrapper”); wrapper.innerHTML = “Your browser does not appear to support” +”the HTML5 Canvas element”; return; } //get a reference to the canvas element var canvas = document. 44 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

getElementById(“stageCanvas”); //copy the canvas bounds to the bounds instance. bounds = new Rectangle(); bounds.width = canvas.width; bounds.height = canvas.height; //pass the canvas element to the EaselJS Stage instance stage = new Stage(canvas); //Create an EaselJS Graphics element to create the //commands to draw a circle var g = new Graphics(); //stroke of 1 px g.setStrokeStyle(1); //Set the stroke color, using the EaselJS g.beginStroke(Graphics.getRGB(255,255,255,.7)); //draw the circle g.drawCircle(0,0, CIRCLE_RADIUS); circle = new Shape(g); //set the initial x position, and the reset position circle.x = circleXReset = -CIRCLE_RADIUS; //set the y position circle.y = canvas.height / 2; //add the circle to the stage. stage.addChild(circle); //tell the stage to render to the canvas stage.update();

Continued on page... 46


Overview Developers

Popular Open Source IDEs for Web Development Let us explore popular open source IDEs for Web development. The IDEs mentioned here are just to whet the appetite of readers so that they may delve deeper into the subject. The article does not go too deep into specifics but informs just enough to rouse the curiosity of a newbie.

P

rogrammers are always looking for a handy piece of software that acts as a code editor, compiler and debugger, while also providing a fancy GUI. One doesn’t wish to type every piece of code in the text editor or use the command prompt. IDEs always maximise productivity by saving time and removing redundant tasks. For such reasons programmers look for IDEs that provide a large range of features or those that meet their specific requirements. This article lists out a few open source IDEs used for Web development. Note that they are not ranked in any particular order.

Eclipse

Eclipse is a free and open source community of tools and projects and collaborative working groups, on which many development frameworks like Web projects and applications are based. Most developers prefer IDEs rather than console-like text editors. Eclipse projects are focused on building an open development platform comprising extensible frameworks, tools and runtimes for building, deploying and managing software across its life cycle.

Aptana Studio

Aptana Studio is another widely used IDE for Web development. It’s available either as a standalone app or as a plugin for Eclipse. Aptana (the company) also offers hosting

for your projects, so if you use that service, the IDE ties in those services perfectly. It’s based on Eclipse, and supports JavaScript, HTML, DOM, CSS, code-completion, JavaScript debug capabilities, etc.

Joomla

Joomla is a content management system (CMS) that allows users to build websites and online applications. It is an easyto-use, extensible open source software. This CMS keeps track of every piece of content on your website—photos, text, music or videos. It is used in many corporate websites, portals, online news magazines, e-commerce sites, for online reservations, government applications, SME business websites... and the list goes on. Joomla is offered under GPL version 2.0 and its source code can be found at https:// github.com/joomla.

Bluefish

Bluefish is a full-featured Web editor for developers and Web programmers, which runs on Linux, Windows or Mac. It’s an open source project released under the GNU license. It is considered by far the most powerful among HTML editors. Features include a code-sensitive spell check, auto-complete in many different languages (HTML, PHP, CSS, etc), snippets, project management and auto-save. www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 45


Developers

Overview

KompoZer

KompoZer is a lightweight application, but it is a good choice even for advanced programming tasks. This open source IDE is a sweet deal—whether you’re developing in PHP, Ruby on Rails, JavaScript or something else, you’ll find rich editing features, as well as support for FTP and MySQL. With PHP, it offers light on-the-go debugging, alerting you to errors as you type. Whether you’re working with Python, PHP, Ruby, Perl, HTML, CSS or JavaScript, KompoZer provides a clean, intuitive interface with advanced editing capabilities and integrated tools for the most functionality.

Cloud9

Cloud9 is an open source online IDE with the support of up to 40 programming languages. With a pre-setup workspace, collaborative coding features and Web development features, it allows developers to get started with coding immediately. Its source code can be found in https://github.com/c9/core/ GitHub.

NetBeans

NetBeans is another open source IDE written entirely in Java by Oracle. It allows applications to be developed from a set of

modular pieces of software called modules. Though initially it was developed for Java programmers, it soon became popular for Web development. NetBeans is cross-platform and supports a compatible JVM.

Brackets

Brackets is an open source code editor written in HTML, JavaScript and CSS with a focus on Web development. It is licensed under MIT by Adobe Systems. Just like NetBeans, it’s also cross-platform. Its features include Quick Edit (inline editing of HTML, CSS, colour properties and JavaScript), live preview (pushes code instantly to the browser, with no page refresh required), Quick docs, and more. The above listed IDEs are among the many free or open source varieties available for developers. They are worth a try. By: Vinay Patkar The author works as a software development engineer at Dell India R&D Centre, Bengaluru, and has close to two years’ experience in automation and Windows Server OS. He is interested in virtualisation and cloud computing technologies.

Continued from page... 44 Ticker.setFPS(24);

<div width=”400” height=”300” id=”canvasWrapper”> <canvas width=”400” height=”300” id=”stageCanvas”></

Ticker.addListener(this); }

canvas> </div> </body>

//function called by the Tick instance at a set interval

</html>

function tick() { //check and see if the Shape has gone of the right //of the stage. if(circle.x > bounds.width) { //if it has, reset it. circle.x = circleXReset; } //move the circle over 10 pixels

To execute this sample script, follow the instructions given below: 1. Copy this script and paste it into Notepad and rename it game.html 2. Download the easel.js file and place it in the Scripts folder 3. Run game.html in the browser Over the last few years, games built for browsers have been deployed on laptops, tablets, mobiles or any other computing device. With HTML5, we have the true power of writing an application once and deploying it anywhere.

circle.x += 8; //re-render the stage

By: Gobind Vijayakumar and Avinash Bendigeri

stage.update();

Gobind Vijaykumar works in the OS engineering group of Dell India R&D Centre, Bengaluru, and has over six years of experience in server operating systems and storage solutions.

} </script> </head> <body onload=”init()”>

46 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

Avinash Bendigeri is a software development engineer at Dell R&D Centre, Bengaluru. He is interested in the automation and systems management domain.


Let’s Try

Developers

Qt5: GUIs with QtQuick and QML In the previous article on Qt5 (Part 2), we built a small server program that served a random fortune cookie to anyone who connected to it using TCP, and we tested it out by telneting into it. In the third and final part of this series, we’re going to build a small GUI client to go with the server.

W

e’ve been dabbling with Qt5 for some time now, without doing the one thing that Qt is famous for – the GUIs. Now, we’re finally going to build that GUI in the easy and fun new way using QtQuick and QML. We’ll be building a fairly complex GUI with a bit of configuration headroom, without touching a single line of C++ code for the GUI logic. That’s not to say we won’t be using C++ at all –- we’ll use it to write a QML component that does the networking bits for us. In the bargain, you’ll also learn how to extend QML and QtQuick programs with C++ code. But first, here’s a primer on QtQuick and QML.

QtQuick and QML

QtQuick made its debut in Qt4.7 but only became the recommended way of building GUIs in Qt5. Originally, QUICK stood for Qt User Interface Construction Kit, but now it’s just called QtQuick. So what is it? Well, the answer comes in two parts. The first is QML (again, originally Qt Markup Language, but now just called QML), a declarative language very much like JavaScript which can be used to declaratively describe the GUI and its logic. That’s right; you build the GUI and script

it using nothing but JavaScript. The second part is QtQuick itself, which is a set of components (or controls) that you can make use of in your QML based GUIs. QtQuick and QML were first conceived as a new way of writing UIs for Qt applications. These were meant for people without much of a programming background as, back then, Qt was used to write applications for Nokia’s Maemo and then MeeGo (and even today, it’s used to write applications for Sailfish OS). QtQuick 1.0 was quickly hacked together and did its job well, but wasn’t much of a performer. However, that didn’t stop it from being used outside the mobile development space; it was used widely in KDE’s Plasma Active and eventually in parts of Plasma 4 itself. QtQuick 2.0, which came with Qt5, was a major overhaul. Because QtQuick became so popular with developers on both desktops and mobile devices, its creators had to make it a first-class way to build GUIs. So with Qt5, they redid the entire GUI rendering pipeline, making the whole thing 3D based, and using OpenGL as a backend. The downside to this is that QtQuick 2.0 requires OpenGL support to run, even if the GUI consists only of 2D widgets, as these widgets are internally implemented as OpenGL surfaces. The upside is that QtQuick 2.0 GUIs are extremely fast. www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | april 2015 | 47


Developers

Let’s Try

So how do you run QML applications on Qt5 on systems where there’s no 3D support? Well, QtQuick 1.0 still ships with Qt5, so you can use that. Or you can drop to using standard C++ GUIs, which can fall back to 2D rendering if 3D isn’t available on the system. So that's enough of theory. Let’s build something.

Computers are not intelligent. They only think they are.

Starting off

Open up QtCreator and start a new project. This time, choose Qt Quick Application (and not Qt Quick UI, which creates a QML-only application with no C++ code). Hit Choose, set the location and hit Next. Now you’ll be presented with a drop-down list of component sets to use for the application. You’ll need to use the latest available Qt Quick Controls (at the time of writing, this is Qt Quick Controls 1.3). Qt Quick Controls is a set of desktop application widgets implemented on top of raw Qt Quick 2 (which is also available if you want to use it). Once you’re done, hit Next. Run through the rest of the wizard. Make sure Desktop is selected when you’re selecting the kits to use for the application. Check the summary, and then finish the wizard to get started with the code.

QML

At this point, you’ll be dropped into the editor with main. qml open. You’ll be able to inspect this file to figure out what QML applications look like. But let me help you out. At the top of the code, you’ll see a bunch of import statements, like in Python. These lines import the QML components that you’ll be using to write your applications. In the sample main.qml that opens up, the import lines are: import import import import

QtQuick 2.4 QtQuick.Controls 1.3 QtQuick.Window 2.2 QtQuick.Dialogs 1.2

So first, QtQuick 2 itself is imported, followed by a bunch of extensions, including Controls, which implement GUI widgets; Dialogs, which are used to create pop-up dialogue boxes, and Window, which is used to create the main application window in QML. QML components can be written in QML (remember that it’s basically JavaScript; it’s actually powered by Google’s V8, so it’s a full-blown programming language to work in) or C++. We’re going to write a component in C++ to make the QML GUI talk to the fortune cookie server. The rest of the code describes the GUI. It’s very much like HTML. There’s one root element (in this case, an ApplicationWindow, which encapsulates the rest of the element hierarchy). Notice that all elements look exactly like JSON objects, with properties that can either be other objects (like strings or numbers) or JavaScript functions. Once you’ve figured out what QML looks like (don’t 48 | april 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

Figure 1: Fortune cookie

worry if you still don’t understand how to write code yourself), we’re ready to start building our own GUI.

Building the GUI

The first thing you should do is delete the MainForm.ui.qml file in the Projects pane. We won’t be needing it since we’ll be writing the entire UI inside main.qml. Now comes the difficult bit. main.qml in our program is 150 lines long, which is a tad too long to print out in this magazine. So we’re going to have to do it a little differently. First of all, you’re going to have to fetch all the source code for this article. It’s available on my GitHub account, at https://github.com/BaloneyGeek/FortuneClientExample. Like the last article, this is a fully functioning application, so you can just clone the repository, build it and run it. But let’s see some of the code at least. We start with the imports: import import import import import

QtQuick 2.4 QtQuick.Layouts 1.1 QtQuick.Controls 1.3 QtQuick.Window 2.2 QtQuick.Dialogs 1.2

import Fortune 1.0

We’re importing a whole bunch of QtQuick extensions, including Layouts, which we’ll use to build the layout of the GUI (as the name suggests). The last thing we’re importing—Fortune 1.0—does not quite exist yet, so QtCreator is going to give it a red underline. We’ll build this component in C++ later. The next few lines set up the application window, and populate the menu bar and the status bar. We won’t reproduce the code in print, but it’s simple enough and one look will give you an idea of what’s going on. What you’ll find interesting is that there are ampersand characters in some of the strings. This is to set up keyboard shortcuts—the letter right after the ampersand symbol becomes the keyboard shortcut for that item. Then we come to the main UI form of the program. The UI features one giant label in the centre top part of the window displaying the fortune cookie, and one button at the centre bottom that can be clicked to attempt to get a


Let’s Try new fortune cookie: Item { id: mainForm; anchors.fill: parent; GridLayout { rows: 2; columns: 1; rowSpacing: 32; anchors.centerIn: parent; Label { id: mainFortuneLabel; Layout.maximumWidth: 600; Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter; text: qsTr(“Set a server, and click the Get Fortune button”); wrapMode: Text.Wrap; horizontalAlignment: Text.AlignHCenter; font.pointSize: 36; function setText(mtext) { text = qsTr(mtext); horizontalAlignment = Text.AlignLeft; horizontalAlignment = Text.AlignHCenter; } } Button { id: getFortuneButton; Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter; text: “Get Fortune”; onClicked: fortuneClient.getNewFortune();

Developers

At this point, you might find QML overwhelming—let’s face it, we’ve already dealt with about 10 components and a lot more properties of each. The truth is, QML’s component sets are pretty huge, and to study each one of them in-depth before writing code is impractical. Hence this—an application in QML to get you started, and the component reference manuals to refer to as you go along, which are linked to at the end of the article. This brings us to the one component that we must build ourselves, in order to make this GUI talk to the fortune server. This is what it looks like: FortuneClient { id: fortuneClient; onHaveFortune: mainFortuneLabel.setText(fortune); function setServerPort() { serverHost = serverTextField.text; serverPort = portTextField.text; statusBarText.text = qsTr(“OK: Server set to %1:%2”. arg(serverHost).arg(serverPort)); } }

And to explain how it works will involve another theory class and a bit of C++ coding.

The QQuickItem and the QQmlApplicationEngine

To load a QML-based UI into a Qt application, you start by creating a master QApplication instance (like all other Qt applications), but then you create a QQmlApplicationEngine instance, into which you load up your QML file. This engine executes your QML script and takes care of all the plumbing for you. In actual code, it looks something like this: QApplication app; QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral(“qrc:/main.qml”)));

} }

This implements the main form. Notice that we have a setText() function as a part of the main label to change its text. This will be triggered by the Fortune component when it obtains a new fortune cookie from the server. We’ve also had to reset the horizontal alignment every time we change the text. This is because every time the text is changed, the new text is rendered with a very weird alignment. Whether this is a bug or by design is unclear, but resetting the alignment seems to fix this. The next few lines implement the server selection dialogue box. Again, this is fairly simple but somewhat long, and to save space, we won’t reproduce it in print.

True, it’s just three lines. The engine provides a standard QtQuick environment, so all QML components that are installed on the user’s system are available for the programmer to use. But what about custom components? We’ll need to use one, so let’s figure out how to inject one into the QQmlApplicationEngine. It turns out that like the QApplication instance (which works at the global level and doesn’t need to be touched), the QQmlApplicationEngine is also a global object, into which we can inject custom components at will. Now what about those components themselves? Well, technically, any object that inherits from QObject and implements the meta-object system can be used as a QML component. Remember, QML components don’t have to be visible GUI widgets www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | april 2015 | 49


Developers

Let’s Try

only—if you use the HTML analogy, some QML components are like <script> tags and are not rendered on the screen. If you do want to create a widget, you need to inherit from QQuickPaintedItem. This base class has a lot of glue logic that’s needed for painting on the screen already implemented, and it’s easier to get access to the OpenGL context through this. If you don’t need screen access (like us), you can simply derive from QObject or if you want some of the glue taken care of, you can derive from QQuickItem. QQuickPaintedItem derives from this and adds the screen real estate management logic, but does handle screen events; so if you want a component that triggers certain actions within the application based on GUI events (without being visible), you need to derive from QQuickItem. We won’t need any of the special functionality when we implement the fortune client, but we’ll derive from QQuickItem anyway.

The code

Let’s begin. This is what the FortuneClient class looks like: #include #include #include #include

<QQuickItem> <QString> <QByteArray> <QTcpSocket>

class FortuneClient : public QQuickItem { Q_OBJECT Q_PROPERTY(QString serverHost READ serverHost WRITE setServerHost) Q_PROPERTY(int serverPort READ serverPort WRITE setServerPort) private: quint16 mPort; QString mHost;

public slots: void getNewFortune(); };

There’s a lot that’s important here. Let’s begin with the Q_PROPERTY macros, which tell the MOC to expose properties to the QML environment. The minimal syntax looks like this: Q_PROPERTY(property_type property_name READ read_function WRITE write_function)

So now you’ll know that the first Q_PROPERTY line exposes a QString property, called serverHost, to the QML environment. To read this property, the serverHost() function is called, and to write to this property, the setServerHost() function is called. Now let’s take a look at how those functions are implemented. The reader function, serverHost(), is declared const and simply returns a QString. That’s all you need to do - declare your function const, which means telling the compiler this function doesn’t change the state of the object, and return some data of the property type. Now you’ll have to do a little hackery with integer data. QML has an integer data type, and C++ has many integer data types, depending on how many bits you want to use. When you’re specifying a Q_PROPERTY, however, you can only use a standard int as its type, since all the different qint and quint types don’t have equivalents in the QML environment. So your handler functions must take care to check ranges and cast them into properly-sized integers. The other very important bit that you need to know is how the signal and slot mechanisms work with QML. First of all, there are two ways in which you can execute a C++ function from within the QML environment. The first is to precede a function declaration with the Q_INVOKABLE macro, as follows: Q_INVOKABLE void someFunction(QString some_arg);

QTcpSocket * clientSocket; public: FortuneClient(); ~FortuneClient(); QString serverHost() const; void setServerHost(QString host); quint16 serverPort() const; void setServerPort(int port); signals: void haveFortune(QString fortune); 50 | april 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

This makes the function visible from the QML environment. All functions, even public ones, are not visible from the QML environment, due to security concerns. The second way is to simply declare the function as a public slot. All public slots are visible from the QML environment. And that’s what we have done here with getNewFortune()—declared it as a slot. Now for the signals. When you define signals that are to be accessed from the QML environment, you must stick to some naming conventions. You must use camelCase(), with the initial letter being lower case. This is because in the QML environment, the signal gets turned into a property, with the name onCamelCase, to which you assign a function, JavaScript or C++, which gets executed when the signal is emitted. For example,


Let’s Try here we have a signal called haveFortune(), which becomes the property onHaveFortune inside the QML component, and gets assigned an event handler in the QML file, as follows: onHaveFortune: mainFortuneLabel.setText(fortune);

We can now take a look at the C++ code for the object:

Developers

emit haveFortune(QString(fortune)); }

You already know how we’re using this inside QML.

Firing it up

We’ll need to write main.cpp first, which is luckily less than five lines of actual code. Here it is:

#include “fortuneclient.h” FortuneClient::FortuneClient() { mPort = 0; clientSocket = new QTcpSocket(this); } FortuneClient::~FortuneClient() { clientSocket->disconnectFromHost(); clientSocket->deleteLater(); }

#include <QQmlApplicationEngine> #include “fortuneclient.h” int main(int argc, char *argv[]) { QApplication app(argc, argv); QQmlApplicationEngine engine; qmlRegisterType<FortuneClient>(“Fortune”, 1, 0, “FortuneClient”); engine.load(QUrl(QStringLiteral(“qrc:/main.qml”))); return app.exec(); }

/* accessors and mutators for the properties go first */ QString FortuneClient::serverHost() const { return mHost; } void FortuneClient::setServerHost(QString host) { mHost = host; } quint16 FortuneClient::serverPort() const { return mPort; } void FortuneClient::setServerPort(int port) { mPort = (quint16)port; } /* the slot we call to get a new fortune */ void FortuneClient::getNewFortune() { QByteArray fortune; clientSocket->connectToHost(mHost, mPort, QIODevice::ReadOnly); clientSocket->waitForReadyRead(); fortune = clientSocket->readAll(); clientSocket->disconnectFromHost();

The critical line here is the qmlRegisterType() statement, which registers a component and injects it into the QQmlApplicationEngine. The syntax is: qmlRegisterType<object_name>(“namespace”, major_version, minor_version, “component_name”);

So for the above line, you’d import the Fortune 1.0 name space, and create a FortuneClient object within the QML code. You can now go ahead and build the application, and run it. Run the server that we built last month, and in the GUI, go to Application->Set Server Details; fill in the host (127.0.0.1) and the port (56789), and hit OK. The status bar should now say OK: Server set to 127.0.0.1:56789. Go ahead and hit the Get Fortune button. If everything works fine, you’ll be greeted with your fortune cookie. References [1] The QML Documentation - http://doc.qt.io/qt-5/qtqml-index.html [2] The QML Complete Reference - http://doc.qt.io/qt-5/qmlreference.html [3] The QtQuick Documentation - http://doc.qt.io/qt-5/qtquick-index.html [4] The QtQuick QML Types Reference - http://doc.qt.io/qt-5/qtquick-qmlmodule.html

By: Boudhayan Gupta Describing himself as a ‘retard by choice’, the author believes that madness is a cure-all for whatever is wrong or right with society. A social media enthusiast, he can be reached at @BaloneyGeek on Twitter.

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | april 2015 | 51




Developers

Let’s Try

The Link+ Project for Linux Kernel Developers Kernel developers will be interested to learn how to use the LinK+ IDE, which has been developed by a team from C-DAC. The article is detailed and comprehensive.

I

n this article, discover how Linux kernel programming can be simplified using an IDE. Let’s take a look at the IDE named LinK+ which supports Linux kernel configuration, compilation and emulation, system call development and device driver development. At the end of this article, developers of Linux device drivers are sure to start loving it! The LinK+ IDE is a simple IDE for Linux kernel developers. It is based on the Eclipse IDE and is customised for Linux kernel programming. It reduces development time and executes code in an elegant fashion. The LinK+ IDE includes various templates in the categories of character, block and network device driver sub-systems for device driver development. It includes various bus infrastructure templates and also provides Linux device driver code completion, code assistance and code navigation for developers.

Features of the LinK+ IDE

The first release of this IDE is called LinK+ Avatar and it supports the following set of features: Hardware architectures: x86 and x86_64 54 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

Linux device driver auto code generation, completion and navigation Wizard for kernel configuration and compilation Reduced kernel compilation time through ccache and distcc QEMU emulator support for Linux kernel image emulation and debugging Linux system call development Supports both Debian and RPM Linux families Supports Sparse for static analysis of Linux device drivers

LinK+ IDE installation Prerequisites for Ubuntu Linux distributions

Before installing LinK+ IDE, the following set of packages needs to be installed on your machine. You can run the command shown below: dileep@dileepk:~$ sudo apt-get install openjdk-6-jdk libqt4dev libncurses5 sparse qemu qemu-system openssh-server openssh-client bridge-utils iptables dnsmasq linux-headers`uname -r`


Let’s Try

Developers

Prerequisites for other Linux distributions are mentioned in the user manual, which you can download from the link http://sourceforge.net/projects/linkplustest/files/ documentation/. You can now install LinK+ IDE using either one of the following methods.

Method 1

Download the LinK+ IDE installer from the link https:// sourceforge.net/projects/linkplustest/files/installers/. dileep@dileepk:~$ tar -xvf LinK+\ IDE-linux.gtk.x86_64.tar.gz dileep@dileepk:~$ cd LinK+\ IDE-linux.gtk.x86_64/ dileep@dileepk:~/LinK+\ IDE-linux.gtk.x86_64$./linkplus &

Method 2

Install LinK+ plugins. Before installing them, however, you should have a version of Eclipse cPP of the Helios variant already installed on your Pc. Start the Eclipse IDE and add the LinK+ repository by clicking on Help->Install New Software. Then enter the URL of the updated LinK+ site (https:// sourceforge.net/projects/linkplustest/files/repository/) and proceed with further installation procedures.

Method 3: Installation through Eclipse Market Place

Start the Eclipse IDE and click on Help->Eclipse Marketplace. Then, go to the Search button and in the Find space bar, type Linux Kernel Programming IDE. You can then click on the Install button to download the LinK+ plugins. Now that you have installed the LinK+ IDE, we can start building our own projects.

The Linux kernel configuration and compilation project

Let us begin with configuring and compiling the Linux kernel, by selecting File-> New-> Project. click on the Linux Kernel Development (Link+) option and expand it to select Kernel Compilation Project before clicking on the Next button. This will open the kernel compilation wizard as shown in Figure 1, where we can enter the project’s name. Then we need to select the Linux kernel source. Three options are provided: Select Archived Source Code, Import Source Code to Workspace and Link to Existing Kernel Source Code. Select one based on your requirement. Depending on what Linux kernel source was selected, choose the path of the kernel source by clicking on the Browse button. Next, move to the Project Build options. The LinK+ IDE is bundled with different project build options like Configuration, Compilation and Installation. These options are presented to users through multiple ways. Just right-click on the respective project in the Project Explorer view, then go

Figure 1: Kernel compilation project

to LinK to or just click on the icon of the toolbar. In my experience, how long compilation takes depends on your host system’s hardware configuration. In order to speed things up, integrate third party tools such as distcc and ccache into this IDE. To use these features in the LinK+ IDE, go to the preference page (Windows>Preference) and go to Linux Kernel Development. If you want more information on distcc and ccache, refer to the user manual as suggested earlier.

Single step execution

The LinK+ IDE also provides a one-stop solution for all configuration, compilation, installation and emulation needs. To use this feature, right-click on the respective projects in the Project Explorer view, then go to LinK to -> Single Step Execution. This will open a wizard with three pages. The first page has configuration options, the second has compilation options and the third has the option to install on host or emulate with the QEMU file system of your kernel source.

Linux kernel emulation using QEMU

After compiling the Linux kernel image, the QEMU emulator can be used to emulate the working of the Linux kernel before installing on the host. For this process, there are two options—Linux kernel emulation using QEMU with the file system and with the initrd image. You can download the Debian or RPM based ‘qcow2 file system’ image from the Internet and use it for the emulation. Just right click on the respective project under Project Explorer and go to LinK to-> Emulation -> With File System

The QEMU remote system

LinK+ IDE provides communication with remote systems using the Eclipse Remote System Plugin. The advantage of www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 55


Developers

Let’s Try

Figure 3: Toolchain list

image with QEMU and then copy the system call user application to the running QEMU. To do the above, go to LinK to -> System Call. Figure 2: Add system call

using this plugin is that the remote system’s rootfs, either running through QEMU or in the local network, will be mounted onto the IDE as a view. So transferring files to remote systems becomes easy, and the remote system shell can be viewed as a separate console in the LinK+ IDE. The complete procedure to connect with the remote systems is given in the user manual.

Linux kernel debugging using QEMU

Debugging the Linux kernel image is possible with the Eclipse cDT debugger and the QEMU emulator. Avail the debugging option by right-clicking on the respective project under Project Explorer, go to LinK to-> Emulation -> Debug with QEMU and follow the steps as mentioned in the user manual.

A project to create a Linux kernel system call

The LinK+ IDE has a wizard for adding new system calls to the kernel source. This can be done by right-clicking on the respective kernel project in the Project Explorer view, before going to LinK to -> System Call -> Add System Call. clicking on Add System Call will open a wizard as shown in Figure 2. Enter the name of the system call, then select the existing data type and click the Add Argument button. You can also create a new data type by clicking the Create a new data type link. If you want to test your system call with a system call application, enable the Include User Test application. It will create a user space application for system call testing. Finally, rebuild the project to make changes effective.

System call testing with QEMU

There are just two steps to test how the system call works when using QEMU. Run the newly added system call kernel 56 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

A Linux device driver development project

Linux device driver projects are created by selecting File>New->Project. Then go to Linux Kernel Development (Link+) and select Device Driver Project. This will open a wizard that contains three pages—one covering general information, one on the kernel’s features and the page on driver information. You can finish the project at any point in time. In the general information page, we need to fill the fields like author’s name, license type, kernel version and, finally, select the architecture and the toolchain required for it from the Toolchain list as shown in Figure 3. In the Development type dropdown box, there are two options: Custom Driver Development and Typical Driver Development. In the first option, select what you require but in the latter development type, a lot of features are automatically integrated. click on Next for other Kernel Development Features or Finish for Basic module programming. If you choose the Custom Driver Development type, follow the procedure shown below.

Advanced kernel module program and a project to create device drivers

The Linux kernel features’ page is shown in Figure 4 and contains the kernel features like: Module PArAM Delayed Works ->Kernel Timer, Tasklet, Work Queue, Shared Queue Synchronization->Semaphore, Spinlock and other options Kernel Data Types Debugging Mechanisms -> probing, proc, sys attributes All the features are optional. So you can select any feature based on requirements. On selecting a feature, the left pane


Let’s Try

Developers

Figure 5: Linux device driver specific features

Figure 4: Linux kernel features

window options change dynamically. click on Next for specific information on the driver and device, or on the Finish button to create the project with the above features. The third (and last) page has Linux device driver specific features, and is divided into two parts as shown in Figure 5. The first half contains the types of drivers, devices and the bus type, as well as the framework method. In the Driver Type field, select the name of the driver from the list. In the Bus Type field, select the bus name from the list. In the Device Type field, select the device’s name from the list. In the Framework Method field, select the name of the framework method from the list. The second half is dynamic and depends on the user’s first selection. It contains the following: File operations: This has a list of functions. You can select zero or more functions from the list. registration view: This depends on what you selected in the first half. Basic registration tab fields are compulsory and other registration fields like IrQ, IOCTL, Port and Buffer Management are optional. Finally, click on Finish to generate the complete and specific code for the device driver.

Typical driver development

You have an option to choose Typical Driver Development in the General Information page. Select it and click Next. This opens a wizard as shown in Figure 6. Unlike in Custom driver development, in Typical driver development you are asked only driver specific information. Based on your requirement, choose the Framework types,

Figure 6: Driver development wizard

Driver types and Bus infrastructure from the left pane either by double-clicking on the specific type, or by dragging and dropping on to the right pane. Once this job is done, click Finish to generate the device driver code. This in turn speeds up and eases the job of a device driver developer.

Project build and utility options

By default, Build Automatically is enabled and if you want to disable this feature, select Project and uncheck Build Automatically. To build a project, right-click on that project and then click on Build Project. The LinK+ IDE is bundled with different device driver utility options like insmod, rmmod, modprobe, modinfo, dmesg and lsmod. These options can be accessed in multiple ways. One way is to right click on the Project and in the Project Explorer view, select Link+ Driver Development, as www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 57


Developers

Let’s Try

Figure 7: Driver development

shown in Figure 7. Or just click the LinK+ Driver Utility on Toolbar, or just right click on the Editor.

Short keys

To get the device driver utilities (insmod, rmmod, modprobe and dmesg) with short keys, press Shift+Alt+L and it will open the short keys window. Then press the first letter of the command, like ‘d’ for dmesg.

Extending a project

After creating the device driver project, if you want to add features, select the project under the Project Explorer view and click on LinK+ Driver Utility on Toolbar. Then, click on Extend Project to select the additional features you want to use. All features are optional. Finally, click on the Finish button.

Compiling for other kernels

As we know, Linux device drivers are version specific. If you want to compile the device driver project for other kernels, select the project in Project Explorer view and click on LinK+ Driver Utility on Toolbar. click on Compile For Other Kernel and follow the steps indicated.

Static analysis using Sparse

If you want to check for static analysis, this IDE allows it through the Sparse tool. Just click on LinK+ Driver Utility on Toolbar and then click on Static Analysis using Sparse. It will open the LinK+ console, which shows Sparse warnings. Markers will also appear automatically on all warnings in the editor. click on the warning icon in the editor and the LinK+ IDE will provide a quick fix option for code assistance and completion.

Eclipse local terminal plugin

The LinK+ IDE is also bundled with the Linux terminal plugin, which is provided by the Google ELT project plugins. To open the Linux terminal in the Eclipse IDE, click on Window -> Show View -> Other -> General -> Terminal.

Read more stories on Components in

www.electronicsb2b.com

Figure 8: Function pointer structure

Code assistance and a quick-fix utility for LinK+ driver development

As we all know, development of Linux device drivers is quite cumbersome. We need to understand a lot of frameworks and data structures to build them. To ease this process, the LinK+ IDE has code assistance and code completion features. To use this feature, press Ctrl+Space in the function pointer structure to get suggestions as shown in Figure 8. You can also type a few letters of the function name, and press Ctrl+Space to prompt for a list of names that start with a particular letter. After writing the function pointer’s name, the editor automatically gets an error message. In order to solve this, press Ctrl+1 or click on the error marker icon for code suggestion. We can opt for any one of the suggestions for code completion.

Examples of Linux device driver programs

The LinK+ IDE is also bundled with sample programs for Linux device drivers. To view them, go to Window->Show View->Other and then go to LinK+ Views. Then, click on the device driver examples. You can also import the example program into the workspace as a project by right-clicking on the respective example program. This article covers the basic features provided by the LinK+ Avatar release. I hope this information will help you to kickstart Linux kernel programming. In the next issue, I will discuss more features that include support for ARM architecture, network and block device driver development. By: Dileep K. Panjala The author is a senior technical officer currently working with C-DAC, Hyderabad. This IDE has been developed by Dileep K. Panjala, A. Raghavedra Rao, Suman M., Devesh Gupta and S.V. Srikanth.

TOPCOMPONENTS STORIES erters • The latest in power conv trollers • The latest in microcon c components industry • Growth of Indian electroni rt significant amount of • India continues to impo components every year FETs and relays • The latest in IGBTs, MOS ds available in India • Top 12 connector bran

Log on to www.electronicsb2b.com and be in touch with the Electronics B2B Fraternity 24x7

58 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

ELECTRONICS

INDUSTRY IS AT A


Let’s Try

Developers

Developing a Web-app

Using the Eclipse Editor

This article is the first in a series on developing a Web application called ‘Online Banking’ using the Eclipse Editor. The application will perform all the normal functions of offline banking. This task will be spread over a number of articles. In this first article, the author covers the basics of what is required to develop the Web-app, starting with Java.

J

ava is a programming language created by James Gosling from Sun Microsystems in 1991. The first publicly available version of Java (Java 1.0) was released in 1995. The Java virtual machine (JVM) is a software implementation of a computer that executes programs like a real machine. The JVM is written specifically for a particular operating system, e.g., for Linux. A special implementation is required for Windows.

Characteristics of Java

The aim of the creators of Java was to be able to write a program once and then run it on multiple operating systems. Java has the following properties. Platform independence: Java programs use the Java virtual machine as abstraction and do not access the operating system directly. This makes Java programs

highly portable. A Java program (which is standards-compliant and follows certain rules) can run unmodified on all supported platforms, e.g., Windows or Linux. An object-orientated programming language: Except for the primitive data types, all elements in Java are objects. A strongly-typed programming language: Java is strongly-typed; the types of variables used must be pre-defined and conversion to other objects is relatively strict. In most cases, it must be done by the programmer. An interpreted and compiled language: Java source code is transferred into the byte-code format, which does not depend on the target platform. These bytecode instructions are interpreted

by the Java Virtual Machine (JVM). The JVM contains a so called ‘hotspot-compiler’, which translates performance critical bytecode instructions into native code instructions. Automatic memory management: Java manages the memory allocation and de-allocation for creating new objects. The program does not have direct access to the memory. The garbage collector automatically deletes objects to which no active pointer exists.

An introduction to the Java editor—Eclipse

Eclipse is an integrated development environment (IDE) for developing applications using programming languages like Java and others such as C/C++, Python, PERL, Ruby, etc. The Eclipse platform provides the

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 59


Developers

Let’s Try

Figure 1: Java virtual machine request

communication

Web Browser Client

Servlet Web app

response Web Server

Dynamic page

Figure 2: Communication between Servlet and the browser

1. Load Servlet Class 5. Call the destroy() method

2. Create Servlet Instance 3. Call the init() method

4. Call the service() method

Figure 3: Servlet life cycle

foundation for the Eclipse IDE. It is composed of plugins and is designed to be extensible through the use of additional plugins. Developed using Java, the Eclipse platform can be used to develop rich client applications, integrated development environments (IDEs) and other tools. Eclipse can be used as an IDE for any programming language for which a plugin is available. The Java Development Tools (JDT) project provides a plugin that allows Eclipse to be used as a Java IDE PyDev is a plugin that allows Eclipse to be used as a Python IDE C/C++ Development Tools (CDT) is a plugin that allows Eclipse to be used for developing applications using C/C++ The Eclipse Scala plugin allows Eclipse to be used as an IDE to develop Scala applications PHPeclipse is a plugin to Eclipse that provides the complete development tools for PHP

Introducing Servlet

Servlet technology is used to create Web applications and it uses the Java language to do so. Web applications are ‘helper applications’ that reside in the Web server and build dynamic Web pages -- like a page that randomly chooses a picture to display or even a page that displays the current time. As Servlet technology uses Java, Web applications made using Servlet are secure, scalable and robust. The advantages of using Servlet are: Low response time because each request runs in a separate thread Servlet is scalable It is robust and object oriented It is platform independent

The Servlet life cycle

Figure 4: Welcome page 60 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

Loading a Servlet class: A Servlet class is loaded when the first request for the Servlet is received by the Web container. Creating a Servlet instance: After the Servlet class is loaded, the Web


Let’s Try

Developers

container creates an instance of it. A Servlet instance is created only once in its life cycle. Calling the init() method: init() is called by the Web container on a Servlet instance to initialise the Servlet.

Signature of init() method: public void init (ServletConfig config) throws ServletException

Figure 5: Opening account page

Calling the service() method: The containers call the service() method each time the request for Servlet is received.

Signature of service() method: public void service(ServletRequest request,ServletResponse response) throws ServletException, IOException

Figure 6: Confirmation of account opened

Calling the destroy() method: The Web container calls the destroy() method before removing the Servlet instance, giving a chance for cleanup activity.

An introduction to Oracle

Figure 7: Balance checking page

Figure 8: Deposit form

An Oracle database is a collection of data treated as a unit. The purpose of a database is to store and retrieve related information. A database server is the key to solving the problems of information management. In general, a server reliably manages a large amount of data in a multi-user environment so that many users can concurrently access the same data. All this is accomplished while delivering high performance. A database server also prevents unauthorised access and provides efficient solutions for failure recovery. Oracle Database is the first database designed for enterprise grid computing, and is a flexible and cost-effective way to manage information and applications. Enterprise grid computing creates large pools of industry-standard, modular storage and servers. With this architecture, each new system can be rapidly provisioned from the pool of components. There is no need for peak workloads, because capacity can be www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 61


Developers

Let’s Try easily added or reallocated from the resource pools, as needed. The database has logical structures and physical structures. Because the physical and logical structures are separate, the physical storage of data can be managed without affecting the access to logical storage structures.

An introduction to Apache Tomcat Server

Apache Tomcat is an open source Web server and Servlet container developed by the Apache Software Foundation (ASF). Tomcat implements several Java EE specifications including Java Servlet, JavaServer Pages (JSP), Java EL and Web Socket. It also provides a ‘pure Java’ HTTP Web server environment for Java code to run in. The components of Apache are: 1. Catalina 2. Coyote 3. Jasper 4. Cluster Figures 4 to 11 give the UI snaps for the ‘Online Banking’ Web application that we will be building in subsequent articles. The forthcoming articles in this series will deal with Oracle Database, Apache Tomcat Server and Servlet, which have been used in developing this Web application.

Figure 9: Withdrawal form

Figure 10: Transferring amount form

By: Vikas Awasthy The author currently works as an applications developer-J2EE in a multinational corporation. This is his first article, which is dedicated to his late mother, Krishna Sharma, and to his family.

Figure 11: Account closing form

ELECTRONICS • Exclusive: ELCINA’s first greenfield EMC project soon to get land possession

• India is emerging as an attractive destination for international companies to invest • Electronics manufacturing industry in Pune needs a boost • In 5 years, India may rank 2nd in manufacturing competitiveness, worldwide • Highlights of state electronics policies • National Policy on Electronics will Boost R & D in Electronic Manufacturing • Insecure market threatens solar module makers

Log on to www.electronicsb2b.com and be in touch with the Electronics B2B Fraternity 24x7

62 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

INDUSTRY IS AT A


Let’s Try Developers

Selenium: A Popular Software Testing Tool You Can Rely On For the software enthusiast, this article begins with an overview on software testing. The various types of testing and the many software testing tools are enumerated, and then the author goes into detailed discussion on the free and open source automation testing tool, Selenium.

S

oftware testing is a process of evaluating a system or its components to find out whether the specified requirements are met. It can also be referred to as a system to identify any gaps, errors or missing requirements. It comprises verification and validation of the software product. This process starts from the beginning of the software development lifecycle (SDL) till it is delivered to the customer. The purpose of software testing is to deliver a higher quality of product. If the product produces an error at a later stage, then it becomes costly to remove it. Software testing has the potential to save money and time by identifying problems early and delivering a defect-free product. It has three main objectives: Verification: This process confirms that the software meets its technical specifications.

Validation: This process confirms that the software meets the business requirements. Defect: This detects any differences between the expected and actual results. Software testing can be done in various ways and is broadly divided into two types: Manual testing: This type of testing involves software developers running tests manually. There are several stages at which manual testing can be done. These are: Unit testing Integration testing Software testing • Functional testing • Non-functional testing System testing

www.OpenSourceForU.com | OPEN SOURCE FOR YOU | APRil 2015 | 63


Developers

Let’s Try Selenium IDE

Software Testing Selenium Grid

Manual Testing

Selenium Suite

Automation Testing

Web Driver

Figure 1: Types of software testing

Figure 2: Selenium’s components

User acceptance testing Release or deployment testing Automation testing: This type of testing is done using automation tools. It reduces the overall effort and time required in regression testing and speeds up the overall testing process. Various automation tools can be used for this. Some of these tools are: HP Quick Test Professional Selenium IBM Rational Functional Tester SilkTest TestComplete

Selenium RC

Testing Anywhere WinRunner LoadRunner Visual Studio Test Professional WATIR

Introducing Selenium

With the dynamic growth in the IT industry, there has been an increase in testing costs. So, organisations have started choosing open source automation tools rather than their commercial variants. Automation tools, as their name suggests, provide features for automating the

Elements

Description

Base URL

This is the textbox where the URL for the application under test can be specified. All open commands will be relative to the Base URL unless a full path is inserted in the open command. Speed slider is used to vary the speed while playing the test from Fast to Slow Play entire test suite button is used to run all the available test cases in the IDE Play current test case button is used to run a single test which is selected in the IDE. Pause/Resume button is used to pause/resume the test case which is currently running Step through the test once it has paused. This is the record button. This will be engaged when the test is recording

Command selectbox Target textbox Find button Value textbox Test table Log Reference UI-Element Rollup

It has a list of all the commands that are needed to create a test. It is a drop down box which specifies all the available command in selenium IDE It enables to specify the element which is to be tested It can be used to find any particular element on the application under test It is used to specify the value for the target element if required. It is usually used when the requirement is to enter a value in the input box on the web page which is being tested It will keep track of all commands, targets, and values When test case is run information message and error message are displayed in this tab It will display the details about the current command It is for advanced users It allows to execute group of commands in one step

64 | APRil 2015 | OPEN SOURCE FOR YOU | www.OpenSourceForU.com


Let’s Try Developers Selenium allows testers and developers to develop test scripts to drive the browser. It prevents future regression of code; hence, it is popular. It can work on any browser that supports JavaScript, since it has been built using JavaScript. Recorded test cases can be exported to various programming languages such as Java, C#, Python, Ruby, PHP and Perl.

Components of Selenium

Figure 3: Selenium download page

testing of software and Web applications. Various types of automation testing tools are available for the different tests required like regression, performance or functional testing. One of the most Figure 4: Selenium IDE Menu-Items commonly used automation tools is Selenium. It is one of the best options to test Web applications, and can be used for automating the testing of both the GUI as well as the features. It can also be used as a unit testing tool for JavaScript. It provides a record/playback facility to authorise the tests without knowing the test scripting language (Selenium IDE). It is implemented as a Firefox extension, which allows replaying, recording and editing test cases in Firefox.

Selenium is not just a single tool but a suite of products. It has four components—Selenium IDE, Selenium Grid, Web Driver and Selenium RC. Selenium RC and Web Driver have been merged to form a framework known as Selenium 2. Selenium IDE: Selenium IDE is an integrated development environment for Selenium tests. It was developed by Shinya Kasatani. It allows you to use Selenium Core without having to copy it onto the server. Selenium Core is a JavaScript module that allows Selenium to drive the browser. It can interact with Document Object Model (DOM) using JavaScript calls. Scripts are recorded in Selenese, a special scripting language for Selenium. It provides commands for performing actions in Web browsers and for retrieving data from multiple pages. Selenium RC: This is a server written in Java, which accepts commands for the browser via HTTP. It makes it possible to write the tests for Web applications in any programming language. When using Selenium, a core user has to install the whole application under test alongwith the Web server on the local computer. So a server has been created by an engineer named Paul Hammant, which acts as a proxy to trick the browser into considering the Selenium core and Web application that is being tested as coming from the same domain. This is known as Selenium RC (remote control) or Selenium 1. Selenium Web Driver: This is the successor to Selenium RC. It is the first cross-platform framework for testing that controls the browser from the OS level. It was created by Simon Stewart in 2006. It accepts commands,

Commonly used Selenium commands Command

Description

Open

Opens a page for the specified URL

Click

Clicks the elements (target) on the page

clickAndWait

Performs the click operation and waits for a new page to load

verifyTitle

Verifies the target title and continues to execute even if it fails

assertTitle

Verifies the target title and stops execution if it fails

verifyTextPresent

Verifies whether the specified text is present on the page

verifyElementPresent

Verifies whether the specified element is present by using its HTML tag

verifyText

Verifies whether the specified text and its corresponding HTML tag is present on the page

waitForPageToLoad

Pauses execution until an expected new page gets loaded

waitForElementPresent Pauses execution until an expected UI element, as defined by its HTML tag, is present on the page

www.OpenSourceForU.com | OPEN SOURCE FOR YOU | APRil 2015 | 65


Developers

Let’s Try

sends them to a browser and retrieves the result. It does not require any special server to execute tests. Selenium Grid can be used with Web Driver to execute tests on remote systems. At present it is fully implemented and supported in Ruby, Python, C# and Java. Selenium Grid: This is a server that allows tests to use Web browsers running on remote systems. In this, Figure 5: Selenium IDE one server acts as the hub. The tests contact the hub to obtain access to browsers. The hub consists of lists of servers that provide access to browsers (i.e., Web Driver nodes). It allows the running of tests in parallel on multiple machines, and the management of different versions and configurations of browsers, centrally. This helps to spread the load of testing across several machines by running the tests across different platforms or operating systems.

Figure 6: Sample test case execution on Selenium IDE

Installation of Selenium

1. Open a Mozilla Firefox browser. 2. Type the URL http://seleniumhq.org/download/ in the browser and download the latest version as specified in the screenshot. 3. When the download link is clicked, Firefox will enable a pop-up that asks if you want to allow Mozilla Firefox

A comparison between various automation testing tools Parameters

Selenium

QTP

Watir

GEB

Licence cost

Open source software

HP licensed software

Open source software

Open source software

Scripting language

Java, C#, Python, Ruby, PHP, Perl, JavaScript

VB Script

Ruby

Groovy

Operating system support

Windows, Linux, Solaris

Windows 8/XP/ Vista

Windows, Linux, Solaris

Windows, Linux, DOS

Browser support

Firefox, IE, Opera, Safari, Chrome

IE, Firefox, Chrome

Firefox, IE, Opera, Safari, Chrome

Firefox, IE, Opera, Safari, Chrome

Object recognition

Selenium IDE, Firebug, Firepath

Using Object Spy

Open Twebst (Web recorder)

Using GEB IDE

Script execution speed

Low

High

Low

Low

Non-browser based app support

No

Yes

No

No

Device support

Supports iOS and Android

iOS, Android, Blackberry, Windows

iOS and Android

iOS

Ease of support

User and professional community support is available

Has dedicated HP support

Limited support from open source community

Limited support from open source community

Script creation time

Time required is much more

Time required is less

Time required is more

Time required is more

66 | APRil 2015 | OPEN SOURCE FOR YOU | www.OpenSourceForU.com


Let’s Try Developers to install Selenium IDE or not. Click the Allow button. 4. Firefox will automatically install the Selenium IDE software. After completing the installation, it will show one pop-up that states the Selenium IDE installation has been completed. Now restart the browser to use Selenium IDE. Click the Restart Now button. 5. Firefox will restart automatically. Now click on the Tools menu list displayed on top to see the Selenium IDE option as shown in Figure 4. 6. Click on the Selenium IDE option. This will launch the Selenium IDE software window. This is the screen for Selenium IDE, where tests can be recorded, replayed and edited.

Creating the first test script using Selenium

We will be creating a test for clicking on the Search option to open the Search page in the Clean-clouds.com application. 1. Open the Selenium IDE tool and enter the link for the application that is to be tested as shown in Figure 6. 2. To open any link for the application that is to be tested, use the Open command and specify the link in the target value.

3. Click on the Search option, write a new command and specify the ID of the target in the target value. This ID can be obtained with the help of Firebug, by clicking on a particular target, which is the Search option in this case. 4. After specifying every command, the screen will look like what’s shown is Figure 6. This is how a test case can be created using the Selenium IDE. References [1] http://automationinqtp.blogspot.in/2013/01/qtp-vs-selenium.html [2] http://blog.testing-whiz.com/2013/06/comparing-qtpselenium-and-testingwhiz.html [3] http://kedar.nitty-witty.com/blog/selenium-vs-qtp-differencesusage-quick-reference [4] http://docs.seleniumhq.org/docs/01_introducing_selenium.jsp [5] http://www.xoriant.com/blog/software-testing-and-qa/ selenium-open-source-test-automation-tool-an-overview.html [6] http://www.aspiresys.com/WhitePapers/QTPvsSelenium.pdf

By Priyanka Agashe The author is a software engineer and loves to explore new technologies. Her professional spheres of interests include oracle apps, testing, electronics, and robotics.

Please share your feedback/ thoughts/ views via email at osfyedit@efy.in

www.OpenSourceForU.com | OPEN SOURCE FOR YOU | APRil 2015 | 67


Developers

Insight

Face-off with Sizeof()

ent nguage developinlam g programmlanguage

In C programming, the unary operator sizeof() returns the size of its operand in bytes. The sizeof() operator is discussed in detail in this article, along with illustrative examples of code.

S

izeof() is used extensively in the C programming language. It is a compile-time unary operator, which can be used to compute the size (in bytes) of any data type of its operands. The operand may be an actual type-specifier (such as char or ints) or any valid expression. The sizeof() operator returns the total memory allocated for a particular object in terms of bytes. The resultant type of the sizeof() operator is size_t. Sizeof() can be applied both for primitive data types (such as char, ints, floats, etc) including pointers and also for the compound data types (such as structures, unions, etc).

Usage

The sizeof() operator can be used in two different cases depending upon the operand types. Let me elaborate this with syntax, examples and sample codes.

Case 1: When the operand is a type-name

When sizeof() is used with ‘type-name’ as the operand (such as char, int, float, double, etc), it returns the amount of memory that will be used by an object of that type. In this 68 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

case, the operand should be enclosed within parenthesis. The sizeof operator is used when the operand is a type-name as shown in Table 1. Illustration: The sample demo code is shown below (Code 1), and the output of the code when I run it in my system is shown in Figure 1. Code 1 1 #include <stdio.h> 2 #include <stddef.h> 3 4 int main() 5 { 6 printf(“Sizeof(char) : %lu\n”, (long unsigned ) sizeof(char)); 7 printf(“Sizeof(int) : %lu\n”, (long unsigned ) sizeof(int)); 8 printf(“Sizeof(float) : %lu\n”, (long unsigned ) sizeof(float)); 9 printf(“Sizeof(double) : %lu\n”, (long unsigned ) sizeof(double));


Insight

Developers

Table 1: Syntax with some commonly used examples

Syntax

Examples

Sizeof (type-name)

1. 2. 3. 4. 5. 6.

sizeof (char) sizeof (int) sizeof (float) sizeof (double) sizeof (12.5) sizeof (‘A’) etc...

Table 2: Syntax with some commonly used examples

Syntax

Examples

Sizeof (expression)

1. sizeof (i++)

OR

Figure 1: Output of the demo program shown in Code 1

2. sizeof (a+b) etc...

Sizeof expression 10 11 }

return 0;

Figure 2: Output of the demo program shown in Code 2

Note 1: The return value of the sizeof() operator is implementation-defined, and its type (an unsigned integer type) is size_t, defined in <stddef.h>. Figure 3: Output of the demo program shown in Code 3

Note 2: C99 has included %zu as a type specifier for size_t. But for older compilers, %z will fail. Hence, use %lu or %llu along with a typecasting to achieve portability of the code across various platforms.

Case 2: When the operand is an expression

When sizeof() is used with expression as an operand, the operand can be enclosed with or without parenthesis. The syntax of how the sizeof() operator is used preceding the expression is shown in Table 2 along with some examples. Illustration: The sample demo code is shown in the Code 2 snippet, and the output of the code when I run it in my system is shown in Figure 2. Code 2 1 #include <stdio.h> 2 #include <stddef.h> 3 4 int main() 5 { 6 int a = 10; 7 8 double d = 12.34; 9 10 printf(“Sizeof( a + d ): %lu\n”, (long unsigned) sizeof(a + d)); 11 12 return 0;

13 }

From the above demo code, it is very clear that when the sizeof() operator is applied to an expression, it yields a result that is the same as if it had been applied to the typename of the resultant of the expression. Since, at compile time the compiler analyses the expression to determine its type, but it will never evaluate the expression which takes place at runtime. In the example shown in Code 2, ‘a’ is of int type and‘d’ is of double type. When type conversion is applied, as usual, the lower rank data type is promoted to a higher rank data type and the resultant data type is nothing but a double in our case; hence, sizeof( a + d ) yields sizeof(double) which is 8 bytes as shown in Figure 2. In general, if the operand contains the operators that perform type conversions, the compiler considers these conversions in determining the type of the expression.

Behaviour

The sizeof() operator behaves differently in comparison with other operators. In this article, let me point out the uniqueness of this operator by taking two real-time programming examples. The first is about compile-time behaviour and the second one is about runtime behaviour.

Case 1: Compile-time behaviour

To start with, let us consider the simple code as shown in the Code 3 snippet. www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 69


Developers

Insight From Figure 4, we can see that sizeof() is completely evaluated at compile time (the exception is gcc, which supports zero-sized structures as a GNU extension, which is evaluated at the runtime). And the whole sizeof(i++) is replaced by the constant value 4, which is highlighted in the box. Hence, there are no assembly instructions for i++ at all, which is supposed to be evaluated at the runtime.

Case 2: Runtime behaviour

As mentioned earlier, sizeof() is the only operator in C, which is evaluated at the compile time. But, there is an exception for this in C99 standards, for variable length arrays. To start with, let us consider the following code (Code 4): Code 4

Figure 4: Assembly code generated by the compiler for Code 3

Code 3 1 2 3 4 5 6 7 8 9 10

#include <stdio.h> #include <stddef.h> int main() { int i = 10;

11 12 13 14 15 }

size_t size = sizeof(i++); printf(“Size of i : %lu\n”, (long unsigned ) size); printf(“value of i : %d\n”, i); return 0;

Can you guess what the output of the above mentioned program will be? At first glance, anybody would say it is 4 (assuming the sizeof(int) is 4 bytes) and 11. But, when I run the program in my system, it shows 4 and 10 (refer Figure 3 for output). Why are we getting the value of variable ‘i’ as 10 instead of 11? Here is the reason. The sizeof operator is the only one in C, which is evaluated at compile time, where sizeof(i++) in our example is replaced by the value 4 during compile time itself. We can validate this by referring to Figure 4, which contains the assembly code equivalent to the sizeof(i++) in C. Note: To obtain the assembly code as shown in Figure 4, follow the steps shown below: + gcc -g filename.c (in our case, the file name is sizeof_run.c) + objdump -S output_file (in our case, the output file is a.out) 70 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

1 #include <stdio.h> 2 #include <stddef.h> 3 4 int main() 5 { 6 unsigned int size; 7 size_t array_size; 8 9 printf(“Enter the size:”); 10 scanf(“%u”, &size); 11 12 //Declaring the variable length array 13 int array[size]; 14 15 //Finding the size of array 16 array_size = sizeof(array); 17 18 printf(“Size of array : %lu\n”, (long unsigned ) array_size); 19 20 return 0; 21 }

Let us see the output, when the above code is compiled and run (shown in Figure 5). From the above output it is very clear that the sizeof() operator is evaluated at runtime. We can observe the equivalent assembly code generated by the compiler as shown in Figure 6. Also, note the difference between the assembly code in Figures 4 and 6.

The need for sizeof() Case 1: Auto determination of the number of elements in an array

To compute the number of elements of the array automatically, depending on the data-type of the element, the sizeof() operator comes in handy.


Insight

Developers

Figure 5: Output of the sizeof_run.c

For an explanation, let us consider the code snippet given below: 1 #include <stdio.h> 2 #include <stddef.h> 3 4 int main() 5 { 6 int array[] = {10, 20, 30, 40, 50}; 7 8 size_t i; 9 10 for(i = 0; i < sizeof(array) / sizeof(array[0]); i++) 11 { 12 //some code 13 } 14 }

In the example shown above, at line number 10, by using the sizeof() operator the number of elements is automatically computed. The sizes of primitive data types in C are implementation defined. For example, the sizeof(long) on 32-bit architecture may vary from that on 64-bit architecture. So, when we decide statically the sizeof(long) as 4 bytes wide on 32-bit architecture, and when the same code is ported to 64-bit architecture, the results may go wrong. So, in order to avoid the portability issue, it is a best practice to use sizeof() to compute the sizeof variables or arrays, depending on the exact size of a particular data type.

Case 2: To allocate a block of memory dynamically of a particular data type

In case of dynamic memory allocation of an array, sizeof() plays an important role. For example, if we want to allocate a block of memory that is big enough to hold ‘5’ integers in an array, sizeof comes in handy and is a great help, since we do not know the exact sizeof(int) to dynamically allocate the memory using malloc function for a particular architecture. int *iptr = malloc( 5* sizeof(int));

In the above example, we are mallocing the block of memory, which is equal to the number of bytes of type

Figure 6: Assembly code generated by the compiler, for variable length array

int, multiplied by 5, ensuring sufficient space for all five ints is allocated.

Case 3: To determine the sizeof compound data types

Sometimes, it is very difficult to predict the sizes of compound data types such as structures, due to structure padding, and to predict the size of unions. Sizeof() is of great use here.

Cases when sizeof() will not work

The sizeof operator will not work when applied to the following cases: A bit field A function type An incomplete type (such as void) Zero-sized array (except in GCC, which supports zerosized structures as a GNU extension).

sizeof() and incomplete data types

An incomplete type in C is one that describes an identifier, but lacks the information needed to determine the size of the identifier. Examples of incompletely defined types are: 1. An array type whose dimensions have not yet been specified 2. A structure type whose members have not yet been specified

Illustration: An array whose dimensions are not specified File1.c int array[10];

File2.c extern int array;

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 71


Developers

Insight

In the above example, for the code in file1.c, sizeof() can be applied to find the size of the array, as it is completely defined in file1.c. But, in file2.c, the sizeof() operator will not work since the dimensions of the array are missing. Without this information, the compiler has no knowledge of how many elements are in the array and cannot calculate the sizeof of the array.

How sizeof() is different from a function call

Let us consider the following code to understand how sizeof() is different from a function call: 1 2 3 4 5 6 7 8

#include <stdio.h> #include <stddef.h> int main() { int x = 5;

By: Satyanarayana Sampangi printf(“%lu:%lu:%lu\n�, (long unsigned )sizeof(int), (long unsigned )sizeof x, (long

9 10 11 }

In the above example, sizeof() will work even if the braces are not present across operands, whereas in functions, braces are a must. So, here are three reasons why sizeof is not a function: 1. It can be applied for any type of operand. 2. It can also be used, when type is an operand. 3. No brackets needed across operands You can implement your own SIZEOF() macro, which should work like a sizeof() operator. According to the C99 standards, the sizeof() operator yields the size (in integer bytes) of its operand, which may be an expression or the parenthesised name of a type. If the type of the operand is a variable length array type, the operand is evaluated at runtime; otherwise, the operand is not evaluated and the result is an integer constant, during the compile time itself.

unsigned )sizeof 5);

return 0;

72 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

The author is a member of the embedded software team at Emertxe Information Technology (P) Ltd (http://www.emertxe. com). His areas of interest are embedded C programming combined with data structures and microcontrollers. He can be reached at satya@emertxe.com


How To

Developers

Creating an Awesome Web Experience with Drupal Drupal offers developers quick fix solutions for an instant website. However, it is not child’s play. It powers many critical websites including those of the POTUS (President of the United States), Warner Music, NBC, etc. This in-depth article takes the reader through the steps to create and operate a Drupal website.

D

rupal is an open source content management platform that powers millions of websites and applications. It is built, used and supported by an active and diverse community of people around the world (website: www.drupal.org). Drupal is a PHP based Web content management system (CMS), which is distributed under the GNU-GPL license, making it free and open source software that is used to power millions of sites on the World Wide Web. Drupal was originally created by Dries Buytaert as a message board project, and was released as an open source project in 2001. It is now continuously fuelled by contributions from a huge community of around 39,000 users. It is used by organisations large and small, across various verticals like healthcare, retail, government, consumer, media and entertainment, life sciences and many more.

Some sample sites

One really famous Drupal site is whitehouse.gov. The Warner

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 73


Developers

How To drupal.local:8083/install.php

authorize.php

CHANGELOG.txt

COpyriGHt.txt

cron.php

includes

Select an installation profile standard

index.php

INSTALL.mysql.txt

INSTALL.pgsql.txt

install.php

install with commonly used features pre-configured.

iNstALL.sqlite.txt

Minimal Start with only a few modules enabled. Choose profile iNstALL.txt

LiCENsE.txt

MAiNtAiNErs.txt

misc

modules

Choose language

Save and continue

Verity requirements Set up database profiles

rEAdME.txt

robots.txt

scripts

sites

Install profile Configure site Finished

themes

update.php

upGrAdE.txt

web.config

xmlrpc.php

Figure 3: Drupal installation page

Figure 1: Drupal directory structure http://drupal.local:8083/install.php?profile=standard&locale=en

Database configuration Database type* MySql, MariaDB, or equivalent PostgreSQL SQLite The type of database your Drupal data will be stored in. Choose profile Choose language

Figure 2: Virtual host config

Verify requirements

Set up database Install profile

Music Group uses Drupal to power its artists’ websites, while fashion brand Lush uses Drupal for its e-retail store lushco.uk. The Weather Channel at NBC is also powered by Drupal… and the list is long. To check out case studies, you can visit https://www. drupal.org/case-studies and http://www.drupalshowcase. com/

Start building your own website

So let’s learn how to install and get started with a Drupal site, and add some basic content to it. A basic knowledge about using computers and how to install software on them is required. Experience in working on a LAMP, WAMP or MAMP stack is preferable.

Prerequisites

You will need a *AMP stack, which implies a computer, laptop or server with a stable operating system like Windows, Mac OS, UNIX or any Linux based OS like Ubuntu, Fedora, Red Hat, etc. Note that PHP is a requirement since Drupal has been written in it. PHP 5.4 or higher is recommended. Usually, the database used is MySQL. However, other databases like PostgreSQL, SQLite, MS SQL server or Oracle can be chosen. We need a Web server, which could be Apache, Nginx, or Microsoft IIS. Apache is usually chosen. 74 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

Database name* The name of the database your Drupal data will be stored in. It must exist on your server before Drupal can be installed.

Database username*

Configure site Finished

Database password*

ADVANCeD oPTIoNS

Save and continue

Figure 4: Database configuration

For a quick start, you can choose one of the preconfigured packages like WAMPServer, MAMP, XAMPP, or a LAMPserver package on a Linux based OS or Acquia’s Dev Desktop.

Download Drupal

Go to https://www.drupal.org/project/drupal to download Drupal, which will be in the form of a .tar.gz or a .zip file. Extract it and place it into your Web server docroot. Create a virtual host that points to your docroot and assign a dev domain to the virtual host. Do not forget to update your IP tables to point this dev domain to your local host. Ensure that the .htaccess file and .gitignore files also get copied with the Drupal files. Go into your MySQL administration and create a database for the Drupal site.

Creating settings.php and the files directory

Within the sites/default/ directory, as seen in Figure 1, there will be a sample settings file default.settings.php which is what we will use to create our settings.php. Copy default.


How To

Figure 5: Front page

Developers

Figure 7: ‘About me’ page that has been created

Figure 6: Content type list

settings.php to the same location as settings.php and make sure that the file permissions are such that the Apache Web server can write into this file for now. Make sure that you have both the files in the directory, default.settings.php and the newly created settings.php. Within this sites/default directory, create another directory named files. Make sure this directory can be written to by the Web server too. Any file uploaded to the Drupal site or any JavaScript or CSS aggregated files will be stored in here.

Running the installation script

Now get on to your browser and visit this Base URL or the domain set on your virtual host as shown Figure 2, to begin installing Drupal. You should be seeing the page shown in Figure 3. Select the Standard installation profile and click on Save & Continue. The next page should show you a list of languages available to install Drupal in. Since we have not added any support for additional languages, it will, for the time being, just show ‘English’. Click on Save & Continue to proceed. It next checks for the prerequisites for the Web server, PHP version, PHP settings, permission to write into the settings.php file and the files directory. In case there is any issue with any of these aspects, an appropriate message will be displayed. Use corrective measures as suggested by the message and then retry the same step.

Figure 8: Home page

Database configuration

Remember the database you had created earlier? Now, fill in the details like the database’s name, user name and password as shown in Figure 4. In case your database is on a non-standard port or on a different machine, update the database server details accordingly. If all the previous steps went fine, you should now see a screen that displays all the Drupal modules and components being installed, the database being set up and necessary settings being saved.

Site information

Now this is where you add your site’s name, slogan and create an administrative user number 1. Don’t forget to set the country, time zone and to make sure you enable Check for updates automatically. Congratulations! Your site is up. Let’s go visit it.

Front page

Figure 5 shows the front or home page of your site. It shows your site’s name at the top, with the user menu on the right side, a navigation menu, some blocks on the left hand side and an admin menu on top. www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 75


Developers

How To

Figure 9: Managing the fields

Figure 10: User profile

Figure 11: List of registered users

Admin dashboard

The administration section will be visible to you as you are currently logged into the site as an administrator. Notice a black coloured menu on top that presents a list of links for all administrative tasks. Click on the one that says Dashboard.

Let’s create the ‘About Me’ page

Now let us quickly create an ‘About Me’ page. From the top admin menu, click on Add Content. This gives you a list of choices like those shown in Figure 6. Click on Basic Page. This will now open up a form for you to add content to. Add the page title as ‘About Me’ and in the Body field, add any HTML that you desire to be part of your content -- something like what’s shown below: <h2>Read all about me.</h2> <p>Hi! I am an enthusiastic Drupal developer. I like to:</p> <ul> <li>Build sites</li> <li>Explore new technologies</li> </ul>

Now, let's add a menu link, from where this page will be accessible. Scroll down the form and check the checkbox in the Menu settings section that says Provide 76 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

Figure 12: List of menus

a menu link. This will prompt you to add the Menu link title, indicating which menu you want it on. Add details as shown in Figure 8 and save them. Now, when you save the form, the page content gets saved and is displayed to you. You can also see a menu link on top that reads ‘About me’ and the links to this page that you have created. Congratulations! You have created your first ever Drupal page. Let us now create a few articles in the same way. To create a new article, go to the same Add content link and choose the content type as Article. In the form, you will notice that we now have an extra field to upload an image and one to categorise your article using tags. Go ahead and add a few articles with images along with this tag information. Now take a look at the front page; it shows a list of all the articles that you added just now.

A few Drupal basics

We will now discuss the internal structure of Drupal and a few key concepts.

Content and content types

Everything in Drupal revolves around content, which could be a static Web page, an article, a blog post, product


How To

Figure 13: Add module Webform

Figure 14: Webform builder

information, a slide in a slide show, etc. Each of these make up a content type. We can alter the data structure of each content type so that it has all the relevant information captured in the best way. To create your own content type, from the admin menu on top, click on Structure and from the list shown, click on Content types. This will now show you a list of the content types that are present in the system. You can add a new content type, edit the fields that are a part of it, and even decide which fields are to be shown and which hidden (Figure 9).

Menu and path system

Taxonomy

Another important aspect of arranging content on a CMS is categorising features. Using Drupal’s inbuilt taxonomy system, one can easily create vocabularies and associate them with the various contents on the system. These could be a pre-entered list of terms or a free tagging system. Content can then be easily categorised, sorted and filtered using the terms associated with it. You can see them as a list of taxonomies and terms. To view them, click on Structure from the admin menu and then on Taxonomy. This will show a list of the taxonomies in the system and then you can click to add or view more terms. To add it to the contents, just make a Taxonomy Term field as a part of the Content type, to capture which category is associated with the content added.

Users

No digital system is complete without its users. Drupal’s inbuilt user module provides a very good solution for users to be registered on the system and role based permissions to be assigned to them. You can extend the information about a user by adding more fields into the user’s profile information. From the top user menu, click on the My account link to view your user profile (Figure 10). To check the list of users registered on the system, click on the People link from the admin menu (Figure 11). To add more roles or assign special permissions to each role, click on the Permissions tab in the People page that you opened right now.

Developers

In Drupal, every path lands at a unique page that runs a set of functions to create the content and structure for that page. This could be individual content, a list of contents, a list of users, the Home page with aggregated content from the rest of the site, a form and more. In order to make the URLs user friendly, URL aliases are used and mapped to these paths generated by the Drupal system. Next, you can create a list of the paths to build a menu and display it as the main menu or a user menu, secondary side navigation menu and more. Go to Structure from the admin menu, and click on Menus to view the list of menus and a list of links added to each menu (Figure 12).

Modules

The module system of Drupal is at the heart of its extensibility. The plain Drupal installation has some core features and a hook based system that helps other added modules to extend its features. These additional features are packaged into modules that can be added and enabled as per requirements. Some examples could be: a Commerce module to enable commerce capabilities, a ‘Five Star’ rating, CKEditor, Devel for debugging and more. There are close to 30,000 modules that have been published on www.drupal.org, which can be added to your Drupal site to enhance its features. Go on and try one. Let’s try the Webform module at https://www.drupal.org/project/webform. Go to the URL and download the .tar.gz or .zip file. Unzip it and extract the contents into the sites/all/modules/contrib folder within the docroot of your Drupal site. Now, from the top admin menu, click on the Modules page link. This should show you a list of modules with this new module that can be selected to be enabled and installed. As seen in Figure 13, the system checks if there are any dependencies for installing this module. You can see that it requires two other modules, ctools and views, to be installed too. So quickly download them from https:// www.drupal.org/project/ctools and https://www.drupal.org/ project/views, respectively and extract them into the sites/ www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 77


Developers

How To own theme and install it. The Drupal community has contributed over 2000 themes for you to start with. Some of them are base themes that put in a framework for you to build a branded theme and some give you a complete coloured theme. You can find them at https://www.drupal. org/project/project_theme. Let’s try one at https://www.drupal.org/project/ corporateclean. Download the .tar.gz or .zip file, extract it and place it in the sites/all/themes directory. Now navigate to the Appearance page from the admin menu on top. It shows you a list of themes available and the one you just added. Enable it and set it as the default in the Corporate Clean theme, and then navigate to the front page and see the magic (Figure 15).

A good start to building your site on Drupal

Figure 15: Home page

all/modules/contrib directory. Now revisit the Modules page and see that the Webform module can be installed and automatically enables the prerequisite modules too. The aim of this module is to provide you with a way to add more forms to your site using an easy form builder facility. It would have created a content type ‘Webform’ for you on the Content types listing page. You can now go ahead and create a form in the same way as creating a page. Go to Add content and see that Webform is listed as a type there. Click on it, and you will be asked for a title for the form and any menu, path or permissions that you would like to associate with the form. Once you add this information and save it, you will be led to the form builder page, where you can add text fields, select boxes, text area, date and other types of form components. Next, you can program what actions should be taken after submitting the form, like sending a confirmation message, email to the administrator, etc (Figure 14).

Themes

Drupal’s UI architecture beautifully separates out logic, data and presentation. The features that govern the data architecture and logic are separated into the modules and the presentation layer is governed by the Theme layer. Drupal comes with a default theme, Bartik, which is enabled when you install it. Now, to change the appearance, install another theme, or create your 78 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

You are probably well into getting your site built on Drupal. For a quick try out, you can start building and hosting your site on Acquia’s cloud servers, which provide developers with a free version to kickstart their Drupal development. Go to http://www.acquia.com/free to register for your free dev cloud. The Drupal community site hosts an awesome documentation section that provides details about working in the Drupal ecosystem. Do feel free to register on www.drupal.org and visit its forum section to interact with the Drupal community, post your questions and participate in local events. Drupal has been adopted by major systems integrators and IT companies to create great digital experiences for their customers. The Drupal community in India regularly organises events like the Drupal Camps in Delhi and Mumbai held earlier this year, ‘Global training days’ that happen every quarter, and many monthly meet-us for training, code sprints or contribution drives. Come, join for the technology and stay on for the community. References [1] Documentation: https://www.drupal.org/documentation [2] Case studies: https://www.drupal.org/case-studies, http:// www.drupalshowcase.com/ [3] Drupal modules: https://www.drupal.org/project/modules [4] Drupal themes: https://www.drupal.org/project/themes [5] Hosting your site on Acquia Cloud: https://www.acquia. com/free, https://docs.acquia.com/cloud/free [6] Using Acquia Dev Desktop: https://docs.acquia.com/devdesktop2 [7] Acquia library: https://www.acquia.com/resources

By: Pavithra Raman The author is a solutions architect with Acquia Inc and specialises in the architecture of Drupal based solutions. To know more about her, visit in.linkedin.com/in/ramanpavithra/. Connect on Twitter @pavithra_raman.


How To

Admin

FSlint: A ‘Laundromat’ for File Systems Traditionally, lint refers to small loose pieces of fibre that stick to fabric. In computer terminology, lint initially implied programs that flagged suspicious and non-portable constructs, which were likely to be bugs in C programming. Likewise FSLint helps to find and eliminate various kinds of lint on a file system.

F

Slint is a collection of tools to find and clean various forms of lint on a file system. Excess or unnecessary files are referred to as file system lint. FSlint has an intuitive GTK+ GUI as well as command line interface. But for the sake of simplicity we are going to discuss only the GUI interface. The most common forms of lint are duplicate files, improper names, empty directories, broken symbolic links, etc. FSlint provides various utilities to clean file system lint and reclaim disk space. This column walks you through each of the major tools that FSlint provides.

updated packages [narendra]$ sudo apt-get install fslint # Install FSlint package [narendra]$ whereis fslint # Verify the installation FSlint: /usr/share/FSlint /usr/share/man/man1/Fslint.1.gz

Installation

Demystifying the GUI interface

The FSlint package is part of the official repositories of Ubuntu and Fedora. It can be installed using the apt and yum package managers, respectively. To install FSlint on Ubuntu, execute the commands shown below in a terminal: [narendra]$ sudo apt-get update

# Request

That’s it. We are done with the installation. To install FSlint on other GNU/Linux distributions, go through the official website of the FSLint at http://www. pixelbeat.org/FSlint/ which describes installation steps.

Now that the installation is done, let us get our hands dirty with FSlint. For this demonstration, I am using the Ubuntu 14.04.1 MATE edition but FSlint’s usage and experience should be the same on other distributions. To launch FSlint from the GTK+ GUI, traverse to Applications->System Tools->FSlint. Command line junkies www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 79


Admin

How To

Figure 1: FSlint main window

Figure 2: FSlint duplicates

Figure 3: FSlint installed packages

Figure 4: FSlint bad names

can launch it by executing the fslint-gui command from the terminal. After launching it, you will be shown the main window of FSlint (Figure 1). FSlint has a few common interface items. Not every tool uses every interface option, so it is important to understand how these buttons and interfaces work. This will make it easier for you to understand their importance at various times. Let’s take a look at detailed examples of each of these tools. Search path tab: After launching FSlint, you will find the Search path tab. This provides Add and Remove buttons, which allow the user to add or remove one or more directory paths to be searched. By default, it searches from the directory that it has been launched from. If it is launched from the GUI, then it starts searching from the user’s HOME directory. On the right hand side of the main windows there is a recurse? check box, which determines the depth of the search while searching duplicate files. Advanced search parameters tab: FSlint allows advanced and powerful filtration with the aid of regular expressions and wild cards. This tab allows the user to exclude certain file

types and directories. By default, it excludes a few directory paths and file types, but the user can easily manipulate these settings with the help of the Add and Remove buttons. There is also an Extra find parameters text box, which is capable of performing a more refined search. This text box is used to pass parameters to the GNU/Linux’s find command. For instance, to search for the files that only belong to the user, Jerry, the user can add the following text: -user ‘id -u Jerry’. Select button: By using this button, the user can select specific files from the results window. It also provides you the option to select multiple entries using wild cards. This button provides other options as well, but these are self-explanatory. Additionally, the user can bring up the same menu by rightclicking within the results window. Save button: Besides the Select button, there is a Save button. After selecting files, the user can save the search results on the disk. Please note that this will save only the absolute path of the files and not the files themselves. This option is useful if you are planning to do more advanced tasks like providing this result to some automated script.

80 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com


How To

Figure 5: FSlint name clashes

Figure 6: FSlint temp files

Figure 7: FSlint bad IDs

Figure 8: FSlint empty directories

Delete button: As its name suggests, this button is used to delete selected items. I would advise you to perform this operation very carefully, because it deletes files permanently from the system. Before deleting, a confirmation window will appear each time unless the Ask me this in the future? check box is unchecked. Merge button: This operation merges all the files within a group into one physical file using links. To do this, either a hard link or a symbolic link will be used depending on the location of the file. Let us suppose you have two duplicate files, namely, file1.txt and file2.txt; then the merge operation will delete one of the files and create a link (using the ln command) to the other file. If one or more duplicate files are present on the same file system, then the merge option will create a hard link; otherwise, it will create a symbolic link. Find button: The Find button instructs FSlint to perform the selected actions. After completion, it displays the results in the window. Now that we are familiar with FSlint’s GUI interface, let us get some insight into it.

Duplicate files

Admin

One of the very common forms of file system lint is duplicate files. We often copy music files, documents, images and videos at multiple locations on the file system while taking backups. As duplicates grow, they eat up available disk space. So let us figure out how to find and remove duplicate files with just a few clicks of the mouse. The Duplicates tab on the left hand side of the screen is the default tab selected at FSlint startup. Just choose the appropriate directory using the Add button and then click on the Find button. FSlint will show the summary of the duplicate files in the results window. Figure 2 shows the result of the operation. All duplicate files are grouped together under a gray bar giving information such as the number of files in the group and the number of bytes wasted in duplicate files. The total number of bytes wasted in all the files and groups is shown below the Find button. FSlint uses the following algorithm to find duplicate files: 1) First, it scans the file system and filters out the files of different sizes. www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 81


Admin

How To

Figure 9: FSlint non-stripped binaries

Figure10: FSlint redundant white spaces

2) Then, files of the same size are checked to ensure that these are not hard links. 3) Subsequently, it calculates the checksum of the file using md5sum. 4) Finally, to guard against md5sum collisions, FSlint rechecks signatures of any remaining files using the sha1sum checksum.

or when a program wishes to report and save a problem. Removing these temporary files can free up valuable space, and FSlint can find these files so that they can be purged. It is also possible to direct the program to find only files of a specified minimum ‘age’—like those modified in the last ‘N' number of days, for instance. When the minimum age is set to 0, FSlint reports all temporary files. FSlint provides a check box core file mode? which enables a more thorough search for the core files. Figure 6 shows the results of the operation.

Installed packages

This tool lists the installed packages according to their sizes. It supports the Debian package manager (dpkg), the Red Hat package manager (RPM) and the Packman package manager. When a package is selected, a description of it is shown below the results window in a gray box. Figure 3 shows the results of the operation.

Bad names

Another common form of file system lint is bad names. Even though they do not eat up disk space, they may be difficult to use or move. The Bad names tool searches all the files and inspects their naming conventions. You can set the sensitivity level by using the slider bar at the top of the selection window. Level 1 implies the least strict while Level 4 implies a strict POSIX check. Besides the slider, there is a check box, which allows you to select UTF-8 checking. The image in Figure 4 shows the results of the operation.

Name clashes

Another form of file system lint involves files that have identical or similar names. This usually does not cause any significant problems for the user other than slight inconvenience. But finding files with name clashes can be of great help when dealing with multiple versions of files (Figure 5).

Temp files

Temporary files eat up a lot of hard disk space. These are created while editing files, while running some programs, 82 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

Bad symlinks Symbolic links are widely used in GNU/Linux. But broken symbolic links cause great frustration for the user. FSlint looks for symbolic links that have some kind of problem and immediately reports them. It specifically looks for the following problems. 1) Dangling: In this type, a broken symbolic link points to a file that no longer exists in the file system. 2) Suspect: In this type, symbolic links point to a file below their directory structure. 3) Relative: In this type, a symbolic link points to a path that is determined by the current location. 4) Absolute: In this type, a symbolic link points to a path that is determined by the full path. Note: It seems that there is a bug in the GUI tool for this operation. Because, though the command line tool (/ usr/share/fslint/fslint/findbl) reports broken links correctly, the GUI is unable to show correct results.

Bad IDs

GNU/Linux assigns a positive integer number as ‘user id' to each user. When the user moves files between multiple computers, a file will occasionally end up with a user ID that the current system cannot resolve to that user. The most common forms of bad IDs are generated when we extract


How To compressed files created by another user on another system. But FSlint finds and reports such problems. Figure 7 shows the results of the operation. In this example, the FSlint utility reports a file with a bad ID because there is no user or group with ID 1001.

Empty directories

Empty directories clutter a file system, and make it difficult for the average user to find information quickly and efficiently. FSlint can find and clean these annoying empty directories (Figure-8 shows the result of the operation).

Non-stripped binaries

Non-stripped binaries contain extra debugging symbols and tend to be larger in size. These extra debugging symbols are needed while debugging binary files with debuggers like GDB. But often, this extra debugging information is not needed, and a considerable amount of drive space can be freed by stripping the binaries. FSlint finds such non-stripped binaries (Figure-9 shows the result of the operation). In this example, the hello binary was purposefully compiled to contain debugging information. With this tool, when the Search $PATH check box is enabled, FSlint searches the system path for non-stripped binaries. This tool provides a Clean button, which removes extra debugging symbols from the binary.

Admin

Now, remove the trailing white space using FSlint’s clean option. Our modified file will now look like what’s shown below: [narendra]$ cat -e hello.c #include <stdio.h>$ $ int main(void)$ {$ printf(“Hello, World!!!\n”);$ $ return 0;$ }$

In the above examples, the dollar ($) symbol implies the end of the line. FSlint is an extremely useful tool that can be used regularly. These simple yet powerful utilities make GNU/Linux more interesting. You can always learn more about FSlint by digging into it yourself. By: Narendra Kangralkar The author is a FOSS enthusiast and loves exploring anything related to open source. He can be contacted at narendrakangralkar@gmail.com.

Redundant white spaces

FSlint can check text files for a number of white space issues like unnecessary tabs and spaces. This feature is very useful for programmers and writers who need to be aware of the white space within their files. The average user may never need to use this feature, but knowing about this tool could be beneficial. This tool also provides the check box for Bad indenting for indent width which checks text files to ensure that the indenting width is uniform. FSlint can also check for a white space at the end of a line. The Clean button will attempt to fix the white space issues in the selected files (Figure-10 shows the result of the operation). To try this out, let us create a file with a trailing white space, which will look like what follows: [narendra]$ cat -e hello.c #include <stdio.h> $ $ int main(void) $ { $ printf(“Hello, World !!!\n”); $ return 0; $ } $

$

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 83


Admin

Insight

Make Your Own IVR with Asterisk Interactive voice response (IVR) is ubiquitous and now pervades the business and commerce milieu. Using Asterisk, IVR can be easily set up and coded. This fifth article in the series on Asterisk takes a look at how IVR is coded.

A

sterisk provides a generic switching platform to run a variety of applications. IVR is commonly used today in most large corporate PBXes. Typically, these are automated voice menus – what you hear when you call a bank or insurance company. The recorded voice will prompt you to input the intended transaction as a choice in the form of digits (DTMF or dual tone multi-frequency tones). The transactions requested for are executed based on the user inputs. In this session, we will look into IVR coding and then the hardware configuration required. Let’s start with a welcome menu, which is a very common feature nowadays in any Asterisk installation. The code is written in the dial plan, which is the central routing control based on pattern matching. The dial plan is generally found in /etc/asterisk/extensions.conf.

Example 1

Play the welcome message to the caller Ring the extension for 60 seconds If unavailable, pass the call to voicemail Hang up Here’s the code snippet for this example:

84 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

[from-pstn] exten => _.,1, exten => _.,2, exten => _.,3, exten => _.,4, exten => _.,5,

Answer(); Playback(welcome); Dial(SIP/${EXTEN},60); Voicemail(${EXTEN},u); Hangup();

[from-pstn] indicates the context in which the call is processed, which is the incoming calls from the PSTN (public switched telephone network – normal PRI or FXO trunk). exten => is a standard keyword to indicate a pattern matching routine. ‘_.’indicates that any extension is matched and the following actions need to be carried out. The second digit ‘1’ after the comma indicates a sequence number. The lines that follow increase the sequence number in ascending order. Answer() indicates the call has to be answered so that the voice channels are open in both directions. This is required, so that the users can hear the greetings message and provide their inputs. Playback (welcome) instructs the system to search for a file welcome.gsm or welcome.wav in the default voice directory, and play that file for the user to hear. The file


Insight

Admin

The welcome message is played in the background, if the user dials the extension 1234. The function Playback() is blocked and the user will be able to provide the inputs only after the message is completed. In case of Background, the welcome message and ivr-options are played one after the other. The users can input their choice at any point of time. The function TIMEOUT is set for two cases: 1) if the user presses one digit, and 2) if the time exceeds 10 seconds. Also, note that the second parameter ‘n’ takes away the burden of sequencing, like in Example 1, and makes the sequence dynamically next to the previous statement. The ivr-options plays the message, “Please press 1 for sales, 2 for support, 3 for operator...” exten exten exten exten exten exten

Figure 1: A very simple IVR

1

=> => => => => =>

1,1,Dial(SIP/2000&SIP/2001); 1,n,Playback(sendback-to-ivr); 1,n,Goto(1234,1); 2,1,Dial(SIP/2002&SIP/2003); 2,n,Playback(sendback-to-ivr); 2,n,Goto(1234,1);

If the user presses 1, the extensions 2001 and 2002 will ring in parallel. If no one picks up, a voice file stating that, “Currently, no agents are available,” is played and the call is sent back to the main IVR loop. Similarly, if the user presses 2, both the extensions 2003 and 2004 in the sales department will ring. exten => 0,1,Dial(SIP/2111,50); exten => 0,n,Voicemail(2111,u); exten => 0,n,Hangup();

Figure 2: IVR with user input (all details are not shown)

could contain a voice recording of the message, “Welcome to OSFY.” EXTEN saves the value of the extension dialled by the caller. Dial the EXTEN using the SIP protocol and ring for 60 seconds. The user may pick up the call and talk to the caller. If the user is unavailable, call the service’s voicemail with the same EXTEN extension number. After returning from the voicemail, hang up.

Example 2

The next example demonstrates how calls can be routed based on the user’s inputs: [from-pstn] exten => 1234,1,Answer(); exten => 1234,n,Set(TIMEOUT(digit)=1); exten => 1234,n,Set(TIMEOUT(response)=10); exten => 1234,n,Background(welcome); exten => 1234,n,Background(ivr-options); exten => 1234,n,WaitExten();

If the user presses 0 to talk to the operator, the extension 2111 will ring for 50 seconds. If nobody responds, then the call is redirected to the voice mail. exten => i,1,NOOP(wrong input received); exten => i,n,Playback(invalid); exten => i,n,Goto(1234,1);

If the user presses anything other than 1, 2 or 0, the message file with, “You have chosen an invalid input,” is played and the call is sent back to the main loop. exten => t,1,NOOP(no input received); exten => t,n,Playback(pls-select-option); exten => t,n,Goto(1234,1);

If the user comes out of the loop without any input due to the timeout setting of 10 seconds, then another message, “You have not selected any input,” is played and sent back to the main loop. The dial plan also provides the choice to query and store to an external database. In the next example, we will have www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 85


Admin

Insight

students inputting their roll number. After verification, the users’ attendance will be reconfirmed and stored in the database. [from-pstn] exten => 1234,1,Answer(); exten => 1234,n,Set(DID=${EXTEN}); exten => 1234,n,Playback(welcome); exten => 1234,n,Playback(pls-enter-enroll); exten => 1234,n,Read(enroll,beep,10); exten => 1234,n,SayDigits(${enroll}); exten => 1234,n,Set(TIMEOUT(digit)=1); exten => 1234,n,Set(TIMEOUT(response)=10); exten => 1234,n,Background(pls-confirm); exten => 1234,n,WaitExten()

The welcome message and the request for inputting the roll number is played. After that, the roll number is read up to 10 digits. Then the input digits are read out loud and a confirmation is requested. exten exten exten exten

=> => => =>

1,1,NOOP(Caller confirmed entry); 1,n,Goto(autoprocess,submenu,1); 2,1,NOOP(Caller wants to re-enter); 2,n,Goto(1234,3);

If the user confirms that the entry is correct, then the control proceeds to the auto-process sub-menu. Else, the control proceeds to re-enter the inputs. [autoprocess] exten => submenu,1,Set(TIMEOUT(digit)=1); exten => submenu,n,Set(TIMEOUT(response)=1); exten => submenu,n,Background(Pls-select-frm-menu); exten => submenu,n,WaitExten();

A request is made to the user to input the service needed. If the user wants to check the attendance so far, ‘1’ can be pressed. exten => 1,1,NOOP(Caller wants to check attendance); exten => 1,n,MYSQL(Connect connid localhost Admin_DbUser P@55_DbPass school_db); exten => 1,n,MYSQL(Query resultid ${connid} SELECT count(date) from attendance where enroll_no=${enroll} and present=”Y”); exten => 1,n,MYSQL(Fetch fetchid ${resultid} total); exten => 1,n,MYSQL(Clear ${resultid}); exten => 1,n,MYSQL(Disconnect ${connid}) exten => 1,n,Playback(total-attendance-is); exten => 1,n,SayDigits(${total}); exten => 1,n,goto(submenu,1);

When ‘1’ is pressed, a NOOP statement is executed. A connection is made to the database with the correct user 86 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

name and password, and the total attendance is queried. The total attendance is then announced. Similarly, the program can execute any database operation including updation, deletion, etc. As a good programmer, you will have already noticed that the program gets more and more unmanageable as the size grows. Also, the usage of Goto makes the program unreadable, as the size grows. There are multiple other ways to write IVR scripts like AGI-script (Asterisk Gateway Interface-script) or PHP. Let’s explore the latter. To write in PHP, download phpagi2.2 from http://phpagi. sourceforge.net/. Unzip and keep the file inside /var/lib/ asterisk/agi-bin. Now, in the dial plan, we can initiate the PHP script by including the following line: [from-pstn] exten => _.,1,AGI(welcome.php); The following is the printout of welcome.php: !/usr/local/bin/php -q <?php set_time_limit(0); require(‘phpagi.php’); $agi = new AGI(); $agi->answer(); $agi->verbose(“Call Answered inside AGI script\n”,3); $agi->stream_file(‘welcome’); $agi->hangup(); ?>

The PHP program also uses the AGI library. The script creates a new AGI object. It answers the incoming call, renders a verbose three-level message and plays the welcome.gsm file. After playing the message, the call is hung up. All the flexibility that PHP offers can be used in this mode. This includes database access, accessing third party APIs, etc. The power of Asterisk as a platform for creating strong applications has been proven once again by doing so with simple programming.

Hardware

The hardware required is quite simple. You can use almost any Linux hardware with a PCI slot for a PRI card or FXO card. Asterisk needs to be installed on Linux hardware, and then the PCI card must be configured. Connect the PRI line from the service provider to the card, and you are ready to experience the power of Asterisk IVR! By: Devasia Kurian The author is the founder and CEO of *astTECS, an Asterisk software based company providing IP PBX, call centre diallers, etc. He can be contacted at d.kurian@asttecs.com.


Let’s Try Admin

An Overview of OpenShift

OpenShift provides all the resources needed to develop, host and scale Web applications in the public or private cloud. Available on GitHub, it has built-in support for various Web application frameworks. This article provides a tutorial on installing OpenShift and applications like WordPress, Jenkins and Tomcat through it.

C

loud computing is an innovative paradigm that delivers services on demand with a utility based billing model. NIST (National Institute of Standards and Technology, under the US Department of Commerce) has compartmentalised cloud computing into three service models (SaaS, PaaS and IaaS) and four deployment models—public clouds, private clouds, hybrid clouds and community clouds. Cloud computing is reshaping the computing and Internet landscape. With breakthroughs made in appropriate service and business models, it will certainly expand its role as the backbone for IT services. Cloud computing provides elastic and unlimited resources, which can be efficiently utilised during periods of peak loads and normal loads, with a pay per use pricing model. As already stated, the cloud model covers Software as a Service (SaaS), Platform as a Service (PaaS) and Infrastructure as a Service (IaaS). In PaaS, the user can deploy applications on the cloud infrastructure using supported programming languages (Java, PHP, Ruby and

.NET) and the platforms/tools provided by PaaS providers like Web servers, application servers and databases. Since PaaS providers manage the underlying infrastructure resources such as operating systems, virtual servers, networks, Web servers, application servers, databases, backup, disaster recovery, etc, users can focus on the most significant aspect of their business, which is the application itself, rather than worrying about managing resources, platforms and versions. PaaS includes not only the deployment environment but also repositories such as the build environment, the testing environment, performance management, mail services, log services, database services, big data services, search services, enterprise messaging services, application performance management for modern application architectures, code inspection services and so on. OpenShift is a PaaS from Red Hat. OpenShift Origin is an open source version available on Git. Red Hat OpenShift is a PaaS with Apache License 2.0. OpenShift Enterprise is a private cloud version. www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 87


Admin

Let’s Try

Figure 1: Supported technologies

also allows deployment of WAR files. The benefits of OpenShift are: Easy and fast self-service for application deployment Easy application scaling Runs on any hardware, virtual machine, cloud or even on laptops that support Red Hat Enterprise Linux Git integration with automatic deployment triggered by a Git push Gear idling allows OpenShift to support a high density of applications Support for various languages, Web frameworks, databases and application stacks

How to install OpenShift Origin or OpenShift Enterprise

To install OpenShift Origin, copy the sh <(curl -s https:// install.openshift.com/) command and run it from a bash shell. To install OpenShift Enterprise, copy the sh <(curl -s https:// install.openshift.com/ose) command and run it from a bash shell. Table 1: Parameters to execute commands Figure 2: Select the type of application

Figure 3: WordPress configuration on OpenShift-I

OpenShift supports Web-application frameworks such as Rack for Ruby, WSGI for Python and PSGI for Perl. It also supports MySQL, PostgreSQL and MongoDB. It has built-in support for Java, Python, PHP, Perl, Node.js, Ruby and extensible functionality to add languages. For Java, it covers end-to-end support for JBoss AS7, JBoss EAP6, Java EE6, CDI/Weld, Tomcat 6 and 7 (JBoss EWS 1.0 and 2.0), Spring, Liferay, Scala/Play!, Cloud9 IDE, Appcelerator Titanium, Git, Glassfish as DIY, Jetty as DIY, Eclipse, JBoss Tools, Jenkins, SSH access, Maven 3 and Ant. OpenShift offers a Linux platform with lightweight containers called gears that can run applications with open source languages and frameworks, using common services such as databases, as shown in Figure 1. OpenShift uses Git to deploy application source code. It 88 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

Short Full parameter parameter

Explanation

-u

--username USERNAME

Red Hat login username

-p

--password Red Hat login PASSWORD password --use-existing-puppet

-a

--advanced-mode

It enables access to the database server and message server for customisation

-c

--config-file FILEPATH

Provides a path to an alternate configuration file

-w

--workflow WORKFLOW_ID

Represents installer workflow for unattended deployment

-l

--list-workflows

Lists the workflow IDs available for use with unattended deployment

-e

--enterprise-mode

Shows OpenShift Enterprise options

-s

--subscription-type TYPE

Software source for installation packages

-d

--debug

Enables debugging of messages

OpenShift Online

OpenShift Online is a public cloud application development and hosting platform from Red Hat. It automates the


Let’s Try Admin

Figure 6: WordPress dashboard Figure 4: WordPress configuration on OpenShift-II

provisioning, deprovisioning, management and scaling of applications in an efficient manner. It supports programming languages such as Java, Ruby, PHP, Node. js, Python and Perl, and a set of developer tools to increase developer productivity and accelerate application deployment and delivery. It supports command line client tools and a Web management console to launch and manage applications easily. To sign up for OpenShift Online, visit https://www. openshift.com/app/account/new. Check your inbox for an email confirming your account. You must click the link in the email to complete the registration process. Accept the legal terms after verifying your account. You will get a welcome screen at https://openshift.redhat.com/app/console/ applications. Click on Create your first application now. From multiple options, choose the type of application.

Figure 5: WordPress configuration for user

Figure 7: WordPress site

WordPress on OpenShift

Let’s start with the WordPress application. Click on WordPress 4. Provide a domain under which your applications will be grouped. The application will start with an exact copy of the code and configuration provided in this Git repository https://github.com/openshift/ wordpress-example.git. Gears are the application containers running your code. For most applications, the small gear size provides plenty of resources. Applications are composed of cartridges, each one of which exposes a service or capability to your code. All applications must have a Web cartridge. Note the credentials and other important information such as connection URL. Select the language for WordPress installation. Give your username, password, site title, email and other information required. Click on Install Wordpress. Log in to the admin area at https://mywordpress-msclouds.rhcloud.com/wp-login.php. Figure 6 gives the dashboard for the WordPress site we have created on the OpenShift Online. Visit the site (Figure 7).

Figure 8: Jenkins login screen www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 89


Admin

Let’s Try

Table 2: Comparison of OpenShift, Heroku and CloudFoundry

Type Website License Written in Developers

OpenShift

Heroku

CloudFoundry

PaaS, Web development openshift.com Apache License 2.0 Ruby Red Hat

Subsidiary, PaaS heroku.com Proprietary Salesforce.com Released

PaaS cloudfoundry.org Apache License 2.0 Ruby, Go VMware Pivotal Software Released

Production Horizontal, vertical

Production Horizontal, vertical

Public PaaS Clojure, Groovy, Java, Node, PHP, Python, Ruby, Scala Django, Flask, Grails, Play, Rails

Private PaaS Go, Groovy, Java, Node, Ruby, Scala

Postgresql

-

Development Released status Status Production Scaling supported Horizontal, vertical, auto scaling Deployment style Public PaaS Supported Java, Node, Perl, PHP, runtimes Python, Ruby Supported Django, Flask, Drupal, frameworks Rails, Switchyard, Vert.x Supported Jenkins, Mongodb, services Mysql, OpenShift Metrics, Pgrouting, Postgis, Postgresql

Grails, Play, Rails, Sinatra, Spring

Figure 9: Jenkins dashboard

Jenkins on OpenShift

Jenkins is an open source continuous integration server that is a vital part of the DevOps culture. The Jenkins app is provided by OpenShift Online. Select Jenkins from the application types available. Give the public URL for your Jenkins server. Click on Create application, and then click on Visit app in the browser. Access Jenkins in the Web browser. Log in with the credentials provided in the OpenShift dashboard. Figure 9 shows the Jenkins dashboard.

Tomcat on OpenShift

Tomcat is an open source Web server developed by the Apache Software Foundation. Select Tomcat as the type of application from the OpenShift Online dashboard. View Tomcat related information and its status on the OpenShift Online dashboard. Visit and verify the Tomcat server in the browser.

OpenShift dashboard

OpenShift Online supports three free applications. After 90 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

Figure 10: OpenShift Online dashboard

creating these three applications, verify the OpenShift Online dashboard.

References [1] https://install.openshift.com/ [2] http://en.wikipedia.org/wiki/OpenShift [3] http://www.infoworld.com/article/2608610/cloudcomputing/cloud-computing-paas-shoot-out-cloudfoundry-vs-openshift.html [4] The NIST Definition of Cloud Computing, Version 15 [5] https://www.openshift.com/ [6] http://www.paasify.it/

By: Mitesh Soni The author is aKumar technical lead. He loves to write about new By: Anil Pugalia technologies. Blog: http://clean-clouds.com


Overview For U & Me

s p p A d i o r d n A n Te y A d y r e for ev

r U o Y n USe o

e n o h p t Smar An Android phone can be greatly enhanced by installing some good apps. For a newbie, the selection of apps becomes a herculean task as the choice is so vast. This article offers some guidelines for selecting apps, while reviewing the top 10 Android apps for regular use.

G

oogle Play is one of the key reasons why Android has been a grand success in the smartphone market. This store hosts more than 1.3 million applications or apps of every kind, but how does a first time Android user select an app from such a vast range? Each app is unique in nature and serves its purpose, but the real catch is how well suited it is for you and your device. This article showcases some of the best apps in Open source that can be suitable for your daily needs. Device compatibility Resource consumption (such as memory, CPU, data, etc) Updates Data protection Performance ratings All the open source apps mentioned here are available at Google Play as well as F-Droid.

Mozilla Firefox

Mozilla Firefox has been the best open source browser for years. The mobile version of Mozilla Firefox comes with a sleek interface, which enables the user to switch through various options such as recent tabs, history, top sites, bookmarks, etc. Although there are many features and add-ons available for Firefox, I’d like to mention just two of the most outstanding. www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 91


For U & Me

Overview

The Reading List add-on enables you to save Web pages for offline reading. The Save as PDF add-on enables you to convert the Web pages to the PDF without much hassle.

Telegram

Telegram was originally launched in 2013, but it soon became a popular instant messenger (IM) for Android. At present, there are more than 35 million users of Telegram worldwide. Telegram is based on the cloud platform and is aimed at speed and security. While there are plenty of other IM clients for Android, what makes Telegram really stand out from the rest of the apps out there, are the following: It is open source Secret chats Self-destructing messages Group with a maximum capacity of 200 members can be created Support for almost every file format

K-9 Mail

Most of the email clients that come by default in Android devices are sufficient for personal use, but if you’re looking for an option to address your business needs and you receive a lot of mail, then it is worth taking a look at K-9. It can support multiple accounts and each can be configured by you based on your needs. K-9 Mail can connect to Web servers using all popular protocols such as POP3, IMAP and WebDAV. Another important feature is that you can encrypt and decrypt mail using Open PGP and APG methods.

GNU Cash

GNU Cash helps you to track your personal finances. It acts as a companion to the GNU Cash desktop client. So, you can import your accounts and transactions from your desktop client to your mobile app. But you cannot synchronise the desktop client with the mobile client. Some of the features of GNU Cash are: Creates multiple accounts and transactions Double-entry accounting with support for multiple splits Nested account hierarchy Exports the transactions in OFX (Open Financial Exchange) and QIF (Quick Interchange Format) formats Saves your transactions in Google Drive, Sky Drive, Dropbox, etc

VLC Player

VLC Player is the open source media player for Android, which is capable of playing audio and video files. The app

92 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

automatically scans all the files in your device so you’re set to play your media files. You can easily switch between the audio and video players by using the side bar. The app also remembers the position at which the video file last stopped and resumes playing from that point onwards. VLC Player has emerged from the beta stage and has released its first stable version 1.0.0.

Tinfoil for Facebook

It is pretty well known that Facebook tracks users via cookies, but most of us are still compelled to this social networking platform because many of our friends and colleagues use it and we cannot sever all communications with the outside world. But if you are concerned about your privacy, Tinfoil for Facebook protects you by using a wrapper. This app uses the mobile view protected by a wrapper, which prevents the mobile site from accessing online activity. The app provides various options such as allowing you to check and open links inside the app instead of an external browser, blocking all the images. Tinfoil for Facebook doesn’t consume much battery power and is low on data consumption.

The ‘Duck Duck Go’ search widget

As you are aware, Google searches are not secure and your search history is made available to some private corporations for profit. So if you want complete privacy on your searches, then ‘Duck Duck Go’ is the best choice for you. Duck Duck Go enables you to search the Web anonymously. Below the search field, there’s a stream of interesting content that is collected from various sources such as Reddit, Quora, BBC, Ars Technica, etc. You also get to choose the sources as they are provided in the app under various categories. Since the sole purpose of the Duck Duck Go app is to provide anonymity for your searches, you can increase your anonymity by integrating the app with Orbot. The search results can be modified by changing the ‘Region Setting’ to a country of your choice, so that you may get the search results with respect to that country.

Orbot

Orbot is the TOR anonymity client for Android, which protects you from network surveillance. Orbot works both in rooted and non-rooted devices. If your device is not rooted and you do not have super user access, then you can use other apps that work with Orbot to secure your privacy. Merely installing Orbot doesn’t guarantee privacy, though.


Overview For U & Me Some of the other apps that work with Orbot are: Chat Secure Orweb Duck Duck Go Mozilla Firefox When you are done with configuration, you are now ready to run the app. There is an icon of an onion on the notification area to indicate that Orbot is running. You can check if Orbot is properly configured by using the ‘Check browser’option. If your device is successfully configured, a Web page will show that the browser is configured to use TOR.

OSMAND~

OSMAND~ is the acronym for OSM Automated Navigation Directions, which is an Android app for offline map and navigation purposes. OSMAND~ relies on OSM (Open Street Map—a huge collection of offline maps that was contributed by users around the globe) for data. To begin, you need to download the maps according to your preference. These maps often get updated so you can have more precise details about your location. All these maps

are stored in the memory card for offline use. OSMAND~ provides turn-by-turn voice guidance, optional lane guidance, street name display and estimated time of arrival.

Note Cipher

Note Cipher is a simple note-taking app that employs the industry standard 256-bit AES encryption. After installing the app, you will be asked for your password, which once set cannot be changed. Once the app is unlocked, it will show the unlocked icon on the notification, but it will be automatically locked if the app is idle for a few minutes. It will never store data in an unencrypted state. You can share your notes with others just by clicking the ‘Share’ icon on the interface.

By: Magimai Prakash The hasKumar completedPugalia a B.E. in computer science. As he By:author Anil is deeply interested in Linux, he spends most of his leisure time exploring open source.

Customer Feedback Form Open Source For You

None

OSFY?

You can mail us at osfyedit@efy.in You can send this form to ‘The Editor’, OSFY, D-87/1, Okhla Industrial Area, Phase-1, New Delhi-20. Phone No. 011-26810601/02/03, Fax: 011-26817563

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 93


For U & Me

Insight

Android Lollipop: What’s in it for Enterprises? Enterprise mobility offers a wealth lot of opportunities for OEMs, solutions providers, UX designers, and developers. On the face of it, this may appear as easy as mobile applications grabbing business data from enterprise servers, but the reality is completely different. Read on to learn more.

L

et’s start this discussion by defining what enterprise mobility actually is. In my opinion, it is the trend that denotes the shift in how today’s employees think about working from out of the office. It’s about their current expectations regarding accessing enterprise business flows from their mobile devices in a seamless manner. From the perspective of an enterprise’s CIO (Chief Information Officer) or CISO (Chief Information Security Officer), enterprise mobility is an immensely investment hungry trend, because it requires mobile access to enterprise data and sometimes business-critical enterprise data over non-trusted networks—all from an employee’s mobile device. The ‘bring your own device’ (BYOD) practice at work is now inevitable for any enterprise interested in enterprise

94 | april 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

mobility. Various enterprise mobility management (EMM) solutions are available in the market, which are capable of addressing an organisation’s data security and device management needs. Android’s Lollipop OS is quite different from its predecessors in terms of enterprise capabilities. One of the core requirements for supporting BYOD is the identification of enterprise applications and personal applications on the users’ devices. So far, established EMM providers have been addressing this challenge in customised ways. Hence, the capabilities they offer vary from one product to another. However Lollipop is coming out with a new set of APIs called ‘Android for Work’, built over Samsung’s Knox security framework. Currently, all popular OEMs are working with Google to provide support for ‘Android for Work’ on their devices.


Insight Let’s take a closer look at what this means for enterprises and IT workers. Lollipop aims to provide a physical separation between a user’s personal data and enterprise data, using the Knox framework. There will be a separate launcher app for enterprise apps, and all enterprise applications will be marked by the ‘Android for Work’ icon. This separation will empower IT administrators to control enterprise apps and their corresponding data without affecting the user’s personal applications and data. All leading EMM providers are claiming support of Lollipop by leveraging the native capabilities offered by Google. Figure 1 gives a comparative view of the ‘pre-Lollipop’ and ‘Lollipop’ eras. Changes at the application layer and the Android OS layer are expected to bring enterprise-class security in a default manner in Android Lollipop-powered devices. All EMM providers will then be able to leverage this default support in their upcoming releases. A typical EMM solution consists of the following: A web console An on-device EMM agent An EMM library to be used with enterprise applications for policy compliance In the pre-Lollipop scenario, an on-device EMM agent and the EMM library were specific to particular EMM providers. Hence, the enterprise acceptability of an Android device was driven by the capabilities of the selected thirdparty EMM solution. But now, in the Lollipop era, the equivalent of an on-device agent will be provided by Google, and ‘Android for Work’ APIs will replace the EMM library. Hence, going forward, it can be assumed that, by default, Lollipop-powered devices will be enterprise ready. However, third party EMM solutions will still be required to perform administrative activities like enterprise policies management, their deployment on selected sets of devices, etc, in a remote manner. Figure 3 shows an overview of a typical EMM solution in the Lollipop era.

Device and data security

We have already discussed the strong separation between personal and enterprise data and applications in Lollipop. Apart from this, Lollipop includes a device protection feature called the Kill Switch. If this anti-theft protection is enabled on the device and the ‘Lock password’ feature is available, then the device’s ‘Factory reset’ option will ask the user for their registered Google ID credentials. Without providing valid credentials, a thief will not be able to implement a factory reset on a stolen device, and the device will remain unusable.

For U & Me

Figure 1: Comparative view

Figure 2: A typical EMM solution

Figure 3: An EMM solution in the era of Android Lollipop

Support for IT policies and restrictions

EMM providers will be able to use a new set of APIs powered by Knox to enforce a wide set of policies ranging from system settings to application-specific settings.

Knox APIs for secure enterprise apps

EMM providers will be able to use new backend APIs powered by Knox APIs. This will empower IT administrators to take care of remotely deployed devices and securely manage the applications installed on them. Android Lollipop is the largest and most ambitious release from Google, especially from an enterprise mobility perspective. Last but not least, all the changes disscussed above will enable Google to address OEM fragmentation issues to a certain extent. References [1] http://android-developers.blogspot.in/2014/07/knoxcontribution-to-android.html [2] https://www.samsungknox.com/en/androidworkwithknox

By Aditya Saxena The author is director of the mobile practice for Syntel’s Enterprise Solutions Group, which develops and delivers business mobility and BYOD enablement solutions to leading global enterprises.

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | april 2015 | 95


For U & Me

Overview

Manage Your Marketing Activities

with CampaignChain

Open source has extended its reach to all spheres of human endeavour, and business is no exception. CampaignChain is a very handy tool for organising online marketing activities. With a little bit of imagination, this tool can be used to manage social campaigns too.

W

hen every other person is trying to run a business of their own, marketing becomes a must. Be it a start-up or an established firm, everyone depends on marketing to grow their business. And the Web is currently one of the fastest growing marketing platforms. Facebook, Twitter, LinkedIn and Google+—all cater to the growth of businesses by providing platforms for advertisements. However, the downside is that it is quite hard to manage one’s online marketing efforts. That’s exactly why a group of open source enthusiasts have launched CampaignChain, a tool for managing digital marketing campaigns. CampaignChain is an open source campaign management software to plan, execute and monitor a digital marketing campaign across multiple online communication channels, which include Twitter, Facebook, Google Analytics, or third party CMSs, e- commerce and CRM tools. The key features of CampaignChain are planning, execution and monitoring. The ‘Planning’

96 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

module includes defining goals/milestones, scheduling a campaign, and viewing and modifying the campaign activities and operations using an interactive time line. Automatic execution of a scheduled activity, collection of data for analysis and automatic notifications in case of errors, come under the ‘Execution’ module. The ‘Monitoring’ module comprises the Analytics Report covering the number of Facebook ‘likes’, comments, number of Twitter re-tweets and so on. The Budget Report defines the budget spent per channel, and the Sales Report is integrated with CRM and other tools to view and analyse leads generated by each campaign.

The many benefits of CampaignChain

Let’s find out just how handy this tool is. I will jot down some of the problems faced and then offer solutions using CampaignChain. There are many online channels for advertising. So it


Overview For U & Me

Figure 1: Create a new location

Figure 3: Announcement on Facebook

Figure 2: New Facebook status

Figure 4: Managing all activities

becomes cumbersome and hectic to go to individual sites and post an advertisement. CampaignChain provides a common platform where the user can choose whatever online channel is desired. There is an option to add sites, apart from those already being used. The second hurdle is when we are unclear about scheduling a campaign, that is, when to post an advertisement on a specified channel. This tool has configured a feature to resolve this issue. All one has to do is create an activity and schedule it. (Creating a new post for a blog channel is an example of an activity.) The benefit of scheduling is that it saves a lot of time and lets you plan your campaign. After posting the advertisement, one may want to know more about how the advertisement is being received, so statistics about the number of tweets, re-tweets, Facebook ‘likes’, comments, subscriptions or any other key parameters are welcome. This feature is well integrated in CampaignChain. All one has to do is paste a code snippet on the server pages and that’s it. The monitor tab gives a chart of statistics collected per activity per online channel, along with data on how the marketing budget has been utilised. Statistics give a clear indication about how many leads have been generated per campaign and which activity has the highest impact. This helps in deciding future marketing plans. As an example, the video of the ‘Clean India’ campaign or the Ice Bucket Challenge gained a lot of views on YouTube as compared to the 160-character quote on Twitter on the same topics. So more emphasis was given to online video channels for promoting the campaign, as people could see their idols taking up the challenge of cleaning India or going under the ice bucket.

Improper management is a glitch associated with a campaign and this arises mostly because of incomplete data or inconsistent information. The CampaignChain tool provides a tab named ‘Execute’ which shows a clear picture of the upcoming activities, the milestones to achieve and the ongoing activities. This helps in planning one’s marketing campaign accordingly. Any software is considered worthy if it is user friendly and takes good care of the customer. CampaignChain ranks high on both counts. It has a very user-friendly UI, backed by a group of professionals, who help in adapting CampaignChain to fit your marketing objectives and processes. Training is also provided with respect to the technical details of this tool. All you have to do is drop a mail to info@campaignchain.com. If you wish to try your hand at it, download CampaignChain by visiting http://www.campaignchain.com/ try/. The complete installation is provided in a manual at http://doc.campaignchain.com/wp-content/doc/pdf/current/ CampaignChainDocumentation.pdf. But there are some prerequisites, such as your system must have PHP5.4 or a later version, Java 1.5 or a more current version and MySQL; PHP’s system() function must work, etc. All these details can be found in the documentation.

By: Ashish Kumar Sinha The is aKumar software engineer based in Bengaluru. A By:author Anil Pugalia software enthusiast at heart, he is passionate about using open source technology and sharing it with the world. He can be reached at ashi.sinha.87@gmail.com

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 97


Open Gurus

Insight

Audio Video Bridging: Evolution of Multimedia Streaming Technology The Institute of Electrical and Electronics Engineers (IEEE) has developed a set of technical standards that allow time-synchronised low latency streaming services through IEEE 802 networks. This is commonly known as audio video bridging. Read on to learn more about the concept.

I

nitially, when our project was instituted, I was oblivious of the potential of the audio video bridging (AVB) standard and its applications, as I was mainly involved in the protocol implementation to get the desired outcome. It was only when I started monitoring AVB products and the AVB demonstrations held by companies in this domain that I learned about its significance. Let us start with a brief introduction to Ethernet AVB, which has evolved from the existing Ethernet standard. This technology ensures tight control over the quality of service required for streaming real-time high-quality audio and video over wired Ethernet. Before the existence of AVB standards, the audio and video set-up involved a large number of cables intertwined with each other. Now, AVB technology provides a high quality audio and video experience using structured wiring without any complicated set-ups, while coexisting with the other non-media network traffic. AVB technology involves fundamental changes to the Ethernet standards to support the audio-video media distribution, by furnishing high precision network synchronisation, dynamic bandwidth reservation to ensure packet delivery within stipulated latency and traffic shaping to minimise bandwidth needs. It also eliminates media bursts even when passing through multiple network hops, and provides admission control to ensure

98 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

that non-AVB devices don’t degrade the performance of the AVB network and devices. The AVB ecosystem is evolving and creating its own niche in the automotive infotainment, consumer electronics, broadcast system design and other domains. Before the AVB standard came into existence, there was no standard way to synchronise the audio-video devices, to reserve the bandwidth and resources to stream real-time AV data between these devices, and to discover and control them. To understand the functionality of AVB, assume you have listener devices - one speaker in the kitchen, one in the garage and one in your bedroom. You have a talker device, like a mobile, connected with the three speakers in an AVB network, and you wish to stream AV data to these listener devices in real-time. You also want to download data from the Internet, simultaneously, on your mobile device. The realtime streaming will not be affected even when non-AVB traffic faces traffic congestion, and the AV data will be played at the same instant by all the listeners. AVB is the name given to a set of protocol standards developed by the IEEE Audio Video Bridging Task Group. To standardise and improve the interoperability of AVB devices and networks, a consortium of automotive and consumer electronics companies, called the AVnu Alliance, was formed in August 2009. It constantly strives to establish and certify AVB products which


Insight Open Gurus Let me introduce you to the first four basic AVB protocols required to form an AVB network. With these standards, one can have a single talker-listener set-up working in an AVB network. But to establish an AVB network comprising multiple talkers and listeners, one needs to provide the support of the other two (AVDECC and MAAP) standards to manage and control these devices.

Applications IEEE 1722.1

Discovery, Enumeration, Configuration and Control

IEEE 1722/1722a/1733 802.1 Qat SRP

TCP/UDP Services

Streaming Media Services

802.1 AS gPTP

OS

TCP/UDP on IP Protocol Stack

AV Transport Protocol

802.1 Qav

IEEE 802.1AS

The IEEE 802.1AS protocol plays a pivotal role in synchronising AVB devices by exchanging timing information over the network. This exchange of timing information allows the AVB devices to synchronise their local clocks with reference to a standard AVB clock. The model adopted by gPTP is analogous to the slave-master model, where the master exchanges its timing information with the other AVB devices (slaves) and the slaves synchronise their clock with the master (see Figures 3 and 4).

FQTSS

Ethernet Driver Silicon (Core + EMAC +EPHY)

Figure 1: AVB stack layout LISTNER

TaLkER

Stereo Line Out

Stereo Line In

audio Source

Ethernet Hub

LISTNER

TaLkER

Stereo Line Out

Stereo Line In

audio Source

IEEE 802.1Qav

This traffic shaping (queuing and forwarding) protocol is implemented at the hardware layer (MAC). Traffic shaping involves prioritising the transmission of packets to maintain the standard streaming rate required to transfer AVB packets while handling nonAVB network traffic. It can also be termed as bandwidth reservation protocol. To recap, the definition of bandwidth means the number of bits transmitted per unit of time, and the hardware controls the number of packets transmitted per unit of time, using credits. Let us assume credit to be an X constant value. Now, whenever there is an AVB packet to be transmitted, the hardware checks for the value of X. The credits, i.e., the value of X, keeps getting accumulated at a constant rate when an AVB packet is queued. If the value of X is positive, the AVB packet is transmitted out Slave Clock

Master Clock Now, It’s ...

Figure 2: A simple talker and listener set-up

ensure interoperability and improve audio/video quality. In general, an AVB ecosystem deploys the following protocols: IEEE 802.1AS: Timing and synchronisation for timesensitive applications (gPTP) IEEE 802.1Qav: Forwarding and queuing for timesensitive streams (FQTSS) IEEE 802.1Qat: Stream reservation protocol (SRP) IEEE 1722 Layer 2 AVB transport protocol IEEE 1722.1: Audio video discovery, enumeration, connection management and control protocol (AVDECC) IEEE 1722.MAAP: MAC address acquisition protocol How the AVB stack resides in an AVB device can be understood from Figure 1. The talker and listener set-up forming an AVB network can be understood from Figure 2.

Hardware TS removes effect of protocol stack jitter

Network jitter remains other techniques must be used to reduce this effect

PTP UDP IP

OK, thanks 9:25!

PTP UDP IP TSMAC

MACTS PHY

Hardware TS removes effect of protocol stack jitter

Network

PHY IEEE 1588 stack

... 9:25!

Network protocol stack & OS

Now it;s 9:25

Timestamp generation / message detection

Minimize imapct of protocol stack jitter by generating timestamps as close to the physical interface boundary as possible

MI / GMI

PHY

Figure 3: Clock synchronisation using gPTP

1:30:05

1:30:05

1:30:05

1:30:05

MASTEr

1:30:05

1:30:05

Figure 4: Slaves synchronised to master www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 99


Open Gurus e

Slop

nd se

idle

e op Sl

Credit

Insight

three aVB packets are queued

Queue Depth

1

0

Transmitted Data

Time

4th aVB packet is queued

3

2

2

1

1

0

0

Interfering traffic

credit positive, aVB packets launched as soon as interfering traffic is finished

credit positive, 3rd aVB packet launched

credit positive, 3rd aVB packet launched

credit negative, 3rd aVB packet held

IEEE 1722 Layer 2 AVB transport protocol

Figure 5: Qav traffic shaping D R

D

advertise

D

R

R

advertise

advertise

advertise

e R

ertis

D

R

R

T

B3

D

B4

adv

advertise

D

B5

D

advertise advertise

advertise advertise

R

R

Other end station Bridge

R

B1

Listener station

R

R D

Talker station

L B6

D

advertise

D

T

D

B2

D

R

r - registration D - declaration

propagation of talker advertise towards intended listener propagation of talker advertise towards other endpoints

Figure 6: Successful reservation (talker advertise)

D R

D

ready

R

B3 R

advertise

ready

ready T

D D

B4

R

e R

ertis

R

D

adv

B2

D

D

B1

advertise R

D

B5

advertise advertise R

Listener station

Bridge

R D

Talker station

Other end station

advertise

ready R D

B6

D

D

ready

requirements. The bridge receiving this message sets aside or reserves the requested resources, and propagates the message to the next system. The listener responds with a ‘listener ready’ message, which is sent back to the talker. If any bridge fails to allocate the requested resources, it sends a ‘talker fail’ message to the other systems, which results in AV traffic streaming getting aborted. This is how a stream is actually registered with the bridges and the two endpoints – talker and listener – communicate with each other. The resources comprise ensuring port throughput, data rate and registering AVB class. Refer Figure 6 and Figure 7.

R

r - registration D - declaration

propagation of listener ready back to talker (on asame path as advertise propagation of talker advertise towards other endpoints

Figure 7: Reservation acknowledged (listener ready)

of the hardware; otherwise (if the value of X is negative), the AVB packet is buffered until the value of X rises again and becomes positive. During this interval, the hardware gets busy dealing with non-AVB traffic, thus handling AVB and nonAVB traffic efficiently. This is just a short summary of how the hardware reserves bandwidth for AV traffic, to ensure the desired QoS. Refer Figure 5.

IEEE 802.1Qat

The stream reservation protocol ensures the reservation of network resources for specific AV streams traversing bridged networks. It determines the resources required, and exploits a mechanism for dynamic maintenance of those resources. Before the source starts initiating the AV traffic, it sends the ‘talker advertise’ message across the network. This message consists of the following: source and destination MAC address, 16-bit unique ID and information about the resource 100 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

This protocol basically handles the packetising of the AV data into a standard 1722 Ethernet frame. It also shoulders the responsibility of passing down the 1722 AVB packet to the driver for it to transmit over the Ethernet. This protocol is implemented as part of the talker application, which does the following: Reads raw audio/video data from a file Packetises the same data into a standard AVB Ethernet frame Delivers the AVB Ethernet frame to the lower layer driver for its transmission This application has also undergone significant modifications, which involve reading data directly from the AV devices and streaming it to the listener application. The main purpose of this is to extract the raw data and play it in real-time over the loudspeaker/headphones, or when using an ALSA sub-system. We are currently experimenting with an AVB set-up that involves AVB endpoints (talker/listener) designed and developed by XMOS and an AVB Ethernet switch from DSP4U. Initially, our set-up included only one talker and one listener, with support from the first three AVB protocols, but now the AVB stack has evolved and is mature enough to handle multiple AVB devices in an AVB network. We will discuss the AVDECC, MAAP and IEEE 1722 layer 2 transport protocols in the next article about multiple AVB devices in an AVB network. But before we do that, here’s some food for thought. Can you think of another domain where this technology can penetrate? What will an entire AVB network set up using Ethernet LAN cables look like? Quite clumsy, right! So what’s next? An AVB wireless chip? References [1] http://en.wikipedia.org/wiki/Audio_Video_Bridging [2] http://www.ieee802.org/1/pages/avbridges.html [3] http://blog.meinbergglobal.com/category/ieee1588/

Videos [1] https://www.youtube.com/watch?v=R8Hjyu4IIkE [2] http://www.xmos.com/news/videos?search=AVB [3] https://www.youtube.com/watch?v=kQ7FBbH-krM

By: Sumeet Jain The author works at eInfochips as an embedded systems By: Anil Kumar Pugalia engineer. You can reach him at sumeet.jain@einfochips.com


Interview For U & Me

At Open Source India 2014, many tech start-ups wanted to understand how they could leverage open source technology. Well, for a start-up, or any other technology-oriented firm for that matter, getting the best tech solution at minimum cost is the way to go. But this is really not what we would focus on, in this article. While conversing with the owners of start-ups who were present at OSI Days 2014, we understood that one of the biggest issues was generating funds to move ahead in the game. Yes, this is pretty much an issue for almost every startup, particularly in a country like India, where the startup ecosystem is still in its infancy. As they say, if there is a problem, there is a solution too. As we all know, venture capitalists do come to the rescue of such startups, looking to be funded. But the road leading to a VC invariably involves a bumpy ride. In a bid to understand the entire process of reaching out to a VC and how to arrange funds, Diksha P Gupta from Open Source For You spoke to Sushanto Mitra, founder and CEO, Lead Angels, an alumnifocused angel network, and discussed several issues that hamper young entrepreneurs. Read on...

Sushanto Mitra, founder and CEO, Lead Angels

Q

What are the areas in which startups need help and how does Lead Angels pitch in? A. Before I answer that, I would like to share a bit about our origin. In the year 2000, I had set up a consulting firm, helping the early-stage companies to raise money. I continued doing that till 2007, when I joined IIT Bombay as the CEO of its business incubator called SINE. It was a very interesting stint as I was coming across very early-stage ideas and incubating them. But the fact remains that in academic institutions, even though there are very bright people, the exposure to business is very limited. Unfortunately, even today, most of these academic

institutions are not able to interact with the outside world; therefore, the world beyond the campus walls doesn’t get to know what exciting ideas are brewing inside. Students only get a hang of the real world when they move out, which is why a lot of alumni of various institutions want to give back to their institutes. They want to invest in interesting ideas with the aim of giving back in some way and also because they are more comfortable in their own alma mater. There is a level of credibility and comfort already established when it comes to the alumni. So that is the origin of Lead Angels. We are an alumnifocused angel network, with which

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | april 2015 | 101


For U & Me

Interview

‘‘One of the start-ups that we are looking at, which happens to be from Delhi, is using open source components to build a fairly complex product. I think that as the IT availability increases as a result of cloud and mobile technologies, it is creating a level playing field between start-ups and large companies.” alumni from the IITs and the IIMs are associated, to invest in companies emerging from these institutions. Of course, there is nothing exclusive about either the investee companies or the investors. We are not saying that the IITs and the IIMs enjoy an exclusivity with us; in fact, a majority of our members are not from these institutes. But yes, these institutes are our focus. We have our meetings in the IITs and IIMs, and we are involved with their entrepreneurship development cells or incubators. The simple logic is that investors are not interested in merely investing in the name of any institute, although that can be an advantage sometimes. An investor is more focused on interesting ideas. Investees also do not want to restrict themselves to just the alumni. Angel investing is not just about funding —it is about mentoring, offering knowledge value-addition and about connections as well. For the start-ups, business exposure is as important as funds, to grow the business. So, we just don’t arrange funds, we arrange for support in terms of mentorship, guidance and business exposure.

Q

How many start-ups have you funded so far?

A. We have completed the investment process in two start-ups, as of now There are two more companies that we are in the advanced stages of funding. A couple of them are in the pipeline. Getting funds and appropriate mentorship for any start-up takes time. We had set up Lead Angels in July 2013. Our first angel meeting happened in October 2013 in Mumbai. It takes time to build a sizable network of like-minded people that can help

A. No, not necessarily. As an investor, one doesn’t want to be limited to any particular sector. One wants to invest in anything and everything that makes a profit. Of course, I won’t deny that tech and tech-enabled businesses are a major attraction, because they are scalable. But we are not restricting ourselves or our investors to any domain. We are evaluating everything—from concept fast food restaurants to the healthcare sector. We cannot deny that today IT is an integral part of everything we want to do.

the network are in a position to bring business to the start-ups. Let’s not forget that for a start-up, getting that first order is the most important thing. So if we have a start-up that is into warehouse management, and one of our members is associated with a courier company that has a warehouse, it becomes easy for the start-up to get its first trial. The fact remains that nobody wants to give business to a start-up, but members do take such steps, helping the start-ups get their first order. From the technology front, many of the members come with technical qualifications and experience. They can also help on technology if required. Since it is a group of experts in the business, they certainly know how to mentor and manage start-ups in more ways than one. We also have partnerships with multiple incubators like IIIT-Hyderabad, IIT-Delhi, IITBombay and several such institutions. So, if a start-up requires some technical support or even interns, we can arrange all of that. Essentially we aim to provide support to the start-ups at various levels.

Q

As you mentioned, IT is an integral part of any business these days. Do you help the start-ups develop their IT infrastructure?

Q

A. Before I answer that, let me share with you who our members are. They include people who have built successful businesses over a period of time like Faisal Farooqui of Mouthshut.com, Alok Kejriwal of Games To Win, etc. Some of the members are from traditional industries, like one of the founders of Lawrence and Mayo. There are also members working in private equity and venture capital firms, in their individual capacities. They bring the skills of what they do as investors to the network. So this network helps in evaluating the companies and when the investment is made, one of us becomes a board member or observer of the start-up to support and mentor the company, depending on what its critical requirements are. Also, many of the investors in

A. Yes. In fact, one of the startups that we are looking at, which happens to be from Delhi, is using open source components to build a fairly complex product. I think that as the IT availability increases as a result of cloud and mobile technologies, it is creating a level playing field between start-ups and large companies. For example, the two competitors of this start-up are Fortune 100 companies. Their product would be similar to what this start-up is making. In fact, what these kids are creating is a faster product using open source technology and because it is going to be provided as a service, it will be easily and affordably available at any point in time. I am not claiming that

in investing in the companies. Right now, we have 70 investors on board as members, across Delhi, Mumbai and Ahmedabad.

Q

So, are you focusing only on tech start-ups?

102 | april 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

Amongst the tech start-ups that you have worked with, so far, do you see open source technology flourishing?


Interview For U & Me they will beat the biggies, but my point is that they will be operating in the same market. This start-up has built only two critical components on its own, and for the rest, it is using open source. It already has clients like banks and financial institutions, which means that critical domains like banking are open to using open source technologies. I think open source offers a certain level of democracy against large software and hardware product companies. The future is certainly going towards open source, leading to a fair balance in the technology market.

“There are start-ups operating in different domains that use open source technologies in one way or the other. The fact is that young start-ups cannot afford expensive proprietary software. More importantly, they get a good choice with open source technology, so they happily resort to it.”

Q

Q

Are non-tech start-ups also going for open source technologies in a big way? A. Yes, there are start-ups operating in different domains that use open source technologies in one way or the other. The fact is that young start-ups cannot afford expensive proprietary software.

More importantly, they get a good choice with open source technology, so they happily resort to it. For instance, we are a financial services start-up but we use open source technology for our emailing system. And we keep looking for open source alternatives wherever they can be deployed.

So, how does a start-up reach out to you?

A. It actually works both ways. They can reach out to us and we also do keep looking for interesting startups. They can come to our website where they can contact us. In our angel meetings, we have something

called the ‘idea pitch’ apart from the three formal presentations that we have every month. Here people can come and pitch their ideas and take feedback from the investors present at the meeting. If we like an idea, we invite them back to make a formal presentation. We also attend events related to start-ups where we have interactions with them and keep looking for interesting ideas. As I mentioned earlier, we have partnerships with incubators and student entrepreneurship development cells. So all these, put together, bridge the gap between us and the start-ups.

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | april 2015 | 103


TIPS

&

TRICKS

Generating a random password

Today, it is very important to use secure and random passwords for various accounts. The pwgen command on the Linux terminal generates passwords that are designed to be easily memorised by humans, while being as secure as possible. $ pwgen -1 -s

This command generates a single secure password. If we need many passwords, we can skip the ‘-1’ option. Note: If pwgen is not installed, you can install it by using your Linux package manager. —Naveen H, naveenh760@gmail.com

A script to check for a live host in networks

We often come across situations in which we need to check for a live host/computer in the network. Here is a script that will do the job for you. Open a text editor and create a script as live-check.sh with the following contents: #!/bin/bash for((i=1;i<255;i++)) do ##enter your network ip and redirect it to any text-file## ping 192.168.1.$i -c1 | grep “bytes from” | cut -d “” -f4 |cut -d”:” -f1 >> ip_scan.txt

Using awk along with the ssh command

Many users have an issue when executing the awk command with ssh and get the following error: #ssh server149.example.com “uname -a | awk ‘{print $2}’” awk: cmd. awk: cmd. bash: -c: `)’ bash: -c:

line:1: {print $2}) line:1: ^ syntax error line 0: unexpected EOF while looking for matching line 1: syntax error: unexpected end of file

This error is due to awk considering $2 of the local system and not the remote system. To resolve this issue, you can use the awk command as shown below: ssh server149.example.com “uname -a | awk ‘{print \$2}’”

This will use the $2 value of the remote computer and you will get the expected output. —Ravikant Tyagi, ravikanttyagi@gmail.com

Tracking a file in Linux

If you have one important file named ‘/root/mydata. txt’ and need to keep track of who has used it, when it was used and by which program or command, then you can monitor it using the following commands: [root@ns1 ~]# auditctl -w /root/mydata.txt -k “myfile”

done

Run the script using the following command and wait for the scan to complete.

This command will start monitoring the activity on the file: [root@ns1 ~]# ausearch --key “myfile” --raw | aureport --file

$sh live-check.sh

Once the scan is complete you can check the ip_scan. txt file to see the live hosts. —Pulkit Maheshwari, pulkit.maheshwari2008@gmail.com 104 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com

This is how you can audit files and get the required details about who used a file and when. —Amit Setia, amit.2009setia@gmail.com


Split larger files using 7zip # 7z

a

-v200m

-mx0

ubuntu.7z

/test/ubuntu.iso

The command given above will create 200MB sized files from the ubuntu.iso. The -v200m is the volume size (use k for kilobytes and g for gigabytes); and the -mx0 switch tells 7-Zip not to use compression, that is, to just split data into parts. To extract a file, just type: # 7z

x

ubuntu.7z.001

…or type:

/dev/sda6 on / type (rw,errors=remount-ro) proc on /proc type (rw,noexec,nosuid,nodev) sysfs on /sys type (rw,noexec,nosuid,nodev) ... ... ... /dev/sda7 on /home type (rw) systemd on /sys/fs/cgroup/systemd type (rw,noexec,nosuid,nodev,none,name=systemd) gvfsd-fuse on /run/user/1000/gvfs type gvfsd-fuse (rw,nosuid,nodev,user=naru)

ext4 proc sysfs

ext4 cgroup fuse.

# 7z e ubuntu.7z.001

Note: You need to install 7zip if it’s not already installed. To install it on Ubuntu, run the following command: $ sudo apt-get install p7zip-full

—Shiju V, shijusvk@gmail.com

Setting up routes with ipv6

Add the ipv6 route using the ‘ip’ command, as follows:

—Narendra Kangralkar, narendrakangralkar@gmail.com

Find listening network ports

With the help of the following command, you can find the processes that are running and their associated port numbers. This command can help systems administrators troubleshoot various production issues (like when a process is killed and the port number related to the service is still in use). With this command, it’s easy to trace the port number and its associated processes. # netstat -tulpn Active Internet connections (only servers)

#ip -6 route add <ipv6network>/<prefixlength> via <ipv6address> #ip -6 route add 2000::/3 via 2001:0db8:0:f101::1

Add the ipv6 route using ‘route’: #route -A inet6 add <ipv6network>/<prefixlength> gw <ipv6address> [dev <device>] #route -A inet6 add 2000::/3 gw 2001:0db8:0:f101::1

—Shreehari Dhat, shreeharidhat@gmail.com

Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 1138/mysqld tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 850/portmap tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1607/apache2 tcp 0 0 0.0.0.0:55091 0.0.0.0:* LISTEN 910/rpc.statd

—Munish Kumar, munishtotech@gmail.com

Formatted output with the column command

The column utility formats its input into multiple columns. We can use this command to view the formatted output of the mount command: [bash]$ mount | column -t

The output is:

Share Your Linux Recipes! The joy of using Linux is in finding ways to get around problems—take them head on, defeat them! We invite you to share your tips and tricks with us for publication in OSFY so that they can reach a wider audience. Your tips could be related to administration, programming, troubleshooting or general tweaking. Submit them at www.opensourceforu. com. The sender of each published tip will get a T-shirt.

www.OpenSourceForU.com | OpEN SOUrCE FOr YOU | April 2015 | 105


OSFY DVD

DVD OF THE MONTH Try out something new and fresh.

MakuluLinux 8.0 ‘Cinnamon’: This is a Debian based distribution that provides a sleek, smooth and stable user experience on any computer. The new release is the first from the project to be built for 64-bit x86 computers. If you face issues in running the live edition, then try it out in the compatibility mode. The default user name in the live mode is ‘makulu’ and the password is ‘makulu’. The software bundled with the OSFY DVD works in the live mode. Tails 1.3: Tails is a live system that aims to preserve your privacy and anonymity. Tails comes with several built-in applications preconfigured with security in mind: a Web browser, instant messaging client, email client, office suite, image and sound editor, etc. You can find the ISO image of the live version on the DVD under the other_isos folder. Chakra GNU/Linux 2015.03: Chakra is a GNU/Linux distribution with an emphasis on KDE and Qt technologies. It focuses on simplicity from a technical standpoint and is free software. It features a graphical installer, automatic hardware detection and configuration, the latest KDE desktop, and a variety of tools and extras. Originally forked from Arch Linux, the distro comes with a stable core and bleeding edge applications. You can find the ISO image of the live version on the DVD under the other_isos folder.

What is a live DVD? A live CD/DVD or live disk contains a bootable operating system, the core program of any computer, which is designed to run all your programs and manage all your hardware and software. Live CDs/DVDs have the ability to run a complete, modern OS on a computer even without secondary storage, such as a hard disk drive. The CD/DVD directly runs the OS and other applications from the DVD drive itself. Thus, a live disk allows you to try the OS before you install it without erasing or installing anything on your current system. Such disks are used to demonstrate features or try out a release. They are also used for testing hardware functionality, before actual installation. To run a live DVD, you need to boot your computer using the disk in the ROM drive. To know how to set a boot device in BIOS, please refer to the hardware documentation for your computer/laptop.

106 | April 2015 | OpEN SOUrCE FOr YOU | www.OpenSourceForU.com


136

January 2015 | ElEctronics For you

www.EFymag.com


R N I No. DELENG/2012/49440, Mailed on 27/28th of Advance month Published on 27th of Advance month

Delhi Postal Regd. No. DL(S)-01/3443/2013-15

There is a place for Postgres in every datacenter. WE CAN HELP YOU FIND IT. Postgres delivers. Enterprise class Performance, Security, Success. For 80% less. EnterpriseDB - The Postgres Database Company

Sales-india@enterprisedb.com EnterpriseDB Software India Pvt Ltd Unit #3, Godrej Castlemaine Pune - 411 01 India T +91 20 30589500/01


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.