Thursday, July 27, 2017

Getting Started With Matter.js: The Composites and Composite Modules

In the third tutorial of the series, you learned about different methods and properties of the Body module in Matter.js. The Body module enables you to manipulate simple bodies like circles, rectangles, and trapeziums. Matter.js also has other modules to help you create and manipulate some complex but common composite bodies like cars, chains, pyramids, stacks, and soft bodies. 

All these composites and the methods to manipulate them are available in the Composite and Composites modules in Matter.js. In this tutorial, you will begin by learning about different composites like pyramids and cars etc. that can be created using the Composites module. After that, we will go over some important methods and properties available in the Composite module.

Creating a Stack and a Pyramid

A stack and a pyramid are both very similar to each other. A stack can be created by using the stack(xx, yy, columns, rows, columnGap, rowGap, callback) function. Similarly, you can create a pyramid with the help of the pyramid(xx, yy, columns, rows, columnGap, rowGap, callback) function. As you can see, all the parameters are the same in both cases. In fact, the pyramid formation is derived from the stack formation. 

The names of all the parameters are self-explanatory. The xx and yy parameters used in this function are used to specify the starting point of the composite. The columns and rows parameters determine the number of columns and rows in the composite. The gap between different rows and columns can be controlled using the columnGap and rowGap parameters. 

Under the influence of gravity, the rowGap generally vanishes in most cases without changing the composite. However, sometimes the resulting momentum of individual bodies can move the bodies under them. This can change the shape of the composite.

The callback function is used to create bodies that can be arranged in either a grid arrangement or a pyramid arrangement based on the function used. This means that you can use it to create a stack or pyramid of rectangular boxes or trapezoids. You should keep in mind that using a circle will make the arrangements unstable. Here is the code to create a stack of rectangles:

You can make the callback function as complex as you wish. In this case, I have used the render options that we learned about in the Body module tutorial to create only orange rectangles with black outlines.

Here is some very similar code to create pyramid shapes in Matter.js:

When you start creating a lot of pyramids with different parameters, you will notice that the number of rows created is sometimes less than the number of rows you specified. This is because the library uses the following formula to calculate the number of rows:

You can carefully place a stack or another pyramid over a pyramid to create interesting patterns. For example, you could place a smaller pyramid over the red one to create a complete pyramid with two colors.

Creating a Car and a Chain

A car in Matter.js is a structure consisting of two wheels and a body. The wheels are created with a friction of 0.8 and density equal to 0.01. You can create a car using the function car(xx, yy, width, height, wheelSize). The xx and yy parameters are used to specify the position of the car. 

The width and height determine the dimensions of the main body of the car. The wheelSize parameter is used to specify the radius of the wheels. There is no need for a callback function as the type of bodies needed to create a car is predetermined.

You can use the chain(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options) function in Matter.js to chain all the bodies in a given composite together using constraints. The offset parameters in the function are used to determine the relative position of the constraints connecting different boxes. 

You will also need additional constraints to hang the chain from a point in the world. Here is the code to create a chain and hang it to the ceiling of our world. 

The boxes in our chain have been created using the stack() function that you learned about earlier. The constraints created by the chain() function have a stiffness of 1. 

This prevents the length of rope between different boxes from changing at all. The additional constraint that we have created here keeps our boxes hanging from the ceiling. 

Here is a demo with a car and the chain created from the above code. You can move the car forward and backward using the orange buttons. Each click applies a force at the center of the first wheel, moving the whole car.

Creating a Soft Body and Newton's Cradle

A soft body is similar to a stack, with two major differences. The individual elements of the soft body are held together by constraints, and a soft body can only have circles as its constituent elements. You can consider a soft body to be a cross between a mesh and a stack. Creating a soft body is as simple as calling softBody(xx, yy, columns, rows, colGap, rowGap, crossBrace, pRadius, pOptions, cOptions) with the appropriate parameter values. 

You are already familiar with the first six parameters of the function. The crossBrace parameter is a Boolean value that determines if the cross braces should be rendered or not. The pRadius parameter determines the radius of circles, and the pOptions parameter can be used to control other properties of the particles, like mass and inertia. 

The cOptions parameter specifies various options for the constraints that bind the particles together. The following code will create a soft body for our Matter.js world.

Creating a Newton's cradle is also very straightforward using the built-in newtonsCradle(xx, yy, number, size, length) function. The number parameter determines the number of balls in the cradle. The size parameter determines their radius, and the length parameter determines the length of the rope to which the balls are attached. The library sets the restitution and friction values to zero so that they can continue their motion for a long time.

The following code creates the cradle and moves the first ball to a higher position so that it has some velocity when it falls down and strikes other balls. The position specified by the translate() function is relative to the current position of the body. All these functions and properties of the Body module have been discussed in more detail in the previous tutorial of the series.

