Web Development

Free Programming Courses from Harvard, MIT, Microsoft and more (Sponsored)

Did you know that you can learn programming online from institutions like Harvard, MIT and Microsoft on edX.org? The nonprofit site offers 2000 online courses from 140 institutions worldwide. Courses are free to try.

EdX has over 200 courses from Microsoft alone, including an 11 course program for Front End Web Development, described as follows:

If you want to become a front-end web developer, it can be difficult to figure out where to begin. Which frameworks, languages, and libraries should be your focus? The Microsoft Professional Program in Front-End Web Development is a curriculum that eliminates some of this confusion by introducing you to the fundamentals, teaching the most frequently used tools, and then offering a way for you to prove you have the skills through a final capstone project that can be showcased in your portfolio. 

Here are some of the more popular courses Microsoft offers for front end web development:

Besides the Microsoft courses, here are some of the top programming courses and programs to check out. 

CS50 from Harvard

The most popular course on edX gives you an introduction to computer science and programming. Learn how to think algorithmically and solve programming problems efficiently. Gain familiarity in a number of programming languages including C, Python, SQL, JavaScript, CSS and HTML.

Front End Web Developer from W3C

W3C (World Wide Web Consortium) is the organization that develops web standards. It was founded by the inventor of the web, Tim Berners-Lee. In this 5 course program, learn how to code with modern HTML5 tags, draw and animate fun web graphics, and play audio and video elements. Learn CSS best practices for web page design and the fundamentals of JavaScript to help you develop interactive web apps.

Introduction to Computing in Python from Georgia Tech

In this 4 course program, learn the fundamentals of computer science in one of the field’s most popular programming languages, Python 3, including writing code, executing it, interpreting the results, and revising the code based on the outcomes. Rated as one of the most in-demand and beginner-friendly programming languages, a background in Python will give you a solid foundation to build your career. Short videos (2-3 minutes each) are rapidly interwoven with live programming problems and multiple-choice questions to give you constant feedback on your progress and understanding.

C Programming with Linux from Dartmouth

Did you know that smartphones, your car’s navigation system, robots, drones, trains, and almost all electronic devices have some C-code running under the hood? Along with the C programming language comes Linux, an essential operating system that powers almost all supercomputers and most of the servers worldwide, as well as all Android devices and most “Internet of Things” devices. 

In this 7 course program, develop and debug code in the C programming language. Discover the foundations of computer programming and Linux, manipulate the command line, manage processes, files and memory, and compile C code with Linux. 

Data Science from Harvard

Data science is one of the hottest fields in programming. Learn key data science essentials in this 9 course program, including R and machine learning, through real-world case studies to jumpstart your career as a data scientist. Also learn statistical concepts such as probability, inference, and modeling and how to apply them in practice. Gain experience with data visualization with ggplot2 and data wrangling with dplyr. Become familiar with essential tools for practicing data scientists such as Unix/Linux, git and GitHub, and RStudio. This is one of the most popular programs on edX. 

Blockchain for Business from the Linux Foundation

Everyone has heard of blockchain, but most don’t understand how it can apply to their business. Learn exactly what a blockchain is, its impact and potential for change around the world, and analyze use cases in technology, business, and enterprise products and institutions in this fundamental course from the experts at the Linux Foundation.

If you are looking for something else, edX offers beginner to advanced programming courses in C++, C#, Java, Power BI, Artificial Intelligence, Machine Learning, Deep Learning, Cybersecurity, IoT, Cloud Computing, AWS, Azure, DevOps, and more. View more courses here.

The post Free Programming Courses from Harvard, MIT, Microsoft and more (Sponsored) appeared first on David Walsh Blog.

How To Align Things In CSS

How To Align Things In CSS

How To Align Things In CSS

Rachel Andrew

2019-03-28T12:30:41+01:00
2019-03-28T15:51:58+00:00

We have a whole selection of ways to align things in CSS today, and it isn’t always an obvious decision which to use. However, knowing what is available means that you can always try a few tactics if you come across a particular alignment problem.

In this article, I will take a look at the different alignment methods. Instead of providing a comprehensive guide to each, I’ll explain a few of the sticking points people have and point to more complete references for the properties and values. As with much of CSS, you can go a long way by understanding the fundamental things about how the methods behave, and then need a place to go look up the finer details in terms of how you achieve the precise layout that you want.

Aligning Text And Inline Elements

When we have some text and other inline elements on a page, each line of content is treated as a line box. The property text-align will align that content on the page, for example, if you want your text centered, or justified. Sometimes, however, you may want to align things inside that line box against other things, for example, if you have an icon displayed alongside text, or text of different sizes.

In the example below, I have some text with a larger inline image. I am using vertical-align: middle on the image to align the text to the middle of the image.

The line-height Property And Alignment

Remember that the line-height property will change the size of the line-box and therefore can change your alignment. The following example uses a large line-height value of 150px, and I have aligned the image to top. The image is aligned to the top of the line box and not the top of the text, remove that line-height or make it less than the size of the image and the image and text will line up at the top of the text.

