Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials

7018 Articles
article-image-diving-straight-photographic-rendering
Packt
11 Mar 2014
7 min read
Save for later

Diving Straight into Photographic Rendering

Packt
11 Mar 2014
7 min read
(For more resources related to this topic, see here.) Lighting that sets the mood! While a good composition gives us a solid foundation on which to build a photographic render, if we try to render a scene that has no lighting, well let's just say the end results will fall quite a way short of those desired. The brilliant thing about lighting a scene with V-Ray in SketchUp is that a complete day-lighting system that consists of both the Sun and Sky elements is, by default, set up and ready to render with as soon as we start creating geometry in the scene. For newer users, this can obviously help tremendously when it comes to getting up and running with the software. Controlling the placement of the Sun is extremely easy as we simply need to make use of SketchUp's built-in shadow controls, wherein we set the month of the year along with the time of day and time zone, and then we can render. What we instantly get is natural-looking daylight without having to do anything at all! Better still is the fact that V-Ray also sets up a basic indirect (or global) illumination system for us automatically. This means we can even render interior Arch Viz shots right out of the box without having to do any extra set up work beyond, of course, getting our geometry created and then positioned in the scene. Global illumination is a general name for a group of algorithms used in 3D computer graphics that are meant to add more realistic lighting to 3D scenes. Such algorithms take into account not only the light which comes directly from a light source (direct illumination), but also subsequent cases in which light rays from the same source are reflected by other surfaces in the scene, reflective as well as non-reflective (indirect illumination). The source of this content is Wikipedia. To look at the kind of renders we can get from V-Ray without doing any real lighting setup at all, either continue to work with your current scene or open up the Ch01_03_Lighting.skp file from your Exercise_Files folder, if you prefer to work with the same scene as I will be using. Stepping through the render process The scene or camera angle we are using here (Scene 2) has been deliberately chosen to help us properly evaluate the quality and level of lighting that we are getting in our scene. It can do this because it affords us a full view of the environment. With our camera view set to Scene 2, let's take a render by clicking the render button on the V-Ray toolbar. Once the initial translation phase is complete, V-Ray opens up its own frame buffer window and starts the rendering phase. One of the very nice features of V-Ray Version 2.0 is the fact that translation times in scenes are now significantly faster (in the vast majority of cases) than rendering the same scene in V-Ray Version 1.49. The first activity we see in the frame buffer window will be V-Ray's indirect illumination calculations. First of all, the light cache and then the irradiance mapping engines calculate the level of illumination and light bounce requirements for the scene. This is based on the parameters set up in the V-Ray option editor and the materials applied through the materials editor. Irradiance mapping and light cache are the two indirect illumination engines set up by default in V-Ray Version 2.0 for SketchUp. The final part of this process is the rendering of the image itself. In this instance, what we get, as we no doubt could discern from the GI calculations, is way too dark for the type of bright and airy feel in the interior that we are looking for. This brings us to a critical aspect of lighting in V-Ray, exposure! Using V-Ray's physical camera model Another default aspect of the V-Ray setup in SketchUp is that it makes use of a physical camera model for rendering. This means that real-world parameters such as shutter speed, F numbers (or F stops), and ISO (or film speed) values are used to control various aspects of the render, such as exposure, motion blur, and depth of field. Basically, if we understand how to control these elements on a real-world camera, be it film or digital, then we already have a big head start when it comes to rendering using the V-Ray physical camera model. To access the physical camera controls, we need to revisit the V-Ray toolbar and click on the option editor button once more. Then, if we open the Camera rollout, you can see in the following screenshot that we now have access to a wealth of camera controls and parameters. As we have already noted that our render is quite a bit darker than desired, the controls we are interested in would be those capable of affecting the exposure levels, which would be as follows: Shutter Speed F Number Film Speed (ISO) As a general rule, I prefer to handle exposure levels using only the film speed value as much as I possibly can. This is due to the fact that it is the only one of the three controls in what is often referred to as the exposure triangle that isn't used to control some other aspect of the physical camera model. Shutter speed is also used to control motion blur while the F number (or F stop) value will typically be the control mechanism for any Depth of Field (DOF) effects in our render. To get some nice brightness levels in this instance, let's adjust the film speed or ISO value and set it to 1200. Taking another render by hitting the render button on the far right of the V-Ray frame buffer's top toolbar will show us that our illumination levels are now much more appropriate for the bright, airy feel we want to create. The higher the ISO number we use in a render, the more sensitive V-Ray becomes to light, thereby producing a brighter final image. Unlike the ISO setting on a digital camera, we can increase this value as much as we like in V-Ray without the fear of introducing artifacts or noise into our rendered images. Global illumination controls The next aspect of our lighting setup that needs a little attention is the quality of the indirect illumination solution. At this moment, we can see quite a bit of dark splotching on our nice clean geometry. This often happens when we work with scenes that present a little bit of a challenge to the indirect illumination engines, which, of course, interiors nearly always do. Couple this with the reasonably low-quality default settings that V-Ray sets up, and we get splotches or noise patches in our render. To clean this up a little, let's perform the following steps: Jump into the Irradiance map rollout in the option editor, and in the Basic Parameters section, set the minimum and maximum rate values to -2 and -1 respectively. We can also increase the HSph.subdivs value to 125 and the Interp.samples value to 35. Next, we can jump into the Light cache rollout and increase the Subdivs (or subdivisions) value to 1200. If we take another render by hitting the button on the toolbar, we should see a marked improvement in the level of splotchiness present in the image; not that every trace of it will be gone, mind you. When working with interior scenes, creating completely noise-free Global Illumination (GI) renders can prove to be quite costly in terms of the time it takes to render the final image. What we often have to aim for then is a situation that would generally be considered free enough of noise to be called an acceptable final solution. One reason why we can often get away with this is the fact that once materials get applied to the geometry, any slight levels of splotchiness still found in the scene tend to oftentimes just blend into the materials themselves. We do need to bear in mind that every increase in quality settings inside a render engine, such as those we have just applied to the indirect illumination controls, will result in a corresponding increase in the time it takes for the render to complete! This is typically referred to as the speed verses quality conundrum.
Read more
  • 0
  • 0
  • 2496

article-image-article-reporting-with-microsoft-sql
Packt
11 Mar 2014
7 min read
Save for later

Reporting with Microsoft SQL

Packt
11 Mar 2014
7 min read
(For more resources related to this topic, see here.) Server 2012 Power View – Self-service Reporting Self-service reporting is when business users have the ability to create personalized reports and analytical queries without requiring the IT department to get involved. There will be some basic work that the IT department must do, namely creating the various data marts that the reporting tools will use as well as deploying those reporting tools. However, once that is done, IT will be freed of creating reports so that they can work on other tasks. Instead, the people who know the data best—the business users—will be able to build the reports. Here is a typical scenario that occurs when a self-service reporting solution is not in place: a business user wants a report created, so they fill out a report request that gets routed to IT. The IT department is backlogged with report requests, so it takes them weeks to get back to the user. When they do, they interview the user to get more details about exactly what data the user wants on the report and the look of the report (the business requirements). The IT person may not know the data that well, so they will have to get educated by the user on what the data means. This leads to mistakes in understanding what the user is requesting. The IT person may take away an incorrect assumption of what data the report should contain or how it should look. Then, the IT person goes back and creates the report. A week or so goes by and he shows the user the report. Then, they hear things from the user such as "that is not correct" or "that is not what I meant". The IT person fixes the report and presents it to the user once again. More problems are noticed, fixes are made, and this cycle is repeated four to five times before the report is finally up to the user's satisfaction. In the end, a lot of time has been wasted by the business user and the IT person, and the finished version of the report took way longer that it should have. This is where a self-service reporting tool such as Power View comes in. It is so intuitive and easy to use that most business users can start developing reports with it with little or no training. The interface is so visually appealing that it makes report writing fun. This results in users creating their own reports, thereby empowering businesses to make timely, proactive decisions and explore issues much more effectively than ever before. In this article, we will cover the major features and functions of Power View, including the setup, various ways to start Power View, data visualizations, the user interface, data models, deploying and sharing reports, multiple views, chart highlighting, slicing, filters, sorting, exporting to PowerPoint, and finally, design tips. We will also talk about PowerPivot and the Business Intelligence Sematic Model (BISM). By the end of the article, you should be able to jump right in and start creating reports. Getting started Power View was first introduced as a new integrated reporting feature of SQL Server 2012 (Enterprise or BI Edition) with SharePoint 2010 Enterprise Edition. It has also been seamlessly integrated and built directly into Excel 2013 and made available as an add-in that you can simply enable (although it is not possible to share Power View reports between SharePoint and Excel). Power View allows users to quickly create highly visual and interactive reports via a What You See Is What You Get (WYSIWYG) interface. The following screenshot gives an example of a type of report you can build with Power View, which includes various types of visualizations: Sales Dashboard The following screenshot is another example of a Power View report that makes heavy use of slicers along with a bar chart and tables:   Promotion Dashboard We will start by discussing PowerPivot and BISM and will then go over the setup procedures for the two possible ways to use Power View: through SharePoint or via Excel 2013. PowerPivot It is important to understand what PowerPivot is and how it relates to Power View. PowerPivot is a data analysis add-on for Microsoft Excel. With it, you can mash large amounts of data together that you can then analyze and aggregate all in one workbook, bypassing the Excel maximum worksheet size of one million rows. It uses a powerful data engine to analyze and query large volumes of data very quickly. There are many data sources that you can use to import data into PowerPivot. Once the data is imported, it becomes part of a data model, which is simply a collection of tables that have relationships between them. Since the data is in Excel, it is immediately available to PivotTables, PivotCharts, and Power View. PowerPivot is implemented in an application window separate from Excel that gives you the ability to do such things as insert and delete columns, format text, hide columns from client tools, change column names, and add images. Once you complete your changes, you have the option of uploading (publishing) the PowerPivot workbook to a PowerPivot Gallery or document library (on a BI site) in SharePoint (a PowerPivot Gallery is a special type of SharePoint document library that provides document and preview management for published Excel workbooks that contain PowerPivot data). This will allow you to share the data model inside PowerPivot with others. To publish your PowerPivot workbook to SharePoint, perform the following steps: Open the Excel file that contains the PowerPivot workbook. Select the File tab on the ribbon. If using Excel 2013, click on Save As and then click on Browse and enter the SharePoint location of the PowerPivot Gallery (see the next screenshot). If using Excel 2010, click on Save & Send, click on Save to SharePoint, and then click on Browse. Click on Save and the file will then be uploaded to SharePoint and immediately be made available to others. Saving files to the PowerPivot Gallery A Power View report can be built from the PowerPivot workbook in the PowerPivot Gallery in SharePoint or from the PowerPivot workbook in an Excel 2013 file. Business Intelligence Semantic Model Business Intelligence Semantic Model (BISM) is a new data model that was introduced by Microsoft in SQL Server 2012. It is a single unified BI platform that publicizes one model for all end-user experiences. It is a hybrid model that exposes two storage implementations: the multidimensional data model (formerly called OLAP) and the tabular data model, which uses the xVelocity engine (formally called VertiPaq), all of which are hosted in SQL Server Analysis Services (SSAS). The tabular data model provides the architecture and optimization in a format that is the same as the data storage method used by PowerPivot, which uses an in-memory analytics engine to deliver fast access to tabular data. Tabular data models are built using SQL Server Data Tools (SSDT) and can be created from scratch or by importing a PowerPivot data model contained within an Excel workbook. Once the model is complete, it is deployed to an SSAS server instance configured for tabular storage mode to make it available for others to use. This provides a great way to create a self-service BI solution, and then make it a department solution and then an enterprise solution, as shown: Self-service solution: A business user loads data into PowerPivot and analyzes the data, making improvements along the way. Department solution: The Excel file that contains the PowerPivot workbook is deployed to a SharePoint site used by the department (in which the active data model actually resides in an SSAS instance and not in the Excel file). Department members use and enhance the data model over time. Enterprise solution: The PowerPivot data model from the SharePoint site is imported into a tabular data model by the IT department. Security is added and then the model is deployed to SSAS so the entire company can use it. Summary In this article, we learned about the features of Power View and how it is an excellent tool for self-service reporting. We talked about PowerPivot how it relates to Power View. Resources for Article: Further resources on this subject: Microsoft SQL Server 2008 High Availability: Installing Database Mirroring [Article] Microsoft SQL Server 2008 - Installation Made Easy [Article] Best Practices for Microsoft SQL Server 2008 R2 Administration [Article]
Read more
  • 0
  • 0
  • 1127

article-image-snapshots
Packt
25 Feb 2014
8 min read
Save for later

Snapshots

