Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

June 30 2017

12:00

Creating a Blogging App Using React, Part 2: User Sign-Up

In the first part of this tutorial series, you saw how to implement the sign-in functionality. In this part, you'll learn how to implement the sign-up functionality and modify the sign-in functionality to check for valid users from MongoDB.

Getting Started

Let's get started by cloning the source code from the first part of the tutorial.

Once the directory has been cloned, navigate to the project directory and install the required dependencies.

Start the Node.js server and you will have the application running at http://localhost:7777/index.html#/.

Setting Up the Back End

For this application, you'll be using MongoDB as the back end. Follow the instructions in the MongoDB official documentation to install MongoDB on Ubuntu. Once you have MongoDB installed, you'll need a connector to connect MongoDB and Node.js. Install the MongoDB Node.js driver using the Node Package Manager (or npm):

Once you have the driver installed, you should be able to require the driver in the application.

Create a file called user.js where you'll keep the user-related stuff. Inside the user.js file, require the MongoDB client-related dependencies.

You'll be using a library called assert to check the returned response. Include assert in the user.js file.

Let's name our database Blog in MongoDB, so our database URL is as shown:

Inside the user.js file, create and export a function called signup

Using the MongoDB client, try to connect to the database. Once connected, you'll log the connected message in the terminal.

Setting Up the Sign-Up Event

Once you have set up the MongoDB back end, let's implement the sign-up event. Inside the main.jsx page, include the on-change event for the name, email and password input text boxes in the signup class.

Bind the above event changes in the class constructor.

Define the state variables inside the signup class constructor.

Define the signup method inside the signup class. Inside the signup method, using the axios library, make a post method call to the signup method in the user.js file. 

Inside the signup function in the user.js file, you'll implement the database insert.

Add the /signup request handler in the app.js file as shown to handle the sign-up click event. Inside the /signup request handler function, make a call to the user.signup method.

Require the user.js file inside the app.js file.

Save the above changes and restart the server. Point your browser to http://localhost:7777/index.html#/signup and you should have the sign-up page. Click on the Sign Up button and you will have the connected message in the terminal.

Save User Details in MongoDB

To save user details in the Blog database, you'll create a collection called user. Inside the user collection, you'll keep all the user details such as name, email address, and password. The MongoClient.connect returns a db parameter using which you can insert an entry in the user collection. 

You'll make use of the insertOne method to insert a single record in the user collection. Modify the code in the signup method in user.js as shown below:

Here is the complete user.js code:

Modify the /signup request handler in the app.js file to pass in the name, email and password to the user.js signup method.

Save the above changes and restart the server. Point your browser to http://localhost:7777/index.html#/signup. Fill the user sign-up details and click the sign-up button. You will have the Saved the user sign up details. message in the server terminal. Log in to the MongoDB shell and check the user collection in the Blog database. To find the user details, enter the following command in the MongoDB shell:

The above command will display the user details in JSON format.

Implementing User Sign-In Check

In the first part of the tutorial, you hard-coded the user sign-in check since the user sign-up hasn't been implemented. Let's modify the hard-coded sign-in check and look into the MongoDB database for valid user sign-ins.

Create a function called validateSignIn in the user.js file. 

Inside the validateSignIn function, using the MongoDB client you'll connect to the Blog database and query the user table for a user with the specified username and password. You'll make use of the findOne method to query the user collection.

Check the returned result for null in case the entry is not found. 

As seen in the above code, if no entry is found, false is returned in the callback. If an entry is found, true is returned in the callback.

Here is the complete validateSignIn method:

In the /signin method in the app.js file, you'll make a call to the validateSignIn method. In the callback function, you'll check for the response. If true, it will indicate a valid sign-in, else an invalid sign-in. Here is how it looks:

Save the above changes and restart the server. Point your browser to http://localhost:7777/index.html#/. Enter a valid username and password and you will have a success message logged in the browser console. On entering an invalid username and password, it would display an error message.

Wrapping It Up

In this part of the tutorial, you saw how to implement the user sign-up process. You saw how to create the sign-up view and pass the data from the React user interface to Node.js and then save it in the MongoDB. You also modified the user sign-in functionality to check for valid user sign-in from the MongoDB database.

In the next part of the tutorial, you'll implement the add post and display post page functionality.

Source code from this tutorial is available on GitHub.

Do let us know your thoughts or any suggestions in the comments below.

June 29 2017

23:05

Getting Started With Realm Mobile Platform for iOS

In this tutorial, I’ll continue from my previous tutorial on Realm Mobile Database for iOS where we learned about Realm Mobile Database, an on-device database alternative to Core Data. Realm has also developed an equally elegant and seamless server-side solution that syncs our data between our device and the cloud in real time. This is part of Realm’s flagship solution, Realm Mobile Platform.

In this post, we will install a Realm Object Server and improve on the RealmDo app that we started in the previous post.

  • iOS SDK
    Realm Mobile Database for iOS
    Doron Katz

What Is Realm Mobile Platform?

Announced in early 2017, Realm Mobile Platform 1.0 represents the company's efforts to extend its database onto the cloud and provide support for more collaborative features such as live messaging, offline-first experiences, and more impressively, cross-platform.  Through the new Realm Object Server, Realm Mobile Platform takes over and handles the complexities of marshaling and synchronizing data between the Realm Database and server. 

Realm Mobile Platform acts as a conduit between the Realm Object Server and your Realm Mobile Database. When you persist data locally on your device, it gets pushed in real-time, but with the ability to queue and defer-synchronize when offline.
Illustration of data flow in Realm Mobile Platform

In addition to synchronizing data (or Realms) between devices, Realm Object Server also provides authentication and access control services (permission management), as well as serverless event processing through Realm Functions. Let’s learn more about what Realm Mobile Platform provides. Note that some of these features are available to enterprise customers only.

Realm Functions 

Realm Functions act as the app logic layer, powered by JavaScript, allowing you to execute custom logic without a dedicated server and to respond to changes on one or all Realms (databases).

Through the Realm Dashboard you can author, start, stop and delete functions that respond to changes on one or more Realms, with serverless Event Handling. You create functions using JavaScript and Node.js, and the functions are called by the Realm Object Server's global listening API.

Realm Dashboard screenshot

Currently, the developer edition of Realm Mobile Platform is limited to three active functions at any given time, although you are able to have more functions which are inactive. 

Realm Functions are outside the scope of this tutorial, but certainly worth reading up on.

Realm Dashboard

The Realm Dashboard comes baked in with the Realm Object Server installation, as we will illustrate shortly, providing a convenient tool for managing your Realms, managing users and functions, and getting a pulse on how your application server is running.

The browser-based dashboard consists of the following sections:

  • Dashboard provides a real-time pulse of data rates in and out, open connections and open Realms.
  • Realms provides paths, permissions and owners of each of the Realms, and you can traverse down each Realm to view the models and contents of individual Realms.
  • Users provides information and management services for all users, including granting and removing administrative permissions.
  • Functions is where you create and manage your Realm Functions.
  • Logs is where you can view System logs for the Object Server.

The Dashboard is normally accessible via the http://localhost:9080 path locally, or wherever your hosted machine lies. 

Realm Connection

This is an enterprise-only feature, though very useful for some businesses. Realm connection is a conduit that exposes corporate legacy systems to the platform through a modern API gateway, making it easier for developers to hook into previously obfuscated data sources.

The Enterprise Edition of the Realm Object Server offers a Node.js-based adapter API that allows you to access all low-level Object Server operations and data. This can be used to let a synced Realm interact with an existing legacy database such as PostgreSQL: the Realm will also be kept in sync with the external database in real time. Client applications can use the Realm Mobile Database API and get the benefits of working with real-time, native objects.

Service Tiers

The company currently offers three tiers of service. The Developer Edition is the free-tier for small teams, where users would benefit from features like real-time automatic data-sync using live objects. The Professional Edition adds advanced features such as event handling and server-side access.

Realm Mobile Platform pricing table

Catering to the demands of mid-sized teams, the Professional Edition is a good middle ground without the overhead of the Enterprise Edition. Costs are adjusted to your scale, providing an easy migration path from the free tier.

The Professional Edition starts at $1,500 per month, and the Enterprise Edition is custom priced based on the use case.

Your First Realm Server App

Assumed Knowledge

This tutorial assumes you have a working knowledge of Swift, but no Core Data or prior database knowledge is needed. Additionally, it is assumed you have gone through the previous tutorial on Realm Mobile Database for iOS and have completed the tutorial exercises to create the RealmDo app. We're going to continue from where we left off in that post, and add server-side functionality to our app, RealmDo.

As well as Realm, we'll be using the following parts of iOS:

  • UIKit: to demonstrate our data visually
  • CocoaPods: a third-party dependency library that will be used to install Realm Mobile Database

Objectives of This Tutorial 

By the end of this tutorial, you will have continued to build on your knowledge of Realm and enhance the simple to-do app written in Swift, by persisting data remotely on the server through Realm Mobile Platform. You'll get to create a fully functioning Realm-powered to-do app with a server-side back-end, and along the way you'll learn the following concepts:

  1. setting up the Realm Object Server locally
  2. synchronizing the ‘live-object’ model to the Realm Object Server
  3. monitoring data through the dashboard

You can download the complete source code from the tutorial GitHub repo.

Set Up the Realm Object Server

Before we hit Xcode once again to work our project, we will need to set up and get our Realm Object Server running. 

Download the macOS bundle, assuming you will be installing the Object Server locally on your Mac. If you are going to be installing it on a Linux server, refer to the Realm documentation.

Once you've completed the download, in terminal navigate to your Downloads/realm-mobile-platform folder and start the server by typing:

start-object-server.command

Your terminal should now indicate that your server is starting, and your browser will automatically open to launch the Realm Dashboard, at http://localhost:9080.

You will be asked to register as a new user and provide an email and password the first time you run the server. Please go ahead and complete the registration process and remember your credentials, as you will be using them later on.

Realm registation screen

Keep this browser window open as we will return to it later when we run our complete app, to observe how data is stored on the server.

Making Our Project Syncable

Now we are set to start coding, so go ahead and fire up the Xcode project we were working on in the previous tutorial, as we are going to continue to build from there, in the view controller.

The first thing we will do is amend our remindersList global variable to be mutable, so we will need to change it from an RLMResults object to a List type. We will also be adding a new object type, NotificationToken, which we will use to notify us of when there is a change in the realm data object. 

NotificationToken isn't a server-specific object, and we could have used it in our previous tutorial, but it certainly comes in handy when we want to detect real-time changes remotely or locally and react accordingly.

Within the viewDidLoad() method, we will embed a SyncUser.logIn() method, which is Realm's authentication mechanism, accepting a username, password, and server location. This is an interesting topic in its own right, beyond the scope of this tutorial, but for now, we will just hard-code in the credentials we set when we registered our Realm Object Server previously.

We also pass in the server location, along with the name of the realm (database) we want to use, which is http://127.0.0.1:9080. In the realm configuration line, in addition to the server location, you must also set the realm name, which is realmDoApp for the purposes of this demonstration. Go ahead and replace your viewDidLoad() with the following:

In a real-world application, we would get user credentials with a form. In the code above, though, we hard-code our credentials and set a user object once the login is successful. Otherwise, the application will fail with a fatal error.

Finally, the code above uses a synchronous block to associate the realm instance to the realm object server (instead of the on-device database). This is the distinctive line that makes this app cloud-based. 

At the end, I initialize the notificationToken to call a method, updateRemindersList(), every time there is a change in the realm data (locally or remotely).

The code block above also converts the self.realm.objects() it receives from the server, so that we can associate the results with our newly List-typed RemindersList set of objects.

Notice how it is ambiguous whether we are getting the data from our realm database or remotely. This is what makes Realm great—you don't have to worry about synchronization locally or remotely!

And that is it—all the code that is needed to make the app work with Realm Object Server. There is one final thing needed prior to building and running the app. Open up the project’s info.plist as Source Code by right-clicking on the file. Add the following to allow non-TLS requests to work. 

Now, go ahead and build and then run the application, and add a few new reminders. We will switch over to the browser now, where we can see the running server and access its dashboard to observe data being populated into a new realm.

Monitoring Data via Dashboard

Now we are going to monitor and oversee the data through the dashboard that we launched when we started the Realm Object Server. Running the app and dashboard side by side, you can see that when you add an item, it immediately shows up on the dashboard. The same happens when you remove an item, demonstrating that it is indeed real-time.

Realm Object Server

Monitoring Data via Realm Browser

You can also use Realm Browser to monitor your app data. In the previous tutorial, we used Realm Browser to view our on-device data. We can also use it to view Realm Object Server data. 