It turns out that line-height and indeed the size of text is pretty complicated, and I’m not going to head down that rabbit hole in this article. If you are trying to precisely align inline elements and want to really understand what is going on, I recommend reading “Deep Dive CSS: Font Metrics, line-height And vertical-align.”

When Can I Use The vertical-align Property?

The vertical-align property is useful if you are aligning any inline element. This includes elements with display: inline-block. The content of table cells can also be aligned with the vertical-align property.

The vertical-align property has no effect on flex or grid items, and therefore if used as part of a fallback strategy, will cease to apply the minute the parent element is turned into a grid or flex Container. For example, in the next pen, I have a set of items laid out with display: inline-block and this means that I get the ability to align the items even if the browser does not have Flexbox:

See the Pen inline-block and vertical-align by Rachel Andrew.

In this next pen, I have treated the inline-block as a fallback for Flex layout. The alignment properties no longer apply, and I can add align-items to align the items in Flexbox. You can tell that the Flexbox method is in play because the gap between items that you will get when using display: inline-block is gone.

See the Pen inline-block flex fallback by Rachel Andrew.

The fact that vertical-align works on table cells is the reason that the trick to vertically center an item using display: table-cell works.

Now that we do have better ways to align boxes in CSS (as we will look at in the next section), we don’t need to employ the vertical-align and text-align properties in places other than the inline and text elements for which they were designed. However, they are still completely valid to use in those text and inline formats, and so remember if you are trying to align something inline, it is these properties and not the Box Alignment ones that you need to reach for.

Box Alignment

The Box Alignment Specification deals with how we align everything else. The specification details the following alignment properties:

  • justify-content
  • align-content
  • justify-self
  • align-self
  • justify-items
  • align-items

You might already think of these properties as being part of the Flexbox Specification, or perhaps Grid. The history of the properties is that they originated as part of Flexbox, and still exist in the Level 1 specification; however, they were moved into their own specification when it became apparent that they were more generally useful. We now also use them in Grid Layout, and they are specified for other layout methods too, although current browser support means that you won’t be able to use them just yet.

Therefore, next time someone on the Internet tells you that vertical alignment is the hardest part of CSS, you can tell them this (which even fits into a tweet):

.container 
  display: flex;
  align-items: center;
  justify-content: center;

In the future, we may even be able to dispense with display: flex, once the Box Alignment properties are implemented for Block Layout. At the moment, however, making the parent of the thing you want centering a flex container is the way to get alignment horizontally and vertically.

The Two Types Of Alignment

When aligning flex and grid items, you have two possible things to align:

  1. You have the spare space in the grid or flex container (once the items or tracks have been laid out).
  2. You also have the item itself inside the grid area you placed it in, or on the cross axis inside the flex container.

I showed you a set of properties above, and the alignment properties can be thought of as two groups. Those which deal with distribution of spare space, and those which align the item itself.

Dealing With Spare Space: align-content And justify-content

The properties which end in -content are about space distribution, so when you choose to use align-content or justify-content you are distributing available space between grid tracks or flex items. They don’t change the size of the flex or grid items themselves; they move them around because they change where the spare space goes.

Below, I have a flex example and a grid example. Both have a container which is larger than required to display the flex items or grid tracks, so I can use align-content and justify-content to distribute that space.

See the Pen justify-content and align-content by Rachel Andrew.

Moving Items Around: justify-self, align-self, justify-items And align-items

We then have align-self and justify-self as applied to individual flex or grid items; you can also use align-items and justify-items on the container to set all the properties at once. These properties deal with the actual flex or grid item, i.e. moving the content around inside the Grid Area or flex line.

  • Grid Layout
    You get both properties as you can shift the item on the block and inline axis as we have a defined Grid Area in which it sits.
  • Flex Layout
    You can only align on the cross axis as the main axis is controlled by space distribution alone. So if your items are a row, you can use align-self to shift them up and down inside the flex line, aligning them against each other.

In my example below, I have a flex and a grid container, and am using align-items and align-self in Flexbox to move the items up and down against each other on the cross axis. If you use Firefox, and inspect the element using the Firefox Flexbox Inspector, you can see the size of the flex container and how the items are being moved vertically inside of that.


Flex items aligned in their container
Aligned flex items with the flex container highlighted in Firefox (Large preview)

In grid, I can use all four properties to move the items around inside their grid area. Once again, the Firefox DevTools Grid Inspector will be useful when playing with alignment. With the grid lines overlaid, you can see the area inside which the content is being moved:


Aligned grid items
Aligned grid items with the Grid highlighted in Firefox (Large preview)

Play around with the values in the CodePen demo to see how you can shift content around in each layout method:

See the Pen justify-self, align-self, justify-items, align-items by Rachel Andrew.

Confused By align And justify

One of the cited issues with people remembering the alignment properties in Grid and Flexbox, is that no one can remember whether to align or to justify. Which direction is which?