Important Methods and Properties in Composite Module

Now that you have learned how to create different kinds of composite bodies, it is time for you to learn about different methods and properties available in the Composite module to manipulate these composites. You can use rotate(composite, rotation, point, [recursive=true]), scale(composite, scaleX, scaleY, point, [recursive=true]) and translate(composite, translation, [recursive=true]) to rotate, scale and translate any composite. These functions are very similar to their Body module counterparts.

You can also add or remove one or more body(s), constraint(s) and composite(s) from a given composite using the add(composite, object) and remove(composite, object, [deep=false]) functions respectively. If you want to move some bodies from one composite to another, you can do so with the help of the move(compositeA, objects, compositeB) function. This function will move the given objects from composite A to composite B.

If you ever want to access all the bodies, composites and constraints that are direct children of the given composite, you can use the composite.bodies, composite.composites and composite.constraints properties to get access to all of them in the form of an array. 

We have already seen how to use the bodies property to translate a ball from the Newton's cradle to the left and apply a force on the wheel of our car composite. Once you have a reference to individual bodies from the composite, you can use all the methods and properties of the Body module to manipulate them.

Final Thoughts

In this tutorial, you learned how to create some complex composites using the Composite and Composites modules in Matter.js. You also learned about different methods and properties that you can use to manipulate these composites. 

This series was aimed at getting people started with the Matter.js library in a beginner-friendly way. Keeping that in mind, we have covered important functions and properties of the most common modules in the library. 

Matter.js also has a lot of other modules, which we briefly discussed in the first tutorial of the series. If you want to use this library to its full potential, you should read the documentation of all these modules on the official website.

If you have used Matter.js in any of your projects, please tell us about your experience in the comments.


by Monty Shokeen via Envato Tuts+ Code

How to Ensure Your Facebook Page Complies With Facebook Terms

Do you have a Facebook page for your business? Want to be sure your page isn’t disabled (or worse, shut down) for noncompliance with Facebook’s Terms? In this article, you’ll discover four tips to keep your Facebook page in line with Facebook’s Terms. #1: Name Your Page Accurately Setting up a new Facebook page can [...]

This post How to Ensure Your Facebook Page Complies With Facebook Terms first appeared on .
- Your Guide to the Social Media Jungle


by Sarah Kornblet via

Fitty – Makes Text Fit Perfectly with Javascript

Fitty is a javascript library that scales up (or down) text so it fits perfectly to its parent container. Ideal for flexible and responsive websites.


by via jQuery-Plugins.net RSS Feed

VR Arles Festival

The VR Arles festival was created to discover virtual reality through movies, documentaries and artistic creations, and bring the spectator into the best productions in the world.
by via Awwwards - Sites of the day

Grab Our Free Printable Productivity Cheat Sheet

It's pretty easy to fall into the habit of endlessly reading about lifehacks and productivity tricks as a proxy for implementing the kind of solid practices and processes that truly allow you to get more done.

We compiled a list of some of the best habits and principles (and yes, even effective lifehacks) in one place so that you can refer to them at a glance, determine the habits you'd like to work on this month, and avoid the time sink of productivity clickbait.

Building a good set of productivity habits without overcomplicating things or focusing your energy on low-return tricks is the best way to get more out of your day. Grab the cheat sheet from SitePoint's Kevin Wood now.

Continue reading %Grab Our Free Printable Productivity Cheat Sheet%


by Kevin Wood via SitePoint

Wednesday, July 26, 2017

How to Build a Class Booking System with Acuity Scheduling

Cooking

This article was sponsored by Acuity Scheduling. Thank you for supporting the partners who make SitePoint possible.

I recently wrote an article about building an online system to book lessons with a driving instructor. Teaching someone to drive is relatively unique, in that it's guaranteed to be a one-to-one class — or at least, if you did find yourself sharing an instructor's time, then you'd have every right to feel short-changed.

Most other types of class, though, tend to have multiple participants. Unless they're delivered online, they'll most likely have a limit on the number of students due to logistical considerations.

Cookery classes usually have a very well-defined limit on the number of students — you can only really teach as many people as you have cooking stations or cookers. That's going to be the theme of this article — managing those "slots" in a cookery class. The principles remain the same for all sorts of other forms of tuition.

As before, we're going to take advantage of Acuity Scheduling in order to manage bookings for our classes, and everything that entails.

All of the code for this tutorial is available on Github.

What We're Going to Build

Thanchanok delivers Thai cookery classes. There's a general introductory course, as well as two more specialised courses - one covering the many and varied Thai curry pastes, and one that focuses specifically on the region in which she was brought up — the swelteringly hot Northern region around Chiang Mai. She owns a specially fitted-out kitchen to deliver these classes. Each has eight cooking stations. She typically runs around four classes a week — two of those slots for the introductory class which, as you might expect, is by far her most popular.