Launch the app, select Open Sync URL, and type in the location of your remote object server realm (e.g. realm://127.0.0.1:9080/8e090f0fa57366808be106e004800a0f/realmDoApp) along with your username and email. You should get the familiar view we saw in the last tutorial, only this time we are connecting to a real-time back end!

Go ahead and change your properties there, and you should see that reflected in the Dashboard as well as in your app.

To-do app showing reminders

Conclusion & Next Steps 

In this tutorial, you learned how to extend a Realm Mobile Database-powered application—which is very powerful already—with a back-end server solution. All with only a few lines of code. 

In addition to downloading and installing Realm Object Server, we improved our simple reminders app with the following features:

  • a simple authentication mechanism
  • real-time back-end synchronization

Finally, we saw how to monitor live data through the dashboard, as well as through the familiar Realm Object Browser.

The premise of platforms like Realm Object Server is to have developers focus on their client-side code and not worry about the complexities of maintaining a back-end server

We've just scratched the surface in this post. There are lots of documentation and concepts with Realm Object Server, including working with functions to allow for serverless logic triggering. 

Check back here for more posts on back-end services for mobile app development.

  • Android SDK
    Serverless Apps With Firebase Cloud Functions
    Chike Mgbemena
  • Android SDK
    Create an Intelligent App With Google Cloud Speech and Natural Language APIs
    Ashraff Hathibelagal
  • Mobile Development
    Back-End as a Service for Mobile Apps
    Bala Durage Sandamal Siripathi

12:00

Creating a Blogging App Using React, Part 1: User Sign-In

In this tutorial series, you'll see how to get started with creating a blogging app using React. Throughout the course of this tutorial series, you'll be focusing on how to use React for developing the application user interface. You'll be using Node.js for the server side of the application.

In this tutorial, you'll see how to implement the user interface and back end for user registration and user sign-in.

Getting Started

Create a project directory called ReactNodeApp. Navigate to the project directory and initiate the node project.

Fill in the required details and you should have the package.json file created. Here is how it looks:

You'll be using the express framework for serving your application. Install express using the following command:

Using the express framework, let's create our application listening on a port address. Inside the project directory, create a file called app.js. Require the express module inside the app.js and create an app. Set the static path of the application where it can find the static files. Here is how it looks:

Assign a port number for the application to listen on a port. Add the following code to create a server:

Inside the project directory, create a folder called html. Inside the html folder, create a file called index.html. Add the following code to index.html:

Save the above changes and start the server using the following command:

Point your browser to http://localhost:7777/index.html and you should be able to see the index.html page.

Creating the Sign-In View

You'll be using bootstrap to create the user interface. Download and include bootstrap in the index.html page.

Add the required React libraries in the index.html page.

You'll be creating the view using JSX. If you are not familiar with JSX, I would recommend reading an introductory tutorial on React and JSX.

To transform JSX code to JavaScript, you'll need babel, a JavaScript compiler. Include babel in the index.html page.

Create a file called main.jsx inside the html folder. This file will contain the React UI components. 

Let's create a new React component called Signin inside the main.jsx file. 

Add a render method inside the Signin component which will display the UI for our Signin component.

In the above code, it's all HTML with just one difference. The class attribute has been modified to className when used in JSX.

The Signin component, when displayed, will display the HTML code inside the render method. 

Add a container div in the index.html page where you'll render the Signin component.

Render the Signin component inside the .container div in the index.html

Save the above changes and restart the node server. Point your browser to http://localhost:7777/index.html and you should be able to view the sign-in screen.

React Blog App SignIn Screen

Implementing User Sign-In  

To implement the sign-in process, you need to handle the input text onChange event and keep the text box values in a state variable. When the user clicks the button, you'll make use of the state variables to read the email address and password text box values. So, let's add the onChange event to the text boxes:

Define the onChange events in the Signin component:

Bind the above defined events and the state variables in the component constructor method:

Define an onClick method which you'll invoke on button click.

Add the OnClick event to the SignIn button.

Save the above changes and restart the node server. Point your browser to http://localhost:7777/index.html. Enter the email address and password and click the Sign In button, and you should be able to see the email and password pop up.

Posting Data From React to the Node Service 

Once you have the data on the client side, you need to post that data to the Node.js server method to validate the user sign-in. For posting the data, you'll make use of another script called axios. Axios is a promise-based HTTP client for the browser and Node.js. Include axios in the index.html page.

Inside the signin method in the main.jsx file, add the following line of code to make a post request.

The code makes a post request to the /signin method with the parameters shown. Once the request is successful, the promise is resolved in the then callback. On error, the response is logged in the catch callback. 

Let's create a signin method on the Node.js side to validate the user sign-in process. In the app.js file, create a method called signin.

You'll be making use of the body-parser module to parse the request posted from the React client side. Install the body-parser module in the project. 

Require the body-parser module in the app.js file.

Add the following line of code to enable JSON parsing.

Inside the signin method, you can parse the request as shown:

Modify the signin method as shown to validate the user sign-in.

For the time being, the user credentials have been hard-coded. You can replace this with the appropriate service as per your preference.

Once the parameters have been parsed, they are validated against the expected credentials. If true, a success message is passed, else a failure message is returned.

Save the above changes and restart the Node.js server. Enter a valid username and password and click the sign-in method. Based on the credentials, it will return a success or failure message, which will be displayed in the browser console.

Creating the User Registration View

The process of creating the user registration view is quite similar to how you implemented the user sign-in module. Let's start by creating the Signup component in the main.jsx file.

Since sign-up and sign-in are two different components, you need to link the two components. For the purpose of routing, you'll be making use of react-router. If you are new to routing in React, I would recommend reading the React routing tutorial.

Include react-router in the index.html page.

Define the required react-router variables to create links in the main.jsx file.

Define the different application routes and the default route as shown below:

Include a link to the sign-in component in the sign-up component and vice versa. Here is the Signin component's render method with the sign-up link:

Save the above changes and restart the Node.js server. Point your browser to http://localhost:7777/index.html and you should be able to see the sign-in screen with the sign-up link. Click on the sign-up link and you should be navigated to the sign-up screen.

Sign In Screen with Sign Up Link

Implementing user sign-up is similar to how you implemented user sign-in. I'll leave the user sign-up implementation as an exercise. I'll post the user sign-up implementation in the next part of this tutorial series.

Wrapping It Up

In this part of the tutorial series, you created and implemented the Sign In screen. You also saw how to use react-router to implement routing in React. In the next part of this tutorial, you'll see how to implement the Sign Up portion and the Add Post page.

Source code from this tutorial is available on GitHub.

Do let us know your thoughts and suggestions in the comments below.

June 28 2017

16:10

Adding Physics-Based Animations to Android Apps

Animations that feel fluid and realistic tend to make user interfaces more attractive. No wonder Material Design places so much emphasis on them! 

If you've ever tried creating such animations, however, you know that the simple animators and interpolators offered by the Android SDK are often not good enough. That's why recent revisions of the Android Support Library come with a physics module called Dynamic Animation.

With Dynamic Animation, you can create physics-based animations that closely resemble the movements of objects in the real world. You can also make them respond to user actions in real time. In this tutorial, I'll show you how to create a few such animations.

Prerequisites

To follow along, make sure you have the following:

1. Adding Dependencies

To be able to use Dynamic Animation in your project, you must add it as an implementation dependency in your app module's build.gradle file:

In this tutorial, we're going to be animating an ImageView widget. It will, of course, have to display some images, so open the Vector Assets Studio and add the following Material icons to your project:

  • sentiment neutral
  • sentiment very satisfied

Here's what they look like:

Two Material icons

For best results, I suggest you set the size of the icons to 56 x 56 dp.

2. Creating a Fling Animation

When you fling an object in the real world, you give it a large momentum. Because momentum is nothing but the product of mass and velocity, the object will initially have a high velocity. Gradually, however, thanks to friction, it slows down until it stops moving completely. Using Dynamic Animation's FlingAnimation class, you can simulate this behavior inside your app.

For the sake of demonstration, let us now create a layout containing a flingable ImageView widget, displaying the ic_sentiment_neutral_black_56dp icon, and a Button widget users can press to trigger the fling animation. If you place them both inside a RelativeLayout widget, your layout XML file will look like this:

In the above code, you can see that the Button widget has an onClick attribute. By clicking on the red light-bulb icon Android Studio shows beside it, you can generate an associated on-click event handler inside your Activity class:

You can now create a new instance of the FlingAnimation class using its constructor, which expects a View object and the name of an animatable property. Dynamic Animation supports several animatable properties, such as scale, translation, rotation, and alpha.

The following code shows you how to create a FlingAnimation instance that can animate the X-coordinate of our layout's ImageView:

By default, a FlingAnimation instance is configured to use 0 pixels/second as its initial velocity. That means the animation would stop as soon as it's started. To simulate a realistic fling, you must always remember to call the setStartVelocity() method and pass a large value to it.

Additionally, you must understand that without friction, the animation will not stop. Therefore, you must also call the setFriction() method and pass a small number to it.

The following code configures the FlingAnimation instance such that the ImageView is not flung out of the bounds of the user's screen:

At this point, you can simply call the start() method to start the animation.

If you run the app now and press the button, you should be able to see the fling animation.

 

It is worth noting that you don't specify a duration or an end value when creating a physics-based animation—the animation stops automatically when it realizes that its target object is not showing any visible movement on the user's screen.

3. Simulating Springs

Dynamic Animation allows you to easily add spring dynamics to your animations. In other words, it can help you create animations that make your widgets bounce, stretch, and squash in ways that feel natural.

To keep things simple, let's now reuse our layout's ImageView and apply a spring-based animation to it. To allow the user to initiate the animation, however, you'll need to add another Button widget to the layout.

To create a spring-based animation, you must use the SpringAnimation class. Its constructor too expects a View object and an animatable property. The following code creates a SpringAnimation instance configured to animate the x-coordinate of the ImageView:

To control the behavior of a spring-based animation, you'll need a spring. You can create one using the SpringForce class, which allows you to specify the resting position of the spring, its damping ratio, and its stiffness. You can think of the damping ratio as a constant that, like friction, is responsible for slowing the animation down until it stops. The stiffness, on the other hand, specifies how much force is required to stretch the spring.

If all that sounds a bit too complicated, the good news is that the SpringForce class offers several intuitively named constants you can use to quickly configure your spring. For instance, the following code creates a spring that is both very bouncy and very flexible:

In the above code, you can see that we've set the value of the final resting position of the spring to the initial X-coordinate of the ImageView. With this configuration, you can imagine that the ImageView is attached to a tight, invisible rubber band, which quickly pulls the ImageView back to its original position every time it is moved.

You can now associate the spring with the SpringAnimation instance using the setSpring() method.

Lastly, before starting the animation, you must make sure you give it a large initial velocity using the setStartVelocity() method.

If you run the app now, you should see something like this:

 

4. Listening to Animation Events

An animation that's created using the Dynamic Animation library must always be started from the UI thread. You can also be sure that it will start as soon as you call the start() method. However, it runs asynchronously. Therefore, if you want to be notified when it ends, you must attach an OnAnimationEndListener object to it using the addEndListener() method.

To see the listener in action, let's change the Material icon the ImageView displays every time the spring-based animation, which we created in the previous step, starts and ends. I suggest you use the ic_sentiment_very_satisfied_black_56dp icon when the animation starts, and the ic_sentiment_neutral_black_56dp icon when it ends. The following code shows you how:

With the above code, the animation will look like this:

 

5. Animating Multiple Properties

The constructors of both the FlingAnimation and the SpringAnimation classes can only accept one animatable property. If you want to animate multiple properties at the same time, you can either create multiple instances of the classes, which can get cumbersome, or create a new custom property that encapsulates all your desired properties.

To create a custom animatable property, you must create a subclass of the FloatPropertyCompat class, which has two abstract methods: setValue() and getValue(). As you might have guessed, you can update the values of all your desired animatable properties inside the setValue() method. Inside the getValue() method, however, you must return the current value of any one property only. Because of this limitation, you'll usually have to make sure that the values of the encapsulated properties are not completely independent of each other.

For example, the following code shows you how to create a custom property called scale, which can uniformly animate both the SCALE_X and SCALE_Y properties of a widget:

Now that the custom property is ready, you can use it like any other animatable property. The following code shows you how to create a SpringAnimation object with it:

While creating an animation that uses a custom property, it is a good idea to also call the setMinimumVisibleChange() method and pass a meaningful value to it in order to make sure that the animation doesn't consume too many CPU cycles. For our animation, which scales a widget, you can use the following code:

Here's what the custom property animation looks like:

 

Conclusion

You now know the basics of working with Dynamic Animation. With the techniques you learned in this tutorial, you can create convincing physics-based animations in a matter of minutes, even if you have very little knowledge of Newtonian physics.

To learn more about Dynamic Animation, refer to the official documentation. In the meantime, check out some of our other recent posts on Android app development!

  • Android SDK
    Create an Intelligent App With Google Cloud Speech and Natural Language APIs
    Ashraff Hathibelagal
  • Android
    Ensure High-Quality Android Code With Static Analysis Tools
    Chike Mgbemena
  • Android SDK
    Serverless Apps With Firebase Cloud Functions
    Chike Mgbemena
  • Android
    How to Solve Android’s 13 Most Common Error Messages
    Jessica Thornsby

12:00

7 Best Weather WordPress Widgets & Plugins

There are many instances when providing current temperatures and weather forecasts on a website can be useful. Restaurants, retreat centers, country clubs, and many other businesses and organizations can benefit from this kind of feature.

There are a few things you'll want to consider:

  • How does the widget design fit within the current website theme?

Many of the following weather WordPress widgets and plugins have design options built in or can be easily modified to fit your website's design.

  • Does the weather WordPress plugin being considered require another service?

Some weather plugins require the World Weather Online API. Before April 2017, they provided free registered API keys. Now they require a premium subscription.

  • Where will the weather be displayed?

There are a variety of options and features which weather widgets offer. There are some that can only be placed in a widget area, whereas some provide a shortcode option, allowing you to place the weather widget on any page.

Every website has its own unique needs, so you may need to consider additional things as well. Take a look at these 7 best weather WordPress widgets and plugins, and I'm sure you'll find something that will meet your need.

1. Astero WordPress Weather Plugin

The Astero WordPress Weather Plugin includes much of what you'll ever want in a weather WordPress plugin. With its clean lines, multiple sizes and styles, and solid feature set, your weather widget will be looking good, even if the weather isn't.

Astero WordPress Weather Plugin

Some of the technical features include:

  • HTML5 geolocation with IP fallback
  • supports 600+ Google Fonts
  • fully responsive layout
  • local cache
  • and more

And the design features include:

  • use HTML5 video or YouTube for your background
  • or use a static image or flat background
  • simple or full-screen modes
  • unlimited colors
  • and more

As for your weather sources, you can switch between Forecast.io and Openweathermap.org, and users can also leverage the built-in city or zip code search function.

The Astero WordPress Weather Plugin includes excellent features and throws in some impressive design choices, making it a top choice for weather WordPress widgets and plugins.

2. City Weather for WordPress

If you're looking for a nicely designed weather widget that displays the weather for only a predefined location, you might want to give City Weather for WordPress a try. It includes a few basic options and can easily be configured to match just about any design.

City Weather for WordPress

Features included:

  • select a custom background color or use an image
  • supports Fahrenheit and Celsius units
  • select wide or tall widget size
  • fully responsive
  • and more

City Weather for WordPress doesn't include many options, but it's designed well, and it would be perfect for restaurants, country clubs, and other local websites that benefit from users knowing the weather.

3. WeatherSlider Premium WordPress Weather Widget

If you need the weather a little more front and center, then something like the WeatherSlider Premium WordPress Weather Widget is what you want. This weather WordPress widget doesn't just display the current temperature, it's a full-featured weather slider.

WeatherSlider Premium WordPress Weather Widget

The design features include:

  • CSS3 animations with jQuery fallback
  • auto-slideshow and auto-refresh option
  • fully responsive from 240x200 to 1300x600
  • touch control, keyboard navigation, and supported on all major browsers
  • and more

Weather features include:

  • 12 or 24 hour time formats and localization ready
  • display current weather or three-day forecast
  • custom location search bar
  • 48 different weather types
  • and more

You'll also find the detailed documentation and layered graphic elements PSD file very helpful.

Display the weather in style with the WeatherSlider Premium WordPress Weather Widget.

4. aWeather Forecast

The aWeather Forecast weather WordPress plugin displays weather conditions like no other. With its cast of animated icons, animated headers, and full color customization, this is easily one of the most charming weather widgets you'll find.

aWeather Forecast

This widget can display:

  • current weather icon and temperature
  • current weather conditions
  • wind speed and direction
  • pressure, humidity, and more

Some features include, but not limited to:

  • Fahrenheit, Celsius, and Kelvin unit formats
  • 18 animated icons and 4 animated headers
  • select from over 700 Google Fonts
  • and more

The aWeather Forecast plugin is one of the most uniquely designed weather WordPress widgets.

5. Weather WordPress Shortcode & Widget - Simple Weather Plugin

This weather widget can be placed in both widget spaces and via shortcode. Combining this feature with the Weather WordPress Shortcode & Widget - Simple Weather Plugin's sleek design makes it one of the more versatile weather WordPress plugins.

Weather WordPress Shortcode  Widget - Simple Weather Plugin

Some of the great features you'll find include:

  • unlimited color selection and custom date format
  • supports both Fahrenheit and Celsius
  • customize weather update intervals
  • display day and night temperatures
  • location and GPS coordinates
  • seven-day forecast option
  • and more

It's easy to see why the Weather WordPress Shortcode & Widget - Simple Weather Plugin is a favorite among weather WordPress plugins.

6. Weather Widget One

The Weather Widget One weather WordPress plugin is so pretty. Its simple design is a joy to view, and its clever UI makes it very useable. This is clearly one of the best weather WordPress plugins available.

Weather Widget One

Features include, but certainly not limited to:

  • displays temp, wind, humidity, and chance of precipitation
  • auto detect user location via HTML5 Geolocation
  • five-day forecast with 24-hour daily forecast
  • multiple location search options
  • supports multiple units
  • shortcode support
  • and more

With its minimal design and full set of features, the Weather Widget One is an easy favorite among weather WordPress widgets.

7. Bonobo - Weather Widget

This weather WordPress widget is super simple and easy to use. The Bonobo - Weather Widget also boasts a sleek metro style that's minimal and sleek.

Bonobo - Weather Widget

Features include:

  • supports both Fahrenheit and Celsius
  • OpenWeatherMap API
  • multi-language
  • and more 

The included eight color schemes and metro design makes it easy to adapt to your current—or future—WordPress theme.

For a simple, no nonsense weather widget, check out Bonobo - Weather Widget.

BONUS! Weather on Google Maps for WordPress

The Weather on Google Maps for WordPress is not your typical weather WordPress widget, so I consider this to be more of a bonus entry among the other plugins.

Like a TV weather screen, transform Google Maps to an interactive weather map—on your own website.

Weather on Google Maps for WordPress
“Weather on Google Maps is a WordPress plugin, which allows you to easily embed any number of Google Maps with live weather information for any number of cities using simple HTML snippets. You can customize the look and feel of the weather information box via CSS and even choose what data to display.”

Some of the features you'll find here:

  • auto-center of Google Map based cities
  • works with Google Maps API v3
  • weather forecast for four days
  • included weather icons
  • and more

Weather on Google Maps for WordPress is a unique and powerful plugin, combining the power of Google Maps with Yahoo Weather.

Conclusion

Providing weather information for an organization's website can be a super useful feature. It's easy to overlook, but when someone is looking up more information or getting ready to make a booking online, being able to check the forecast can be very helpful.

If you don't see exactly what you're looking for, make sure to check out Envato Tuts+. They have excellent WordPress tutorials, eBooks, and courses. Try WordPress Plugin Development Essentials or maybe the WordPress Hacker's Guide to the Galaxy. Some other helpful eBooks also include Useful Tricks and Techniques for WordPress and Mastering WordPress.

What kind of website will you be using a weather WordPress widget for?

June 27 2017

18:32

Take Our New Course: Get Started With Elixir

Final product image What You'll Be Creating

Do you want to learn the Elixir language? If so, our new course, Get Started With Elixir, is ideal for you.

In this course, experienced instructor Markus Mühlberger will help you learn the Elixir language, starting with Elixir's Ruby-inspired syntax, and moving on to learn how to code distributed and highly concurrent services in the Elixir language.

Elixir website

You can take our new course straight away with a free 10-day trial of our monthly subscription. If you decide to continue, it costs just $15 a month, and you’ll get access to hundreds of courses, with new ones added every week.

 

You can also discover thousands of time-saving code scripts and plugins over on Envato Market, so head over there to see what you can find.

15:40

Code a Real-Time NativeScript App: Geolocation and Google Maps

NativeScript is a framework for building cross-platform native mobile apps using XML, CSS, and JavaScript. In this series, we'll try out some of the cool things you can do with a NativeScript app: geolocation and Google Maps integration, SQLite database, Firebase integration, and push notifications. Along the way, we'll build a fitness app with real-time capabilities that will use each of these features.

In this tutorial, you'll learn how to work with geolocation and Google Maps in NativeScript apps. 

I'm assuming that you already know how to create apps in NativeScript. If you're new to NativeScript, I recommend that you first check out one of the earlier tutorials in NativeScript before trying to follow this tutorial.

What You'll Be Creating

You'll be creating a walking tracker using geolocation and Google Maps. It will show the user how much distance they've covered and the number of steps they've taken to cover that distance. There will also be a map that will show the user's current location.

To give you an idea, here's what the final output will look like:

app final

Setting Up the Project

Start by creating a new NativeScript app:

To make it easier to set up the UI of the app, I've created a GitHub repo which includes both the starter and final version of the project. You can go ahead and copy the contents of the app folder to your project's app folder. We will only be working with two files: main-page.xml and main-page.js file. The rest is just boilerplate from the NativeScript demo project. 

Running the App

We will be using the Android emulator provided by Android Studio to test the app. This will allow us to use the Android GPS Emulator to simulate the changing of locations from the comfort of our own homes. I don't really like aimlessly walking around outside to test geolocation either! But if that's your thing then I won't stop you.

If you execute tns run android, it will automatically call the Android emulator if it's already installed. If it's not yet installed, you can install it by launching Android Studio, clicking configure, and selecting SDK Manager. This will open the SDK Platforms by default. Click on the SDK Tools tab and make sure to select Android Emulator, and click on Apply to install it.

To use the GPS emulator, download it from GitHub and run the executable war file:

Once that's done, you should be able to access http://localhost:8080/gpsemulator/ from your browser and connect to localhost. Make sure that the Android emulator is already running when you do this. Once you're connected, simply zoom in the map and click on any place you want to use as the location. The app will detect this and use it as its current location.

GPS Emulator

Working With Geolocation

Geolocation in NativeScript is similar to the Geolocation API in JavaScript. The only difference in functionality is the addition of a distance() function which is used for calculating the distance between two locations.

Installing the Geolocation Plugin

In order to work with geolocation, you first need to install the geolocation plugin:

Once that's done, you can now include it from your script files:

Getting the User's Current Location

The NativeScript geolocation plugin includes three functions which you can use for working with the user's current location. We will be using each of these in this app:

  • getCurrentLocation
  • watchLocation
  • distance

Open the main-view-model.js file and add the following code inside the createViewModel() function. Here we're initializing the variables that we will be using later on for storing the different values that are needed for keeping track of the user's location. 

I've added some comments in the code so you know what's going on. There are also some lines of code that are commented out; these are for the Google Maps integration. I've commented them out for now to keep things simple. Once we get to the Google Maps integration, you'll need to remove those comments.

Next, add the code for getting the user's current location. This code is executed when the user taps on the button for starting and stopping the location tracking. The geolocation.getCurrentLocation() method is used to get the current location. 

Here we've specified three options: desiredAccuracy, updateDistance, and timeoutdesiredAccuracy allows you to specify the accuracy in meters. It has two possible values: Accuracy.high, which is about 3 meters, and Accuracy.any, which is about 300 meters. updateDistance specifies how much difference (in meters) there must be between the previous location and the current location before it will update. Lastly, timeout specifies how many milliseconds to wait for a location. 

Once a location is received, we set it as the start_location and push it on the locations array. Later on, this location will be used along with the first location that will be fetched from watching the user's current location to determine the distance traveled.

Watching for the User's Current Location

To get the current location, we use the geolocation.watchLocation() function. This function is similar to the setInterval() function in JavaScript, because it also executes the callback function repeatedly until you stop it with the geolocation.clearWatch() function. The callback function is automatically called based on the updateDistance and minimumUpdateTime

In the code below, the location will be updated if it is at least 5 meters different from the previous location that was fetched. But this update will only happen every 5 seconds. This means that if the user hasn't walked 5 meters or more within 5 seconds, the location won't update. 

Once the user indicates that they want to stop tracking, you need to call the geolocation.clearWatch() function. You also need to reset the rest of the values that are being updated every time the location is changed. 

Getting the Distance Between Two Locations

Now we're ready to get the distance. This can be done by calling the geolocation.distance() function. This function accepts two location objects as its arguments, so we'll use the last two locations that were pushed to the locations array to determine the distance (in meters) traveled by the user from a previously recorded location to the current one. From there, we can use an approximate conversion from meters to the number of steps—I say approximate because not all people will travel the same distance in a single step. 

After that, we can just add the resulting distance and steps to the total_distance and total_steps so we can keep track of the total distance and steps they have taken since they started tracking their location.

At this point, you can now start testing the app using the GPS emulator that I mentioned earlier. Do note that you need to hit save on the main-view-model.js file to trigger an app reload. 

Then pick a location in the GPS emulator so that a fresh location will be fetched by the app once it loads. If you don't do this, it will default to the Googleplex location in Mountain View, California. This means that the next time you pick a location on the emulator, it will jump from this location to the location that you picked. If it's far away then you'll get a really large number for the distance and steps. 

Alternately, you could test on a real device with internet and GPS enabled. Only GPS is required at this point, but once we add Google Maps, the app will need an internet connection.

Working With Google Maps

We will now use Google Maps to add a map that shows the user's current location.

Installing the Google Maps Plugin

Once installed, you need to copy the template string resource files for Android:

Next, open the app/App_Resources/Android/values/nativescript_google_maps_api.xml file and add your own Google Maps API key (server key):

Make sure that you have enabled the Google Maps Android API from the Google Console before you try to use it.

Adding the Map

For the map, open the main-page.xml file and you should see the following:

Here we've specified three options (longitudelatitude, and zoom) and a function to execute once the map is ready. longitude and latitude specify the location you want to render in the map. The zoom specifies the zoom level of the map. mapReady is where we specify the function for adding the marker on the map. This marker represents the user's current location, so it will be rendered at the center of the map.

By default, this won't work as you haven't added the schema definition for the maps yet. So in your Page element, add the definition for the maps element:

Once that's done, a Google map instance should be rendered right below the button for tracking location. It won't have any maps yet since the latitude and longitude haven't been specified yet. To do that, go back to the main-view-model.js file and remove the comments for the lines of code for working with Google Maps:

Adding the Marker

Since we've already declared default coordinates for the marker, we can actually plot a marker once the map is ready:

Next, we need to update the marker position once the user starts tracking their location. You can do that inside the success callback function for the getCurrentLocation() function:

We also need update it when the user's location is updated (inside the success callback function for watchLocation):

Once that's done, a map which renders the default location should show in the app.

Conclusion

In this tutorial, you've created a NativeScript app that allows the user to track how much distance they have covered and the approximate number of steps they've taken to cover that distance. You've also used Google Maps to let the user view their current location. By doing so, you've learned how to use the geolocation and Google Maps plugins for NativeScript.

This is just the start! In the next posts of this series, we'll add a local database, push notifications and other cool features to our app.

In the meantime, check out some of our other posts on NativeScript and cross-platform mobile coding.

  • Mobile App
    Create a Weather App With TypeScript and NativeScript
    Wernher-Bel Ancheta
  • Mobile Development
    Introducing Vue and Weex for Native Mobile Apps
    Lawrence Turton
  • Ionic
    Get Started With Ionic Services: Auth
    Wernher-Bel Ancheta

For a comprehensive introduction to NativeScript, try our video course Code a Mobile App With NativeScript. In this course, Keyvan Kasaei will show you step by step how to build a simple application. Along the way, you'll learn how to implement a simple app workflow with network requests, an MVVM architecture, and some of the most important NativeScript UI components. By the end, you'll understand why you should consider NativeScript for your next mobile app project.

 

12:00

Create a Mobile Application for Displaying Your Website RSS Content With Ionic

Final product image What You'll Be Creating

In this tutorial we will take a look at creating a mobile application which displays the RSS content of a website. We will configure the RSS URL and the application will download it, parse it and display the posts from the RSS. 

To create the mobile application, we will use the Ionic Framework v1 together with AngularJS. To complete this tutorial, you need to have some experience with JavaScript and HTML. Also, it helps if you've worked with AngularJS before. 

If you have never worked with Ionic Framework before, I recommend at least taking a look at the Getting Started guide as it gives you a quick insight into how things work.

Let's begin!

Setting Up the Ionic Project

I will assume that you have installed Node on your system and you also have the npm (the Node package manager). Installing the Ionic framework is as easy as running the following:

This will install both Cordova and Ionic on your computer. 

Cordova is the core technology for Ionic, and basically it allows us to have an embedded browser in our mobile application. In that browser we will be able to run all our HTML and JavaScript code. This is called a hybrid mobile application, as the application does not run native code, but runs inside the browser. 

Next to Cordova, Ionic adds to that the possibility of using AngularJS for writing our code, and it also adds a very neat UI framework.

With Ionic in place, we can create our project using the Ionic CLI, a very useful command-line tool. Ionic provides three default project templates which can be used as a starting point:

  • blank: as the name says, it's an empty project with only the minimal necessary components in place.
  • tabs: an application using tabs for navigating through its screens.
  • sidemenu: an application using a standard mobile side menu for navigation.

For this tutorial, we will be using the tabs application template. To start our project, let's run:

Ionic will download and install all components needed, and it will create the project folder named myWebsiteOnMobile. Go into the project directory by running:

Because our application is a hybrid mobile application, we have the advantage of being able to run the application inside a browser. To do this, Ionic provides a neat built-in web server which runs our application like this:

This will open a browser with our application loaded, and it will look like this:

The Ionic homescreen

To stop the server, use Control-C on your command-line screen. To get a better idea of how the application looks on a mobile, you can use:

This will open the application in the browser, showing an iOS and an Android preview of the app side by side.

The iOS and Android Preview

The tabs Ionic application template has three tabs: Status, Chats, and Account. In the next steps we will adjust the application to fit our needs.

How to Adjust the Default Ionic Tabs Template Application

For our application we will have two tabs:

  • Latest posts: showing a list of latest posts retrieved from the RSS feed.
  • Settings: where the user will be able to configure several aspects of the application.

From the Latest posts tab, the user will be able to click on any of the latest posts and see more information about the post, with the possibility of opening up the post in an external browser.

Since our Latest posts tab is similar to the Chats tab provided by the template, we will reuse that together with the Account tab, which will become our Settings tab. We can do all modifications with the Ionic webserver running, and Ionic will reload the app for us. This is a very neat feature which will speed up development.

As mentioned before, Ionic uses AngularJS, and the whole application is actually an AngularJS module. The module is defined in www/js/app.js, and here is also where the paths or routes of the application are defined. Each screen of the application has a corresponding route.

Let's remove the Status tab since we will not need it. To do this, we first need to change the default screen (or route) of our application to point to the Chats screen, which will become our main screen. The default screen is configured via $urlRouterProvider.otherwise(), so let's change that to:

If we now reload http://localhost:8100 in our browser, we will see that the Chats tab will be loaded by default.

To remove the Status tab, we need to edit the www/templates/tabs.html file that holds the template for the tab component. We will remove the element:

When saving, we will see that the application now has only two tabs: Chats and Account.

While in the www/templates/tabs.html file we notice that there are some HTML tags that are not standard HTML, like ion-tabs, ion-tab, and ion-nav-view. These are actually AngularJS directives defined by the Ionic Framework. The directives are tags that pack functionality behind them, and they are very convenient ways to write more structured and more concise code.

In our case, the ion-tabs directive is the tabs component, which for each tab requires an ion-tab directive.

Let's change our tabs from Chat and Account to our required names Latest posts and Settings. To do this, we will modify several things in the www/templates/tabs.html file:

  • title attribute of the ion-tab elements which determines the text on the tab button. We will change that to Latest posts and Settings respectively.
  • href attribute of the ion-tab elements which points to the route or screen URL. We will change those to #/tab/latest-posts and #/tab/settings.
  • name attribute of the ion-nav-view elements to tab-latest-posts and tab-settings. These are the identifiers for the view templates used for the Latest posts and Settings screens.

As a result, www/templates/tabs.html should look like this:

After making these changes, we will get some errors. This is because we also have to adjust our routes to use the new identifiers we have used. In www/js/app.js, we need to change the state identifiers, the view identifiers and the url for each route according to what we have set above.

For each route (or screen), there is a controller defined. This is a basic MVC (Model-View-Controller) design pattern. Controllers are defined within the file www/js/controllers.js. For consistency purposes, we will change the names of the controllers in both www/js/app.js and www/js/controller.js:

  • ChatsCtrl becomes LatestPostsCtrl.
  • ChatDetailCtrl becomes PostDetailCtrl.
  • AccountCtrl becomes SettingsCtrl.

Also, for each route we have a view template defined, so let's change them too. Edit www/js/app.js and modify templateUrl like this:

  • Change tab-chats.html to tab-latest-posts.html. Also rename the file www/templates/tab-chats.html to www/templates/tab-latest-posts.html.
  • Change chat-detail.html to post-detail.html. Also rename the file www/templates/chat-detail.html to www/templates/post-detail.html.
  • Change tab-account.html to tab-settings.html. Also rename the file www/templates/tab-account.html to www/templates/tab-settings.html.
  • Finally, change the view that gets loaded by default to latest-posts by using $urlRouterProvider.otherwise('/tab/latest-posts').

If all went well then you should end up with the www/js/app.js file looking like this:

And our cleaned up www/js/controllers.js file looks like this:

Now that we have restructured the app to fit our needs, let's move on to the next part and add some functionality.

How to Retrieve an RSS Feed With Ionic

In order to display the list of latest posts, our application will need to retrieve the RSS feed from a URL. As a best practice, it is advisable that this kind of functionality reside in the service layer of the application. In this way we can use it more easily in our controller and then present it to the user by using a view.

The RSS service will make use of Yahoo's YQL REST API to retrieve the RSS of our website. To call on the REST API, we will use the $http provider offered by AngularJS.

Ionic services are usually defined in the www/js/services.js file, so that's where we will put ours too. The code will look like this:

We declare the service using the service() method provided by AngularJS. We then inject Angular's $http module so we can call it in our service.

The self variable is a reference to the RSS service so that we can call it from within the service's methods. The main method of the service is the download() method, which downloads the feed information and processes it. There are two main formats used for website feeds: RSS and ATOM. For our application, we have used the feed of tutorials from Tuts+ https://tutorials.tutsplus.com/posts.atom which is in ATOM format, but for completeness we have taken into account the RSS format too.

The download() method calls on the YQL API and parses the results using the parseAtom() or the parseRSS() methods depending on the type of feed. The idea here is to have the same output format which will be passed further via the callback next(). With the RSS service in place, we can move on to the controller.

Hooking the RSS Service to the Latest Posts Controller

In our www/js/controllers.js file, we need to load the RSS data and pass it to our view. To do that, we only need to modify our LatestPostsCtrl controller like this:

Using Angular's dependency injection mechanism, we only need to specify the $scope and RSS variables as method parameters, and it will know how to load those modules. The $scope module allows us to set variables on the model bound to the view. Any values set in the scope can be then retrieved and displayed inside the view associated with the controller.

When the view for latest posts is loaded, it will call on the LatestPostsCtrl controller, and this in turn will use the RSS service to download the feed information. The results are parsed and passed back as an array using the posts variable, which we store in the current scope.

With all that out of the way, we can now move on to the view part, displaying the list of posts retrieved from the feed.

Hooking the Latest Posts View to the Feed Data

We now need to modify our view for the latest posts. If you remember, this is configured in the www/js/app.js file via the templateUrl attribute, and it points to the www/templates/tab-latest-posts.html file.

What we will want to do is display the list of feeds. Since the feed information may contain HTML, and this will only clutter the list of latest posts, we need something to extract the text without the HTML tags from a post's content. The easiest way to do that is by defining an AngularJS filter that strips the HTML tags from text. Let's do that in www/js/services.js by adding:

No back to our view inside the www/templates/tab-latest-posts.html file, let's modify it to look like this:

We are using the Ionic list UI component together with Angular's ng-repeat directive, which will iterate through the posts set on the scope of our controller. For each post entry, we will have a list item with its title and with the description stripped of HTML tags by the use of the htmlToPlaintext filter. Also note that clicking a post should take us to the detail of the post because of the href attribute set to #/tab/latest-posts/{{post.id}}. That does not work yet, but we will take care of that in the next section.

If we now run the application using ionic serve --lab, we should get something like this:

Viewing Latest Posts

Showing the Details of a Post

When clicking on a post in the list, we go to the post details screen of the application. Because each screen of the application has its own controller and therefore its own scope, we can't access the list of posts to display a specific post. We can call the RSS service again, but that would be inefficient.

To solve this problem, we can make use of the $rootScope directive offered by Angular. This references a scope that overarches all controllers in the application. Let's modify our LatestPostCtrl to set the posts in the $rootScope and then search for the specific post that the user clicked in the PostDetailCtrl. The resulting code in www/js/controllers.js will look like this:

We simply injected $rootScope in both controllers and used it for passing posts between the two controllers. Please note that we don't need to make any changes in our latest posts view as $rootScope and $scope are both accessible in the same way from the view.

Inside the PostDetailCtrl controller, we simply search for the post with the id passed in the link clicked by the user. We do that by comparing each post ID with the value in the URL passed via the $stateParams.postId variable. If we find a match then we set the post on the scope so we can use it in our view.

Let's now adjust our post detail view www/templates/post-detail.html like this:

This is what we have done in the view:

  • We have placed the title of the post in the header of the screen.
  • We have placed an "Open" button in the header on the right. This button will open the post link in an external browser because of the attribute target="_system". We have to do this because the application is already running in a browser due to Cordova. If we didn't set that attribute, the post would have opened in the same browser as the application, and then we would not have a way to return to the application.
  • We display the description of the post as HTML by using Angular's ng-bind-html directive.

While running the application, I noticed that if the post description contains images, some of them fall off the screen. This might be the case with other HTML elements like videos. We can easily fix this by adding the following CSS rule in www/css/style.css.

If we now take a look at the application and click on one of the posts, we should see something like this:

Seeing posts for Tuts articles

And our application is almost complete. In the next section, we will take a look at implementing the settings screen.

Adding Settings for Our Ionic Application

For our settings screen, we will implement a way to indicate how many posts to display on the main screen of the application. We will store this setting in the localStorage memory, which is not erased when the application is closed. Let's edit the controllers file www/js/controllers.js and change the SettingsCtrl controller like this:

Also, we need to modify the settings screen in www/templates/tab-settings.html like this:

The controller retrieves the setting myWebsiteOnMobile.maxPosts from the localStorage. If it does not exist, it will be null, and we will consider that there is no limit for the maximum number of posts.

We call the $scope.$watch() method to monitor changes of the settings.maxPosts variable, which is bound to the radio control in the settings screen.

With all this in place, every time we change the maximum number of posts on the settings screen, the setting will be stored in the localStorage, and it will be retrieved from there when the application restarts.

Now let's make use of this setting. This is as simple as adding this in the LatestPostsCtrl from www/js/controllers.js:

And adding a directive in the latest posts screen www/templates/tab-latest-posts.html:

Notice the limitTo:maxPosts Angular filter. This will limit the number of posts displayed to the number taken from the localStorage. By default, this will be null, which will display all the feeds retrieved by the RSS service.

Congratulations! We now have a fully working application displaying an RSS feed.

Conclusion

In this tutorial, we have seen how to create a hybrid mobile application using the Ionic Framework and AngularJS. There is only one more thing to do: run the application on a mobile device or mobile emulator. This is very simple with Ionic. To run the application on an Android emulator, just run:

If you want to download a premade Ionic application template for transforming any website to a mobile application, try the Website to Mobile Ionic Application Template from CodeCanyon.

An application template on CodeCanyon

June 26 2017

17:59

What Are Dictionary Comprehensions in Python?

 

Recently, we looked at list comprehensions in Python. Similar to its sibling the list comprehension, a dictionary comprehension is nothing more than a shorthand way of creating a new dictionary collection. While it may seem a little more complicated than the list version, it is actually quite simple to understand. 

In this video tutorial from my course on Data Handling With Python, I'll show you exactly what dictionary comprehensions are and how you can use them.

Dictionary comprehensions in Python

Watch the Full Course

Do you want to learn Python in depth? If so, the full course, Data Handling With Python, is for you. It goes beyond the basics and takes you through Python data management in detail. Beyond comprehensions, we'll also look at map, filter, lambdas, and generators, as well as reading and writing to files and complex objects. 

And if you want something even more comprehensive, try my seven-hour course Learn to Code With Python, which includes the lessons on data management but also covers a whole lot more aspects of the Python language.

12:00

How to Deploy a WordPress Plugin From TravisCI to WordPress.org

Not everyone likes subversion. If you use Git to manage WordPress plugin development, keeping your Git repo and the WordPress.org SVN repo in sync is tedious. Luckily, we can use TravisCI deployment provider to automate SVN deployment after tests.

Prerequisites

You need these before moving on:

  1. GitHub account
  2. TravisCI account
  3. Plugin source code
  4. WordPress.org plugin SVN repo (You get this after plugin review approval.)

First Push to GitHub

In order to use TravisCI, we have to host the plugin repository on GitHub.

First, create a new repository on GitHub by going to this page and filling in the repository name.

create new GitHub repository GitHub new repository page

Then, we are going to commit all plugin files into Git and push it to this GitHub repository. Remember to replace the remote URL with yours.

Connecting TravisCI

Connect your GitHub repository with TravisCI by going to your TravisCI account page and switching on your repository. Click Sync account in the upper right corner if your newly created repository doesn't show up in the list.

TravisCI account settings

You're all set. Every time you push new commits or someone makes pull requests to GitHub, it will trigger a build on TravisCI.

First Build on TravisCI

TravisCI uses a YAML file named .travis.yml in the root of your repository to customize the builds. Learn more from the build customizing document to see how you can control the build lifecycle.

This is a basic configuration file that instructs TravisCI to run builds on PHP 7.0 and 7.1. Since testing is out of the scope of this tutorial, I replaced the actual test commands with echo 'Tested'

Commit this file and push it to GitHub. TravisCI builds will be triggered automatically.

TravisCI current build

Adding Deployment Provider Configuration

Deployment providers run if the tests passed and pre-defined conditionals (the on section) are met. TravisCI provides nearly 40 official deployment providers. Sadly, none of them support WordPress.org subversion repositories. Thus, I made my own custom provider. You can find it on GitHub and its pull request.

To use it, add these lines to the end of .travis.yml.

Configuration Explanation

before_deploy

The before_deploy section copies three files into the build directory which is to be checked into the WordPress.org subversion repository. In the real world, this is where you want to run gulp or grunt tasks to prepare the production-ready plugin. 

Don't copy test files or any unnecessary files into build as the whole build directory is released to users, and users don't need your test files.

provider and edge

We tell TravisCI to install my provider from the add-wordpress-plugin-deployment branch https://github.com/TypistTech/dpl. Once the pull request has been merged, the edge part is unnecessary.

on

The on section controls whether a deployment should be performed. Deployment is triggered only when all requirements are met.

In the above example, we deploy to WordPress.org only when:

  1. it's a PHP 7.1 build
  2. it's a tagged commit
  3. it's triggered by the TangRufus/tutsplus-dpl-demo repo (forks and pull requests would not trigger deployment)

slug

The plugin's slug. 

If your plugin's URL is https://wordpress.org/plugins/my-awesome-plugin/, then my-awesome-plugin is the plugin's slug. 

username

Your WordPress.org account username with which you submitted the plugin for review approval.

password

The password of the WordPress.org account. Never save this password in the .travis.yml in plain text!

In the above example, we use the $WORDPRESS_ORG_PASSWORD environment variable, which can be set on the TravisCI web dashboard. Choose Settings from the cog menu, and click on Add in the Environment Variables section. Never enable the "Display value in build log" option!

TravisCI-environment-variables-settings

build_dir

Everything in this directory will be committed to the WordPress.org subversion repository, i.e. will be included in the downloadable zip file. 

We set this to build because we have copied plugin files into build during before_deploy.

Tagging

Assume that we have fixed some bugs and are ready to publish a new version to WordPress.org.

These commands commit the changes to the master branch but do not trigger a deployment:

Only tagged commits trigger deployment:

Results

Head back to TravisCI and open the PHP 7.1 build log. You should see a deployment is logged.

And on the WordPress.org trac (https://plugins.trac.wordpress.org/browser/<your-plugin-slug>):

WordPress plugin subversion trac

Caveats

svn commit Twice

Since TravisCI ships with an old version of subversion which doesn't play well with subdirectories, I do svn commit twice.

The first svn commit removes everything inside trunk. The second svn commit copies everything from build_dir to trunk.

Experimental

This provider is still experimental and is not merged to TravisCI's official repo yet. You can keep track of TravisCI's feedback on its pull request.

Using edge doesn't merge my branch into the upstream master. There is a chance that my branch is behind the official repo. When it happens, you can fork my branch and rebase it, and then change source in .travis.yml to your GitHub repository.

Wrapping Up

To use this deployment provider:

  1. Host the plugin repository on GitHub.
  2. Connect GitHub and TravisCI.
  3. Add the configuration to .travis.yml.
  4. Push a tag.

I hope all the above helps you deploy plugins to WordPress.org faster. 

WordPress has an incredibly active economy. There are themes, plugins, libraries, and many other products that help you build out your site and project. The open-source nature of the platform also makes it a great option for you to improve your programming skills. Whatever the case, you can see everything we have available in the Envato Marketplace.

Thanks for reading!

06:57

Now Available on Envato Elements: Unlimited Stock Photos

Welcome to unlimited stock photos on Envato Elements!

If you're already an Elements subscriber, you'll now see that, along with all the graphics, fonts, web templates, 3D models and everything else you've been used to downloading, you have unlimited access to over 240,000 high-quality stock images. Enjoy!

If you're not an Elements subscriber, here's how it works. For a single monthly subscription of US$29, you get unlimited downloads from a broad and highly curated selection of:

  • graphics (vectors, icons, patterns, textures, illustrations and more)
  • add-ons (think Photoshop and Illustrator actions, Lightroom presets, etc.)
  • fonts
  • graphic templates (logos, infographics, product mockups, etc.)
  • presentation templates (Keynote and PowerPoint)
  • web templates (landing pages, full websites, email newsletters, etc.)
  • CMS templates (Shopify, Magento, OpenCart, and a lot more)
  • 3D models

Oh, and you also get free access to over 1,000 courses and 170 eBooks here on Envato Tuts+, as well as free AND CO membership to help you with invoicing and contracts. 

And because all of that just wasn't enough, now you get almost a quarter of a million stock photos too.

Stock photo on Envato Elements Workplace image from Envato Elements

Why Envato Elements?

Of course, there are loads of stock photo sites out there already, both free and paid. So why should you bother with Envato Elements? Here are a few reasons:

1. Get Premium Quality

On some other stock photo sites, the emphasis is on quantity: thousands of people uploading millions of images, with little quality control. On Envato Elements, the collection is carefully curated to make sure you have access to the very best images, without having to wade through tons of mediocre ones.

Photography image on Envato Elements Photography image on Envato Elements

2. Get Broad Commercial Rights

No matter whether you're using photos for a website, an artwork, a client project or a professional document, you need to know that you have the right to use those images and won't get sued for copyright infringement. All the items on Envato Elements come with a simple, easy-to-understand commercial license, so that you can use them in your projects with confidence—and without having to squint at a mass of small print.

Happy couple image on Envato Elements Happy couple image on Envato Elements

3. Find Exactly What You Need

Elements offers some useful filters to help you find what you need quickly and effectively. You can search by subject, of course, but you can also filter for image orientation (landscape, portrait, or square) and for the predominant colours in the image. So you can find images that not only convey the right message, but also fit seamlessly with your overall design.

Image of Tuscany from Envato Elements Image of Tuscany from Envato Elements

4. Get a Lot of Other Stuff Too

As I mentioned above, you get a ton of other useful things bundled with an Elements subscription. There are no usage limits, no credits to keep track of. You just use as many photos, templates, fonts and graphics as you need for the projects you're working on. So whether you're a web designer, a developer, an artist a businessperson or a freelancer in a number of creative fields, you'll be able to get good value out of an Elements subscription.

Food image on Envato Elements Food image on Envato Elements

What to Do Next

To learn more about the new selection of photos, head over to Envato Elements. You can browse the full selection of items even if you don't have an account, so take a look around to get an idea of what's on offer and decide whether it would be useful for you.

Keep in mind that Envato Elements is expanding all the time, both in terms of the number of categories being offered and the number of items in each category. So this is a subscription that's only going to get more valuable over time.

June 23 2017

14:34

Securing iOS Data at Rest: Encryption

In this post, we'll look at advanced uses of encryption for user data in iOS apps. We'll start with a high-level look at AES encryption, and then go on to look at some examples of how to implement AES encryption in Swift.

In the last post, you learned how to store data using the keychain, which is good for small pieces of information such as keys, passwords, and certificates. 

  • iOS SDK
    Securing iOS Data at Rest: The Keychain
    Collin Stuart

If you are storing a large amount of custom data that you want to be available only after the user or device authenticates, then it's better to encrypt the data using an encryption framework. For example, you may have an app that can archive private chat messages saved by the user or private photos taken by the user, or which can store the user's financial details. In these cases, you would probably want to use encryption.

There are two common flows in applications for encrypting and decrypting data from iOS apps. Either the user is presented with a password screen, or the application is authenticated with a server which returns a key to decrypt the data. 

It's never a good idea to reinvent the wheel when it comes to encryption. Therefore, we are going to use the AES standard provided by the iOS Common Crypto library.

AES

AES is a standard that encrypts data given a key. The same key used to encrypt the data is used to decrypt the data. There are different key sizes, and AES256 (256 bits) is the preferred length to be used with sensitive data.

RNCryptor is a popular encryption wrapper for iOS that supports AES. RNCryptor is a great choice because it gets you up and running very quickly without having to worry about the underlying details. It is also open source so that security researchers can analyze and audit the code.  

On the other hand, if your app deals with very sensitive information and you think your application will be targeted and cracked, you may want to write your own solution. The reason for this is that when many apps use the same code, it can make the hacker's job easier, allowing them to write a cracking app that finds common patterns in the code and applies patches to them. 

Keep in mind, though, that writing your own solution only slows down an attacker and prevents automated attacks. The protection you are getting from your own implementation is that a hacker will need to spend time and dedication on cracking your app alone. 

Whether you choose a third-party solution or choose to roll your own, it's important to be knowledgeable about how encryption systems work. That way, you can decide if a particular framework you want to use is really secure. Therefore, the rest of this tutorial will focus on writing your own custom solution. With the knowledge you'll learn from this tutorial, you'll be able to tell if you're using a particular framework securely. 

We'll start with the creation of a secret key that will be used to encrypt your data.

Create a Key

A very common error in AES encryption is to use a user's password directly as the encryption key. What if the user decides to use a common or weak password? How do we force users to use a key that is random and strong enough (has enough entropy) for encryption and then have them remember it? 

The solution is key stretching. Key stretching derives a key from a password by hashing it many times over with a salt. The salt is just a sequence of random data, and it is a common mistake to omit this salt—the salt gives the key its vitally important entropy, and without the salt, the same key would be derived if the same password was used by someone else.

Without the salt, a dictionary of words could be used to deduce common keys, which could then be used to attack user data. This is called a "dictionary attack". Tables with common keys that correspond to unsalted passwords are used for this purpose. They're called "rainbow tables".

Another pitfall when creating a salt is to use a random number generating function that was not designed for security. An example is the rand() function in C, which can be accessed from Swift. This output can end up being very predictable! 

To create a secure salt,  we will use the function SecRandomCopyBytes to create cryptographically secure random bytes—which is to say, numbers that are difficult to predict. 

To use the code, you'll need to add the following into your bridging header:
#import <CommonCrypto/CommonCrypto.h>

Here is the start of the code that creates a salt. We will add to this code as we go along:

Now we are ready to do key stretching. Fortunately, we already have a function at our disposal to do the actual stretching: the Password-Based Key Derivation Function (PBKDF2). PBKDF2 performs a function many times over to derive the key; increasing the number of iterations expands the time it would take to operate on a set of keys during a brute force attack. It is recommended to use PBKDF2 to generate your key.

Server-Side Key

You may be wondering now about the cases where you don't want to require users to provide a password within your app. Perhaps they are already authenticating with a single sign-on scheme. In this case, have your server generate an AES 256-bit (32 byte) key using a secure generator. The key should be different for different users or devices. On authenticating with your server, you can pass the server a device or user ID over a secure connection, and it can send the corresponding key back. 

This scheme has a major difference. If the key is coming from the server, the entity that controls that server has the capacity to be able to read the encrypted data if the device or data were ever obtained. There is also the potential for the key to be leaked or exposed at a later time. 

On the other hand, if the key is derived from something only the user knows—the user's password—then only the user can decrypt that data. If you are protecting information such as private financial data, only the user should be able to unlock the data. If that information is known to the entity anyway, it may be acceptable to have the server unlock the content via a server-side key.

Modes and IVs

Now that we have a key, let's encrypt some data. There are different modes of encryption, but we'll be using the recommended mode: cipher block chaining (CBC). This operates on our data one block at a time. 

A common pitfall with CBC is the fact that each next unencrypted block of data is XOR’d with the previous encrypted block to make the encryption stronger. The problem here is that the first block is never as unique as all the others. If a message to be encrypted were to start off the same as another message to be encrypted, the beginning encrypted output would be the same, and that would give an attacker a clue to figuring out what the message might be. 

To get around this potential weakness, we'll start the data to be saved with what is called an initialization vector (IV): a block of random bytes. The IV will be XOR’d with the first block of user data, and since each block depends on all blocks processed up until that point, it will ensure that the entire message will be uniquely encrypted, even if it has the same data as another message. In other words, identical messages encrypted with the same key will not produce identical results. So while salts and IVs are considered public, they should not be sequential or reused. 

We will use the same secure SecRandomCopyBytes function to create the IV.

Putting It All Together

To complete our example, we'll use the CCCrypt function with either kCCEncrypt or kCCDecrypt. Because we are using a block cipher, if the message doesn’t fit nicely into a multiple of the block size, we will need to tell the function to automatically add padding to the end. 

As usual in encryption, it is best to follow established standards. In this case, the standard PKCS7 defines how to pad the data. We tell our encryption function to use this standard by supplying the KCCOptionPKCS7Padding option. Putting it all together, here is the full code to encrypt and decrypt a string.

And here is the decryption code:

Finally, here is a test to ensure that data is decrypted correctly after encryption:

In our example, we package all the necessary information and return it as a Dictionary so that all the pieces can later be used to successfully decrypt the data. You only need to store the IV and salt, either in the keychain or on your server.

Conclusion

This completes the three-part series on securing data at rest. We have seen how to properly store passwords, sensitive pieces of information, and large amounts of user data. These techniques are the baseline for protecting stored user information in your app.

It is a huge risk when a user's device is lost or stolen, especially with recent exploits to gain access to a locked device. While many system vulnerabilities are patched with a software update, the device itself is only as secure as the user's passcode and version of iOS. Therefore it is up to the developer of each app to provide strong protection of sensitive data being stored. 

All of the topics covered so far make use of Apple's frameworks. I will leave an idea with you to think about. What happens when Apple's encryption library gets attacked? 

When one commonly used security architecture is compromised, all of the apps that rely on it are also compromised. Any of iOS's dynamically linked libraries, especially on jailbroken devices, can be patched and swapped with malicious ones. 

However, a static library that is bundled with the binary of your app is protected from this kind of attack because if you try and patch it, you end up changing the app binary. This will break the code signature of the app, preventing it from being launched. If you imported and used, for example, OpenSSL for your encryption, your app would not be vulnerable to a widespread Apple API attack. You can compile OpenSSL yourself and statically link it into your app.

So there is always more to learn, and the future of app security on iOS is always evolving. The iOS security architecture even now supports cryptographic devices and smart cards! In closing, you now know the best practices for securing data at rest, so it's up to you to follow them!

In the meantime, check out some of our other content about iOS app development and app security.

  • Security
    How to Hack Your Own App
    Tanya Janca
  • iOS
    Go Further With Swift: Animation, Networking, and Custom Controls
    Markus Mühlberger
  • Swift
    Swift From Scratch: Delegation and Properties
    Bart Jacobs

12:00

How to Work With Elixir Comprehensions

Elixir is a very young programming language (emerged in 2011), but it is gaining popularity. I was initially interested in this language because when using it you can look at some common tasks programmers usually solve from a different angle. For instance, you can find out how to iterate over collections without the for cycle, or how to organize your code without classes.

Elixir has some very interesting and powerful features that may be hard to get your head around if you came from the OOP world. However, after some time it all starts to make sense, and you see how expressive the functional code can be. Comprehensions are one such feature, and this article I will explain how to work with them.

Comprehensions and Mapping

Generally speaking, a list comprehension is a special construct that allows you to create a new list based on existing ones. This concept is found in languages like Haskell and Clojure. Erlang also presents it and, therefore, Elixir has comprehensions as well.

You might ask how comprehensions are different from the map/2 function, which also takes a collection and produces a new one? That would be a fair question! Well, in the simplest case, comprehensions do pretty much the same thing. Take a look at this example:

Here I am simply taking a list with three numbers and producing a new list with all the numbers multiplied by 2. The map call can be further simplified as Enum.map( &(&1 * 2) ).

The do_something/1 function can now be rewritten using a comprehension:

This is what a basic comprehension looks like and, in my opinion, the code is a bit more elegant than in the first example. Here, once again, we take each element from the list and multiply it by 2. The el <- list part is called a generator, and it explains how exactly you wish to extract the values from your collection.

Note that we are not forced to pass a list to the do_something/1 function—the code will work with anything that is enumerable:

In this example, I am passing a range as an argument.

Comprehensions work with binstrings as well. The syntax is slightly different as you need to enclose your generator with << and >>. Let's demonstrate this by crafting a very simple function to "decipher" a string protected with a Caesar cipher. The idea is simple: we replace each letter in the word with a letter a fixed number of positions down the alphabet. I'll shift by 1 position for simplicity:

This is looking pretty much the same as the previous example except for the << and >> parts. We take a code of each character in a string, decrement it by one, and construct a string back. So the ciphered message was "elixir"!

But still, there is more than that. Another useful feature of comprehensions is the ability to filter out some elements.

Comprehensions and Filtering

Let's further extend our initial example. I am going to pass a range of integers from 1 to 20, take only the elements that are even, and multiply them by 2:

Here I had to require the Integer module to be able to use the is_even/1 macro. Also, I am using Stream to optimize the code a bit and prevent the iteration from being performed twice.

Now let's rewrite this example with a comprehension again:

So, as you see, for can accept an optional filter to skip some elements from the collection.

You are not limited to only one filter, so the following code is legit as well:

It will take all even numbers less than 10. Just don't forget to delimit filters with commas.

The filters will be evaluated for each element of the collection, and if evaluation returns true, the block is executed. Otherwise, a new element is taken. What's interesting is that generators can also be used to filter out elements by using when:

This is very similar to what we do when writing guard clauses:

Comprehensions With Multiple Collections

Now suppose we have not one but two collections at once, and we'd like to produce a new collection. For example, take all even numbers from the first collection and odd from the second one, and then multiply them:

This example illustrates that comprehensions may work with more than one collection at once. The first even number from collection1 will be taken and multiplied by each odd number from collection2. Next, the second even integer from collection1 will be taken and multiplied, and so on. The result will be: 

What's more, the resulting values are not required to be integers. For instance, you may return a tuple containing integers from the first and the second collections:

Comprehensions With the "Into" Option

Up to this point, the final result of our comprehension was always a list. This is, actually, not mandatory either. You can specify an into parameter that accepts a collection to contain the resulting value. 

This parameter accepts any structure that implements the Collectable protocol, so for example we may generate a map like this:

Here I simply said into: Map.new, which can be also replaced with into: %{}. By returning the {el1, el2} tuple, we basically set the first element as a key and the second as the value.

This example is not particularly useful, however, so let's generate a map with a number as a key and its square as a value:

In this example I am using Erlang's :math module directly, as, after all, all modules' names are atoms. Now you can easily find the square for any number from 1 to 20.

Comprehensions and Pattern Matching

The last thing to mention is that you can perform pattern matching in comprehensions as well. In some cases it may come in pretty handy.

Suppose we have a map containing employees' names and their raw salaries:

I want to generate a new map where the names are downcased and converted to atoms, and salaries are calculated using a tax rate:

In this example we define a module attribute @tax with an arbitrary number. Then I deconstruct the data in the comprehension using {name, salary} <- collection. Lastly, format the name and calculate the salary as needed, and store the result in the new map. Quite simple yet expressive.

Conclusion

In this article we have seen how to use Elixir comprehensions. You may need some time to get accustomed to them. This construct is really neat and in some situations can fit in much better than functions like map and filter. You can find some more examples in Elixir's official docs and the getting started guide.

Hopefully, you've found this tutorial useful and interesting! Thank you for staying with me, and see you soon.

June 22 2017

13:00

Creating a Grocery List Manager Using Angular, Part 2: Managing Items

In the first part of this Angular tutorial series, you saw how to get started with creating a Grocery List Manager using Angular. You learnt how to create the view for the Grocery component, adding items to the grocery list and displaying the added items.

In this part, you'll implement the features to mark completed items, edit existing items, and remove added items.

Getting Started

Let's get started by cloning the source code from the first part of the tutorial. From your terminal, write in the following code to clone the source code:

Once the source code has been cloned, navigate to the project folder and install the required dependencies.

After installing the dependencies, you will be able to start the server. From the project folder, type in the following commands:

Point your browser to http://localhost:4200/ and you should have the application running.

Updating Grocery Items

Once you have the grocery items added to the list, you should be able to edit and update the items. Let's provide an edit button in the listing grid which, when clicked, will enable the editing of existing items.

Modify the app.grocery.html code to include the edit button inside the grid.

Save the above changes and restart the server. Load the page and enter a few items and you will have the edit button for each item.

Grocery List Manager - Edit Button

When the user clicks the edit button, you need to add an on click method to handle the item edit. Modify the app.grocery.html to add an on click event for editing the item.

Pass the task to the onEdit method as shown in the above code to identify the item to be edited.

Inside the GroceryComponent class initialize the task scope variable as shown:

In the onClick method, you'll check for the id to see if it's an existing item or a new item. Modify the onClick method as shown:

As seen, you have assigned a unique time stamp as id to each task. Now let's define the onEdit method to edit the existing item. Inside the onEdit method, assign the passed in item to the task variable.

Save the changes and restart the server. Enter a new item in the grocery list and click on the corresponding edit button. You will be able to edit and update the entry by clicking the OK button.

Grocery List Manager - Edit and Update

Deleting Grocery Items

Let's add a delete icon to remove the existing items. Update the app.grocery.html file to modify the HTML code as shown:

Here is how the complete app.grocery.html file looks:

Add an on click event to the remove icon to delete the grocery item.

Save the changes and restart the server. Try adding new items to the grocery manager app and you will have the items listed along with the delete and edit icons.

Grocery List Manager App - Delete View

To implement the delete functionality, you need to add the onDelete method in the app.grocery.ts file as shown:

Once the user clicks the delete icon, you need to check the item id against the grocery item list and remove the entry from the tasks list. Here is how the onDelete method looks:

As seen in the above code, you have iterated the tasks list and checked it against the clicked item id. If it matched the item in the tasks list, it is removed using the splice method.

Save the above changes and restart the server. Add a few items to the grocery list manager. It will be added with the delete and edit icons to the task list grid. Try clicking on the remove icon and the item will be deleted from the items list.

Marking the Grocery Item as Done

Let's add the functionality to strike out the items added to the list. Once the user is done with the tasks in the grocery list manager, it should be possible to strike out the completed tasks. To track the new and completed tasks, add a new variable strike to the task information. 

Modify the onClick method to include the new strike variable as shown:

Add a new class called strike in the src/style.css file which would strike out the item.

Include an on click event on the item to toggle the strike variable in the items variable. You'll be applying the strike class to the items based on the boolean value of the strike variable. By default, it will be false. Here is the onStrike method to toggle the strike variables value:

As seen in the above method, you iterate through the list of items. Once the item is found, you toggle the strike value.

Based on the strike variable, you need to apply the class strike to the task name span. Here is how it looks:

As seen, you have used the ngClass directive to apply the class strike to the span element if the task.strike value is true.

Save the above changes and restart the server. Add the items to the list and click on the added item. Once clicked, the item will be struck out as expected.

Grocery List Manager - Strike Out Completed Task

Wrapping It Up

In this tutorial, you saw how to update, delete and mark the task as complete in the grocery manager app using Angular. I hope you enjoyed the tutorial. Do let me know your thoughts in the comments below.

JavaScript has become one of the de facto languages of working on the web. It’s not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

Oh, and don't forget that the source code from this tutorial is available on GitHub.

12:00

Using Celery With Django for Background Task Processing

Web applications usually start out simple but can become quite complex, and most of them quickly exceed the responsibility of only responding to HTTP requests.

When that happens, one must make a distinction between what has to happen instantly (usually in the HTTP request lifecycle) and what can happen eventually. Why is that? Well, because when your application becomes overloaded with traffic, simple things like this make the difference. 

Operations in a web application can be classified as critical or request-time operations and background tasks, the ones that happen outside request time. These map to the ones described above: 

  • needs to happen instantly: request-time operations
  • needs to happen eventually: background tasks

Request-time operations can be done on a single request/response cycle without worrying that the operation will time out or that the user might have a bad experience. Common examples include CRUD (Create, Read, Update, Delete) database operations and user management (Login/Logout routines).

Background tasks are different as they are usually quite time-consuming and are prone to failure, mostly due to external dependencies. Some common scenarios among complex web applications include:

  • sending confirmation or activity emails
  • daily crawling and scraping some information from various sources and storing them
  • performing data analysis
  • deleting unneeded resources
  • exporting documents/photos in various formats

Background tasks are the main focus of this tutorial. The most common programming pattern used for this scenario is the Producer Consumer Architecture. 

In simple terms, this architecture can be described like this: 

  • Producers create data or tasks.
  • Tasks are put into a queue that is referred to as the task queue. 
  • Consumers are responsible for consuming the data or running the tasks. 

Usually, the consumers retrieve tasks from the queue in a first-in-first-out (FIFO) fashion or according to their priorities. The consumers are also referred to as workers, and that is the term we will be using throughout, as it is consistent with the terminology used by the technologies discussed.

What kind of tasks can be processed in the background? Tasks that:

  • are not essential for the basic functionality of the web application
  • can't be run in the request/response cycle since they are slow (I/O intensive, etc.)
  • depend on external resources that might not be available or not behave as expected
  • might need to be retried at least once
  • have to be executed on a schedule

Celery is the de facto choice for doing background task processing in the Python/Django ecosystem. It has a simple and clear API, and it integrates beautifully with Django. It supports various technologies for the task queue and various paradigms for the workers.

In this tutorial, we're going to create a Django toy web application (dealing with real-world scenarios) that uses background task processing.

Setting Things Up

Assuming you are already familiar with Python package management and virtual environments, let's install Django:

I've decided to build yet another blogging application. The focus of the application will be on simplicity. A user can simply create an account and without too much fuss can create a post and publish it to the platform. 

Set up the quick_publisher Django project:

Let's get the app started:

When starting a new Django project, I like to create a main application that contains, among other things, a custom user model. More often than not, I encounter limitations of the default Django User model. Having a custom User model gives us the benefit of flexibility.

Make sure to check out the Django documentation if you are not familiar with how custom user models work.

Now we need to tell Django to use this User model instead of the default one. Add this line to the quick_publisher/settings.py file:

We also need to add the main application to the INSTALLED_APPS list in the quick_publisher/settings.py file. We can now create the migrations, apply them, and create a superuser to be able to log in to the Django admin panel:

Let's now create a separate Django application that's responsible for posts:

Let's define a simple Post model in publisher/models.py:

Hooking the Post model with the Django admin is done in the publisher/admin.py file like this:

Finally, let's hook the publisher application with our project by adding it to the INSTALLED_APPS list.

We can now run the server and head over to http://localhost:8000/admin/ and create our first posts so that we have something to play with:

I trust you've done your homework and you've created the posts. 

Let's move on. The next obvious step is to create a way to view the published posts. 

Let's associate our new view with an URL in: quick_publisher/urls.py

Finally, let's create the template that renders the post in: publisher/templates/post.html

We can now head to http://localhost:8000/the-slug-of-the-post-you-created/ in the browser. It's not exactly a miracle of web design, but making good-looking posts is beyond the scope of this tutorial.

Sending Confirmation Emails

Here's the classic scenario:

  • You create an account on a platform.
  • You provide an email address to be uniquely identified on the platform.
  • The platform checks you are indeed the owner of the email address by sending an email with a confirmation link.
  • Until you perform the verification, you are not able to (fully) use the platform.

Let's add an is_verified flag and the verification_uuid on the User model:

Let's use this occasion to add the User model to the admin:

Let's make the changes reflect in the database:

We now need to write a piece of code that sends an email when a user instance is created. This is what Django signals are for, and this is a perfect occasion to touch this subject. 

Signals are fired before/after certain events occur in the application. We can define callback functions that are triggered automatically when the signals are fired. To make a callback trigger, we must first connect it to a signal.

We're going to create a callback that will be triggered after a User model has been created. We'll add this code after the User model definition in: main/models.py

What we've done here is we've defined a user_post_save function and connected it to the post_save signal (one that is triggered after a model has been saved) sent by the User model.

Django doesn't just send emails out on its own; it needs to be tied to an email service. For the sake of simplicity, you can add your Gmail credentials in quick_publisher/settings.py, or you can add your favourite email provider. 

Here's what Gmail configuration looks like:

To test things out, go into the admin panel and create a new user with a valid email address you can quickly check. If all went well, you'll receive an email with a verification link. The verification routine is not ready yet. 

Here's how to verify the account:

Hook the views up in: quick_publisher/urls.py

Also, remember to create a home.html file under main/templates/home.html. It will be rendered by the home view.

Try to run the entire scenario all over again. If all is well, you'll receive an email with a valid verification URL. If you'll follow the URL and then check in the admin, you can see how the account has been verified.

Sending Emails Asynchronously

Here's the problem with what we've done so far. You might have noticed that creating a user is a bit slow. That's because Django sends the verification email inside the request time. 

This is how it works: we send the user data to the Django application. The application creates a User model and then creates a connection to Gmail (or another service you selected). Django waits for the response, and only then does it return a response to our browser. 

Here is where Celery comes in. First, make sure it is installed:

We now need to create a Celery application in our Django application:

Celery is a task queue. It receives tasks from our Django application, and it will run them in the background. Celery needs to be paired with other services that act as brokers. 

Brokers intermediate the sending of messages between the web application and Celery. In this tutorial, we'll be using Redis. Redis is easy to install, and we can easily get started with it without too much fuss.

You can install Redis by following the instructions on the Redis Quick Start page. You'll need to install the Redis Python library, pip install redis, and the bundle necessary for using Redis and Celery: pip install celery[redis].

Start the Redis server in a separate console like this: $ redis-server

Let's add the Celery/Redis related configs into quick_publisher/settings.py:

Before anything can be run in Celery, it must be declared as a task. 

Here's how to do this:

What we've done here is this: we moved the sending verification email functionality in another file called tasks.py

A few notes:

  • The name of the file is important. Celery goes through all the apps in INSTALLED_APPS and registers the tasks in tasks.py files.
  • Notice how we decorated the send_verification_email function with @app.task. This tells Celery this is a task that will be run in the task queue.
  • Notice how we expect as argument user_id rather than a User object. This is because we might have trouble serializing complex objects when sending the tasks to Celery. It's best to keep them simple.

Going back to main/models.py, the signal code turns into:

Notice how we call the .delay method on the task object. This means we're sending the task off to Celery and we don't wait for the result. If we used send_verification_email(instance.pk) instead, we would still be sending it to Celery, but would be waiting for the task to finish, which is not what we want.

Before you start creating a new user, there's a catch. Celery is a service, and we need to start it. Open a new console, make sure you activate the appropriate virtualenv, and navigate to the project folder.

This starts four Celery process workers. Yes, now you can finally go and create another user. Notice how there's no delay, and make sure to watch the logs in the Celery console and see if the tasks are properly executed. This should look something like this:

Periodic Tasks With Celery

Here's another common scenario. Most mature web applications send their users lifecycle emails in order to keep them engaged. Some common examples of lifecycle emails:

  • monthly reports
  • activity notifications (likes, friendship requests, etc.)
  • reminders to accomplish certain actions ("Don't forget to activate your account")

Here's what we're going to do in our app. We're going to count how many times every post has been viewed and send a daily report to the author. Once every single day, we're going to go through all the users, fetch their posts, and send an email with a table containing the posts and view counts.

Let's change the Post model so that we can accommodate the view counts scenario.

As always, when we change a model, we need to migrate the database:

Let's also modify the view_post Django view to count views:

It would be useful to display the view_count in the template. Add this <p>Viewed {{ post.view_count }} times</p> somewhere inside the publisher/templates/post.html file. Do a few views on a post now and see how the counter increases.

Let's create a Celery task. Since it is about posts, I'm going to place it in publisher/tasks.py:

Every time you make changes to the Celery tasks, remember to restart the Celery process. Celery needs to discover and reload tasks. Before creating a periodic task, we should test this out in the Django shell to make sure everything works as intended:

Hopefully, you received a nifty little report in your email. 

Let's now create a periodic task. Open up quick_publisher/celery.py and register the periodic tasks:

So far, we created a schedule that would run the task publisher.tasks.send_view_count_report every minute as indicated by the crontab() notation. You can also specify various Celery Crontab schedules

Open up another console, activate the appropriate environment, and start the Celery Beat service. 

The Beat service's job is to push tasks in Celery according to the schedule. Take into account that the schedule makes the send_view_count_report task run every minute according to the setup. It's good for testing but not recommended for a real-world web application.

Making Tasks More Reliable

Tasks are often used to perform unreliable operations, operations that depend on external resources or that can easily fail due to various reasons. Here's a guideline for making them more reliable:

  • Make tasks idempotent. An idempotent task is a task that, if stopped midway, doesn't change the state of the system in any way. The task either makes full changes to the system or none at all.
  • Retry the tasks. If the task fails, it's a good idea to try it again and again until it's executed successfully. You can do this in Celery with Celery Retry. One other interesting thing to look at is the Exponential Backoff algorithm. This could come in handy when thinking about limiting unnecessary load on the server from retried tasks.

Conclusions

I hope this has been an interesting tutorial for you and a good introduction to using Celery with Django. 

Here are a few conclusions we can draw:

  • It's good practice to keep unreliable and time-consuming tasks outside the request time.
  • Long-running tasks should be executed in the background by worker processes (or other paradigms).
  • Background tasks can be used for various tasks that are not critical for the basic functioning of the application.
  • Celery can also handle periodic tasks using the celery beat service.
  • Tasks can be more reliable if made idempotent and retried (maybe using exponential backoff).

June 21 2017

13:19

Android Design Patterns: The Observer Pattern

What Is the Observer Pattern?

The Observer Pattern is a software design pattern that establishes a one-to-many dependency between objects. Anytime the state of one of the objects (the "subject" or "observable") changes, all of the other objects ("observers") that depend on it are notified.

Let's use the example of users that have subscribed to receive offers from Envato Market via email. The users in this case are observers. Anytime there is an offer from Envato Market, they get notified about it via email. Each user can then either buy into the offer or decide that they might not be really interested in it at that moment. A user (an observer) can also subscribe to receive offers from another e-commerce marketplace if they want and might later completely unsubscribe from receiving offers from any of them. 

This pattern is very similar to the Publish-Subscribe pattern. The subject or observable publishes out a notification to the dependent observers without even knowing how many observers have subscribed to it, or who they are—the observable only knows that they should implement an interface (we'll get to that shortly), without worrying about what action the observers might perform.

Benefits of the Observer Pattern

  • The subject knows little about its observers. The only thing it knows is that the observers implement or agree to a certain contract or interface. 
  • Subjects can be reused without involving their observers, and the same goes for observers too.
  • No modification is done to the subject to accommodate a new observer. The new observer just needs to implement an interface that the subject is aware of and then register to the subject.  
  • An observer can be registered to more than one subject it's registered to.

All these benefits give you loose coupling between modules in your code, which enables you to build a flexible design for your application. In the rest of this post, we'll look at how to create our own Observer pattern implementation, and we'll also use the built-in Java Observer/Observable API as well as looking into third-party libraries that can offer such functionality. 

Building Our Own Observer Pattern

1. Create the Subject Interface

We start by defining an interface that subjects (observables) will implement.

In the code above, we created a Java Interface with three methods. The first method registerObserver(), as it says, will register an observer of type RepositoryObserver (we'll create that interface shortly) to the subject. removeObserver() will be called to remove an observer that wants to stop getting notifications from the subject, and finally, notifyObserver() will send a broadcast to all observers whenever there is a change. Now, let's create a concrete subject class that will implement the subject interface we have created:

The class above implements the Subject interface. We have an ArrayList that holds the observers and then creates it in the private constructor. An observer registers by being added to the ArrayList and likewise, unregisters by being removed from the  ArrayList

Note that we are simulating a network request to retrieve the new data. Once the setUserData() method is called and given the new value for the full name and age, we call the notifyObservers() method which, as it says, notifies or sends a broadcast to all registered observers about the new data change. The new values for the full name and age are also passed along. This subject can have multiple observers but, in this tutorial, we'll create just one observer. But first, let's create the observer interface. 

2. Create the Observer Interface

In the code above, we created the observer interface which concrete observers should implement. This allows our code to be more flexible because we are coding to an interface instead of a concrete implementation. A concrete Subject class does not need to be aware of the many concrete observers it may have; all it knows about them is that they implement the RepositoryObserver interface. 

Let's now create a concrete class that implements this interface.

The first thing to notice in the code above is that UserProfileActivity implements the RepositoryObserver interface—so it must implement the method onUserDataChanged(). In the onCreate() method of the Activity, we got an instance of the UserDataRepository which we then initialized and finally registered this observer to. 

In the onDestroy() method, we want to stop getting notifications, so we unregister from receiving notifications. 

In the onUserDataChanged() method, we want to update the TextView widgets—mTextViewUserFullName and mTextViewUserAge—with the new set of data values.  

Right now we just have one observer class, but it's possible and easy for us to create other classes that want to be observers of the UserDataRepository class. For example, we could easily have a SettingsActivity that wants to also be notified about the user data changes by becoming an observer. 

Push and Pull Models

In the example above, we are using the push model of the observer pattern. In this model, the subject notifies the observers about the change by passing along the data that changed. But in the pull model, the subject will still notify the observers, but it does not actually pass the data that changed. The observers then pull the data they need once they receive the notification. 

Utilising Java's Built-In Observer API

So far, we have created our own Observer pattern implementation, but Java has built-in Observer / Observable support in its API. In this section, we are going to use this. This API simplifies some of the implementation, as you'll see. 

1. Create the Observable

Our UserDataRepository—which is our subject or observable—will now extend the java.util.Observable superclass to become an Observable. This is a class that wants to be observed by one or more observers. 

Now that we have refactored our UserDataRepository class to use the Java Observable API, let's see what has changed compared to the previous version. The first thing to notice is that we are extending a super class (this means that this class can't extend any other class) and not implementing an interface as we did in the previous section. 

We are no longer holding an ArrayList of observers; this is handled in the super class. Similarly, we don't have to worry about registration, removal, or notification of observers—java.util.Observable is handling all of those for us. 

Another difference is that in this class we are employing a pull style. We alert the observers that a change has happened with notifyObservers(), but the observers will need to pull the data using the field getters we have defined in this class. If you want to use the push style instead, then you can use the method notifyObservers(Object arg) and pass the changed data to the observers in the object argument. 

The setChanged() method of the super class sets a flag to true, indicating that the data has changed. Then you can call the notifyObservers() method. Be aware that if you don't call setChanged() before calling notifyObsevers(), the observers won't be notified. You can check the value of this flag by using the method hasChanged() and clear it back to false with clearChanged(). Now that we have our observable class created, let's see how to set up an observer also.  

2. Create the Observer

Our UserDataRepository observable class needs a corresponding Observer to be useful, so let's refactor our UserProfileActivity to implement the java.util.Observer interface. 

In the onCreate() method, we add this class as an observer to the UserDataRepository observable by using the addObserver() method in the java.util.Observable super class.  

In the update() method which the observer must implement, we check if the Observable we receive as a parameter is an instance of our UserDataRepository (note that an observer can subscribe to different observables), and then we cast it to that instance and retrieve the values we want using the field getters. Then we use those values to update the view widgets. 

When the activity is destroyed, we don't need to get any updates from the observable, so we'll just remove the activity from the observer list by calling the method deleteObserver()

Libraries to Implement an Observer Pattern

If you don't want to build your own Observer pattern implementation from scratch or use the Java Observer API, you can use some free and open-source libraries that are available for Android such as Greenrobot's EventBus. To learn more about it, check out my tutorial here on Envato Tuts+.

  • Android
    Communication Within an Android App With EventBus
    Chike Mgbemena

Or, you might like RxAndroid and RxJava. Learn more about them here:

  • Android
    Getting Started With ReactiveX on Android
    Ashraff Hathibelagal

Conclusion

In this tutorial, you learned about the Observer pattern in Java: what is it, the benefits of using it, how to implement your own, using the Java Observer API, and also some third-party libraries for implementing this pattern. 

In the meantime, check out some of our other courses and tutorials on the Java language and Android app development!

  • Android SDK
    RxJava 2 for Android Apps: RxBinding and RxLifecycle
    Jessica Thornsby
  • Android SDK
    Practical Concurrency on Android With HaMeR
    Tin Megali
  • Android
    Ensure High-Quality Android Code With Static Analysis Tools
    Chike Mgbemena
  • Android SDK
    Create an Intelligent App With Google Cloud Speech and Natural Language APIs
    Ashraff Hathibelagal

12:00

12 Best Contact Form PHP Scripts

Contact forms are a must have for every website. They encourage your site visitors to engage with you while potentially lowering the amount of spam you get.

For businesses, this engagement with visitors increases the chances of turning them into clients or customers and thus increasing revenue.

Whether your need is for a simple three-line contact form or a more complex one that offers loads of options and functions, you’re sure to find the right PHP contact form here in our 12Best Contact Form PHP Scripts on CodeCanyon.

1. Perfect Contact Us Form

Perfect Contact Us Form is a Bootstrap-based form which is fully customisable and easy to use. It integrates easily with HTML and PHP pages, and all fields use jQuery validation script.

Perfect Contact Us Form

Best features:

  • AJAX based
  • both SMPT and PHP email script
  • jQuery-based Captcha is included for anti spam
  • and more

The PerfectContact Us Form is an easy-to-use form that will appeal to both beginners and more experienced alike.

2. Quform- Responsive AJAX Contact Form

Quform is a versatile AJAX contact form that can be adapted to be a register form, quote form, or any other form needed.

Quform - Responsive AJAX Contact Form

Best features:

  • three ready-to-use themes with six variations
  • ability to integrate into your own theme design
  • ability to create complex form layouts
  • file uploads supported
  • and more

With tons of other customisations available, Quform- Responsive AJAX Contact Form is bound to keep the most discerning user happy.  

3. PHP Form Builder

A CodeCanyon top seller, PHP Form Builder includes the jQuery live validation plugin which enables you to build any type of form, connect your database, insert, update or delete records and send your emails using customizable HTML/CSS templates.

PHP Form Builder

Best features:

  • over 50 prebuilt templates included
  • accepts any HTML5 form elements
  • default options ready for Bootstrap
  • email sending with advanced options
  • and more

With loads of options for creating a variety of elegant contact forms and extensive documentation to help you on your way, PHP Form Builder is definitely a top choice for PHP site owners.

4. SLEEK Contact Form

Having made its debut in April 2017, SLEEK Contact Form is the newest contact form PHP Script on CodeCanyon, and with its simple and beautiful design and functionality, it promises to have a great future.

SLEEK Contact Form

Best features:

  • invisible Google reCaptcha anti-spam system
  • ability to add attachments of any type
  • automatically get the IP and location of the sender inside email
  • easy to modify and implement new fields
  • and more

If you want a simple contact form with a bit of a wow factor, SLEEK Contact Form may be just what you’re looking for.

5. Ultimate PHP, HTML5 & AJAX Contact Form

The Ultimate PHP, HTML5 and AJAX Contact Form replaces the hugely successful AJAX Contact Form and allows you to easily place and manage a self-contained contact form on any page of your existing PHP website.

Ultimate PHP HTML5  AJAX Contact Form

Best features:

  • supports file uploads to attach to email
  • field type validation
  • multiple forms per page allowed
  • Google reCAPTCHA capable
  • and more

The Ultimate PHP, HTML5 & AJAX Contact Form is loaded with useful features that will satisfy PHP site owners looking for a reliable contact form.

6. Contact Form Generator - Easy & Powerful Form Builder

Contact Form Generator is one of CodeCanyon’s best-selling Contact Form PHP Scripts.  It features a user-friendly drag-and-drop interface that helps you build contact forms, feedback forms, online surveys, event registrations etc. and get responses via email in a matter of minutes.

Contact Form Generator - Easy  Powerful Form Builder

Best features:

  • instant email or SMS notifications
  • custom email auto-responder
  • integrated with MailChimp, AWeber and five other email subscription services
  • anti-spam protection
  • and more

Contact Form Generator - Easy & Powerful Form Builder is a highly effective form builder that enables you to create well-designed contact forms and extend their range to include other functions.

7. KONTAKTO - AJAX Contact Form with Styled Map

KONTAKTO only entered the market in March of 2017 but has already developed a name for itself as one of the top-rated scripts in this category. The standout feature of this beautifully designed contact form is the stylish map with a location pin that comes integrated in the form.

KONTAKTO - AJAX Contact Form with Styled Map

Best features:

  • required field validation
  • anti spam with simple Captcha math
  • defaults to PHP mail but SMTP option available
  • repeat submission prevention
  • and more

Simple yet stylish, KONTAKTO - AJAX Contact Form with Styled Map can be easily integrated with your HTML or PHP page and will be a fast favourite with many PHP site owners.

8. ContactPLUS+ PHP Contact Form

ContactPlus+ is another clean and simple contact form which comes in three styles: an un-styled version that you can build to suit your taste, a normal form with just the essential information needed on a contact form, and a longer form to accommodate an address.

ContactPLUS - PHP Contact Form

Best features:

  • Captcha verification
  • successful submission message
  • two styled and one un-styled version
  • and more

If you’re looking for a clean and simple contact form that will integrate easily on you PHP website, ContactPLUS+ PHP Contact Form is the one for you.

9. AJAX Contact Pro - Multi-language HTML5, Bootstrap Contact Form

Built using jQuery and PHP, AJAX Contact Pro comes in eight style variations and has four HTML email templates. One of the features that make this form so special is that it enables users to translate the form fields into their language in real time. If a preferred language isn’t present in the predefined list, the site administrator can add it to the list.

AJAX Contact Pro - Multi-language HTML5 Bootstrap Contact Form

Best features:

  • AJAX form
  • field validations
  • animations
  • modular construction so it can be integrated in an existing project
  • and more

AJAXContact Pro - Multi-language HTML5, Bootstrap Contact Form is certainly a cool addition to the contact form PHP scripts offerings.

10. Hello Form Builder - Contact Form

Powered by AJAX and jQuery, the Hello Form Builder employs an easy-to-use drag-and-drop function to help site owners custom build contact forms with a variety of fields and features like file upload, file attachment, Captcha system, etc.

Hello Form Builder - Contact Form

Best features:

  • 50 background images included
  • ability to customise error messages
  • one-click installation
  • auto responder message
  • and more

Hello Form Builder - Contact Form is a user-friendly builder that will appeal to a wide cross-section of users.

11. Responsive Contact Form

The Responsive Contact Form has just one main option to configure—your email address—to make the script functional on your PHP site.

Responsive Contact Form

Best features

  • AJAX back end to save your bandwidth
  • uses JavaScript jQuery slide
  • very easy to integrate into any existing HTML or PHP page on your website
  • all fields have a validation script
  • and more

See Responsive Contact Form in action over at Code Canyon.

12. ContactForm with Custom Auto Responder

Another of Code Canyon’s top sellers, Contact Form with Custom Auto Responder is easy to edit and add to your PHP or HTML pages.

Contact Form With Custom Auto Responder

Best features:

  • dropdown subject selection with different emails
  • custom auto responder message
  • custom Captcha filter
  • no separate page needed for thank you message
  • and more

ContactForm With Custom Auto Responder has been around for a while but is still holding its own among the newcomers.

Conclusion

These 12 Best Contact Form PHP Scripts just scratch the surface of products available at Envato Market, so if none of them fit your needs, there are plenty of other great options you may prefer.

And if you want to improve your PHP skills, check out the ever so useful free PHP tutorials we have on offer.

11:51

Learn the Basics of PHP for WordPress in Our New Course

PHP is the language of WordPress. If you want to customize WordPress, for example by coding themes or plugins, PHP is the programming language you'll need to learn.

In our new Coffee Break Course, WordPress Coding Basics: Learn PHP, Envato Tuts+ instructor Rachel McCollin will give you a quick, ten-minute introduction to PHP coding in WordPress. 

You'll get an overview of PHP coding standards, and take a look at some of the most common WordPress functions that you'll be hooking up to with your code. You'll also learn about core WordPress coding concepts, such as actions and hooks, and you'll get lots of links to tutorials, courses and books that will help you keep learning.

Watch the introduction below to find out more.

 

You can take our new Coffee Break Course straight away with a free 10-day trial of our monthly subscription. If you decide to continue, it costs just $15 a month, and you’ll get access to hundreds of courses, with new ones added every week.

You can also find loads of useful PHP scripts and WordPress plugins over on Envato Market to help you with your WordPress development. And if you want to learn WordPress development from start to finish, check out our learning guide: Learn WordPress Development.

June 20 2017

19:55

How to Use the Google Cloud Vision API in Android Apps

Computer vision is considered an AI-complete problem. In other words, solving it would be equivalent to creating a program that's as smart as humans. Needless to say, such a program is yet to be created. However, if you've ever used apps like Google Goggles or Google Photos—or watched the segment on Google Lens in the keynote of Google I/O 2017—you probably realize that computer vision has become very powerful.

Through a REST-based API called Cloud Vision API, Google shares its revolutionary vision-related technologies with all developers. By using the API, you can effortlessly add impressive features such as face detection, emotion detection, and optical character recognition to your Android apps. In this tutorial, I'll show you how.

Prerequisites

To be able to follow this tutorial, you must have:

If some of the above requirements sound unfamiliar to you, I suggest you read the following introductory tutorial about the Google Cloud Machine Learning platform:

  • Android SDK
    How to Use Google Cloud Machine Learning Services for Android
    Ashraff Hathibelagal

1. Enabling the Cloud Vision API

You can use the Cloud Vision API in your Android app only after you've enabled it in the Google Cloud console and acquired a valid API key. So start by logging in to the console and navigating to API Manager > Library > Vision API. In the page that opens, simply press the Enable button.

Enable Cloud Vision API

If you've already generated an API key for your Cloud console project, you can skip to the next step because you will be able to reuse it with the Cloud Vision API. Otherwise, open the Credentials tab and select Create Credentials > API key.

Create API key

In the dialog that pops up, you will see your API key.

2. Adding Dependencies

Like most other APIs offered by Google, the Cloud Vision API can be accessed using the Google API Client library. To use the library in your Android Studio project, add the following compile dependencies in the app module's build.gradle file:

Furthermore, to simplify file I/O operations, I suggest you also add a compile dependency for the Apache Commons IO library.

Because the Google API Client can work only if your app has the INTERNET permission, make sure the following line is present in your project's manifest file:

3. Configuring the API Client

You must configure the Google API client before you use it to interact with the Cloud Vision API. Doing so primarily involves specifying the API key, the HTTP transport, and the JSON factory it should use. As you might expect, the HTTP transport will be responsible for communicating with Google's servers, and the JSON factory will, among other things, be responsible for converting the JSON-based results the API generates into Java objects. 

For modern Android apps, Google recommends that you use the NetHttpTransport class as the HTTP transport and the AndroidJsonFactory class as the JSON factory.

The Vision class represents the Google API Client for Cloud Vision. Although it is possible to create an instance of the class using its constructor, doing so using the Vision.Builder class instead is easier and more flexible.

While using the Vision.Builder class, you must remember to call the setVisionRequestInitializer() method to specify your API key. The following code shows you how:

Once the Vision.Builder instance is ready, you can call its build() method to generate a new Vision instance you can use throughout your app.

At this point, you have everything you need to start using the Cloud Vision API.

4. Detecting and Analyzing Faces

Detecting faces in photographs is a very common requirement in computer vision-related applications. With the Cloud Vision API, you can create a highly accurate face detector that can also identify emotions, lighting conditions, and face landmarks.

For the sake of demonstration, we'll be running face detection on the following photo, which features the crew of Apollo 9:

Sample photo for face detection

I suggest you download a high-resolution version of the photo from Wikimedia Commons and place it in your project's res/raw folder.

Step 1: Encode the Photo

The Cloud Vision API expects its input image to be encoded as a Base64 string that's placed inside an Image object. Before you generate such an object, however, you must convert the photo you downloaded, which is currently a raw image resource, into a byte array. You can quickly do so by opening its input stream using the openRawResource() method of the Resources class and passing it to the toByteArray() method of the IOUtils class.

Because file I/O operations should not be run on the UI thread, make sure you spawn a new thread before opening the input stream. The following code shows you how:

You can now create an Image object by calling its default constructor. To add the byte array to it as a Base64 string, all you need to do is pass the array to its encodeContent() method.

Step 2: Make a Request

Because the Cloud Vision API offers several different features, you must explicitly specify the feature you are interested in while making a request to it. To do so, you must create a Feature object and call its setType() method. The following code shows you how to create a Feature object for face detection only:

Using the Image and the Feature objects, you can now compose an AnnotateImageRequest instance.

Note that an AnnotateImageRequest object must always belong to a BatchAnnotateImagesRequest object because the Cloud Vision API is designed to process multiple images at once. To initialize a BatchAnnotateImagesRequest instance containing a single AnnotateImageRequest object, you can use the Arrays.asList() utility method.

To actually make the face detection request, you must call the execute() method of an Annotate object that's initialized using the BatchAnnotateImagesRequest object you just created. To generate such an object, you must call the annotate() method offered by the Google API Client for Cloud Vision. Here's how:

Step 3: Use the Response

Once the request has been processed, you get a BatchAnnotateImagesResponse object containing the response of the API. For a face detection request, the response contains a FaceAnnotation object for each face the API has detected. You can get a list of all FaceAnnotation objects using the getFaceAnnotations() method.

A FaceAnnotation object contains a lot of useful information about a face, such as its location, its angle, and the emotion it is expressing. As of version 1, the API can only detect the following emotions: joy, sorrow, anger, and surprise.

To keep this tutorial short, let us now simply display the following information in a Toast:

  • The count of the faces
  • The likelihood that they are expressing joy

You can, of course, get the count of the faces by calling the size() method of the List containing the FaceAnnotation objects. To get the likelihood of a face expressing joy, you can call the intuitively named getJoyLikelihood() method of the associated FaceAnnotation object. 

Note that because a simple Toast can only display a single string, you'll have to concatenate all the above details. Additionally, a Toast can only be displayed from the UI thread, so make sure you call it after calling the runOnUiThread() method. The following code shows you how:

You can now go ahead and run the app to see the following result:

Face detection results

5. Reading Text

The process of extracting strings from photos of text is called optical character recognition, or OCR for short. The Cloud Vision API allows you to easily create an optical character reader that can handle photos of both printed and handwritten text. What's more, the reader you create will have no trouble reading angled text or text that's overlaid on a colorful picture.

The API offers two different features for OCR:

  • TEXT_DETECTION, for reading small amounts of text, such as that present on signboards or book covers
  • and DOCUMENT_TEXT_DETECTION, for reading large amounts of text, such as that present on the pages of a novel

The steps you need to follow in order to make an OCR request are identical to the steps you followed to make a face detection request, except for how you initialize the Feature object. For OCR, you must set its type to either TEXT_DETECTION or DOCUMENT_TEXT_DETECTION. For now, let's go with the former.

You will, of course, also have to place a photo containing text inside your project's res/raw folder. If you don't have such a photo, you can use this one, which shows a street sign:

Sample photo for text detection

You can download a high-resolution version of the above photo from Wikimedia Commons.

In order to start processing the results of an OCR operation, after you obtain the BatchAnnotateImagesResponse object, you must call the getFullTextAnnotation() method to get a TextAnnotation object containing all the extracted text.

You can then call the getText() method of the TextAnnotation object to actually get a reference to a string containing the extracted text.

The following code shows you how to display the extracted text using a Toast:

If you run your app now, you should see something like this:

Text detection results

Conclusion

In this tutorial you learned how to use the Cloud Vision API to add face detection, emotion detection, and optical character recognition capabilities to your Android apps. I'm sure you'll agree with me when I say that these new capabilities will allow your apps to offer more intuitive and smarter user interfaces.

It's worth mentioning that there's one important feature that's missing in the Cloud Vision API: face recognition. In its current form, the API can only detect faces, not identify them.

To learn more about the API, you can refer to the official documentation.

And meanwhile, check out some of our other tutorials on adding computer learning to your Android apps!

  • Android SDK
    How to Use Google Cloud Machine Learning Services for Android
    Ashraff Hathibelagal
  • Android SDK
    Create an Intelligent App With Google Cloud Speech and Natural Language APIs
    Ashraff Hathibelagal
  • Android Things
    Android Things and Machine Learning
    Paul Trebilcox-Ruiz

June 19 2017

13:36

What's New in Swift 4

Swift 4 has been in the works for the last few months. If you're like me, you might follow Swift Evolution to stay up to date with all the proposals and changes. Even if you do, now is a good time to review all the additions and changes to the language in this new iteration.

A snapshot of Swift 4 was already available a few weeks before Xcode 9 was announced at WWDC 2017. In this post you'll learn all about the new features introduced in Swift 4—from brand new APIs to improvements to the language syntax.

Let's first see how you can get the new compiler installed on your machine.

Xcode Setup

There are two ways to run Swift 4. You can either install the Xcode 9 beta if you have a developer account with access to it or you can set up Xcode 8 to run with a Swift 4 snapshot. In the former case, download the beta from your developer account download page.

If you prefer to use Xcode 8, simply head over to Swift.org to download the latest Swift 4.0 Development snapshot. Once the download finishes, double-click to open the .pkg file, which installs the snapshot. 

Switch to Xcode now and go to Xcode > Toolchains > Manage Toolchains. From there, select the newly installed Swift 4.0 snapshot. Restart Xcode and now Swift 4 will be used when compiling your project or playground. Note that all the code presented in this tutorial is also available in a GitHub repo.

Swift 40 snapshot setup in Xcode 83

New Features

Let's take a look at the new features added to Swift 4. One caveat: the language is still in beta, and we will most likely see more changes and bug fixes before the official version is released. Moreover, some of the most recently approved proposals may still not be implemented at this time, so keep an eye on future release notes to see what will be implemented and fixed.

Encoding and Decoding

JSON parsing is one of the most discussed topics in the Swift community. It's great to see that someone finally took care of writing proposals SE-0166 and SE-0167 and pushed the idea to refresh the archival and serialization APIs in the Foundation framework. In Swift 4, there is no longer any need to parse or encode your class, struct or enum manually. 

New Encodable and Decodable protocols have been added, and you can make your classes conform to them by simply adding Codable (which is an alias for Decodable & Encodable) to the class's inheritance list. Then you can use the JSONEncoder to encode an instance of the class:

As you can see, you instantiate a JSONEncoder object to convert the struct to a JSON string representation. There are a few settings that you can tweak to get the exact JSON format you need. For example, to set a custom date format, you can specify a dateEncodingStrategy in the following way:

The reverse process to decode a string works very similarly, thanks to the JSONDecoder class.

As you can see, by passing the type of the object to the decode method, we let the decoder know what object we expect back from the JSON data. If everything is successful, we'll get an instance of our model object ready to be used.

That's not even all the power and the modularity of the new API. Instead of using a JSONEncoder, you can use the new PropertyListEncoder and PropertyListDecoder in case you need to store data in a plist file. You can also create your own custom encoder and decoder. You only need to make your decoder conform to the Decoder and your encoder to the Encoder protocol.

Strings

As part of the String Manifesto, the String type also received quite a big refresh. It now conforms once again (after being removed in Swift 2) to the Collection protocol thanks to proposal SE-0163. So now you can simply enumerate over a string to get all characters.

Substring is a new type that conforms to the same StringProtocol to which String also conforms. You can create a new Substring by just subscripting a String. The following line creates a Substring by omitting the first and last character.

A nice addition that should make it easier to work with big pieces of text is multi-line strings. If you have to create a block of text which spans across multiple lines, you previously had to manually insert \n all over the place. This was very inelegant and difficult to manage. A better way now exists to write multi-line strings, as you can see from the following example:

There are few rules that go along with this new syntax. Each string begins with a triple quotation mark ("""). Then, if the entire string is indented, the spacing of the closing characters decides the spacing to be stripped from each line in the string. For example, if the closing character is indented by 2 tabs, the same amount will be removed from each line. If the string has a line that doesn't have this amount of spacing, the compiler will throw an error.

Key Paths

Key paths were added in Swift 3 to make it easier to reference properties in an object. Instead of referencing an object key with a simple string literal, key paths let us enforce a compile-time check that a type contains the required key—eliminating a common type of runtime error. 

Key paths were a nice addition to Swift 3, but their use was limited to NSObjects and they didn't really play well with structs. These were the main motivations behind proposal SE-0161 to give the API a refresh.

A new syntax was agreed by the community to specify a key path: the path is written starting with a \. It looks like the following:

The nameKeyPath object describes a reference to the name property. It can then be used as a subscript on that object.

If you change the variable from let to var of wwdc, you can also modify a specific property via the key-path subscript syntax.

One-Sided Ranges

SE-0172 proposed to add new prefix and postfix operators to avoid unnecessarily repeating a start or end index when it can be inferred. For example, if you wanted to subscript an array from the second index all the way to the last one, you could write it in the following way:

Previously, the endIndex had to be specified. Now, a shorter syntax exists:

Or, if you want to begin with the start index:

The same syntax can also be used for pattern matching in a switch statement.

Generic Subscripts

Before Swift 4, subscripts were required to define a specific return value type. SE-0148 proposed the possibility of defining a single generic subscript that would infer the return type based on the defined result value. Aside from the type annotation, it works pretty much the same way as before.

As you can see, this really improves the readability of your objects in the cases where you need to access them via the subscript syntax.

Class and Subtype Existentials

One of the missing features from the Swift type system to date has been the ability to constrain a class to a specific protocol. This has been fixed in Swift 4—you can now specify the type of an object and the protocols to which it has to conform, thanks to SE-0156. You can, for example, write a method that takes a UIView that conforms to the Reloadable protocol with the following syntax:

Dictionary and Set Improvements

Dictionary and Set also received a nice refresh in Swift 4. They are much more pleasant to use thanks to a few utility methods that have been added.

mapValues

Dictionary now has a mapValues method to change all values, avoiding the use of the generic map method that requires working with key, value tuples.

filter Return Type

The filter method now returns an object of the same type you're filtering with.

Defaults for Dictionary Lookup

When working with dictionaries, you can provide a default value when using the subscript syntax to avoid having to later unwrap an optional.

Dictionary Grouping Initializer

Finally, a Dictionary(grouping:) initializer has been introduced to facilitate creating a new dictionary by grouping the elements of an existing collection according to some criteria. 

In the following examples, we create a dictionary by grouping together all conferences that have the same starting letter. The dictionary will have a key for each starting letter in the conferences collection, with each value consisting of all keys that start with that letter.  

Resources

If you are interested in going deeper into the new Swift 4 features, here are a few more resources:

Conclusion

Now that you have taken a look at some of the major new features in Swift 4, you're probably champing at the bit to start using them, to help keep your codebase fresh and clean. Start to write your new code to take advantage of the useful new features and think about refactoring some of your previous code to make it simpler and easier to read.

In the meantime, check out some of our other posts on iOS app development!

  • iOS
    Swift Animation Basics
    Markus Mühlberger
  • Mobile Development
    WWDC 2017 Aftermath: The Most Important Announcements
    Bart Jacobs
  • iOS SDK
    Realm Mobile Database for iOS
    Doron Katz
  • iOS
    What's New in iOS 10
    Markus Mühlberger

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.

Don't be the product, buy the product!

Schweinderl