For Grid Layout, you need to know if you are aligning in the Block or Inline Direction. The Block direction is the direction blocks lay out on your page (in your writing mode), i.e. for English that is vertically. The Inline direction is the direction in which sentences run (so for English that is left to right horizontally).

To align things in the Block Direction, you will use the properties which start with align-. You use align-content to distribute space between grid tracks, if there is free space in the grid container, and align-items or align-self to move an item around inside the grid area it has been placed in.

The below example has two grid layouts. One has writing-mode: horizontal-tb (which is the default for English) and the other writing-mode: vertical-rl. This is the only difference between them. You can see that the alignment properties which I have applied work in exactly the same way on the block axis in both modes.

See the Pen Grid Block Axis Alignment by Rachel Andrew.

To align things in the inline direction, use the properties which begin with justify-. Use justify-content to distribute space between grid tracks, and justify-items or justify-self to align items inside their grid area in the inline direction.

Once again, I have two grid layout examples so that you can see that inline is always inline — no matter which writing mode you are using.

See the Pen Grid Inline Alignment by Rachel Andrew.

Flexbox is a little trickier due to the fact that we have a main axis which can be changed to row or column. So, let’s first think about that main axis. It is set with the flex-direction property. The initial (or default) value of this property is row which will lay the flex items out as a row in the writing mode currently in use — this is why when working in English, we end up with items laid out horizontally when we create a flex container. You can then change the main axis to flex-direction: column and the items will be laid out as a column which means they are laid out in the block direction for that writing mode.

As we can do this axis switching, the most important factor in Flexbox is asking, “Which axis is my main axis?” Once you know that, then for alignment (when on your main axis) you simply use justify-content. It doesn’t matter if your main axis is row or column. You control space between the flex items with justify-content.

See the Pen justfy-content in Flexbox by Rachel Andrew.

On the cross axis, you can use align-items which will align the items inside the flex container or flex line in a multi-line flex container. If you have a multi-line container using flex-wrap: wrap and have space in that container, you can use align-content to distribute the space on the cross axis.

In the example below, we are doing both with a flex container displayed as a row and a column:

See the Pen Cross axis alignment in Flexbox by Rachel Andrew.

When justify-content Or align-content Do Not Work

The justify-content and align-content properties in Grid and Flexbox are about distributing extra space. So the thing to check is that you have extra space.

Here is a Flex example: I have set flex-direction: row and I have three items. They don’t take up all of the space in the flex container, so I have spare space on the main axis, the initial value for justify-content is flex-start and so my items all line up at the start and the extra space is at the end. I am using the Firefox Flex Inspector to highlight the space.


Flex items aligned left, highlighted spare space on the right
The spare space at the end of the container (Large preview)

If I change flex-direction to space-between, that extra space is now distributed between the items:


Flex items aligned so space is distributed between the items
The spare space is now between the items (Large preview)

If I now add more content to my items so they become larger and there is no longer any additional space, then justify-content does nothing — simply because there is no space to distribute.


Flex items are filling the container with no spare space
There is now no space to distribute (Large preview)

A common question I’m asked is why justify-content isn’t working when flex-direction is column. This is generally because there is no space to distribute. If you take the above example and make it flex-direction: column, the items will display as a column, but there will be no additional space below the items as there is when you do flex-direction: row. This is because when you make a Flex Container with display: flex you have a block level flex container; this will take up all possible space in the inline direction. In CSS, things do not stretch in the block direction, so no extra space.


Flex items arranged as a column
The column is only as tall as needed to display the items (Large preview)

Add a height to the container and — as long as that is more than is required to display the items — you have extra space and therefore justify-content will work on your column.


A column of flex items with space between them.
Adding a height to the container means we have spare space (Large preview)

Why Is There No justify-self In Flexbox?

Grid Layout implements all of the properties for both axes because we always have two axes to deal with in Grid Layout. We create tracks (which may leave additional space in the grid container in either dimension,) and so we can distribute that space with align-content or justify-content. We also have Grid Areas, and the element in that area may not take up the full space of the area, so we can use align-self or justify-self to move the content around the area (or align-items, justify-items to change the alignment of all items).

Flexbox does not have tracks in the way that Grid layout does. On the main axis, all we have to play with is the distribution of space between the items. There is no concept of a track into which a flex item is placed. So there is no area created in which to move the item around in. This is why there is no justify-self property on the main axes in Flexbox.

Sometimes, however, you do want to be able to align one item or part of the group of items in a different way. A common pattern would be a split navigation bar with one item being separated out from the group. In that situation, the specification advises the use of auto margins.

An auto margin will take up all of the space in the direction it is applied, which is why we can center a block (such as our main page layout) using a left and right margin of auto. With an auto margin on both sides, each margin tries to take up all the space and so pushes the block into the middle. With our row of flex items, we can add margin-left: auto to the item we want the split to happen on, and as long as there is available space in the flex container, you get a split. This plays nicely with Flexbox because as soon as there is no available space, the items behave as regular flex items do.