Currently her website includes an email address and telephone number for making bookings, but there are a number of issues with that. First is that it's easy to forget to update the website to indicate that it's fully-booked, which on occasion has left potential attendees disappointed and with a poor impression of the company.

The second is that she has to rely on good old-fashioned pen-and-paper to manage her list of pupils, along with their contact details and whether they've paid for the lesson ahead of time. She'd very much like to add a feature to her website that allows people to view class availability as well as book online, and to then help her class schedule and attendee lists. That's what we're going to do in the course of this tutorial.

Let's break down the requirements as far as the public-facing website is concerned:

  • The website needs to show all of the upcoming classes.
  • If a class is fully booked, it needs to say so.
  • Classes not fully booked should show the number of available slots.
  • Visitors should be able to book a place on classes that have availability.

By integrating all of this with Acuity Scheduling, we effectively get the back-end requirements handled without having to develop it ourselves:

  • The number of people who've booked for each upcoming class.
  • A list of attendees, along with their contact details.
  • Constant updates about upcoming classes and bookings.
  • Thanchanok's calendar, all in one place.

Let's get started.

Setting Up Acuity Scheduling

The first thing you'll need to do, if you haven't already, is to sign up at Acuity Scheduling. The free trial will be perfectly adequate for following along.

The next thing we need to do is set up the three classes. In Acuity terminology these are appointment types.

If you've just signed up, click the Create your Appointment types button at the top of the screen, or click Appointment Types under Business Settings on the sidebar.

Next, click the New Type of Group Class button.

Creating an appointment type

You'll need to name the class. For the purposes of this tutorial we'll call them Introduction to Thai Cookery, Thai Curry Pastes and Taste of the North, but you can call them whatever you want.

Create a new class

Enter a duration in minutes — for example, 180 — and optionally provide a price. In order to keep things simple, we won't be covering payment.

Click the Create Appointment Type button to save the information. Once we've created the appointment type — i.e., the class — we need to provide some dates and times. To do this, click the Offer Class button.

Offering the class

Enter the date and time that the course will run. If it's a regular thing then you can set it as recurring — this allows you to enter multiple dates in bulk. Thanchanok offers the introductory class twice weekly at 1pm, and the other two courses once per week.

Next, go to the Appointment Types and check the three URLs to the newly-created classes. They contain an id query parameter which we'll need shortly, so make a note of those now.

The final step on the Acuity side is to get the API credentials for our integration:

  1. Click Integrations under Business Settings on the sidebar.
  2. Click API to scroll down to the relevant part of the page.
  3. Click view credentials.

Acuity API

Copy and paste the User ID and API Key for use later.

Beginning the Implementation

For the purposes of this tutorial we're going to use Lumen, although the principles are pretty much the same whatever your framework of choice happens to be.

Start by creating the project from the command-line:

composer create-project --prefer-dist laravel/lumen thaicookery

Create a file in your project folder named .env and add the following lines, replacing the values appropriately:

ACUITY_USER_ID=your_user_id
ACUITY_API_KEY=your_api_key
APP_DEBUG=true

This will allow you to retrieve the user ID and API key like this:

$userId = env( 'ACUITY_USER_ID' );
$apiKey = env( 'ACUITY_API_KEY' );

As I hinted at earlier, we're going to integrate with Acuity Scheduling via the API. This is even easier with an SDK.
There are SDKs for Node.js and PHP on the developer site; we're going to be using the one for PHP. It's avalailable on Packagist, so we simply need to install it using Composer:

composer require acuityscheduling/acuityscheduling

Now we need to make the Acuity Scheduling SDK available throughout the site. The ideal way to do this is to use a service provider to inject it into the application's service container.

Open up app/Providers/AppServiceProvider.php and add a use statement to the top of the file:

use AcuityScheduling;

Then add the following to the register() method:

$this->app->singleton( 'AcuityScheduling', function ( $app ) {
    return new AcuityScheduling( [
        'userId' => env( 'ACUITY_USER_ID' ),
        'apiKey' => env( 'ACUITY_API_KEY' ),
    ] );
} );

Now register the service provider by opening up bootstrap/app.php and uncommenting the following line:

$app->register(App\Providers\AppServiceProvider::class);

The next step is to define the classes for displaying them on the site. In practice you'd probably store these in a database, but for the purposes of this exercise we'll simply hard-code them in an array as a property of the base controller — you'll find this in app/Http/Controllers/Controller.php.

Create the array, being sure to substitute your own appointment type IDs:

protected $classes = [
    [
        'name'  =>  'Introduction to Thai Cookery',
        'key'   =>  'introduction-to-thai-cookery',
        'description' => 'A basic introduction to Thai cookery, which teaches you to make three popular Thai dishes - Tom Yum, a ferocious hot and sour prawn soup, a fragrant green chicken curry and a dessert of mangoes with cocounut and sticky rice"',
        'acuity_id' => 3027517,
    ],
    [
        'name'  =>  'Thai Curry Pastes',
        'key' => 'thai-curry-pastes',
        'description' => 'Pestle and mortar at the ready, as we take a look at Thai curry pastes, the foundation of all Thai curries. Specifically, the course teaches you to make red, green and Panang curry pastes. We will also be cooking a roast duck red curry with sticky rice.',
        'acuity_id' => 3027529,
    ],
    [
        'name'  =>  'Taste of the North',
        'key' => 'taste-of-the-north',
        'description' => 'An in-depth look at the cusine of the North of Thailand.',
        'acuity_id' => 3027535,
    ],
];

As you can probably gather from the code, we're defining a key for identifying each course in an SEO-friendly manner, along with some basic information about each class and that all-important appointment type ID that allows us to integrate with Acuity.

Now all of that's set up, it's time to integrate with Acuity Scheduling.

Listing the Classes and their Availability

The first thing we need to do is list the classes, and the dates on which each class is offered. We've already set all of that up on the Acuity side, along with our meta-data, so the next step is to call the API to get the availability. The endpoint for this is availability/classes. The SDK makes calling this a breeze.

availability/classes gives you the classes for a specified month. By default it only includes those classes with available slots, although you can override that behaviour. We'll do that, but mark the ones with no available slots appropriately.

Create a new controller class — app/Http/Controllers/HomeController — and add the following method:

/**
 * Get the available classes for the given month
 *
 * @param Carbon $month
 * @return array
 */
public function getAvailablity( $month )
{
    return app( 'AcuityScheduling' )->request(
        'availability/classes',
        [
            'query' => [
                'month' => $month->format( 'Y-m' ),
                'includeUnavailable' => 'true',
            ],
        ]
    );
}

Now for the homepage. Create a new method called index(), and we'll begin by getting the availability for the current and next month:

/**
 * The homepage
 *
 * @return \Illuminate\View\View
 */
public function index( )
{
    // Get the dates for this month...
    $availability = $this->getAvailablity( Carbon::now( ) );

    // ...and next month
    $availability += $this->getAvailablity( Carbon::now( )->addMonth( ) );

}

This will return an array of results. Before we render that out, let's use the power of Lumen's collections to do two things:

  1. "Inject" a Carbon instance that represents the date and time of each class; this is a property of the results called time
  2. Group the results by the class; this is represented by the appointmentTypeID property

Here's the code for that:

// Now go through and inject the date as a Carbon instance, then group by the class
$instances = collect(
    $availability
)->map( function( $instance ) {
    $instance[ 'date' ] = Carbon::parse( $instance[ 'time' ] );
    return $instance;
} )->groupBy( 'appointmentTypeID' );

Finally, return the page:

The layout template isn't included here for brevity, but you can grab a copy from GitHub.

// Return the rendered homepage
return view( 'home.index', [ 'classes' => $this->classes, 'instances' => $instances ] );

Now create a new file in resources/views/home/index.blade.php:

@extends( 'layouts.default' )

@section( 'content' )

<p>We offer three different classes, detailed below.</p>

@foreach( $classes as $class )
    <h2></h2>
    <p></p>
    <ul class="instances">
    @foreach( $instances->get( $class[ 'acuity_id' ] ) as $instance )
        <li>
            <h5>
                <time datetime=""> at </time>
                @if ( $instance[ 'slotsAvailable' ] == 0 )
                    <span class="badge badge-danger">Fully booked</span>
                @elseif ( $instance[ 'slotsAvailable' ] < 2 )
                    <span class="badge badge-warning">Only  available</span>
                @else
                    <span class="badge badge-success"> slots available</span>
                @endif
            </h5>

            @if ( $instance[ 'slotsAvailable' ] > 0 )
                <a href="////book" class="btn btn-primary btn-sm">Book Now</a>
            @endif
        </li>
        @endforeach
    </ul>
@endforeach

@stop

The code should be relatively straightforward. We're iterating through the available classes and displaying the information about them. Then we're going through and listing the actual classes along with a label that provides some information about availability, and finally showing a button for booking into classes which have available slots.

You can take what we've done so far for a spin — fire up Terminal and enter:

Continue reading %How to Build a Class Booking System with Acuity Scheduling%


by Lukas White via SitePoint

A Digital Nomad's Guide To Using Google Maps - #infographic

The paper map is dead! Well, in fact this isn’t quite true. There is still an undeniable charm and – for some – creative thrill in penning a set of dubiously proportioned directions on the back of a napkin, drawing a treasure map for your kids to go hunting with, or poring over historical maps in...

[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Irfan Ahmad via Digital Information World