Packt
25 Feb 2014
8 min read
(For more resources related to this topic, see here.) Much ado about snapshots (Intermediate) Snapshots are a fantastic feature of VMware Fusion because they allow you to roll the VM back in time to a previously saved state. Using snapshots is easy, but understanding how they work is important. Now, first things first. A snapshot is not a backup, but rather a way to either safely roll back in time or to keep multiple configurations of an OS but share the same basic configuration. The latter is very handy when building websites. For example, you can have one snapshot with IE7, another with IE8, another with IE9, another with IE10, and so on. A backup is a separate copy of the entire VM and/or its contents ("Your VM" and "Your Data") on a different disk or backup service. A snapshot is about rolling back in time on the same machine. If you took the snapshot when we finished installing Windows 7 but before upgrading to Windows 8, you can easily switch back and forth between Windows 7 and 8 by simply restoring the state. Let's see how. Getting ready Firstly, the VM doesn't have to be running, but it can be. The snapshot feature is powerful enough to work even when the VM is still running, but goes much faster if the virtual machine is powered off or suspended. We can use the snapshot we took when we finished installing Windows 7. If you didn't take a snapshot at that time, you can go ahead and take a new snapshot now by clicking on the Take button from the snapshot window. How to do it... Snapshots are best taken when a VM is powered off. It doesn't have to be, but your computer will complete the "Take Snapshot" operation much faster if the VM is powered off or suspended. Both fully powered off and suspended tasks are much faster because the VM isn't in motion when the snapshot is taken, allowing the operation to finish at a single stroke. Otherwise, the way the snapshot mechanism works when a VM is running is that once it finishes, it has to now gather the new data that changed from when the snapshot operation started. So, if it took five minutes to take a snapshot, it then has to gather itself up to date for those five minutes. That might take a minute. After that, it has to go back again to gather that last minute. If that minute takes 20 seconds, it has to then gather those 20 seconds again. This is made worse with the more things you're doing within the virtual machine. So, get it done in one motion by suspending or powering off the VM first. Launching the snapshot window and examining the tree The following sequence of steps is used to initiate the snapshot process: Click on the Snapshots button in the VM window and have a look at the snapshot interface. In my example, the following was the view of my "tree" right after we finished installing Windows 7: When I finished upgrading to Windows 8, I took another snapshot. This allows me to go back in time to both a fresh Windows 7 and Windows 8 installation, as shown in the following screenshot: Restoring a snapshot Having a TARDIS or DeLorean might be more fun, but for the rest of us, we can go back in time by restoring a snapshot. Let's go back to Windows 7 from our Windows 8 VM. Follow these steps: In the Snapshot Manager window, simply double-click on the base disk at the top of the tree to restore it. It will ask about saving the current state. Choose Save when prompted asks as shown in the following screenshot. You can rename the snapshot at any time from this window by right-clicking on the name and clicking on Get Info. After a few seconds, depending on the speed of your Mac, the older version should now show as the Current State, as shown in the following screenshot. If the VM was running, it should just show up now as being Windows 7. If you see a spinning wheel in the upper-right corner, that's the "disk cleanup" activity working in the background. You can use the VM while it's doing this; however, it might be a bit slow on disk access while it's cleaning up the disks. If the VM is suspended or powered off when restoring, the operation is much faster because the VM isn't changing/running. With this technique, you can switch between Windows 7 and Windows 8 with ease. How it works... In Fusion, all of the VM's files, are stored under Documents | Virtual Machines by default. Your C: drive in Windows is actually a series of files on the Mac named in sequence, with a .vmdk extension inside the Virtual Machines folder, as shown in the following screenshot. You can view the files by right-clicking on the VM and clicking on Show Package Contents from the Virtual Machines folder in the Finder. When you create a VM, it starts with one virtual disk (called the base disk). This virtual disk, or VMDK, is broken up into 2 GB "chunks" by default, but it can be one big chunk if desired. So, for a 20 GB disk, you end up with about 10 or 11 .vmdk files. This is for easy transport with drives that don't support large drives (such as MS-DOS/FAT32-formatted drives), and you may also have a performance benefit in certain cases. When you take a snapshot, the currently active VMDK goes into read-only mode, and a new VMDK is created. All writes go to the new VMDK, and reads happen from the original VMDK when the bits are there. Fusion is smart enough to keep track of what files are where; so, when the VM is running, Fusion is reading all of the snapshots in the current state's chain. A .vmdk file is thus named <disk_name>-<snapshot_number>-<slice>.vmdk. So, in my example, Virtual Disk is my disk name. (I could have customized and specified something different by performing a Custom Virtual Machine operation at the beginning.) I have three disks: Virtual Disk, Virtual Disk-000001, and Virtual Disk-000003. This means I have two snapshots and a base disk. (I took one snapshot and deleted it, which is why there's no Virtual Disk-000002). Each of those disks are of 60 GB capacity, so there are 31 slices. (s001 to s031). Each file starts around 300 KB and can grow to just over 2 GB. You can see where things can start to get confusing now. It gets even better when you have snapshots that are based on snapshots. You can have multiple snapshots with a common parent, which introduces a new concept in Fusion, that is, snapshot trees. Snapshots are also a great way to make sure something new isn't going to destroy your VM. So, if you are about to install some software that might be risky, take a snapshot. It's easy to roll back if something goes wrong. There's more... Snapshots are complicated, but there's great material out there by the gurus behind Fusion itself about how they work on a more technical level. More information You can read more about snapshots from Eric Tung, one of the original developers of Fusion (the blog is a bit old, but still completely accurate with respect to how snapshots work) at http://blogs.vmware.com/teamfusion/2008/11/vmware-fusion-3.html. A great article by Eric to dispel some of the confusion around snapshots and how to use them is available at http://blogs.vmware.com/teamfusion/2008/11/bonustip-snaps.html. One thing to note is that the more snapshots you have, the more effort the Mac has to make to "glue" them all together when you're running your virtual machine. As a rule of thumb, don't take snapshots and keep them around forever if you don't intend on rolling back to them regularly. Also, each snapshot can grow to be the size of the entire C: drive in Windows. Use them when necessary, but be aware of their performance and disk-usage costs. Summary In this article, we studied about snapshots and their usage. It shows you how to use this to make one virtual machine with both Windows 7 and Windows 8. Resources for Article: Further resources on this subject: An Introduction to VMware Horizon Mirage [Article] Windows 8 with VMware View [Article] Securing vCloud Using the vCloud Networking and Security App Firewall [Article]
Read more
  • 0
  • 0
  • 9836

article-image-mongodb-data-modeling
Packt
20 Feb 2014
5 min read
Save for later

MongoDB data modeling

Packt
20 Feb 2014
5 min read
(For more resources related to this topic, see here.) MongoDB data modeling is an advanced topic. We will instead focus on a few key points regarding data modeling so that you will understand the implications for your report queries. These points touch on the strengths and weaknesses of embedded data models. The most common data modeling decision in MongoDB is whether to normalize or denormalize related collections of data. Denormalized MongoDB models embed related data together in the same database documents while normalized models represent the same records with references between documents. This modeling decision will impact the method used to extract and query data using Pentaho, because the normalized method requires joining documents outside of MongoDB. With normalized models, Pentaho Data Integration is used to resolve the reference joins. The following table provides a list of objects that form the fundamental building blocks of a MongoDB database and the associated object names in the pentaho database. MongoDB objects Sample MongoDB object names Database Pentaho Collection sessions, events, and sessions_events Document The sessions document fields (key-value pairs) are as follows: id: 512d200e223e7f294d13607 ip_address: 235.149.145.57 id_session: DF636FB593684905B335982BEA3D967B browser: Chrome date_session: 2013-02-20T15:47:49Z duration_session: 18.24 referring_url: www.xyz.com The events document fields (key-value pairs) are as follows: _id: 512d1ff2223e7f294d13c0c6 id_session: DF636FB593684905B335982BEA3D967B event: Signup Free Offer The sessions_events document fields (key-value pairs) are as follows: _id: 512d200e223e7f294d13607 ip_address: 235.149.145.57 id_session: DF636FB593684905B335982BEA3D967B browser: Chrome date_session: 2013-02-20T15:47:49Z duration_session: 18.24 referring_url: www.xyz.com event_data: [array] event: Visited Site event: Signup Free Offer This table shows three collections in the pentaho database: sessions, events, and sessions_events. The first two collections, sessions and events, illustrate the concept of normalizing the clickstream data by separating it into two related collections with a reference key field in common. In addition to the two normalized collections, the sessions_events collection is included to illustrate the concept of denormalizing the clickstream data by combining the data into a single collection. Normalized models Because multiple clickstream events can occur within a single web session, we know that sessions have a one-to-many relationship with events. For example, during a single 20-minute web session, a user could invoke four events by visiting the website, watching a video, signing up for a free offer, and completing a lead form. These four events would always appear within the context of a single session and would share the same id_session reference. The data resulting from the normalized model would include one new session document in the sessions collection and four new event documents in the events collection, as shown in the following figure: Each event document is linked to the parent session document by the shared id_session reference field, whose values are highlighted in red. This normalized model would be an efficient data model if we expect the number of events per session to be very large for a couple of reasons. The first reason is that MongoDB limits the maximum document size to 16 megabytes, so you will want to avoid data models that create extremely large documents. The second reason is that query performance can be negatively impacted by large data arrays that contains thousands of event values. This is not a concern for the clickstream dataset, because the number of events per session is small. Denormalized models The one-to-many relationship between sessions and events also gives us the option of embedding multiple events inside of a single session document. Embedding is accomplished by declaring a field to hold either an array of values or embedded documents known as subdocuments. The sessions_events collection is an example of embedding, because it embeds the event data into an array within a session document. The data resulting from our denormalized model includes four event values in the event_data array within the sessions_events collection as shown in the following figure: As you can see, we have the choice to keep the session and event data in separate collections, or alternatively, store both datasets inside a single collection. One important rule to keep in mind when you consider the two approaches is that the MongoDB query language does not support joins between collections. This rule makes embedded documents or data arrays better for querying, because the embedded relationship allows us to avoid expensive client-side joins between collections. In addition, the MongoDB query language supports a large number of powerful query operators for accessing documents by the contents of an array. A list of query operators can be found on the MongoDB documentation site at http://docs.mongodb.org/manual/reference/operator/. To summarize, the following are a few key points to consider when deciding on a normalized or denormalized data model in MongoDB: The MongoDB query language does not support joins between collections The maximum document size is 16 megabytes Very large data arrays can negatively impact query performance In our sample database, the number of clickstream events per session is expected to be small—within a modest range of only one to 20per session. The denormalized model works well in this scenario, because it eliminates joins by keeping events and sessions in a single collection. However, both data modeling scenarios are provided in the pentaho MongoDB database to highlight the importance of having an analytics platform, such as Pentaho, to handle both normalized and denormalized data models. Summary This article expands on the topic of data modeling and explains MongoDB database concepts essential to querying MongoDB data with Pentaho. Resources for Article: Further resources on this subject: Installing Pentaho Data Integration with MySQL [article] Integrating Kettle and the Pentaho Suite [article] Getting Started with Pentaho Data Integration [article]
Read more
  • 0
  • 0
  • 2682

article-image-form-handling
Packt
20 Feb 2014
22 min read
Save for later

Form Handling

Packt
20 Feb 2014
22 min read
(For more resources related to this topic, see here.) Collecting user data is a basic function of many websites and web applications, from simple data collection techniques such as registration or login information, to more complex scenarios such as payment or billing information. It is important that only relevant and complete information is collected from the user. To ensure this, the web developer must enforce validation on all data input. It is also important to provide a good user experience while enforcing this data integrity. This can be done by providing useful feedback to the user regarding any validation errors their data may have caused. This article will show you how to create an attractive web form that enforces data integrity while keeping a high-quality user experience. A very important point to note is that any JavaScript or jQuery validation is open to manipulation by the user. JavaScript and jQuery resides within the web browser, so a user with little knowledge can easily modify the code to bypass any client-side validation techniques. This means that client-side validation cannot be totally relied on to prevent the user from submitting invalid data. Any validation done within the client side must be replicated on the server, which is not open for manipulation by the user. We use client-side validation to improve the user experience. Because of this, the user does not need to wait for a server response. Implementing basic form validation At the most basic level of form validation, you will need to be able to prevent the user from submitting empty values. This recipe will provide the HTML and CSS code for a web form that will be used for recipes 1 through 8 of this article. Getting ready Using your favorite text editor or IDE, create a blank HTML page in an easily accessible location and save this file as recipe-1.html. Ensure that you have the latest version of jQuery downloaded to the same location as this HTML file. This HTML page will form the basis of most of this article, so remember to keep it after you have completed this recipe. How to do it… Learn how to implement basic form validation with jQuery by performing the following steps: Add the following HTML code to index.html. Be sure to change the source location of the JavaScript included for the jQuery library, pointing it to where the latest version of jQuery is downloaded on your computer. <!DOCTYPE html> <html > <head>    <title>Chapter 5 :: Recipe 1</title>    <link type="text/css" media="screen" rel="stylesheet" href="styles.css" />    <script src = "jquery.min.js"></script>    <script src = "validation.js"></script> </head> <body>    <form id="webForm" method="POST">       <div class="header">          <h1>Register</h1>       </div>       <div class="input-frame">          <label for="firstName">First Name:</label>          <input name="firstName" id="firstName" type="text"             class="required" />       </div>       <div class="input-frame">          <label for="lastName">Last Name:</label>          <input name="lastName" id="lastName" type="text"             class="required" />       </div>       <div class="input-frame">          <label for="email">Email:</label>          <input name="email" id="email" type="text"             class="required email" />       </div>       <div class="input-frame">          <label for="number">Telephone:</label>          <input name="number" id="number" type="text"             class="number" />       </div>       <div class="input-frame">          <label for="dob">Date of Birth:</label>          <input name="dob" id="dob" type="text"             class="required date"             placeholder="DD/MM/YYYY"/>       </div>       <div class="input-frame">          <label for="creditCard">Credit Card #:</label>          <input name="creditCard" id="creditCard"             type="text" class="required credit-card" />       </div>       <div class="input-frame">          <label for="password">Password:</label>          <input name="password" id="password"             type="password" class="required" />       </div>       <div class="input-frame">          <label for="confirmPassword">Confirm             Password:</label>             <input name="confirmPassword"                id="confirmPassword" type="password"                class="required" />       </div>       <div class="actions">          <button class="submit-btn">Submit</button>       </div>    </form> </body> </html> Create a CSS file named styles.css in the same directory and add the following CSS code to add style to our HTML page and form: @import url(http: //fonts.googleapis.com/css?family=Ubuntu); body {    background-color: #FFF;    font-family: 'Ubuntu', sans-serif; } form {    width: 500px;    padding: 20px;    background-color: #333;    border-radius: 5px;    margin: 10px auto auto auto;    color: #747474;    border: solid 2px #000; } form label {    font-size: 14px;    line-height: 30px;    width: 27%;    display: inline-block;    text-align: right; } .input-frame {    clear: both;    margin-bottom: 25px;    position: relative; } form input {    height: 30px;    width: 330px;    margin-left: 10px;    background-color: #191919;    border: solid 1px #404040;    padding-left: 10px;    color: #DB7400; } form input:hover {    background-color: #262626; } form input:focus {    border-color: #DB7400; } form .header {    margin: -20px -20px 25px -20px;    padding: 10px 10px 10px 20px;    position: relative;    background-color: #DB7400;    border-top-left-radius: 4px;    border-top-right-radius: 4px; } form .header h1 {    line-height: 50px;    margin: 0px;    padding: 0px;    color: #FFF;    font-weight: normal; } .actions {    text-align: right; } .submit-btn {    background-color: #DB7400;    border: solid 1px #000;    border-radius: 5px;    color: #FFF;    padding: 10px 20px 10px 20px;    text-decoration: none;    cursor: pointer; } .error input {    border-color: red; } .error-data {    color: red;    font-size: 11px;    position: absolute;    bottom: -15px;    left: 30%; } In addition to the jQuery library, the previous HTML page also uses another JavaScript file. Create a blank JavaScript file in the directory where the index.html file is saved. Save this file as validation.js and add the following JavaScript code: $(function(){    $('.submit-btn').click(function(event){       //Prevent form submission       event.preventDefault();       var inputs = $('input');       var isError = false;       //Remove old errors       $('.input-frame').removeClass('error');       $('.error-data').remove();       for (var i = 0; i < inputs.length; i++) {          var input = inputs[i];          if ($(input).hasClass('required') &&             !validateRequired($(input).val())) {             addErrorData($(input), "This is a required             field");             isError = true;          }         }       if (isError === false) {          //No errors, submit the form          $('#webForm').submit();       }    }); });   function validateRequired(value) {    if (value == "") return false;    return true; }   function addErrorData(element, error) {    element.parent().addClass("error");    element.after("<div class='error-data'>" + error + "</div>"); } Open index.html in a web browser and you should see a form similar to the following screenshot: If you click on the Submit button to submit an empty form, you will be presented with error messages under the required fields. How it works… Now, let us understand the steps performed previously in detail. HTML The HTML creates a web form with various fields that will take a range of data inputs, including text, date of birth, and credit card number. This page forms the basis for most of this article. Each of the input elements has been given different classes depending on what type of validation they require. For this recipe, our JavaScript will only look at the required class, which indicates a required field and therefore cannot be blank. Other classes have been added to the input fields, such as date and number, which will be used in the later recipes in this article. CSS Basic CSS has been added to create an attractive web form. The CSS code styles the input fields so they blend in with the form itself and adds a hover effect. The Google Web Font Ubuntu has also been used to improve the look of the form. jQuery The first part of the jQuery code is wrapped within $(function(){});, which will ensure the code is executed on page load. Inside this wrapper, we attach a click event handler to the form submit button, shown as follows: $(function(){     $('.submit-btn').click(function(event){         //Prevent form submission         event.preventDefault();             }); }); As we want to handle the form submission based on whether valid data has been provided, we use event.preventDefault(); to initially stop the form from submitting, allowing us to perform the validation first, shown as follows: var inputs = $('input'); var isError = false; After the preventDefault code, an inputs variable is declared to hold all the input elements within the page, using $('input') to select them. Additionally, we create an isError variable, setting it to false. This will be a flag to determine if our validation code has discovered an error within the form. These variable declarations are shown previously. Using the length of the inputs variable, we are able to loop through all of the inputs on the page. We create an input variable for each input that is iterated over, which can be used to perform actions on the current input element using jQuery. This is done with the following code: for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; } After the input variable has been declared and assigned the current input, any previous error classes or data is removed from the element using the following code: $(input).parent().removeClass('error'); $(input).next('.error-data').remove(); The first line removes the error class from the input's parent (.input-frame), which adds the red border to the input element. The second line removes the error information that is displayed under the input if the validation check has determined that this input has invalid data. Next, jQuery's hasClass() function is used to determine if the current input element has the required class. If the current element does have this class, we need to perform the required validation to make sure this field contains data. We call the validateRequired() function within the if statement and pass through the value of the current input, shown as follows: if ($(input).hasClass('required') && !validateRequired($(input).val())) { addErrorData($(input), "This is a required field");    isError = true; } We call the validateRequired() function prepended with an exclamation mark to check to determine if this function's results are equal to false; therefore, if the current input has the required class and validateRequired() returns false, the value of the current input is invalid. If this is the case, we call the addErrorData() function inside the if statement with the current input and the error message, which will be displayed under the input. We also set the isError variable to true, so that later on in the code, we will know a validation error occurred. The JavaScript's for loop will repeat these steps for each of the selected input elements on the page. After the for loop has completed, we check if the isError flag is still set to false. If so, we use jQuery to manually submit the form, shown as follows: if (isError === false) {    //No errors, submit the form    $('#webForm').submit(); } Note that the operator === is used to compare the variable type of isError (that is, Boolean) as well as its value. At the bottom of the JavaScript file, we declare our two functions that have been called earlier in the script. The first function, validateRequired(), simply takes the input value and checks to see if it is blank or not. If the value is blank, the function returns false, meaning validation failed; otherwise, the function returns true. This can be coded as follows: function validateRequired(value) {     if (value == "") return false;     return true; } The second function used is the addErrorData() function, which takes the current input and an error message. It uses jQuery's addClass() function to add the error class to the input's parent, which will display the red border on the input element using CSS. It then uses jQuery's after() function to insert a division element into the DOM, which will display the specified error message under the current input field, shown as follows: function validateRequired(value) {    if (value == "") return false;    return true; } function addErrorData(element, error) {    element.parent().addClass("error");    element.after("<div class='error-data'>" + error + "</div>"); } There's more... This structure allows us to easily add additional validation to our web form. Because the JavaScript is iterating over all of the input fields in the form, we can easily check for additional classes, such as date, number, and credit-card, and call extra functions to provide the alternative validation. The other recipes in this article will look in detail at the additional validation types and add these functions to the current validation.js file. See also Implementing input character restrictions Adding number validation When collecting data from a user, there are many situations when you will want to only allow numbers in a form field. Examples of this could be telephone numbers, PIN codes, or ZIP codes, to name a few. This recipe will show you how to validate the telephone number field within the form we created in the previous recipe. Getting ready Ensure that you have completed the previous recipe and have the same files available. Open validation.js in your text editor or IDE of choice. How to do it… Add number validation to the form you created in the previous recipe by performing the following steps: Update validation.js to be as follows, adding the valdiateNumber() function with an additional hasClass('number') check inside the for loop: $(function(){    $('.submit-btn').click(function(event){       //Prevent form submission       event.preventDefault();       var inputs = $('input');       var isError = false;       //Remove old errors       $('.input-frame').removeClass('error');       $('.error-data').remove();       for (var i = 0; i < inputs.length; i++) {          var input = inputs[i];            if ($(input).hasClass('required') &&             !validateRequired($(input).val())) {                addErrorData($(input), "This is a required                   field");                isError = true;             } /* Code for this recipe */          if ($(input).hasClass('number') &&             !validateNumber($(input).val())) {                addErrorData($(input), "This field can only                   contain numbers");                isError = true;             } /* --- */         }       if (isError === false) {          //No errors, submit the form          $('#webForm').submit();       }    }); });   function validateRequired(value) {    if (value == "") return false;    return true; }   /* Code for this recipe */ function validateNumber(value) {    if (value != "") {       return !isNaN(parseInt(value, 10)) && isFinite(value);       //isFinite, in case letter is on the end    }    return true; } /* --- */ function addErrorData(element, error) {    element.parent().addClass("error");    element.after("<div class='error-data'>" + error + "</div>"); } Open index.html in a web browser, input something other than a valid integer into the telephone number field, and click on the Submit button. You will be presented with a form similar to the following screenshot: How it works… First, we add an additional if statement to the main for loop of validation.js to check to see if the current input field has the class number, as follows: if ($(input).hasClass('number') &&    !validateNumber($(input).val())) {    addErrorData($(input), "This field can only contain numbers");    isError = true; } If it does, this input value needs to be validated for a number. To do this, we call the validateNumber function inline within the if statement: function validateNumber(value) {    if (value != "") {       return !isNaN(parseInt(value, 10)) && isFinite(value);       //isFinite, in case letter is on the end    }    return true; } This function takes the value of the current input field as an argument. It first checks to see if the value is blank. If it is, we do not need to perform any validation here because this is handled by the validateRequired() function from the first recipe of this article. If there is a value to validate, a range of actions are performed on the return statement. First, the value is parsed as an integer and passed to the isNaN() function. The JavaScript isNaN() function simply checks to see if the provided value is NaN (Not a Number). In JavaScript, if you try to parse a value as an integer and that value is not actually an integer, you will get the NaN value. The first part of the return statement is to ensure that the provided value is a valid integer. However, this does not prevent the user from inputting invalid characters. If the user was to input 12345ABCD, the parseInt function would ignore ABCD and just parse 12345, and therefore the validation would pass. To prevent this situation, we also use the isFinite function, which returns false if provided with 12345ABCD. Adding credit card number validation Number validation could be enough validation for a credit card number; however, using regular expressions, it is possible to check for number combinations to match credit card numbers from Visa, MasterCard, American Express, and more. Getting ready Make sure that you have validation.js from the previous two recipes in this article open and ready for modification. How to do it… Use jQuery to provide form input validation for credit card numbers by performing the following step-by-step instructions: Update validation.js to add the credit card validation function and the additional class check on the input fields: $(function(){    $('.submit-btn').click(function(event){       //Prevent form submission       event.preventDefault();       var inputs = $('input');       var isError = false;       for (var i = 0; i < inputs.length; i++) {   // -- JavaScript from previous two recipes hidden                       if ($(input).hasClass('credit-card') &&             !validateCreditCard($(input).val())) {             addErrorData($(input), "Invalid credit card                number");             isError = true;          }         } // -- JavaScript from previous two recipes hidden    }); });   // -- JavaScript from previous two recipes hidden   function validateCreditCard(value) {    if (value != "") {       return /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9]) [0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}| (?:2131|1800|35d{3})d{11})$/.test(value);    }    return true; } // -- JavaScript from previous two recipes hidden } Open index.html and input an invalid credit card number. You will be presented with the following error information in the form: How it works… To add credit card validation, as with the previous two recipes, we added an additional check in the main for loop to look for the credit-card class on the input elements, as follows: if ($(input).hasClass('credit-card') &&    !validateCreditCard($(input).val())) {    addErrorData($(input), "Invalid credit card number");    isError = true; } The validateCreditCard function is also added, which uses a regular expression to validate the input value, as follows: function validateCreditCard(value) {    if (value != "") {       return /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-          9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-          9]{13}|3(?:0[0-5]|[68][0-9])[0-          9]{11}|(?:2131|1800|35d{3})d{11})$/.test(value);    }    return true; } The first part of this function determines if the provided value is blank. If it isn't, the function will perform further validation; otherwise, it will return true. Most credit card numbers start with a prefix, which allows us to add additional validation to the inputted value on top of numeric validation. The regular expression used in this function will allow for Visa, MasterCard, American Express, Diners Club, Discover, and JCB cards. See also Adding number validation
Read more
  • 0
  • 0
  • 2025

article-image-understanding-process-variation-control-charts
Packt
19 Feb 2014
10 min read
Save for later

Understanding Process Variation with Control Charts

Packt
19 Feb 2014
10 min read
(For more resources related to this topic, see here.) Xbar-R charts and applying stages to a control chart As with all control charts, the Xbar-R charts are used to monitor process stability. Apart from generating the basic control chart, we will look at how we can control the output with a few options within the dialog boxes. Xbar-R stands for means and ranges; we use the means chart to estimate the population mean of a process and the range chart to observe how the population variation changes. For more information on control charts, see Understanding Statistical Process Control by Donald J. Wheeler and David S. Chambers. As an example, we will study the fill volumes of syringes. Five syringes are sampled from the process at hourly intervals; these are used to represent the mean and variation of that process over time. We will plot the means and ranges of the fill volumes across 50 subgroups. The data also includes a process change. This will be displayed on the chart by dividing the data into two stages. The charts for subgrouped data can use a worksheet set up in two formats. Here the data is recorded such that each row represents a subgroup. The columns are the sample points. The Xbar-S chart will use data in the other format where all the results are recorded in one column. The following screenshot shows the data with subgroups across the rows on the left, and the same data with subgroups stacked on the right: How to do it… The following steps will create an Xbar-R chart staged by the Adjustment column with all eight of the tests for special causes: Use the Open Worksheet command from the File menu to open the Volume.mtw worksheet. Navigate to Stat | Control Charts | Variables charts for subgroups. Then click on Xbar-R…. Change the drop down at the top of the dialog to Observations for a subgroup are in one row of columns:. Enter the columns Measure1 to Measure5 into the dialog box by highlighting all the measure columns in the left selection box and clicking on Select. Click on Xbar-R Options and navigate to the tab for Tests. Select all the tests for special causes. Select the Stages tab. Enter Adjustment in the Define Stages section. Click on OK in each dialog box. How it works… The R or range chart displays the variation over time in the data by plotting the range of measurements in a subgroup. The Xbar chart plots the means of the subgroups. The choice of layout of the worksheet is picked from the drop-down box in the main dialog box. The All observations for a chart are in one column: field is used for data stacked into columns. Means of subgroups and ranges are found from subgroups indicated in the worksheet. The Observations for a subgroup are in one row of columns: field will find means and ranges from the worksheet rows. The Xbar-S chart example shows us how to use the dialog box when the data is in a single column. The dialog boxes for both Xbar-R and Xbar-S work the same way. Tests for special causes are used to check the data for nonrandom events. The Xbar-R chart options give us control over the tests that will be used. The values of the tests can be changed from these options as well. The options from the Tools menu of Minitab can be used to set the default values and tests to use in any control chart. By using the option under Stages, we are able to recalculate the means and standard deviations for the pre and post change groups in the worksheet. Stages can be used to recalculate the control chart parameters on each change in a column or on specific values. A date column can be used to define stages by entering the date at which a stage should be started. There's more… Xbar-R charts are also available under the Assistant menu. The default display option for a staged control chart is to show only the mean and control limits for the final stage. Should we want to see the values for all stages, we would use the Xbar-R Options and Display tab. To place these values on the chart for all stages, check the Display control limit / center line labels for all stages box. See Xbar-S charts for a description of all the tabs within the Control Charts options. Using an Xbar-S chart Xbar-S charts are similar in use to Xbar-R. The main difference is that the variation chart uses standard deviation from the subgroups instead of the range. The choice between using Xbar-R or Xbar-S is usually made based on the number of samples in each subgroup. With smaller subgroups, the standard deviation estimated from these can be inflated. Typically, with less than nine results per subgroup, we see them inflating the standard deviation, which increases the width of the control limits on the charts. Automotive Industry Action Group (AIAG) suggests using the Xbar-R, which is greater than or equal to nine times the Xbar-S. Now, we will apply an Xbar-S chart to a slightly different scenario. Japan sits above several active fault lines. Because of this, minor earthquakes are felt in the region quite regularly. There may be several minor seismic events on any given day. For this example, we are going to use seismic data from the Advanced National Seismic System. All seismic events from January 1, 2013 to July 12, 2013 from the region that covers latitudes 31.128 to 45.275 and longitudes 129.799 to 145.269 are included in this dataset. This corresponds to an area that roughly encompasses Japan. The dataset is provided for us already but we could gather more up-to-date results from the following link: http://earthquake.usgs.gov/monitoring/anss/ To search the catalog yourself, use the following link: http://www.ncedc.org/anss/catalog-search.html We will look at seismic events by week that create Xbar-S charts of magnitude and depth. In the initial steps, we will use the date to generate a column that identifies the week of the year. This column is then used as the subgroup identifier. How to do it… The following steps will create an Xbar-S chart for the depth and magnitude of earthquakes. This will display the mean, and standard deviation of the events by week: Use the Open Worksheet command from the File menu to open the earthquake.mtw file. Go to the Data menu, click on Extract from Date/Time, and then click on To Text. Enter Date in the Extract from Date/time column: section. Type Week in the Store text column in: section. Check the selection for Week and click on OK to create the new column. Navigate to Stat | Control Charts | Variable charts for Subgroups and click on Xbar-S. Enter Depth and Mag into the dialog box as shown in the following screenshot and Week into the Subgroup sizes: field. Click on the Scale button, and select the option for Stamp. Enter Date in the Stamp columns section. Click on OK. Click on Xbar-S Options and then navigate to the Tests tab. Select all tests for special causes. Click on OK in each dialog box. How it works… Steps 1 to 4 build the Week column that we use as the subgroup. The extracts from the date/time options are fantastic for quickly generating columns based on dates. Days of the week, week of the year, month, or even minutes or seconds can all be separated from the date. Multiple columns can be entered into the control chart dialog box just as we have done here. Each column is then used to create a new Xbar-S chart. This lets us quickly create charts for several dimensions that are recorded at the same time. The use of the week column as the subgroup size will generate the control chart with mean depth and magnitude for each week. The scale options within control charts are used to change the display on the chart scales. By default, the x axis displays the subgroup number; changing this to display the date can be more informative when identifying the results that are out of control. Options to add axes, tick marks, gridlines, and additional reference lines are also available. We can also edit the axis of the chart after we have generated it by double-clicking on the x axis. The Xbar-S options are similar for all control charts; the tabs within Options give us control over a number of items for the chart. The following list shows us the tabs and the options found within each tab: Parameters: This sets the historical means and standard deviations; if using multiple columns, enter the first column mean, leave a space, and enter the second column mean Estimate: This allows us to specify subgroups to include or exclude in the calculations and change the method of estimating sigma Limits: This can be used to change where sigma limits are displayed or place on the control limits Tests: This allows us to choose the tests for special causes of the data and change the default values. The Using I-MR chart recipe details the options for the Tests tab. Stages: This allows the chart to be subdivided and will recalculate center lines and control limits for each stage Box Cox: This can be used to transform the data, if necessary Display: This has settings to choose how much of the chart to display. We can limit the chart to show only the last section of the data or split a larger dataset into separate segments. There is also an option to display the control limits and center lines for all stages of a chart in this option. Storage: This can be used to store parameters of the chart, such as means, standard deviations, plotted values, and test results There's more… The control limits for the graphs that are produced vary as the subgroup sizes are not constant; this is because the number of earthquakes varies each week. In most practical applications, we may expect to collect the same number of samples or items in a subgroup and hence have flat control limits. If we wanted to see the number of earthquakes in each week, we could use Tally from inside the Tables menu. This will display a result of counts per week. We could also store this tally back into the worksheet. The result of this tally could be used with a c-chart to display a count of earthquake events per week. If we wanted to import the data directly from the Advanced National Seismic System, then the following steps will obtain the data and prepare the worksheet for us: Follow the link to the ANSS catalog search at http://www.ncedc.org/anss/catalog-search.html. Enter 2013/01/01 in the Start date, time: field. Enter 2013/06/12 in the End date, time: field. Enter 3 in the Min magnitude: field. Enter 31.128 in the Min latitude field and 45.275 in the Max latitude field. Enter 129.799 in the Min longitude field and 145.269 in the Max longitude filed. Copy the data from the search results, excluding the headers, and paste it into a Minitab worksheet. Change the names of the columns to C1 Date, C2 Time, C3 Lat, C4 Long, C5 Depth, C6 Mag. The other columns, C7 to C13, can then be deleted. The Date column will have copied itself into Minitab as text; to convert this back to a date, navigate to Data | Change Data Type | Text to Date/Time. Enter Date in both the Change text columns: and Store date/time columns in: sections. In the Format of text columns: section, enter yyyy/mm/dd. Click on OK. To extract the week from the Date column, navigate to Data | Date/Time | Extract to Text. Enter 'Date' in the Extract from date/time column: section. Enter 'Week' in the Store text column in: field. Check the box for Week and click on OK.
Read more
  • 0
  • 0
  • 13801
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
article-image-article-beating-back-the-horde
Packt
18 Feb 2014
9 min read
Save for later

Beating Back the Horde

Packt
18 Feb 2014
9 min read
(For more resources related to this topic, see here.) What kind of game will we be making? We are going to make one of the classics, a Tower Defense game. (http://old.casualcollective.com/#games/FETD2.) Our game won't be as polished as the example, but it gives you a solid base to work with and develop further. Mission briefing We will use the cloning tools again to create hordes of enemies to fight. We will also use these tools to create cannons and cannonballs. It's easy to re-use assets from other projects in Scratch 2.0. The new Backpack feature allows you to easily exchange assets between projects. How this works will be demonstrated in this article. Why is it awesome? This example is a lot more involved than the previous one. The final result will be a much more finished game which still leaves plenty of room to adapt and continue building on. While making this game, you will learn how to draw a background and how to make and use different costumes for a single sprite. We will make full use of the cloning technique to create many copies of similar objects. We will also use more variables and another type of variable called List to keep track of all the things going on in the game. You will also learn about a simple way to create movement patterns for computer-controlled objects. Your Hotshot objectives We will divide the articlein to the following tasks based primarily on the game sprites and their behavior: Creating a background Creating enemies Creating cannons Fighting back Mission checklist Click on the Create button to start a new project. Remove the Scratch cat by right-clicking on it and selecting delete. Creating a background Because the placement and the route to walk is important in this kind of game, we will start with the creation of the background. To the left of the Sprites window, you will see a separate picture. Underneath is the word Stage and another word, the name of the picture that's being shown. This picture is white when you start a new project because nothing is drawn on it yet. The following is an example with our background image already drawn in:   Engage thrusters We will draw a grassy field with a winding road running through it when looked at from the top, by going through the following steps: Click on the white image. Next click on the Backdrops tab to get to the drawing tool. This is similar to the Costumes tab for sprites, but the size of the drawing canvas is clearly limited to the size of the stage. Choose a green color and draw a rectangle from the top-left to the bottom-right of the canvas. Then click on the Fill tool and fill the rectangle with the same color to create a grassy background. On top of the field, we will draw a path which the enemies will use to walk on. Switch the Fill tool to a brown color. Draw rectangles to form a curving path as shown in the following screenshot. The background is now done. Let's save our work before moving on. Objective complete – mini debriefing The background is just a pretty picture with no direct functionality in the game. It tells the player what to expect in the game. It will be logical that enemies are going to follow the road that was drawn. We will also use this road as a guideline when scripting the movement path of the enemies. The open spaces between the path make it obvious where the player could place the cannons. Creating enemies We will quickly create an enemy sprite to make use of the background we just drew. These enemies will follow the path drawn in the background. Because the background image is fixed, we can determine exactly where the turns are. We will use a simple movement script that sends the enemies along the path from one end of the stage to the other. Like with the targets in the previous project, we will use a base object that creates clones of itself that will actually show up on stage. Prepare for lift off We will first draw an enemy sprite. Let's keep this simple for now. We can always add to the visual design later. The steps to draw it are as follows: Click on the paintbrush icon to create a new sprite. Choose a red color and draw a circle. Make sure the circle is of proper size compared to the path in the background. Fill the circle with the same color. We name the new sprite enemy1. That's all for now! We will add more to the appearance of the enemy sprite later. The enemy sprite appears as a red circle large enough to fit the path.   Engage thrusters Let's make it functional first with a script. We will place the base enemy sprite at the start of the path and have it create clones. Then we will program the clones to follow the path as shown in the following steps: The script will start when the when <green flag> clicked block is clicked. Place the sprite at the start of the path with a go to x: -240 y: 0 block. Wait for three seconds by using the wait ... secs block to allow the player to get ready for the game. Add a repeat … block. Fill in 5 to create five clones per wave. Insert a create clone of <myself> block. Then wait for two seconds by using the wait ... secs block so the enemy clones won't be spawned too quickly. Before we start moving the clones, we have to determine what path they will follow. The key information here are the points where the path bends in a new direction. We can move the enemies from one bend to another in an orderly manner. Be warned that it may take some time to complete this step. You will probably need to test and change the numbers you are going to use to move the sprites correctly. If you don't have the time to figure it all out, you can check and copy the image with the script blocks at the end of this step to get a quick result. Do you remember how the xy-coordinate system of the stage worked from the last project? Get a piece of paper (or you can use the text editor on your computer) and get ready to take some notes. Examine the background you drew on the stage, and write down all the xy-coordinates that the path follows in order. These points will serve as waypoints. Look at the screenshot to see the coordinates that I came up with. But remember that the numbers for your game could be different if you drew the path differently. To move the enemy sprites, we will use the glide … secs to x: … y: ... blocks. With this block, a sprite will move fluidly to the given point in the given amount of time as shown in the following steps: Start the clone script with a when I start as a clone block. Beyond the starting point, there will be seven points to move to. So stack together seven glide … blocks. In the coordinate slots, fill in the coordinates you just wrote down in the correct order. Double-check this since filling in a wrong number will cause the enemies to leave the path. Deciding how long a sprite should take to complete a segment depends on the length of that segment. This requires a bit of guesswork since we didn't use an exact drawing method. Your most accurate information is the differences between the coordinates you used from point to point. Between the starting point (-240,0) and the first waypoint (-190,0), the enemy sprite will have moved 50 pixels. Let's say we want to move 10 pixels per second. That means the sprite should move to it's new position in 5 seconds. The difference between the first (-190,0) and the second (-190,125) waypoint is 125. So according to the same formula, the sprite should move along this segment of the path in 12.5 seconds. Continue calculating the glide speeds like this for the other blocks. These are the numbers I came up with : 5, 12.5, 17, 26.5, 15.5, 14, and 10.5, but remember that yours may be different You can use the formula new position – old position / 10 = result to figure out the numbers you need to use. To finish off, delete the clone when it reaches the end of the path. Test your script and see the enemies moving along the path. You might notice they are very slow and bunched together because they don't travel enough distances between spawns. Let's fix that by adding a variable speed multiplier. Not only can we easily tweak the speed of the sprites but we can also use this later to have other enemy sprites move at different speeds, as shown in the following steps: Create a variable and make sure it is for this sprite only. Name it multiplier_R. The R stands for red, the color of this enemy. Place set <multiplier_R> to … at the start of the <green flag> script. Fill in 0.3 as a number for the basic enemy. Take the speed numbers you filled in previously and multiply them with the multiplier. Use a ...*... operator block. Place the multiplier_R variable in one slot. Type the correct number in the other slot. Place the calculation in the glide block instead of the fixed number.The completed scripts for enemy movement will look as follows: Objective complete – mini debriefing Test the game again and see how the enemies move much faster, about three times as fast if you have used 0.3 for the multiplier. You can play with the variable number a bit to see the effect. If you decrease the multiplier, the enemies will move even faster. If you increase the number, the enemies will become slower.
Read more
  • 0
  • 0
  • 2900

article-image-query-performance-tuning
Packt
18 Feb 2014
5 min read
Save for later

Query Performance Tuning

Packt
18 Feb 2014
5 min read
(For more resources related to this topic, see here.) Understanding how Analysis Services processes queries We need to understand what happens inside Analysis Services when a query is run. The two major parts of the Analysis Services engine are: The Formula Engine: This part processes MDX queries, works out what data is needed to answer them, requests that data from the Storage Engine, and then performs all calculations needed for the query. The Storage Engine: This part handles all the reading and writing of data, for example, during cube processing and fetching all the data that the Formula Engine requests when a query is run. When you run an MDX query, then, that query goes first to the Formula Engine, then to the Storage Engine, and then back to the Formula Engine before the results are returned back to you. Performance tuning methodology When tuning performance there are certain steps you should follow to allow you to measure the effect of any changes you make to your cube, its calculations or the query you're running: Always test your queries in an environment that is identical to your production environment, wherever possible. Otherwise, ensure that the size of the cube and the server hardware you're running on is at least comparable, and running the same build of Analysis Services. Make sure that no-one else has access to the server you're running your tests on. You won't get reliable results if someone else starts running queries at the same time as you. Make sure that the queries you're testing with are equivalent to the ones that your users want to have tuned. As we'll see, you can use Profiler to capture the exact queries your users are running against the cube. Whenever you test a query, run it twice; first on a cold cache, and then on a warm cache. Make sure you keep a note of the time each query takes to run and what you changed on the cube or in the query for that run. Clearing the cache is a very important step—queries that run for a long time on a cold cache may be instant on a warm cache. When you run a query against Analysis Services, some or all of the results of that query (and possibly other data in the cube, not required for the query) will be held in cache so that the next time a query is run that requests the same data it can be answered from cache much more quickly. To clear the cache of an Analysis Services database, you need to execute a ClearCache XMLA command. To do this in SQL Management Studio, open up a new XMLA query window and enter the following: <Batch > <ClearCache> <Object> <DatabaseID>Adventure Works DW 2012</DatabaseID> </Object> </ClearCache> </Batch> Remember that the ID of a database may not be the same as its name—you can check this by right-clicking on a database in the SQL Management Studio Object Explorer and selecting Properties. Alternatives to this method also exist: the MDX Studio tool allows you to clear the cache with a menu option, and the Analysis Services Stored Procedure Project (http://tinyurl.com/asstoredproc) contains code that allows you to clear the Analysis Services cache and the Windows File System cache directly from MDX. Clearing the Windows File System cache is interesting because it allows you to compare the performance of the cube on a warm and cold file system cache as well as a warm and cold Analysis Services cache. When the Analysis Services cache is cold or can't be used for some reason, a warm filesystem cache can still have a positive impact on query performance. After the cache has been cleared, before Analysis Services can answer a query it needs to recreate the calculated members, named sets, and other objects defined in a cube's MDX Script. If you have any reasonably complex named set expressions that need to be evaluated, you'll see some activity in Profiler relating to these sets being built and it's important to be able to distinguish between this and activity that's related to the queries you're actually running. All MDX Script related activity occurs between Execute MDX Script Begin and Execute MDX Script End events; these are fired after the Query Begin event but before the Query Cube Begin event for the query run after the cache has been cleared and there is one pair of Begin/End events for each command on the MDX Script. When looking at a Profiler trace you should either ignore everything between the first Execute MDX Script Begin event and the last Execute MDX Script End event or run a query that returns no data at all to trigger the evaluation of the MDX Script, for example: SELECT {} ON 0 FROM [Adventure Works] Designing for performance Many of the recommendations for designing cubes will improve query performance, and in fact the performance of a query is intimately linked to the design of the cube it's running against. For example, dimension design, especially optimizing attribute relationships, can have significant effect on the performance of all queries—at least as much as any of the optimizations. As a result, we recommend that if you've got a poorly performing query the first thing you should do is review the design of your cube to see if there is anything you could do differently. There may well be some kind of trade-off needed between usability, manageability, time-to-develop, overall 'elegance' of the design and query performance, but since query performance is usually the most important consideration for your users then it will take precedence. To put it bluntly, if the queries your users want to run don't run fast, your users will not want to use the cube at all!
Read more
  • 0
  • 0
  • 2461

article-image-understanding-python-regex-engine
Packt
18 Feb 2014
8 min read
Save for later

Understanding the Python regex engine

Packt
18 Feb 2014
8 min read
(For more resources related to this topic, see here.) These are the most common characteristics of the algorithm: It supports "lazy quantifiers" such as *?, +?, and ??. It matches the first coincidence, even though there are longer ones in the string. >>>re.search("engineer | engineering", "engineering").group()'engineer' This also means that order is important. The algorithm tracks only one transition at one step, which means that the engine checks one character at a time. Backreferences and capturing parentheses are supported. Backtracking is the ability to remember the last successful position so that it can go back and retry if needed In the worst case, complexity is exponential O(Cn). We'll see this later in Backtracking. Backtracking Backtracking allows going back and repeating the different paths of the regular expression. It does so by remembering the last successful position, this applies to alternation and quantifiers, let’s see an example: Backtracking As we see in the image the regex engine tries to match one character at a time until it fails and starts again with the following path it can retry. The regex used in the image is the perfect example of the importance of how the regex is built, in this case the expression can be rebuild as spa (in | niard), so that the regex engine doesn’t have to go back up to the start of the string in order to retry the second alternative. This leads us to what is called catastrophic backtracking a well-known problem with backtracking that can give you several problems, ranging from slow regex to a crash with a stack overflow. In the previous example, you can see that the behavior grows not only with the input but also with the different paths in the regex, that’s why the algorithm is exponential O(Cn), with this in mind it’s easy to understand why we can end up with a stack overflow. The problem arises when the regex fails to match the String. Let’s benchmark a regex with technique we’ve seen previously, so we can understand the problem better. First let’s try a simple regex: >>> def catastrophic(n): print "Testing with %d characters" %n pat = re.compile('(a+)+c') text = "%s" %('a' * n) pat.search(text) As you can see the text we’re trying to match it’s always going to fail due to there is no c at the end. Let’s test it with different inputs. >>> for n in range(20, 30): test(catastrophic, n) Testing with 20 characters The function catastrophic lasted: 0.130457 Testing with 21 characters The function catastrophic lasted: 0.245125 …… The function catastrophic lasted: 14.828221 Testing with 28 characters The function catastrophic lasted: 29.830929 Testing with 29 characters The function catastrophic lasted: 61.110949 The behavior of this regex looks like quadratic. But why? what’s happening here? The problem is that (a+) starts greedy, so it tries to get as many a’s as possible and after that it fails to match the (a+)+, that is, it backtracks to the second a, and continue consuming a’s until it fails to match c, when it tries again (backtrack) the whole process starting with the second a. Let’s see another example, in this case with an exponential behavior: >>> def catastrophic(n): print "Testing with %d characters" %n pat = re.compile('(x+)+(b+)+c') text = 'x' * n text += 'b' * n pat.search(text) >>> for n in range(12, 18): test(catastrophic, n) Testing with 12 characters The function catastrophic lasted: 1.035162 Testing with 13 characters The function catastrophic lasted: 4.084714 Testing with 14 characters The function catastrophic lasted: 16.319145 Testing with 15 characters The function catastrophic lasted: 65.855182 Testing with 16 characters The function catastrophic lasted: 276.941307 As you can see the behavior is exponential, which can lead to a catastrophic scenarios. And finally let’s see what happen when regex has a match. >>> def non_catastrophic(n): print "Testing with %d characters" %n pat = re.compile('(x+)+(b+)+c') text = 'x' * n text += 'b' * n text += 'c' pat.search(text) >>> for n in range(12, 18): test(non_catastrophic, n) Testing with 10 characters The function catastrophic lasted: 0.000029 …… Testing with 19 characters The function catastrophic lasted: 0.000012 Optimization recommendations In the following sections we will find a number of recommendations that could be used to apply to improve regular expressions. The best tool will always be the common sense, and even following these recommendations common sense will need to be used. It has to be understood when the recommendation is applicable and when not. For instance the recommendation don’t be greedy cannot be used in the 100% of the cases. Reuse compiled patterns To use a regular expression we have to convert it from the string representation to a compiled form as RegexObject. This compilation takes some time. If instead of using the compile function we are using the rest of the methods to avoid the creation of the RegexObject, we should understand that the compilation is executed anyway and a number of compiled RegexObject are cached automatically. However, when we are compiling that cache won’t back us. Every single compile execution will consume an amount of time that perhaps could be negligible for a single execution, but it’s definitely relevant if many executions are performed. Extract common parts in alternation Alternation is always a performance risk point in regular expressions. When using them in Python, and therefore in a sort of NFA implementation, we should extract any common part outside of the alternation. For instance if we have /(Hello⇢World|Hello⇢Continent|Hello⇢Country,)/, we could easily extract Hello⇢ having the following expression /Hello⇢(World|Continent|Country)/. This will make our engine to just check Hello⇢ once, and not going back and recheck for each possibility. Shortcut the alternation Ordering in alternation is relevant; each of the different options present in the alternation will be checked one by one, from the left to the right. This can be used in favor of performance. If we place the more likely options at the beginning of the alternation, more checks will mark the alternation as matched sooner. For instance, we know that the more common colors of cars are white and black. If we are writing a regular expression accepting some colors, we should put white and black first, as those are the more likely to appear. This is: /(white|black|red|blue|green)/. For the rest of the elements, if they have the very same odds of appearing, if could be favorable to put the shortest ones before the longer ones. Use non capturing groups when appropriate Capturing groups will consume some time per each group defined in an expression. This time is not very important but is still relevant if we are executing a regular expression many times. Sometimes we are using groups but we might not be interested in the result. For instance when using alternation. If that is the case we can save some execution time to the engine by marking that group as non-capturing. This is: (?:person|company).. Be specific When the patterns we define are very specific, the engine can help us performing quick integrity checks before the actual pattern matching is executed. For instance, if we pass to the engine the expression /w{15}/ to be matched against the text hello, the engine could decide to check if the input string is actually at least 15 characters long instead of matching the expression. Don’t be greedy The quantifiers and we learnt the difference between greedy and reluctant quantifiers. We also found that the quantifiers are greedy by default. What does this mean to performance? It means that the engine will always try to catch as many characters as possible and then reducing the scope step by step until it's done. This could potentially make the regular expression slow if the match is typically short. Keep in mind, however, this is only applicable if the match is usually short. Summary In this article, we understood how to see the engine working behind the scenes. We learned some theory of the engine design and how it's easy to fall in a common pitfall—the catastrophic backtracking. Finally, we reviewed different general recommendations to improve the performance of our regular expressions. Resources for Article: Further resources on this subject: Python LDAP Applications: Part 1 - Installing and Configuring the Python-LDAP Library and Binding to an LDAP Directory [Article] Python Data Persistence using MySQL Part III: Building Python Data Structures Upon the Underlying Database Data [Article] Python Testing: Installing the Robot Framework [Article]
Read more
  • 0
  • 0
  • 18289

Packt
18 Feb 2014
5 min read
Save for later

XenMobile™ Solutions Bundle

Packt
18 Feb 2014
5 min read
(For more resources related to this topic, see here.) Introduction to XenMobile™ Solution The XenMobile Solution allows to manage mobile devices, the applications inside these devices, and the data in these applications. This enables users to access their apps, which may be mobile-, SaaS-, web-, or Windows-based from a universal app store. It provides administrators with a granular level control over the devices and manages them accordingly by implementing multiple security policies. It provides admins with the options to securely deliver productivity apps such as e-mails or intranet websites to end users. Also, it permits options to securely wrap applications before deployment without compromising application security and productivity. With more and more enterprises welcoming the Bring Your Own Device (BYOD) concept, a scenario where the employees are allowed to bring their own devices at work, XenMobile components allow admins to securely manage these devices without hampering the end-user device experience. In this section, we will introduce our readers to the following XenMobile Solution components and their role in the XenMobile Solution: NetScaler Gateway: This is a secure, access-control management solution allowing users to securely access internal resources. It also provides administrators with granular control policies to manage how devices will function once they are connected to internal resources. These internal resources can be an intranet portal, corporate e-mails, or in-house apps. XenMobile Device Manager: The XenMobile Device Manager allows administrators to manage devices, users, enroll devices, deploy applications and files, and set policies. XenMobile Device Manager also has the option to integrate Active Directory and detailed reporting features. App Controller: App Controller allows users to access the Web, SaaS-based applications, iOS and Android apps, and integrate ShareFile apps on their device from anywhere on an internal network. When integrated with NetScaler Gateway, the XenMobile Solution provides the users with access to these resources from an external network. Administrators have granular security policies to implement on devices connecting either from an internal or external network. MDX Toolkit: The MDX toolkit is a software that must be installed on Mac OS to wrap iOS or Android-based apps and ensures the apps are secure and compliant when installed on end-user devices. Administrators can also define a set of default policies while wrapping the app to limit how it works. Worx Apps: These are client-based apps that communicate with App Controller and allow users to access internal resources anywhere. They contain Worx Home for user enrollment, Worx Web to access web-based resources, and WorxMail for accessing corporate e-mails. ShareFile: This is a cloud-based, file-sharing service that enables users to securely share documents from different apps or access shared resources on a desktop from mobile devices. ShareFile data can be accessed as an app, web resource, or through integration with Outlook as an add-in. The XenMobile Solution with its components creates a highly secure and enterprise-compliant solution. The following diagram is a detailed network diagram for the XenMobile Solution provided by Citrix: © Citrix Systems, Inc. All Rights Reserved. XenMobile™ Solution features XenMobile contains some of the most sought-after features when compared to its competitors. In this section, we will list some of the features available in XenMobile, as follows: Configuring, provisioning, and managing mobile devices on Windows Mobile, Symbian, iOS, and Android platforms Mobile Content Management using SharePoint and network-driven integration Secure mobile web browser App-specific micro VPN Integrating Windows apps Unified app store Secure document sharing, syncing, and editing The deployment flowchart While implementing a Mobile Device Management (MDM) solution, it's very important to have a deployment pattern. This helps in understanding which components are required or are not suitable as per the environment needs. This brings in the requirement to have a detailed flowchart of the Solution deployment. The following diagram shows the Citrix-recommended best practice's deployment flowchart for the XenMobile Solution: © Citrix Systems, Inc. All Rights Reserved. Explanation In this section, we will break down the deployment flowchart to understand the component selection phase. The flowchart is based upon our requirements and will vary from one scenario to other. Phase 1 The essentials for phase 1 are as follows: Requirement: Do we want an MDM solution to manage the enrolled devices? Decision: If an MDM solution is required, then we proceed with the XenMobile Device Manager installation; alternatively, we can move to the next requirement Phase 2 The essentials for phase 2 are as follows: Requirement: Is application and content management required? Decision: If application and content integration is required then we can deploy the XenMobile Solutions Bundle; alternatively, move to the next requirement Phase 3 The essentials for phase 3 are as follows: Requirement: Will there be users accessing the integrated applications and data from the public Internet? Decision: If Yes, then move ahead with the NetScaler Gateway deployment; alternatively, move to the next requirement Phase 4 The essentials for phase 4 are as follows: Requirement: Is access to XenApp or XenDesktop required? Decision: If Yes, then connect using StoreFront Summary This article provided a brief overview of XenMobile Solution and each of its components. We also covered many of its features that make it unique and the Network architecture of the solution. Additionally, we have addressed the best practice deployment flowchart of the XenMobile Solution as recommended by Citrix. Resources for Article: Further resources on this subject: So, what is XenMobile? [Article] Gesture [Article] Creating Quizzes [Article]
Read more
  • 0
  • 0
  • 1966
article-image-processing-tweets-apache-hive
Packt
18 Feb 2014
6 min read
Save for later

Processing Tweets with Apache Hive

Packt
18 Feb 2014
6 min read
(For more resources related to this topic, see here.) Extracting hashtags In this part and the following one, we'll see how to extract data efficiently from tweets such as hashtags and emoticons. We need to do it because we want to be able to know what the most discussed topics are, and also get the mood across the tweets. And then, we'll want to join that information to get people's sentiments. We'll start with hashtags; to do so, we need to do the following: Create a new hashtag table. Use a function that will extract the hashtags from the tweet string. Feed the hashtag table with the result of the extracted function. So, I have some bad news and good news: Bad news: Hive provides a lot of built-in user-defined functions, but unfortunately, it does not provide any function based on a regex pattern; we need to use a custom user-defined function to do that. This is such a bad news as you will learn how to do it. Good news: Hive provides an extremely efficient way to create a Hive table from an array. We'll then use the lateral view and the Explode Hive UDF to do that. The following is the Hive-processing workflow that we are going to apply to our tweets: Hive-processing workflow The preceding diagram describes the workflow to be followed to extract the hashtags. The steps are basically as follows: Receive the tweets. Detect all the hashtags using the custom Hive user-defined function. Obtain an array of hashtags. Explode it and obtain a lateral view to feed our hashtags table. This kind of processing is really useful if we want to have a feeling of what the top tweeted topics are, and is most of the time represented by a word cloud chart like the one shown in the following diagram: Topic word cloud sample Let's do this by creating a new CH04_01_HIVE_PROCESSING_HASH_TAGS job under a new Chapter4 folder. This job will contain six components: One to connect to Hive; you can easily copy and paste the connection component from the CH03_03_HIVE_FORMAT_DATA job One tHiveRow to add the custom Hive UDF to the Hive runtime classpath. The following would be the steps to create a new job: First, we will add the following context variable to our PacktContext group: Name Value custom_udf_jar PATH_TO_THE_JAR For Example: /Users/bahaaldine/here/is/the/jar/extractHashTags.jar This new context variable is just the path to the Hive UDF JAR file provided in the source file Now, we can add the "add jar "+context.custom_udf_jar Hive query in our tHiveRow component to load the JAR file in the classpath when the job is being run. We use the add jar query so that Hive will load all the classes in the JAR file when the job starts, as shown in the following screenshot: Adding a Custom UDF JAR to Hive classpath. After the JAR file is loaded by the previous component, we need tHiveRow to register the custom UDF into the available UDF catalog. The custom UDF is a Java class with a bunch of methods that can be invoked from Hive-QL code. The custom UDF that we need is located in the org.talend.demo package of the JAR file and is named ExtractPattern. So we will simply add the "create temporary function extract_patterns as 'org.talend.demo.ExtractPattern'" configuration to the component. We use the create temporary function query to create a new extract_patterns function in Hive UDF catalog and give the implementation class contained in our package We need one tHiveRow to drop the hashtags table if it exists. As we have done in the CH03_02_HIVE_CREATE_TWEET_TABLE job, just add the "DROP TABLE IF EXISTS hash_tags" drop statement to be sure that the table is removed when we relaunch the job. We need one tHiveRow to create the hashtags table. We are going to create a new table to store the hashtags. For the purpose of simplicity, we'll only store the minimum time and description information as shown in the following table: Name Value hash_tags_id String day_of_week String day_of_month String time String month String hash_tags_label String The essential information here is the hash_tags_label column, which contains the hashtag name. With this knowledge, the following is our create table query: CREATE EXTERNAL TABLE hash_tags ( hash_tags_id string, day_of_week string, day_of_month string, time string, month string, hash_tags_label string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ';' LOCATION '/user/"+context.hive_user+"/packt/chp04/hashtags' Finally we need a tHiveRow component to feed the hashtags table. Here, we are going to use all the assets provided by the previous components as shown in the following query: insert into table hash_tags select concat(formatted_tweets.day_of_week, formatted_tweets. day_of_month, formatted_tweets.time, formatted_tweets.month) as hash_id, formatted_tweets.day_of_week, formatted_tweets.day_of_month, formatted_tweets.time, formatted_tweets.month, hash_tags_label from formatted_tweets LATERAL VIEW explode( extract_patterns(formatted_tweets.content,'#(\\w+)') ) hashTable as hash_tags_label Let's analyze the query from the end to the beginning. The last part of the query uses the extract_patterns function to parse in the formatted_tweets.content all hashtags based on the regex #(+). In Talend, all strings are Java string objects. That's why we need here to escape all backslash. Hive also needs special character escape, that brings us to finally having four backslashes. The extract_patterns command returns an array that we inject in the exploded Hive UDF in order to obtain a list of objects. We then pass them to the lateral view statement, which creates a new on-the-fly view called hashTable with one column hash_tags_label. Take a breath. We are almost done. If we go one level up, we will see that we selected all the required columns for our new hash_tags table, do a concatenation of data to build hash_id, and dynamically select a runtime-built column called hash_tags_label provided by the lateral view. Finally, all the selected data is inserted in the hash_tags table. We just need to run the job, and then, using the following query, we will check in Hive if the new table contains our hashtags: $ select * from hash_tags The following diagram shows the complete hashtags-extracting job structure: Hive processing job Summary By now, you should have a good overview of how to use Apache Hive features with Talend, from the ELT mode to the lateral view, passing by the custom Hive user-defined function. From the point of view of a use case, we have now reached the step where we need to reveal some added-value data from our Hive-based processing data. Resources for Article: Further resources on this subject: Visualization of Big Data [article] Managing Files [article] Making Big Data Work for Hadoop and Solr [article]
Read more
  • 0
  • 0
  • 2225

article-image-mobile-application-development-ibm-worklight
Packt
18 Feb 2014
13 min read
Save for later

Mobile application development with IBM Worklight

Packt
18 Feb 2014
13 min read
(For more resources related to this topic, see here.) The mobile industry is evolving rapidly with an increasing number of mobile devices, such as smartphones and tablets. People are accessing more services from mobile devices than ever before. Mobile solutions are directly impacting businesses, organizations, and their growing number of customers and partners. Even employees now expect to access services on a mobile river. Several approaches currently exist for mobile application development; which include: Web Development: Uses open web (HTML5, JavaScript) client programming modules. Hybrid Development: The app source code consists of web code executed within a native container that is provided by Worklight and consist of native libraries. Hybrid Mixed: The developer uses arguments in the web code with native language to create unique features and access native APIs that are not yet available via JavaScript, such as AR, NFC, and others. Native Development: In this approach, the application is developed using native languages or transcoded into a native language via MAP tool's native appearance device capabilities, and performance. To achieve a similar application in different platforms, requires a different level of expertise hitting the cost, time, and complexity. The preceding list outlines the major aspects of the development approaches. Reviewing this list can help you choose which development approach is correct for your particular mobile application. The IBM Worklight solution In 2012, IBM acquired its very first set of mobile development and integration tools called IBM Worklight, which allows organizations to transform their business and deliver mobile solutions to their customers. IBM Worklight provides a truly open approach for developers to build an application and run it across multiple mobile platforms without having to port it for each environment, that is, Apple iOS, Google Android, Blackberry, and Microsoft Windows Phone. IBM Worklight also makes the developer's life easier by using standard technologies such as HTML5 and JavaScript with extensions for popular libraries such as jQuery Mobile, Dojo Toolkit, and Sencha Touch. IBM Worklight is a mobile application platform containing all of the tools needed to develop a mobile application. If we combine IBM Worklight components into a stream, it would be clean to say that hybrid mobile application development is tightly coupled with a baseline. Every specified component provides a bundle of functionalities and supports. Here is the lifecycle of Mobile Application Development; Worklight Studio: IBM Worklight provides a robust development Eclipse based environment called Worklight Studio that allow developers to quickly construct mobile application for multiple operating platforms. Worklight Server: This component is a runtime server that activates or enables secure data transmission through centralized back-end connectivity with adapters, used for offline encrypted storage, unified Push Notification and many more. Worklight Device Runtime: The device runtime provides a rich set of APIs that are cross-platform in nature and offer easy access to the services provided by the IBM Worklight Server. Worklight Console: This is a web dependent interface for real-time analytics, Managing Push Notification Authority and Mobile Version Management. The Worklight Console is a web-based interface and dedicated for ongoing administration of Worklight Server and its deployed apps, adapters and push notification services. Worklight Application Center: It's a cross-platform Mobile Application Store which pretends specific needs for Mobile Application Development team. There is a big advantage for using Worklight to creating user interface and that reflects on development at client side as well as server side. In general developer faces problems during development and support for creation of hybrid app by using other product, are typical not straight to define the use cases, debugging, preview testing for enterprise application but using a Worklight, developer can make simple architecture and enhanced improvised structures are amend to have mobile application. Creating a Simple IBM Worklight Application Let's start by creating a simple HelloWorld Worklight project; The steps described for creating an app are similar for IBM Worklight Studio and Eclipse IDE. The following is what you'll need to do: Start IBM Worklight Studio. Navigate to File| New and select Worklight Project, as shown in the following screenshot: Create New Worklight Project In the dialog that is displayed in the following screenshot, select Hybrid Application as the type of application defined in project templates, enter HelloWorld as the name of the first mobile project, and click on Next. Asked for Worklight Project Name and Project Type. You will see another dialog for Hybrid Application. In Application name, provide HelloWorld as the name of the application. Leave the checkboxes unchecked for now; these are used to extend supported JavaScript libraries into the app. Click on Finish. Define Worklight App Name in the window After clicking on Finish, you will see your project has been created from design perspective in Project Explorer, as shown in the following screenshot: Project Explore after complete Wizard. Adding an environment We have covered IBM Worklight Studio features and what they offer developers. It's time to see how this tool and plugin will make your life even easier. The cross platform development feature is a great deal to implement. It provides you with the means to achieve cross-development environment without any hurdles and with just a few clicks within its efficient interface. To add an environment for Android, iPhone, or any other platform, right-click on the Apps folder next to the adapters and navigate to New| Worklight Environment. You will see that a dialog box appears with checkboxes for currently supported environments, which you need to create an application for. The following screenshot illustrates this feature—we're adding an Android environment for this application: Worklight Environment selection window IBM Worklight Client Side API In this article, you will learn how the IBM Worklight client-side API can improve mobile application development. You will also see the IBM Worklight server side API improve client/server integration and communication between mobile applications and back end systems. The IBM Worklight client-side API allows mobile applications to access most of the features that are available in IBM Worklight during runtime, in order to get access to some defined libraries that appear to be bundled into the mobile application. Integration of the libraries for your mobile application using Worklight Server is used to access predefined communication interfaces. These libraries also offer unified access to native device features, which streamlines application development. The IBM Worklight client-side API contains hybrid, native, mixed hybrid, and web-based APIs. Besides, it extends those of these APIs that are responsible for supporting every mobile development framework. The development framework for a mobile application is used to improve security including custom and built-in authentication mechanisms for IBM Worklight provided by client-side API modules. It provides a semantic connection between web technologies such as HTML5, CSS3, and JavaScript with native functions that are available for different mobile platforms. Exploring Dojo Mobile Regarding the Dojo UI framework, you'll learn about Dojo Mobile in detail. Dojo Mobile, an extension for Dojo Toolkit, provides a series of widgets, or components, optimized for use on a mobile device, such as a smartphone or tablet. The Dojo framework is an extension of JavaScript and provides a built-in library which contains custom components such as text fields, validation menus, and image galleries. The components are modelled on their native counterparts and will look and feel native to those familiar with smartphone applications. The components are completely customizable using themes that let you make various customizations, such as pushing different sets of styles to iOS and Android users. Authentication and Security Modules Worklight has built-in authentication framework that allows developer to configure and use it with very little effort. The Worklight project has an authentication configuration file, which is used to declare and force security on mobile application, adapters, data and web resources which consist following security entities. We will talk about the various pre-defined authentication realms and security tests that are provided in Worklight out-of-box. To identify the importance of Mobile security you can see that in today's life we keep our personal and business data on mobile devices. The data and applications are both important to us. Both the data and applications should be protected against unauthorized access, particularly if they contain sensitive information or transmitting over the network. There are number of ways via a device can be compromised and it can leak data to malicious users. Worklight security principles, concepts and terminology IBM Worklight provides various security roles to protect applications, adapter procedures, and static resources from an unauthorized access. Each role can be defined by a security test that comprises one or more authentication realms. The authentication realm defines a process that will be used to authenticate the users. The authentication realm has the following parts: Challenge handler: This is a component on the device side Authenticator and login module: This is a component on the server One authentication realm can be used to protect multiple resources. We will look into each component in detail. Device Request Flow: The following screenshot shows a device that makes a request to access a protected resource, for example, an adapter function, on the server. In response to the request, the server sends back an authentication challenge to the device to submit its authenticity: Request/Response flow between Worklight application and enterprise server diagram> Push notification Mobile OS vendors such as Apple, Google, Microsoft, and others provide a free of cost feature through which a message can be delivered to any device running on the respective OS. The OS vendors send a message commonly known as a push message to a device for a particular app. It is not required for an app to be running in order to receive a push message. A push message can contain the following: Alerts: These would appear in the form of text messages Badges: These are small, circular marks on the app icon Sounds: These are audio alerts Alerts - Text Messages Messages will appear in the notification center (for iOS) and notification bar (for Android). IBM Worklight provides a unified push notification architecture that simplifies sending push messages across multiple devices running on different platforms. It provides a central management console to manage mobile vendor services, for example, APNS and GCM, in the background. Worklight provides the following push notification benefits: Easy to use: Users can easily subscribe and unsubscribe to a push service Quick message delivery: The push message gets delivered to a user's device even if the app is currently not running on the device Message feedback: It is possible to send feedback whenever a user receives and reads a push message Cordova Plugins A Cordova plugin is an open source, cross-platform mobile development architecture that allows the creation of multiplatform-deployable mobile apps. These apps can access native component features of devices using an API having web technologies such as HTML 5, JavaScript, and CSS 3. Apache Cordova Plugins are integrated into IBM Worklight Android and iOS projects. In this article, we will describe how Apache Cordova leverages the ability to merge the JavaScript interface as a wrapper on the web side in a native container with the device native interface on the mobile device platform. The most critical aspect of Cordova plugins is to deal with the native functionalities such as camera, bar code scanning, contacts list, and many other native features, currently running on multiple platforms. JavaScript doesn't provide such extensibility to enhance the scripting with respect to the native devices. In order to have a native feature's accessibility, we provide a library corresponding to the device's native feature so that JavaScript can communicate through it. When the need arises for a web page to execute the native feature functionality, the following points of access are available: The scenario has to be implemented in platform-specific manner, for example, in Android, iOS, or any other device In order to handle requests and responses between web pages and native pages, we need to communicate to/from web and native pages that are encrypted. By selecting the first option from the preceding list, we would find ourselves implementing and developing platform-dependent mobile applications. As we are in need of implementing mobile applications for a cross-platform mobile, and because it leads to provide cost-ineffective solutions, it is not a wise choice for Enterprise Mobile Development Solutions. It seems to be a really poor extensible for future enhancements and needs. Encrypted Offline Cache Encrypted Offline Cache (EOC) is the mechanism that is used for storing the repeated and the most sensitive data, which is used in the client's application. Encrypted Offline Cache is precisely known as EOC. It permits a flexible on-device data storage procedure for Android, iOS, BlackBerry, and Windows. This procedure provides a better alternative to the user for storing the manipulated data or the fetched response using the defined adapter data when offline and synchronizing the data for the usage of the server, which provides modifications that were completely developed when offline or without Internet connectivity. In order to dedicatedly create any mobile application for multiple platforms such as iOS and Android, consider using JSONStore rather than EOC. It seems to be much more practical to implement and is supposed to be the best practices of IBM. The JSONStore provides a mechanism to ease cryptographic procedures for encrypting forms and implementing security. PBKDF2 is a key derivation function that would act as the password to access encrypted data, which would be provided by the user. HTML5 cache can be used in EOC, which is not guaranteed to be persistent and is not a proper solution for the future updated versions of iOS. Storage JSONStore The local replica is a JSONStore. IBM Worklight delivers an API which do its work with a JSON Store consuming the class WL.JSONStore using the JavaScript defined method. You can generate an application that endures a local storage manipulated data with data copy and thrusts the local updates to a back-end provisioned service. Nearly every single method or process which is delivered in API for retrieving synchronized data to activate the native copy of the defined data that is kept on the client application or on-device. By means of the JSONStore API, you can encompass the functionality of existing adapter connectivity model to store data locally and impulse modifications from the client to a server. You can pursuit the local data storage and apprise or delete data within it. It can be used to protect the local data store by using password-based encryption. Summary In this article, we have discussed modern world mobile development techniques using IBM Worklight which surely allows an easy ,integrated, and secure enterprise mobile application with respect to time and development efforts. Beside it, most of the key functional areas have been covered including IBM Worklight components, mobile cross-platform environment handling and authentication, push notifications, Dojo mobile framework, and Encrypted Cache for Offline storage. IBM Worklight has the most diverse mechanism to enhance the mobile application functionalities with a more optimum and efficient way. This article also completely concludes the mobile application development techniques and features, by using which enterprise mobile app development will no longer be disquiet. Resources for Article: Further resources on this subject: Creating and configuring a basic mobile application [Article] Viewing on Mobile Devices [Article] Creating mobile friendly themes [Article]
Read more
  • 0
  • 0
  • 5831

article-image-baritem-class-and-radoutlookbar-control
Packt
18 Feb 2014
6 min read
Save for later

The BarItem class and the RadOutlookBar control

Packt
18 Feb 2014
6 min read
(For more resources related to this topic, see here.) The next aspect of the system we want to review is the BarItem class. The design of this class is set up to be used by the RadOutlookBarItem and RadMenuItem classes. The reason for this setup was to match the properties of the Telerik item classes. The following is a screenshot of the class design: The main properties include Header, Position, and ReferId. The Header property is set up to match the Header property from the RadOutlookBarItem and RadmenuItem classes. The Position property orders the items on the system for proper display, and the ReferId property creates the structure of the view. The ReferId values are set up so that if the ReferId property is zero, this item becomes the header, otherwise the rest of the items become the items under that main item. Now that we've covered the new concepts within this article, let's start to work with the navigation containers for Telerik. The next sections of this article will cover the RadOutlookBar and RadMenu controls using the concepts from this section to load these controls based on the level of user access. RadOutlookBar The first control I will review in this article will be the RadOutlookBar control. This control is unique to the Telerik toolset. The standard Visual Studio control library does not contain a control like the RadOutlookBar control. The first example I will review will be to set the binding of the control's tabs using both a list of class objects from the object layer, and the database to populate the list of objects and authenticate the user. The first step will be to create a new window in the current WPF project; name this new window Chap5OutlookWindow.xaml. Once you have created the new window, you will need to add the RadOutlookBar control: RadOutlookBar: Name the outlook bar RadTestOutlook The final appearance of the window should be the following screenshot: Notice that the RadOutlookBar control is already loaded with the options. This is the fully functioning example, but gives you an idea for how the window should look once we've finished this section. RadOutlook with GenericList, DataBinding, and database security This is the first example of populating the RadOutlookBar with the menu links from the database. The concept we are demonstrating is that the menu links inside the RadOutlookBar control will be populated based on the user that is authenticated into the system. In this example, we will be using database security. This means that the database will store the username and password, and security link information for the RadOutlookBar control. Since we don't have a login form to gather the username and password, we will create the user information within the App.xaml.cs file instead. This will allow us to simulate the login process and authenticate the user in the system. This should not be done for a production application—this setup is for demonstration purposes only. Hard-coding a username and password is always a bad practice in a real-world application. The following screenshot shows how the code should look inside the App.xaml.cs file: Let's review the preceding code. The first step is to create an instance of the UserEntity class. The next step is to determine the type of security the system will be using to authenticate the user. The app.config file has a setting for the type of security as shown in the following line of code: <add key="SecurityType" value="DB"/> This key value is passed to the system, and used by the system to determine which type of security is used in the App.xaml.cs class. The value is read by the system; it sets an enum property from the UserEntity class called SecurityType. This enumeration is then evaluated to determine the security setup for the system. The next step is to set the UserName and UserChkPwd properties. Once these properties are set we can then call the Authenticate method to verify the user information against the database. The next step will be to set the CurrentUser property in the application request class. This object is passed to each window to persist base application information to each window. The final step will be to create an instance of the OutlookBarWindow class to open the window. Notice the code for the instance; we are passing the AppRequest object to the window using the instance method of the window. The following screenshot is the instance code: Now that the window code is set up, let's review the LoadRadOutlook method from the BaseWindow class. This method requires two values: the OutlookBar object to be loaded, and a generic list of BarItem objects. The BarItem class takes the information from the database and loads the RadOutlookBar control using BarItems to create the RadOutlookBarItem objects to load the RadOutlookBar control. The LoadRadOutlook method also creates a RadTreeView control of the options within each RadOutlookBarItem object. The database version then handles the gathering of the BarItem class and loading the RadOutlookBar control using a method called FetchMenuOptions. This method takes BarItems from the database query, and created a RadOutlookBar object with all the menu options for the current user. This method gathers the menu information based on the current username and generates a generic list of the BarItem classes. This list is used by the BaseWindow class to load the RadOutlookBar control. RadOutlookBar using generic list binding with XML security The next method for populating the RadOutlookBar control on the window will be to use a serialized XML to populate the generic list of objects to load the RadOutlookBar control. The XML file has the group information and pulls the BarItem objects based on the user's group information. The example we will be using has the group information hard-coded into the group list, but this is just an example. You should not hard-code the groups in a real-world application. Here is the method for gathering the menu items from the XML file: Notice that we first load the XDocument object, then deserialize the XDocument object to gather the list of BarItem objects. Once the full list is loaded, we use a Linq query to gather the items based on the user group for the current user. Now that we have that new list, we can populate the UserMenuItems property for use in the application. The application then calls the LoadOutlookBar method to generate the RadOutlookBar control again. Summary Thus in this article we learned what a RadOutlookBar control is and how it can be used with GenericList, DataBinding, database security and generic list binding with XML security. We also had a glance over the BarItem class and how the design of this class is set up to be used by the RadOutlookBarItem and RadMenuItem classes. Resources for Article: Further resources on this subject: WPF 4.5 Application and Windows [Article] Windows Presentation Foundation Project - Basics of Working [Article] Introduction to Web Experience Factory [Article]
Read more
  • 0
  • 0
  • 1712
article-image-publishing-generated-code-diff-review-board
Packt
18 Feb 2014
2 min read
Save for later

Publishing the generated code diff to Review Board

Packt
18 Feb 2014
2 min read
(For more resources related to this topic, see here.) You have authored some code changes and prepared a code diff. Now you want to publish it to Review Board so as to share it with the team for review. Let us create and publish a code review request with the code diff that we generated. When you log in to your Review Board site, you see different tabs at the top navigation bar. New Review Request is one of them. Clicking on this tab will lead you to the following screen: You have to provide the following details in the case of an SVN repository: Repository: This dropdown lets you choose the repository on which you are working. It lists all of the repositories added by the admin. Base Directory: This shows the absolute path of the directory for which you have generated the SVN diff. Diff: The process of uploading the code diff varies from VCS to VCS; that is, the fields required for creating the new review request will change as per the selected repository (if the repositories are of a different type of VCS). Let's see what the screen for creating a review request looks like for Git: In the case of Git, the diff option remains the same; you don't have to provide a base directory in this case(unlike SVN). There is an additional field named Parent Diff that is a common field for distributed version control systems such as Git or Mercurial. As a standard practice, you should make sure that all of the branches in your Git repository are made available in the Review Board server. If that is not the case, you will not be able to post the code diff for a branch that is not available directly because Review Board will not be able to show the code diff. In this case, you have to use the Parent Diff feature of Review Board. Summary This article explained briefly about one of the methods of publishing the generated code diff to Review Board to get it reviewed by others. Resources for Article: Further resources on this subject: Learn Cinder Basics – Now [article] Using Image Processing Techniques [article] Using Gerrit with GitHub [article]
Read more
  • 0
  • 0
  • 1916

article-image-finishing-touches-and-publishing
Packt
18 Feb 2014
7 min read
Save for later

Finishing Touches and Publishing

Packt
18 Feb 2014
7 min read
(For more resources related to this topic, see here.) Publishing a Video Demo project Due to its very nature, a Video Demo project can only be published as an .mp4 video file. In the following exercise, you will return to the encoderVideo.cpvc project and explore the available publishing options: Open the encoderVideo.cpvc file under Chapter08. Make sure the file opens in Edit mode. If you are not in Edit mode, click on the Edit button at the lower-right corner of the screen. (If the Edit button is not displayed on the screen, it simply means that you already are in Edit mode.) When the file is open in Edit mode, take a look at the main toolbar at the top of the interface. Click on the Publish icon or navigate to File | Publish. The Publish Video Demo dialog opens. In the Publish Video Demo dialog, make sure the Name of the project is encoderVideo. Click on the … button and choose the publish folder of your exercises as the destination of the published video file. Open the Preset dropdown. Take some time to inspect the available presets. When done, choose the Video - Apple iPad preset. Make sure the Publish Video Demo dialog looks similar to what is shown in the following screenshot and click on the Publish button: Publishing a Video Demo project can be quite a lengthy process, so be patient. When the process is complete, a message asks you what to do next. Notice that one of the options enables you to upload your newly created video to YouTube directly. Click on the Close button to discard the message. Use Windows Explorer (Windows) or the Finder (Mac) to go to the publish folder of your exercises. Double-click on the encoderDemo.mp4 file to open the video in the default video player of your system. Remember that a Video Demo project can only be published as a video file. Also remember that the published .mp4 video file can only be experienced in a linear fashion and does not support any kind of interactivity. Publishing to Flash In the history of Captivate, publishing to Flash has always been the primary publishing option. Even though HTML5 publishing is a game changer, publishing to Flash is still an important capability of Captivate. Remember that this publishing format is currently the only one that supports every single feature, animation, and object of Captivate. In the following exercise, you will publish the Encoder Demonstration project in Flash using the default options: Return to the encoderDemo_800.cptx file under Chapter08. Click on the Publish icon situated right next to the Preview icon. Alternatively, you can also navigate to File | Publish. The Publish dialog box opens as shown in the following screenshot: Notice that the Publish dialog of a regular Captivate project contains far more options than its Publish Video Demo counterpart in .cpvc files. The Publish dialog box is divided into four main areas: The Publish Format area (1): This is where you choose the format in which you want to publish your projects. Basically, there are three options to choose from: SWF/HTML5, Media, and Print. The other options (E-Mail, FTP, and Adobe Connect) are actually suboptions of the SWF/HTML5, Media, and Print formats. The Output Format Options area (2): The content of this area depends on the format chosen in the Publish Format (1) area. The Project Information area (3): This area is a summary of the main project preferences and metadata. Clicking on the links of this area will bring you back to the corresponding preferences dialog boxes. The Advanced Options area (4): This area provides some additional advanced publishing options. You will now move on to the actual publication of the project in the Flash format. In the leftmost column of the Publish dialog, make sure the chosen format is SWF/HTML5. In the central area, change the Project Title to encoderDemo_800_flash. Click on the Browse… button situated just below the Folder field and choose to publish your movie in the publish folder of your exercises folder. Make sure the Publish to Folder checkbox is selected. Take a quick look at the remaining options, but leave them all at their current settings. Click on the Publish button at the bottom-right corner of the Publish dialog box. When Captivate has finished publishing the movie, an information box appears on the screen asking whether you want to view the output. Click on No to discard the information box and return to Captivate. You will now use the Finder (Mac) or the Windows Explorer (Windows) to take a look at the files Captivate has generated. Use the Finder (Mac) or the Windows Explorer (Windows) to browse to the publish folder of your exercises. Because you selected the Publish to Folder checkbox in the Publish dialog, Captivate has automatically created the encoderDemo_800_flash subfolder in the publish folder. Open the encoderDemo_800_flash subfolder to inspect its content.There should be five files stored in this location: encoderDemo_800_flash.swf: This is the main Flash file containing the compiled version of the .cptx project encoderDemo_800_flash.html: This file is an HTML page used to wrap the Flash file standard.js: This is a JavaScript file used to make the Flash player work well within the HTML page demo_en.flv: This is the video file used on slide 2 of the movie captivate.css: This file provides the necessary style rules to ensure there is proper formatting of the HTML page If you want to embed the compiled Captivate movie in an existing HTML page, only the .swf file (plus, in this case, the .flv video) is needed. The HTML editor (such as Adobe Dreamweaver) will recreate the necessary HTML, JavaScript, and CSS files. Captivate and DreamweaverAdobe Dreamweaver CC is the HTML editor of the Creative Cloud and the industry-leading solution for authoring professional web pages. Inserting a Captivate file in a Dreamweaver page is dead easy! First, move or copy the main Flash file (.swf) as well as the needed support files (in this case, the .flv video file), if any, somewhere in the root folder of the Dreamweaver site. When done, use the Files panel of Dreamweaver to drag and drop the main .swf file onto the HTML page. That's it! More information on Dreamweaver can be found at http://www.adobe.com/products/dreamweaver.html. You will now test the compiled project in a web browser. This is an important test as it closely recreates the conditions in which the students will experience the movie once uploaded on a web server. Double-click on the encoderDemo_800_flash.html file to open it in a web browser. Enjoy the final version of the demonstration you have created! Now that you have experienced the workflow of publishing the project to Flash with the default options, you will explore some additional publishing options. Using the Scalable HTML content option Thanks to Scalable HTML content option of Captivate, the eLearning content is automatically resized to fit the screen on which it is viewed. Let's experiment with this option hands on using the following steps: If needed, return to the encoderDemo_800.cptx file under Chapter08. Click on the Publish icon situated right next to the Preview icon. Alternatively, you can also navigate to File | Publish. In the leftmost column, make sure the chosen format is SWF/HTML5. In the central column, change the Project Title to encoderDemo_800_flashScalable. Click on the Browse… button situated just below the Folder field and ensure that the publish folder is still the publish folder of your exercises. Make sure the Publish to Folder checkbox is selected. In the Advanced Options section (lower-right corner of the Publish dialog), select the Scalable HTML content checkbox. Leave the remaining options at their current value and click on the Publish button at the bottom-right corner of the Publish dialog box. When Captivate has finished publishing the movie, an information box appears on the screen asking whether you want to view the output. Click on Yes to discard the information box and open the published movie in the default web browser. During the playback, use your mouse to resize your browser window and notice how the movie is resized and always fits the available space without being distorted. The Scalable HTML content option also works when the project is published in HTML5.
Read more
  • 0
  • 0
  • 11054
Modal Close icon
Modal Close icon