Flexbox And Micro-Components

One of the things I think is often overlooked is how useful Flexbox is for doing tiny layout jobs, where you might think that using vertical-align is the way to go. I often use Flexbox to get neat alignment of small patterns; for example, aligning an icon next to text, baseline aligning two things with different font sizes, or making form fields and buttons line up properly. If you are struggling to get something to line up nicely with vertical-align, then perhaps try doing the job with Flexbox. Remember that you can also create an inline flex container if you want with display: inline-flex.

There is no reason not to use Flexbox, or even Grid for tiny layout jobs. They aren’t just for big chunks of layout. Try the different things available to you, and see what works best.

People are often very keen to know what the right or wrong way to do things is. In reality, there often is no right or wrong; a small difference in your pattern might mean the difference between Flexbox working best, where otherwise you would use vertical-align.

Wrapping Up

To wrap up, I have a quick summary of the basics of alignment. If you remember these few rules, you should be able to align most things with CSS:

  1. Are you aligning text or an inline element? If so, you need to use text-align, vertical-align, and line-height.
  2. Do you have an item or items you want to align in the center of the page or container? If so, make the container a flex container then set align-items: center and justify-content: center.
  3. For Grid Layouts, the properties that start with align- work in the Block direction; those which start with justify- work in the inline direction.
  4. For Flex Layouts, the properties that start with align- work on the Cross Axis; those which start with justify- work on the main axis.
  5. The justify-content and align-content properties distribute extra space. If you have no extra space in your flex or grid container, they will do nothing.
  6. If you think you need justify-self in Flexbox, then using an auto margin will probably give you the pattern you are after.
  7. You can use Grid and Flexbox along with the alignment properties for tiny layout jobs as well as main components — experiment!

For more information about alignment, see these resources:

Smashing Editorial
(il)

Building Real-Time Charts With GraphQL And Postgres

Building Real-Time Charts With GraphQL And Postgres

Building Real-Time Charts With GraphQL And Postgres

Rishichandra Wawhal

2019-03-27T13:00:08+01:00
2019-03-28T03:35:01+00:00

Charts form an integral part of any industry that deals with data. Charts are useful in the voting and polling industry, and they’re also great at helping us better understand the different behaviors and characteristics of the users and clients we work with.

Why are real-time charts so important? Well, they’re useful in cases when new data is produced continuously; for example, when using live-time series for visualizing stock prices is a great use for real-time charts. In this tutorial, I’ll explain how to build real-time charts with open-source technologies apt for exactly this particular task.

Note: This tutorial requires basic knowledge of React and GraphQL.

Stack

  1. PostgreSQL
    The very point behind using Charts is to visualize “huge” volumes data. We, therefore, need a database that efficiently handles large data and provides an intuitive API to restructure it. SQL databases allow us to make views that abstract and aggregate data for us. We will be using Postgres which is a time-tested and highly efficient database. It also has fancy open-source extensions like Timescale and PostGIS which allow us to build geolocation-based and time-series-based charts respectively. We will be using Timescale for building our time series chart.
  2. GraphQL Engine
    This post is about building real-time charts, and GraphQL comes with a well-defined spec for real-time subscriptions. Hasura GraphQL Engine is an open-source GraphQL server that takes a Postgres connection and allows you to query the Postgres data over realtime GraphQL. It also comes with an access control layer that helps you restrict your data based on custom access control rules.
  3. ChartJS
    ChartJS is a popular and well maintained open source library for building charts with JavaScript. We will use chart.js along with its ReactJS abstraction react-chartjs-2. About why React, it is because React empowers developers with an intuitive event-driven API. Also, React’s unidirectional data flow is ideal for building charts that are data-driven.

Requirements

For this tutorial, you will need the following on your system:

  1. Docker CE
    Docker is a software that lets you containerize your applications. A docker image is an independent packet that contains software along with its dependencies and a minimalistic operating system. Such docker images can be technically run in any machine that has docker installed. You will need docker for this tutorial.

  2. npm: npm is the package manage for JavaScript.

Demo

We will build the following live time series chart that shows the maximum temperature of a location in intervals of 5 seconds over the past 20 minutes from the present moment.

GIF Demo of the realtime chart
GIF Demo of the realtime chart

Setting Up The Backend

Running The Services

The backend comprises of a Postgres database, its timescale extension, and Hasura GraphQL Engine. Let us get the database and our GraphQL server running by running the respective docker images. Create a file called docker-compose.yaml and paste this content into it.

Note: docker-compose is a utility to run multiple docker images declaratively.

