Monday, June 11, 2018

What Is a CDN and How Does It Work?

CDN - you keep seeing the acronym. Maybe in URLs, maybe on landing pages, but it never quite clicked - what are Content Delivery Networks, what do they do exactly?

We'll explain in this overview article, and demonstrate on two popular ones in followup posts.

Network

CDN Basics

A CDN is a network of computers that delivers content.

More specifically, it's a bunch of servers geographically positioned between the origin server of some web content, and the user requesting it, all with the purpose of delivering the content faster by reducing latency. This is their primary purpose.

These geographically closer servers, also called PoPs or Points of Presence, also cache the cacheable content which removes a lot of the load from the origin server. There are different types of CDNs offering different kinds of services, and they can have differing network topology: scattered CDNs aim to have as many servers scattered around the world as possible. Akamai is one such CDN. Consolidated CDNs have fewer points, but bigger ones built for network performance, throughput, and DDoS resistance.

Types of CDNs

We said that their primary purpose was to reduce latency and speed up rendering. But in the modern world of 2MB images and 500kb JavaScript libraries that take 3 minutes to boot up on websites, this latency matters little. But there are other purposes to CDNs, too, which evolved over time.

Content-oriented CDNs

Initially, CDNs were just for static content (JS, CSS, HTML). You had to push content to them as you created/uploaded it (they didn't know they needed to update their cache with your content, not even as someone requested it).

Then, they added origin pulling, making things more automatic - this meant that a user requested the CDN's URL, and then the CDN requested the origin website's URL automatically, caching what ever it got back. Additionally, availability became an important factor. Many CDNs now cache a website's "last alive" state so that if the origin goes down, the CDNed content is still accessible to users, creating the illusion of stability until things return to normal.

Additionally, modern CDNs often offer auto-optimization layers which will automagically resize images and save them for future use based on the image size requested. This means what if your site has a 2MB header image and someone requests it on a 300px wide screen, the CDN will make a copy that's 30kb in size and 300px wide and serve that in the future to all mobile users, automatically making the site faster.

Security-oriented CDNs

The final layer of practicality added to CDNs was DDoS and bot protection. CDNs like Incapsula specialize in this.

As the CDN is the outermost layer of a website's infrastructure and the first recipient of traffic, it can detect DDoS attacks early and block them with special DDoS protection servers called scrubbers without them ever reaching the origin server and crashing it.

The post What Is a CDN and How Does It Work? appeared first on SitePoint.


by Bruno Skvorc via SitePoint

Cardea HTML

‘Cardea’ is a One Page HTML portfolio template with a refreshing, colorful design. The template loads project items using AJAX allowing the potential client to browse your full portfolio without reloading the page. Other features include a sticky header navigation, smooth scroll to sections, marketing copy slider, about section with video overlay, blog feed, pricing table, skills graph, team, unique testimonial slider with alongside client logos and ends strong with an enquiry form. Awesome work once again by CocoBasic and what a bargain for $9!

Is you’re after a content management system, Cardea is also available for WordPress.


by Rob Hope @robhope via One Page Love

Use Parcel to Bundle a Hyperapp App & Deploy to GitHub Pages

In a previous post we met Hyperapp, a tiny library that can be used to build dynamic, single-page web apps in a similar way to React or Vue.

In this post we’re going to turn things up a notch. We’re going to create the app locally (we were working on CodePen previously), learn how to bundle it using Parcel (a module bundler similar to webpack or Rollup) and deploy it to the web using GitHub Pages.

Don’t worry if you didn’t complete the project from the first post. All the code is provided here (although I won’t go into detail explaining what it does) and the principles outlined can be applied to most other JavaScript projects.

If you’d like to see what we’ll be ending up with, you can view the finished project here, or download the code from our GitHub repo.

Basic Setup

In order to follow along, you’ll need to have both Node.js and npm installed (they come packaged together). I’d recommend using a version manager such as nvm to manage your Node installation (here’s how), and if you’d like some help getting to grips with npm, then check out our beginner-friendly npm tutorial.

We’ll be using the terminal commands to create files and folders, but feel free to do it by just pointing and clicking instead if that’s your thing.

To get started, create a new folder called hyperlist:

mkdir hyperlist

Now change to that directory and initialize a new project using npm:

cd hyperlist/
npm init

This will prompt you to answer some questions about the app. It’s fine to just press enter to accept the default for any of these, but feel free to add in your name as the author and to add a description of the app.

This should create a file called package.json inside the hyperlist directory that looks similar to the following:

{
  "name": "hyperlist",
  "version": "1.0.0",
  "description": "A To-do List made with Hyperapp",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "DAZ",
  "license": "MIT"
}

Now we need to install the Hyperapp library. This is done using npm along with the --save flag, which means that the package.json file will be updated to include it as a dependency:

npm install --save hyperapp

This might give some warnings about not having a repository field. Don’t worry about this, as we’ll be fixing it later. It should update the package.json file to include the following entry (there might be a slight difference in version number):

"dependencies": {
  "hyperapp": "^1.2.5"
}

It will also create a directory called node_modules where all the Hyperapp files are stored, as well as a file called package-lock.json. This is used to keep track of the dependency tree for all the packages that have been installed using npm.

Now we’re ready to start creating the app!

Folder Structure

It’s a common convention to put all of your source code into a folder called src. Within this folder, we’re going to put all of our JavaScript files into a directory called js. Let’s create both of those now:

mkdir -p src/js

In the previous post we learned that apps are built in Hyperapp using three main parts: state, actions and view. In the interests of code organization, we’re going to place the code for each part in a separate file, so we need to create these files inside the js directory:

cd src/js
touch state.js actions.js view.js

Don’t worry that they’re all empty. We’ll add the code soon!

Last of all, we’ll go back into the src directory and create our “entry point” files. These are the files that will link to all the others. The first is index.html, which will contain some basic HTML, and the other is index.js, which will link to all our other JavaScript files and also our SCSS files:

cd ..
touch index.html index.js

Now that our folder structure is all in place, we can go ahead and start adding some code and wiring all the files together. Onward!

Some Basic HTML

We’ll start by adding some basic HTML code to the index.html file. Hyperapp takes care of creating the HTML and can render it directly into the <body> tag. This means that we only have to set up the meta information contained in the <head> tag. Except for the <title> tag’s value, you can get away with using the same index.html file for every project. Open up index.html in your favorite text editor and add the following code:

<!doctype html>
<html lang='en'>
  <head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <title>HyperList</title>
  </head>
  <body>
    <script src='index.js'></script>
  </body>
</html>

Now it’s time to add some JavaScript code!

ES6 Modules

Native JavaScript modules were introduced in ES6 (aka ES2015). Unfortunately, browsers have been slow to adopt the use of ES6 modules natively, although things are now starting to improve. Luckily, we can still use them to organize our code, and Parcel will sort out piecing them all together.

Let’s start by adding the code for the initial state inside the state.js file:

const state = {
  items: [],
  input: '',
  placeholder: 'Make a list..'
};

export default state;

This is the same as the object we used in the previous article, but with the export declaration at the end. This will make the object available to any other file that imports it. By making it the default export, we don’t have to explicitly name it when we import it later.

Next we’ll add the actions to actions.js:

const actions = {
  add: () => state => ({
    input: '',
    items: state.items.concat({
      value: state.input,
      completed: false,
      id: Date.now()
    })
  }),
  input: ({ value }) => ({ input: value }),
  toggle: id => state => ({
    items: state.items.map(item => (
      id === item.id ? Object.assign({}, item, { completed: !item.completed }) : item
    ))
  }),
  destroy: id => state => ({
    items: state.items.filter(item => item.id !== id)
  }),
  clearAllCompleted: ({ items }) => ({
    items: items.filter(item => !item.completed)
  })
};

export default actions;

Again, this is the same as the object we used in the previous article, with the addition of the export declaration at the end.

Last of all we’ll add the view code to view.js:

import { h } from 'hyperapp'

const AddItem = ({ add, input, value, placeholder }) => (
  <div class='flex'>
    <input
      type="text"
      onkeyup={e => (e.keyCode === 13 ? add() : null)}
      oninput={e => input({ value: e.target.value })}
      value={value}
      placeholder={placeholder}
    />
    <button onclick={add}>+</button>
  </div>
);

const ListItem = ({ value, id, completed, toggle, destroy }) => (
  <li class={completed && "completed"} id={id} key={id} onclick={e => toggle(id)}>
    {value} <button onclick={ () => destroy(id) }>x</button>
  </li>
);

const view = (state, actions) => (
  <div>
    <h1><strong>Hyper</strong>List</h1>
    <AddItem
      add={actions.add}
      input={actions.input}
      value={state.input}
      placeholder={state.placeholder}
    />
    <ul id='list'>
      {state.items.map(item => (
        <ListItem
          id={item.id}
          value={item.value}
          completed={item.completed}
          toggle={actions.toggle}
          destroy={actions.destroy}
        />
      ))}
    </ul>
    <button onclick={() => actions.clearAllCompleted({ items: state.items }) }>
      Clear completed items
    </button>
  </div>s
);

export default view;

First of all, this file uses the import declaration to import the h module from the Hyperapp library that we installed using npm earlier. This is the function that Hyperapp uses to create the Virtual DOM nodes that make up the view.

This file contains two components: AddItem and ListItem. These are just functions that return JSX code and are used to abstract different parts of the view into separate building blocks. If you find that you’re using a large number of components, it might be worth moving them into a separate components.js file and then importing them into the view.js file.

Notice that only the view function is exported at the end of the file. This means that only this function can be imported by other files, rather than the separate components.

Now we’ve added all our JavaScript code, we just need to piece it all together in the index.js file. This is done using the import directive. Add the following code to index.js:

import { app } from 'hyperapp'

import state from './js/state.js'
import actions from './js/actions.js'
import view from './js/view.js'

const main = app(state, actions, view, document.body);

This imports the app function from the Hyperapp library, then imports the three JavaScript files that we just created. The object or function that was exported from each of these files is assigned to the variables state,actions and view respectively, so they can be referenced in this file.

The last line of code calls the app function, which starts the app running. It uses each of the variables created from our imported files as the first three arguments. The last argument is the HTML element where the app will be rendered — which, by convention, is document.body.

The post Use Parcel to Bundle a Hyperapp App & Deploy to GitHub Pages appeared first on SitePoint.


by Darren Jones via SitePoint

Truffle: Testing Smart Contracts

In our introduction to Truffle, we discussed what Truffle is and how it can help you automate the job of compiling, testing and deploying smart contracts.

In this article, we’ll explore how to test smart contracts. Testing is the most important aspect of quality smart contract development.

Why test extensively? So you can avoid stuff like this, or this. Smart contracts handle value, sometimes a huge amount of value — which makes them very interesting prey for people with the time and the skills to attack them.

You wouldn’t want your project to end up on the Blockchain graveyard, would you?

Getting Started

We’re going to be making HashMarket, a simple, smart-contract based used goods market.

Open your terminal and position yourself in the folder where you want to build the project. In that folder, run the following:

mkdir HashMarket
cd HashMarket
truffle init

You should get a result that looks a little bit like this:

Downloading...
Unpacking...
Setting up...
Unbox successful. Sweet!

Commands:

  Compile:        truffle compile
  Migrate:        truffle migrate
  Test contracts: truffle test

You’ll also get a file structure that looks like this:

.
├── contracts
│   └── Migrations.sol
├── migrations
│   └── 1_initial_migration.js
├── test
├── truffle-config.js
└── truffle.js

For a refresher on the files, take a look at the previous article. In a nutshell, we have the basic truffle.js and the two files used for making the initial migrations onto the blockchain.

Preparing the test environment

The easiest way to test is on the local network. I highly recommend using the ganache-cli (previously known as TestRPC) tool for contract testing.

Install ganache-cli (which requires the Node Package Manager):

npm install -g ganache-cli

After that, open a separate terminal window or tab and run this:

ganache-cli

You should see an output similar to this:

Ganache CLI v6.1.0 (ganache-core: 2.1.0)

Available Accounts
==================
(0) 0xd14c83349da45a12b217988135fdbcbb026ac160
(1) 0xc1df9b406d5d26f86364ef7d449cc5a6a5f2e8b8
(2) 0x945c42c7445af7b3337834bdb1abfa31e291bc40
(3) 0x56156ea86cd46ec57df55d6e386d46d1bbc47e3e
(4) 0x0a5ded586d122958153a3b3b1d906ee9ff8b2783
(5) 0x39f43d6daf389643efdd2d4ff115e5255225022f
(6) 0xd793b706471e257cc62fe9c862e7a127839bbd2f
(7) 0xaa87d81fb5a087364fe3ebd33712a5522f6e5ac6
(8) 0x177d57b2ab5d3329fad4f538221c16cb3b8bf7a7
(9) 0x6a146794eaea4299551657c0045bbbe7f0a6db0c

Private Keys
==================
(0) 66a6a84ee080961beebd38816b723c0f790eff78f0a1f81b73f3a4c54c98467b
(1) fa134d4d14fdbac69bbf76d2cb27c0df1236d0677ec416dfbad1cc3cc058145e
(2) 047fef2c5c95d5cf29c4883b924c24419b12df01f3c6a0097f1180fa020e6bd2
(3) 6ca68e37ada9b1b88811015bcc884a992be8f6bc481f0f9c6c583ef0d4d8f1c9
(4) 84bb2d44d64478d1a8b9d339ad1e1b29b8dde757e01f8ee21b1dcbce50e2b746
(5) 517e8be95253157707f34d08c066766c5602e519e93bace177b6377c68cba34e
(6) d2f393f1fc833743eb93f108fcb6feecc384f16691250974f8d9186c68a994ef
(7) 8b8be7bec3aca543fb45edc42e7b5915aaddb4138310b0d19c56d836630e5321
(8) e73a1d7d659b185e56e5346b432f58c30d21ab68fe550e7544bfb88765235ae3
(9) 8bb5fb642c58b7301744ef908fae85e2d048eea0c7e0e5378594fc7d0030f100

HD Wallet
==================
Mnemonic:      ecology sweet animal swear exclude quote leopard erupt guard core nice series
Base HD Path:  m/44'/60'/0'/0/{account_index}

Listening on localhost:8545

This is a listing of all the accounts ganache-cli created for you. You can use any account you wish, but these accounts will be preloaded with ether, so that makes them very useful (since testing requires ether for gas costs).

After this, go to your truffle.js or truffle-config.js file and add a development network to your config:

module.exports = {
    networks: {
      development: {
        host: "127.0.0.1",
        port: 8545,
        network_id: "*"
      }
    }
};

The post Truffle: Testing Smart Contracts appeared first on SitePoint.


by Mislav Javor via SitePoint

Faune

Colorful, long-scrolling One Pager promoting the Faune typeface by Alice Savoie. Make sure you check out the interactive sliders to demo the font weights, really well done.


by Rob Hope @robhope via One Page Love

Quality Solidity Code with OpenZeppelin and Friends

Given the fact that all of Ethereum’s computations need to be reproduced on all the nodes in the network, Ethereum’s computing is inherently costly and inefficient. (In fact, Ethereum’s developer docs on GitHub state that we shouldn’t expect more computational power from Ethereum than we do from a 1999 phone.)

So, security on the Ethereum Virtual Machine — meaning, the security of smart contracts deployed on Ethereum blockchain — is of paramount importance. All the errors on it cost real money — whether it’s errors thrown by badly-written contracts, or hackers exploiting loopholes in contracts, like in the well-known DAO hack, which caused a community split and sprang the Ethereum Classic blockchain into existence.

Turing Completeness — and a whole range of other design decisions that have made Ethereum a lot more capable and sophisticated — have come at a cost. Ethereum’s richness has made it more vulnerable to errors and hackers.

To add to the problem, smart contracts deployed on Ethereum cannot be modified. The blockchain is an immutable data structure.

This and this article go into more depth regarding security of smart contracts, and the ecosystem of tools and libraries to help us to make our smart contracts secure.

Let’s look at some amazing upgrades to our toolset we can use today to utilize the best practices the Solidity environment can offer.

Helper Tools

One of the coolest tools in the toolset of an Ethereum developer is OpenZeppelin’s library. It’s a framework consisting of many Solidity code patterns and smart contract modules, written in a secure way. The authors are Solidity auditors and consultants themselves, and you can read about a third-party audit of these modules here. Manuel Araoz from Zeppelin Solutions, an Argentinian company behind OpenZeppelin, outlines the main Solidity security patterns and considerations.

OpenZeppelin is establishing itself as an industry standard for reusable and secure open source (MIT) base of Solidity code, which can easily be deployed using Truffle. It consists of smart contracts which, once installed via npm, can be easily imported and used in our contracts.

The process of installing truffle

The Truffle Framework published a tutorial for using OpenZeppelin with Truffle and Ganache.

These contracts are meant to be imported and their methods are meant to be overridden, as needed. The files shouldn’t be modified in themselves.

ICO patterns

OpenZeppelin’s library contains a set of contracts for publishing tokens on the Ethereum platform — for ERC20 tokens, including a BasicToken contract, BurnableToken, CappedToken. This is a mintable token with a fixed cap, MintableToken, PausableToken, with which token transfers can be paused. Then there is TokenVesting, a contract that can release its token balance gradually like a typical vesting scheme, with a cliff and vesting period, and more.

There’s also set of contracts for ERC721 tokens — or non-fungible, unique tokens of the CryptoKitties type.

ERC827 tokens contracts, standard for sending data along with transacted tokens, are also included.

There’s also a set of crowdsale contracts — contracts for conducting Initial Coin Offerings. These can log purchases, deliver/emit tokens to buyers, forward ETH funds. There are functions for validating and processing token purchases.

The FinalizableCrowdsale contract provides for execting some logic post-sale. PostDeliveryCrowdsale allows freezing of withdrawals until the end of the crowdsale. RefundableCrowdsale is an extension of the Crowdsale contract that adds a funding goal, and the possibility of users getting a refund if the goal is not met.

Destructible contracts can be destroyed by the owner, and have all the funds sent to the owner. There are also contracts for implementing pausability to child contracts.

OpenZeppelin provides many helpers and utilities for conducting ICOs — like a contract which enables recovery of ERC20 tokens mistakenly sent to an ICO address instead of ETH. A heritable contract provides for transferring of ownership to another owner under certain circumstances. The Ownable contract has an owner address, and provides basic authorization/permissions and transferring of ownership.

The RBAC contract provides utilities for role-based access control. We can assign different roles to different addresses, with an unlimited number of roles.

Zeppelin also provides a sample crowdsale starter Truffle project which hasn’t been audited yet, so it’s best used as an introduction to using OpenZeppelin. It makes it easy to start off with a crowdsale and a token fast.

The post Quality Solidity Code with OpenZeppelin and Friends appeared first on SitePoint.


by Tonino Jankov via SitePoint

Creating Stylish and Responsive Progress Bars Using ProgressBar.js

Nothing on the web happens instantly. The only difference is in the time it takes for a process to complete. Some processes can happen in a few milliseconds, while others can take up to several seconds or minutes. For example, you might be editing a very large image uploaded by your users, and this process can take some time. In such cases, it is a good idea to let the visitors know that the website is not stuck somewhere but it is actually working on your image and making some progress.

One of the most common ways to show readers how much a process has progressed is to use progress bars. In this tutorial, you will learn how to use the ProgressBar.js library to create different progress bars with simple and complex shapes.

Creating a Basic Progress Bar

Once you have included the library in your project, creating a progress bar using this library is easy. ProgressBar.js is supported in all major browsers, including IE9+, which means that you can use it in any website you are creating with confidence. You can get the latest version of the library from GitHub or directly use a CDN link to add it in your project.

To avoid any unexpected behavior, please make sure that the container of the progress bar has the same aspect ratio as the progress bar. In the case of a circle, the aspect ratio of the container should be 1:1 because the width will be equal to the height. In the case of a semicircle, the aspect ratio of the container should be 2:1 because the width will be double the height. Similarly, in the case of a simple line, the container should have an aspect ratio of 100:strokeWidth for the line.

When creating progress bars with a line, circle, or semicircle, you can simply use the ProgressBar.Shape() method to create the progress bar. In this case, the Shape can be a Circle, Line, or SemiCircle. You can pass two parameters to the Shape() method. The first parameter is a selector or DOM node to identify the container of the progress bar. The second parameter is an object with key-value pairs which determine the appearance of the progress bar.

You can specify the color of the progress bar using the color property. Any progress bar that you create will have a dark gray color by default. The thickness of the progress bar can be specified using the strokeWidth property. You should keep in mind that the width here is not in pixels but in terms of a percentage of the canvas size. For instance, if the canvas is 200px wide, a strokeWidth value of 5 will create a line which is 10px thick.

Besides the main progress bar, the library also allows you to draw a trailing line which will show readers the path on which the progress bar will move. The color of the trail line can be specified using the trailColor property, and its width can be specified using the trailWidth property. Just like strokeWidth, the trailWidth property also computes the width in percentage terms.

The total time taken by the progress bar to go from its initial state to its final state can be specified using the duration property. By default, a progress bar will complete its animation in 800 milliseconds.

You can use the easing property to specify how a progress bar should move during the animation. All progress bars will move with a linear speed by default. To make the animation more appealing, you can set this value to something else like easeIn, easeOut, easeInOut, or bounce.

After specifying the initial parameter values, you can animate the progress bars using the animate() method. This parameter accepts three parameters. The first parameter is the amount up to which you want to animate the progress line. The two other parameters are optional. The second parameter can be used to override any animation property values that you set during initialization. The third parameter is a callback function to do something else once the animation ends.

In the following example, I have created three different progress bars using all the properties we have discussed so far.

Animating Text Values With the Progress Bar

The only thing that changes with the animation of the progress bars in the above example is their length. However, ProgressBar.js also allows you to change other physical attributes like the width and color of the stroking line. In such cases, you will have to specify the initial values for the progress bar inside the from parameter and the final values inside the to parameter when initializing the progress bars.

You can also tell the library to create an accompanying text element with the progress bar to show some textual information to your users. The text can be anything from a static value to a numerical value indicating the progress of the animation. The text parameter will accept an object as its value. 

This object can have a value parameter to specify the initial text to be shown inside the element. You can also provide a class name to be added to the text element using the className parameter. If you want to apply some inline styles to the text element, you can specify them all as a value of the style parameter. All the default styles can be removed by setting the value of style to null. It is important to remember that the default values only apply if you have not set a custom value for any CSS property inside style.

The value inside the text element will stay the same during the whole animation if you don't update it yourself. Luckily, ProgressBar.js also provides a step parameter which can be used to define a function to be called with each animation step. Since this function will be called multiple times each second, you need to be careful with its use and keep the calculations inside it simple.

Creating Progress Bars With Custom Shapes

Sometimes, you might want to create progress bars with different shapes that match the overall theme of your website. ProgressBar.js allows you to create progress bars with custom shapes using the Path() method. This method works like Shape() but provides fewer parameters to customize the progress bar animation. You can still provide a duration and easing value for the animation. If you want to animate the color and width of the stroke used for drawing the custom path, you can do so inside the from and to parameters.

The library does not provide any way to draw a trail for the custom path, as it did for simple lines and circles. However, you can create the trail yourself fairly easily. In the following example, I have created a triangular progress bar using the Path() method.

Before writing the JavaScript code, we will have to define our custom SVG path in HTML. Here is the code I used to create a simple triangle:

You might have noticed that I created two different path elements. The first path has a light gray color which acts like the trail we saw with simple progress bars in the previous section. The second path is the one that we animate with our code. We have given it an id which is used to identify it in the JavaScript code below.

Final Thoughts

As you saw in this tutorial, ProgressBar.js allows you to easily create different kinds of progress bars with ease. It also gives you the option to animate different attributes of the progress bar like its width and color. 

Not only that, but you can also use this library to change the value of an accompanying text element in order to show the progress in textual form. This tutorial covers everything that you need to know to create simple progress bars. However, you can go through the documentation to learn more about the library.

If there is anything that you would like me to clarify in this tutorial, feel free to let me know in the comments.


by Monty Shokeen via Envato Tuts+ Code