version: '2'
services:
  timescale:
    image: timescale/timescaledb:latest-pg10
    restart: always
    environment:
      POSTGRES_PASSWORD: postgrespassword
    volumes:
    - db_data:/var/lib/postgresql/data
  graphql-engine:
    image: hasura/graphql-engine:v1.0.0-alpha38
    ports:
    - "8080:8080"
    depends_on:
    - "timescale"
    restart: always
    environment:
      HASURA_GRAPHQL_DATABASE_URL: postgres://postgres:postgrespassword@timescale:5432/postgres
      HASURA_GRAPHQL_ACCESS_KEY: mylongsecretkey
    command:
      - graphql-engine
      - serve
      - --enable-console
volumes:
  db_data:

This docker-compose.yaml contains the spec for two services:

  1. timescale
    This is our Postgres database with Timescale extension installed. It is configured to run at port 5432.
  2. graphql-engine
    This is our Hasura GraphQL Engine instance, i.e. the GraphQL server that points to the database and gives GraphQL APIs over it. It is configured to run at the port 8080, and the port 8080 is mapped to the port 8080 of the machine that this docker container runs on. This means that you can access this GraphQL server through at localhost:8080 of the machine.

Let’s run these docker containers by running the following command wherever you have placed your docker-compose.yaml.

docker-compose up -d

This command pulls the docker images from the cloud and runs them in the given order. It might take a few seconds based on your internet speed. Once it is complete, you can access your GraphQL Engine console at http://localhost:8080/console.


Hasura GraphQL Engine Console
Hasura GraphQL Engine console (Large preview)

Setting Up The Database

Next, let us create a table called temperature that stores the values of temperatures at different times. Go to the Data tab in the console and go to the SQL section. Create our temperature table by running this SQL block:

CREATE TABLE temperature (
  temperature numeric not null,
  location text not null,
  recorded_at timestamptz not null default now()
);

This creates a simple Postgres table in the database. But we wish to leverage the time interval partitioning of the Timescale extension. To do this, we must convert this table into timescale’s hypertable by running the SQL command:

SELECT create_hypertable('temperature', 'recorded_at');

This command creates a hypertable that is partitioned by time in the field recorded_at.

Now, since this table is created, we can directly start making GraphQL queries over it. You can try them out by clicking on the GraphiQL tab on top. Try making a mutation first:

mutation 
  insert_temperature (
    objects: [
      temperature: 13.4
      location: "London"
    ]
  ) 
    returning 
      recorded_at
      temperature
    
  

The GraphQL mutation above inserts a row in the temperature table. Now try to make a GraphQL query to check if the data was inserted.

Then try making a query:

query 
  temperature 
    recorded_at
    temperature
    location
  

Hope it worked 🙂

Now, the task at our hand is to create a live time-series chart that shows the maximum temperature of a location in intervals of 5 seconds over the past 20 minutes from the present moment. Let’s create a view that gives us exactly this data.

CREATE VIEW last_20_min_temp AS (
  SELECT time_bucket('5 seconds', recorded_at) AS five_sec_interval,
  location,     
    MAX(temperature) AS max_temp
  FROM temperature
  WHERE recorded_at > NOW() - interval '20 minutes'    
  GROUP BY five_sec_interval, location    
  ORDER BY five_sec_interval ASC
);

This view groups the data from the temperature table in 5-second windows with their max temperature (max_temp). The secondary grouping is done using the location field. All this data is only from the past twenty minutes from the present moment.

That’s it. Our backend is set up. Let us now build a nice real-time chart.

Frontend

Hello GraphQL Subscriptions

GraphQL subscriptions are essentially “live” GraphQL queries. They operate over WebSockets and have exactly the same response structure like GraphQL queries. Go back to http://localhost:8080/console and try to make a GraphQL subscription to the view we created.

subscription 
  last_20_min_temp(
    order_by: 
      five_sec_interval: asc
    
    where: 
      location: 
        _eq: "London"
      
    
  ) 
    five_sec_interval
    location
    max_temp
  

This subscription subscribes to the data in the view where the location is London and it is ordered in ascending order of the five_second_intervals.

Naturally, the response from the view would be an empty array because we have not inserted anything in the database in the past twenty minutes. (You might see the entry that we inserted sometime back if you reached this section within twenty minutes.)


  "data": 
    "last_20_min_temp": []
  

Keeping this subscription on, open another tab and try inserting another value in the temperatures table using the same mutation that we performed earlier. After inserting, if you go back to the tab where the subscription was on, you would see the response having updated automatically. That’s the realtime magic that GraphQL Engine provides. Let’s use this subscription to power our real-time chart.

Getting Started With Create-React-App

Let us quickly get started with a React app starter using create react app. Run the command:

npx create-react-app time-series-chart

This will create an empty starter project. cd into it and install the GraphQL and chart libraries. Also, install moment for converting timestamps to a human-readable format.

cd time-series-chart
npm install --save apollo-boost apollo-link-ws subscriptions-transport-ws graphql react-apollo chart.js react-chartjs-2 moment

Finally, run the app with npm start and a basic React app would open up at http://localhost:3000.


Raw create-react-app
Raw creat-react-app (Large preview)

Setting Up Apollo Client For Client-Side GraphQL

Apollo client is currently the best GraphQL client that works with any GraphQL compliant server. Relay modern is good too but the server must support the relay spec to leverage all the benefits of Relay modern. We’ll use Apollo client for client-side GraphQL for this tutorial. Let us perform the setup to provide Apollo client to the app.

I am not getting into the subtleties of this setup because the following code snippets are taken directly from the docs. Head to src/index.js in the React app directory and instantiate Apollo client and add this code snippet above ReactDOM.render.

import  WebSocketLink  from 'apollo-link-ws';
import  ApolloClient  from 'apollo-client';
import  ApolloProvider  from 'react-apollo';
import  InMemoryCache  from 'apollo-cache-inmemory';

// Create a WebSocket link:
const link = new WebSocketLink(
  uri: 'ws://localhost:8080/v1alpha1/graphql',
  options: 
    reconnect: true
  
);
const cache = new InMemoryCache();
const client = new ApolloClient(
  link,
  cache
);

Finally, wrap the App inside ApolloProvider so that we can use Apollo client in the children components. Your App.js should finally look like:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import  WebSocketLink  from 'apollo-link-ws';
import  ApolloClient  from 'apollo-client';
import  ApolloProvider  from 'react-apollo';
import  InMemoryCache  from 'apollo-cache-inmemory';

// Create a WebSocket link:
const link = new WebSocketLink(
  uri: `ws://localhost:8080/v1alpha1/graphql`,
  options: 
    reconnect: true
  
);
const cache = new InMemoryCache();
const client = new ApolloClient(
  link,
  cache
);

ReactDOM.render(
  (
    <ApolloProvider client=client> 
      <App />
    </ApolloProvider>
  ),
  document.getElementById('root')
);

Apollo client has been set up. We can now easily use real-time GraphQL from our App. Head to src/App.js.

Building The Chart

ChartJS provides a pretty neat API for building charts. We will be building a line chart; so a line chart expects data of the form:


  "labels": ["label1", "label2", "label3", "label4"],
  "datasets": [
    "label": "Sample dataset",
    "data": [45, 23, 56, 55],
    "pointBackgroundColor": ["red", "brown", "green", "yellow"],
    "borderColor": "brown",
    "fill": false
  ],

If the above dataset is used for rendering a line chart, it would look something like this:


Sample line chart
Sample line chart (Large preview)

Let us try to build this sample chart first. Import Line from react-chartjs-2 and render it passing the above object as a data prop. The render method would look something like:

render() 
  const data = 
    "labels": ["label1", "label2", "label3", "label4"],
    "datasets": [
      "label": "Sample dataset",
      "data": [45, 23, 56, 55],
      "pointBackgroundColor": ["red", "brown", "green", "yellow"],
      "borderColor": "brown",
      "fill": false
    ],
  
  return (
    <div
      style=display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '20px'
    >
      <Line
        data=data
      />
    </div>
  );

Next, we will subscribe to the data in our view and feed it to the Line chart. But how do we perform subscriptions on the client?

Apollo’s <Subscription> components work using the render prop pattern where the children of a component are rendered with the context of the subscription data.

<Subscription
  subscription=gql`subscription  parent  child  `
/>
  
    (data, error, loading) => 
      if (error) return <Error error=error />;
      if (loading) return <Loading />;
      return <RenderData data=data />;
    
  
</Subscription>

Let us use one such Subscription component to subscribe to our view and then transform the subscription data to the structure that ChartJS expects. The transforming logic looks like this:

let chartJSData = 
  labels: [],
  datasets: [
    label: "Max temperature every five seconds",
    data: [],
    pointBackgroundColor: [],
    borderColor: 'brown',
    fill: false
  ]
;
data.last_20_min_temp.forEach((item) => 
  const humanReadableTime = moment(item.five_sec_interval).format('LTS');
  chartJSData.labels.push(humanReadableTime);
  chartJSData.datasets[0].data.push(item.max_temp);
  chartJSData.datasets[0].pointBackgroundColor.push('brown');
)

Note: You can also use the open-source library graphq2chartjs for transforming the data from GraphQL response to a form that ChartJS expects.

After using this inside the Subscription component, our App.js looks like:

import React,  Component  from 'react';
import  Line  from 'react-chartjs-2';
import  Subscription  from 'react-apollo';
import gql from 'graphql-tag';
import moment from 'moment';

const TWENTY_MIN_TEMP_SUBSCRIPTION= gql'
  subscription 
    last_20_min_temp(
      order_by: 
        five_sec_interval: asc
      
      where: 
        location: 
          _eq: "London"
        
      
    ) 
      five_sec_interval
      location
      max_temp
    
  
'

class App extends Component 
  render() 
    return (
      <div
        style=display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '20px'
      >
        <Subscription subscription=TWENTY_MIN_TEMP_SUBSCRIPTION>
          
            (data, error, loading) => 
              if (error) 
                console.error(error);
                return "Error";
              
              if (loading) 
                return "Loading";
              
              let chartJSData = 
                labels: [],
                datasets: [
                  label: "Max temperature every five seconds",
                  data: [],
                  pointBackgroundColor: [],
                  borderColor: 'brown',
                  fill: false
                ]
              ;
              data.last_20_min_temp.forEach((item) => 
                const humanReadableTime = moment(item.five_sec_interval).format('LTS');
                chartJSData.labels.push(humanReadableTime);
                chartJSData.datasets[0].data.push(item.max_temp);
                chartJSData.datasets[0].pointBackgroundColor.push('brown');
              )
              return (
                <Line
                  data=chartJSData
                  options=
                    animation: duration: 0,
                    scales:  yAxes: [ticks:  min: 5, max: 20 ]
                  
                />
              );
            
          
        </Subscription>
      </div>
    );
  


export default App;

You will have a fully working real-time chart ready at http://localhost:3000 . However, it would be empty, so let’s populate some sample data so we can actually see some magic happen.

Note: I have added some more options to the Line chart because I don’t like those fancy animations in ChartJS. A time series looks sweet when it’s simple, however, you can remove the options prop if you like.

Inserting Sample Data

Lets write a script that populates our database with dummy data. Create a separate directory (outside this app) and create a file called script.js with the following content,

const fetch = require('node-fetch');
setInterval(
  () => 
    const randomTemp = (Math.random() * 5) + 10;
    fetch(
      `http://localhost:8080/v1alpha1/graphql`,
      
        method: 'POST',
        body: JSON.stringify(
          query: `
            mutation ($temp: numeric) 
              insert_temperature (
                objects: [
                  temperature: $temp
                  location: "London"
                ]
              ) 
                returning 
                  recorded_at
                  temperature
                
              
            
          `,
          variables: 
            temp: randomTemp
          
        )
      
    ).then((resp) => resp.json().then((respObj) => console.log(JSON.stringify(respObj, null, 2))));
  ,
  2000
);

Now run these two commands:

npm install --save node-fetch
node script.js

You can go back to http://localhost:3000 and see the chart updating.

Finishing Up

You can build most of the real-time charts using the ideas that we discussed above. The algorithm is:

  1. Deploy GraphQL Engine with Postgres;
  2. Create tables where you wish to store data;
  3. Subscribe to those tables from your React app;
  4. Render the chart.

You can find the source code here.

Smashing Editorial
(dm, ra, il)

10 features every nonprofit website should have

Sometimes best practices for nonprofit websites seem obvious, but let’s begin with a story that illustrates how fundamental these features are for success.

For years a neighborhood association asked members to join and renew at its 4th of July parade. But not everyone attended the parade or reached the membership table. The association had a PayPal button for dues payments on their website, but no one was automatically reminded to renew. As the parade outreach effort faltered, the organization resorted to inconsistent, volunteer-led member retention efforts.

After setting up membership software with automatic recurring credit card payments, the association quickly doubled its renewal rate. They were also shocked to see that many members also opted to add on significant additional recurring donation amounts beyond their dues payment. Making this one change possibly saved the association from extinction.

Recurring donations or memberships

Nonprofits with paper membership processes or PayPal donate buttons are losing significant revenue. Certainly setting up membership management software requires time and resources. But proceeds from auto-recurring payments and one-time renewal payments spurred by automatic reminders should more than compensate. Be sure to set up multiple past due/failed payment reminders in your system to accommodate today’s distracted members.

Email list signup

The people most likely to become donors and members are those already on your prospect email list. Set up an account with MailChimp or another email marketing platform. MailChimp is free for up to 2000 subscribers as long as you send less than 12,000 emails per month. Add an email signup widget to your website.

Automated blog post emails or an e-newsletter

Nonprofits that are volunteer-run or short-staffed find it hard to draft a regular e-newsletter. But how else will members know what you are doing for them? In some cases, writing blog posts that are automatically sent to your email list is better than an e-newsletter because:

  • A post doesn’t need to be designed in an email marketing platform.
    Information reaches your subscribers sooner.
  • If your recipients are just as likely to open one email from you as another, why put so much effort into an e-newsletter?
  • Headlines from your blog posts (which should be your email subject line) are more click-worthy than a subject line like, “Our Monthly Newsletter.”

But be careful not to send communications too often or you risk unsubscribes. Check your unsubscribe rate after each mass email.

Pictures and good design

Like the adage says, “A picture is worth 1000 words.” Your current and prospective donors and members want to see themselves as part of an energetic organization. Pictures are the best way to tell that story. You have around seven seconds to prove to visitors that your site is worth exploring. Consider running a usability test to be sure you are doing a good job.

Members only content or benefits

Members join because they want to belong, but benefits play a role. Your welcome and renewal emails should link to a page where you list all of your benefits. Create content such as articles or a member directory that only members can see. Offer events or tickets just for donors. Your membership software should allow you to limit access to specific pages, posts and events.

Contact information

Donors may be diverse in term of age, education and tech savviness, so offer them different ways to connect. Older donors like to reach out by phone, while younger members may want to be able to message you on Facebook. Meet members and where they are, but only if staff can fully support each method (such as regularly posting on Facebook or having set times when you are answering the phone).

Scalability for desktop, mobile and tablets

Half of visitors to nonprofit websites are using a mobile or tablet device. If people receive your emails and want to take action, be sure that they can complete the entire task on their phone without having to scroll right or zoom in to read. Google also favors mobile-friendly sites in search results.

Events calendar

Events — in person or virtual — are a core function of most nonprofits. Your membership software should support online event registration and payments. If your site is in WordPress, your system may offer widgets to promote a list of upcoming events in the site-wide sidebar or footer.

Clear call-to-action

Is it clear what action you want a first time or returning website visitor to take? If the main goal is driving membership, there should be a benefits list on the home page as well as a Join button. Ask friends to look at the home page. Can they accurately answer, “What is the primary action we are asking you to take?

Volunteer information

On average, those who volunteered in the last 12 months donate ten times more money to charities than non-volunteers. Make it easy:

  • Include a volunteer link in the website navigation.
    Maintain an updated list of volunteer opportunities.
  • Designate a volunteer coordinator to connect volunteers to opportunities and stay connected to this key group.
  • Ask members to indicate what volunteer opportunities interest them.

Have other ideas? Let us know in the comments.

This is a guest post by Amy Hufford, a Technologist at MembershipWorks.

JavaScript Proxy

I’ve always loved the flexibility of Objects and prototypes in JavaScript, but for a long time, I felt that a level of dynamism was lacking. JavaScript eventually added get and set methods for object properties, which was an awesome step, but there was still room for improvement.

The JavaScript Proxy API was an awesome improvement: a virtualizing interface to control the modification behavior of an object!

Proxy Format

Proxy accepts an object to proxy for and an object with handlers (“traps”) for get, set, has and other common object methods:

const proxy = new Proxy(, 
  get: (obj, prop) =>  ... ,
  set: (obj, prop, value) =>  ... ,
  // more props here
);

Any attempt to set or get a property is run through the trap, allowing you to run additional logic, especially if the property is unwanted, doesn’t exist, or requires validation.

Basic Usage

Let’s create a basic proxy that returns defaults for any given property:

const proxy = new Proxy(, 
  get: (obj, prop) => 
    return prop in obj ? obj[prop] : null;
  
);

// proxy.whatever => null

The example above illustrates that no matter the property the code attempts to set, your Proxy logic can capture and modify it as desired. Instead of undefined being returned for a property that doesn’t exist, you can instead return null.

Validation

The most obvious and useful usage of Proxy is validation; since you monitor validate any property coming in, you can keep your data as pure as possible.

const proxy = new Proxy(,  
  set: (obj, prop, value) => 
    // Don't allow age > 100
    if (prop === "age" && value > 100) 
      // Set to max age
      value = 100;
    
    obj[prop] = value;
  
);

proxy.age = 120;
proxy.age; // 100

You can choose to modify incoming data like the example above, or you can throw an error:

const proxy = new Proxy(,  
  set: (obj, prop, value) => 
    // Ensure age is of type Number
    if (prop === "age" && isNaN(value)) 
      throw new Error("Invalid age value!");
      return;
    
    obj[prop] = value;
  
);

proxy.age = "yes";  // Uncaught error: Invalid age value!

Debugging

You can even use Proxy to provide yourself debugging points or events to see how and when values are being set and retrieved:

const proxy = new Proxy(,  
  set: (obj, prop, value) => 
    console.log(`Setting $prop from $obj[prop] to $value`);
    obj[prop] = value;
  
);

proxy.prop = 1;
proxy.prop = 2;

// Setting prop from undefined to 1
// Setting prop from 1 to 2

Even if you don’t modify any input or output, having a hook to value changes on an object is incredibly valuable.

Formatting

Another simple usage is formatting data that comes into the object:

const proxy = new Proxy(,  
  set: (obj, prop, value) => 
    if (prop === "age") 
      obj[prop] = Number(value);
    
  
);

proxy.prop = "1"; // 1

You can format from String to Number, Number to String, or simply set defaults.

Using Proxies with Existing Objects

In the examples provided above, we use an empty object (), but you can also use an existing object:

const myObj =  x: "x", y: "y" ;

// Use existing object, simply set value as is given
const proxy = new Proxy(myObj,  
  set: (obj, prop, value) =>  
    obj[prop] = value; 
   
);

// 
proxy.x = "XXX";
proxy.x; // "XXX"
myObj.x; // "XXX"

Note that the original object does change, as well as the proxy, so the proxy does not act as a “copy”, so to speak.

People love to hate on PHP but one thing I loved about the language was “magic properties” that you could spy on and dynamically react to. The Proxy API feels like JavaScript’s answer to that. The more you can control what’s coming and going out, the better your application can become!

The post JavaScript Proxy appeared first on David Walsh Blog.