Post image
Strategy

Blurry Website – Mainly Font : webdev


Hello,

I am currently in the process of creating a basic HTML website. I have attached a picture for you to see, do you notice that it’s all just really blurry? Mainly the font, but the pictures seem to sometimes be affected as well, are just blurred and I have no idea why. As you zoom in the quality increases and it looks perfect at larger scales as soon as I zoom out to 100% it all becomes slightly blurred. I have tested various fonts and when I change them they still blur so I’m positive it’s not the font.

Any ideas what this could be?

Help would really be appreciated!

Post image



Source link

Create a D3 Dashboard With Cube.js
Strategy

Create a D3 Dashboard With Cube.js


In this tutorial, I’ll cover building a basic dashboard application with Cube.js and the most popular library for visualizing data — D3.js. Although Cube.js doesn’t provide a visualization layer itself, it is very easy to integrate with any existing charting library. Additionally, you can use Cube.js Templates to scaffold a frontend application with your favorite charting library, frontend framework, and UI kit. The scaffolding engine will wire it all together and configure it to work with the Cube.js backend.

You can check the online demo of this dashboard here and the complete source code of the example app is available on Github.

We are going to use Postgres to store our data. Cube.js will connect to it and act as a middleware between the database and the client, providing our API, abstraction, caching, and a lot more. On the frontend, we’ll have React with Material UI and D3 for chart rendering. Below, you can find a schema of the whole architecture of the example app.

If you have any questions while going through this guide, please feel free to join this Slack community and post your question there.

Happy Hacking!

You may also like:
Cube.js: Ultimate Guide to the Open-Source Dashboard Framework

Setting Up a Database and Cube.js

The first thing we need to have in place is a database. We’ll use Postgres for this tutorial. However, you can use your favorite SQL (or Mongo) database. Please refer to the Cube.js documentation on how to connect to different databases.

If you don’t have any data for the dashboard, you can load our sample e-commerce Postgres dataset.

Now, as we have data in the database, we’re ready to create the Cube.js Backend service. Run the following commands in your terminal:

The commands above install Cube.js CLI and create a new service configured to work with a Postgres database.

Cube.js uses environment variables for configuration. It uses environment variables starting with CUBEJS_. To configure the connection to our database, we need to specify the DB type and name. In the Cube.js project folder, replace the contents of the .env file with the following:

Now let’s start the server and open the developer playground at http://localhost:4000.

The next step is to create a Cube.js data schema. Cube.js uses the data schema to generate SQL, which will be executed in your database. Cube.js Playground can generate simple schemas based on the database’s tables. Let’s navigate to the Schema page and generate the schemas we need for our dashboard. Select the line_itemsordersproductsproduct_categories, and users tables and click Generate Schema.

Generating schema

Generating schema

Let’s test our newly generated schema. Go to the Build page and select a measure in the dropdown. You should be able to see a simple line chart. You can choose D3 from the charting library dropdown to see an example of a D3 visualization. Note that it is just an example and you can always customize and expand it.
Beginning D3 visualization

Now, let’s make some updates to our schema. The schema generation makes it easy to get started and test the dataset, but for real-world use cases, we almost always need to make manual changes.

In the schema, we define measures and dimensions and how they map into SQL queries. You can find extensive documentation about data schema here. We’re going to add a priceRange dimension to the Orders cube. It will indicate whether the total price of the order falls into one of the buckets: “$0 – $100”, “$100 – $200”, “$200+”.

To do this, we first need to define a price dimension for the order. In our database, orders don’t have a price column, but we can calculate it based on the total price of the line_items inside the order. Our schema has already automatically indicated and defined a relationship between the Orders and LineTimes cubes. You can read more about joins here.

The LineItems cube has price measure with a sum type. We can reference this measure from the Orders cube as a dimension, and it will give us the sum of all the line items that belong to that order. It’s called a subQuery dimension; you can learn more about it here.

Now, based on this dimension, we can create a priceRange dimension. We’ll use a case statement to define a conditional logic for our price buckets.

Let’s try our newly created dimension! Go to the Build page in the playground, select the Orders count measure with the Orders price range dimension. You can always check the generated SQL by clicking the SQL button on the control bar.

That’s it for the backend! In the next part, we’ll look closer at how to render the results of our queries with D3.

Rendering Chart With D3.js

Now, as we can build our first chart, let’s inspect the example code playground uses to render it with the D3. Before that, we need to understand how Cube.js accepts and processes a query and returns the result back.

A Cube.js query is a simple JSON object containing several properties. The main properties of the query are measuresdimensionstimeDimensions, and filters. You can learn more about the Cube.js JSON query format and its properties here. You can always inspect the JSON query in the playground by clicking the JSON Query button next to the chart selector.

Inspecting JSON query

Inspecting JSON query

The Cube.js backend accepts this query and then uses it and the schema we created earlier to generate an SQL query. This SQL query will be executed in our database and the result will be sent back to the client.

Although Cube.js can be queried via a plain HTTP REST API, we’re going to use the Cube.js JavaScript client library. Among other things, it provides useful tools to process the data after it has been returned from the backend.

Once the data is loaded, the Cube.js client creates a ResultSet object, which provides a set of methods to access and manipulate the data. We’re going to use two of them now: ResultSet.series and ResultSet.chartPivot. You can learn about all the features of the Cube.js client library in the docs.

The ResultSet.series method returns an array of data series with key, title, and series data. The method accepts one argument, pivotConfig. It is an object, containing rules about how the data should be pivoted; we’ll talk about it a bit. In a line chart, each series is usually represented by a separate line. This method is useful for preparing data in the format expected by D3.

The next method we need is ResultSet.chartPivot. It accepts the same pivotConfig argument and returns an array of data with values for the X-axis and for every series we have.

As mentioned above, the pivotConfig argument is an object used to control how to transform, or pivot, data. The object has two properties: x and y, both are arrays. By adding measures or dimensions to one of them, you can control what goes to the X-axis and what goes to the Y-axis. For a query with one measure and one timeDimensionpivotConfig has the following default value:

Here, “measures” is a special value, meaning that all the measures should go to the Y-axis. In most cases, the default value of the pivotConfig should work fine. In the next part, I’ll show you when and how we need to change it.

Now, let’s look at the frontend code playground generates when we select a D3 chart. Select a measure in the playground and change the visualization type to the D3. Next, click the Code button to inspect the frontend code to render the chart.

Code to render the chart

Code to render the chart

Here is the full source code from that page:

The React component that renders the chart is just a single line wrapping a draw function, which does the entire job.

There is a lot going on in this draw function. Although it renders a chart already, think about it as an example and a good starting point for customization. As we’ll work on our own dashboard in the next part, I’ll show you how to do it.

Feel free to click the Edit button and play around with the code in Code Sandbox.

Editing in Code Sandbox

Editing in Code Sandbox

Building a Frontend Dashboard

Now, we are ready to build our frontend application. We’re going to use Cube.js Templates, which is a scaffolding engine for quickly creating frontend applications configured to work with the Cube.js backend. It provides a selection of different frontend frameworks, UI kits, and charting libraries to mix together. We’ll pick React, Material UI, and D3.js. Let’s navigate to the Dashboard App tab and create a new dashboard application.

Creating a new dashboard

Creating a new dashboard

It could take several minutes to generate an app and install all the dependencies. Once it is done, you will have a dashboard-app folder inside your Cube.js project folder. To start a frontend application, either go to the “Dashboard App” tab in the playground and hit the “Start” button, or run the following command inside the dashboard-app folder:

Make sure the Cube.js backend process is up and running since our frontend application uses its API. The frontend application is running on http://localhost:3000. If you open it in your browser, you should be able to see an empty dashboard.

Empty dashboard

Empty dashboard

To add a chart to the dashboard, we can either build it in the playground and click the add to dashboard button or edit the src/pages/DashboardPage.js file in the dashboard-app folder. Let’s go with the latter option. Among other things, this file declares the DashboardItems variable, which is an array of queries for charts.

Edit dashboard-app/src/pages/DashboardPage.js to add charts to the dashboard.

As you can see above, we’ve just added an array of Cube.js query objects.

If you refresh the dashboard, you should be able to see your charts!

Dashboards

Dashboards

You can notice that one of our queries has the pivotConfig defined as the following:

As I mentioned in the previous section, the default value for the pivotConfig usually works fine, but in some cases, like this one, we need to adjust it to get the desired result. We want to plot a bar chart here with the cities on the X-Axis and the number of orders on the Y-Axis grouped by the orders’ statuses. That is exactly what we are passing here in the pivotConfigUsers.city to the X-Axis and measures with Orders.status to the Y-axis to get the grouped result.

To customize the rendering of the charts, you can edit the dashboard-app/src/pages/ChartRenderer.js file. It should look familiar to what we saw in the previous part.

You can check the online demo of this dashboard here and the complete source code of the example app is available on Github.

Congratulations on completing this guide! 

I’d love to hear from you about your experience following this tutorial. Please send any comments or feedback you might have here in the comments or in this Slack Community. Thank you and I hope you found this guide helpful!

Further Reading



Source link

line-chart-on-desk
Strategy

Create Charts in an Angular 7 Application Using Chart.js


line-chart-on-desk

Chart.js is a powerful open source data visualization library. This helps to visualize or represent a data inside a web application using JavaScipt. It helps to plot the data into 8 different types of chart like bars, lines, pies, etc. This Chart.js graphs are highly customizable and used in web application development to build a responsive and beautiful graph.

Prerequisites

Project Implementation Steps

  1. Database.
  2. Web API to fetch data from the database.
  3. Angular 7 project.

You may also like: Cube.js and Chart.js Example With Dynamic Dataset.

Step 1

Open SQL Server Management Studio and create a table Tblplayer and add some demo data into this table.

CREATE TABLE [dbo].[Tblplayer](  
    [Id] [int] IDENTITY(1,1) NOT NULL,  
    [PlayerName] [varchar](50) NULL,  
    [Run] [varchar](50) NULL,  
PRIMARY KEY CLUSTERED   
(  
    [Id] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
) ON [PRIMARY]  

GO  
SET ANSI_PADDING OFF  
GO  
SET IDENTITY_INSERT [dbo].[Tblplayer] ON   

GO  
INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (1, N'Rohit Sharma', N'59')  
GO  
INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (2, N'Sikar Dhwan', N'19')  
GO  
INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (3, N'Virat Kholi', N'79')  
GO  
INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (4, N'Rishabh Panth', N'99')  
GO  
INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (5, N'Ms Dhoni', N'119')  
GO  
INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (6, N'H Pandya', N'9')  
GO  
INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (7, N'B kumar', N'51')  
GO  
INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (8, N'K Yadav', N'11')  
GO  
INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (9, N'Chahal', N'4')  
GO  
INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (10, N'Bumrah', N'9')  
GO  
INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (11, N'Shami', N'5')  
GO  
SET IDENTITY_INSERT [dbo].[Tblplayer] OFF  
GO  

Step 2

Open Visual Studio and create a new project.

Go to File > New > Project.

Creating a new project

Select Web API as a Template and click on the OK button.

Selecting a web API template

Step 3

Right-click on the Models folder from Solution Explorer and go to Add >> New Item >> Data. Create Charts In Angular 7 Application Using Chart.js Click on the ADO.NET Entity Data Model option and click Add. Create Charts In Angular 7 Application Using Chart.js Select EF designer from the database and click the Next button. Create Charts In Angular 7 Application Using Chart.js Add the connection properties and select the database name on the next page. Then, click OK. Create Charts In Angular 7 Application Using Chart.js Check Table checkboxes. The internal options will be selected by default. Now, click the Finish button. Create Charts In Angular 7 Application Using Chart.js Our data model is created now.

Step 4

Right-click on the Controllers folder and add a new controller. Name it as “Chartscontroller.”

Add the following namespace in the Charts Controller.

using GraphDemo.Models

Add a new method to fetch data from the database.

[Route("GetCharts")]  
        [HttpGet]  
        public object GetChartsData()  
        {  
            ChartsDemoEntities DB = new ChartsDemoEntities();  
            return Json(DB.Tblplayers.ToList());  
        }  

Complete the Chartscontroller code.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Web.Http;  
using GraphDemo.Models;  

namespace GraphDemo.Controllers  
{  
    [RoutePrefix("API/Charts")]  

    public class ChartsController : ApiController  
    {  
        [Route("GetCharts")]  
        [HttpGet]  
        public object GetChartsData()  
        {  
            ChartsDemoEntities DB = new ChartsDemoEntities();  
            return Json(DB.Tblplayers.ToList());  
        }  
    }  
}  

Step 5

Now, let’s enable Cors. Go to Tools, open NuGet Package Manager, search for Cors, and install the Microsoft.Asp.Net.WebApi.Cors package.

Open Webapiconfig.cs and add the following lines.

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");    
config.EnableCors(cors);  

Angular 7 Project

Step 1

Create an Angular 7 project with the name “chartjsdemo” by using the following command.

ng new chartjsdemo

Step 2

Open Visual Studio Code, open the newly created project, and add Chart.js to this project by using the following command.

npm install chart.js --save

Step 3

Now, create 5 components for the bar chart, line chart, doughnut chart, pie Chart respectively. To create the components, open terminal and use the following commands.

  1.  ng g c linechart 
  2.  ng g c barchart 
  3.  ng g c doughnut 
  4.  ng g c piechart 
  5.  ng g c polararea 

Running aforementioned commands

Step 4

Create a class named “Data” by using the following command.

ng g class Data

Add the following properties in the Data class.

export class Data {  
    PlayerName :string;  
    Run:string;  
  }  

Step 5 – Line Chart

Open the linechart.component.ts file and add the required chart.js module, class, and other required modules.

import { Chart } from 'chart.js';  
import { HttpClient } from '@angular/common/http';  
import { Data } from '../../app/Data'; 

linechart.component.ts file

import { Component, OnInit } from '@angular/core';  
import { Chart } from 'chart.js';  
import { HttpClient } from '@angular/common/http';  
import { Data } from '../../app/Data';  
@Component({  
  selector: 'app-linechart',  
  templateUrl: './linechart.component.html',  
  styleUrls: ['./linechart.component.css']  
})  
export class LinechartComponent implements OnInit {  

  url = 'http://localhost:58617/API/Charts/GetCharts';  
  data: Data[];  
  Player = [];  
  Run = [];  
  Linechart = [];  
  constructor(private httpClient: HttpClient) { }  

  ngOnInit() {  
    this.httpClient.get(this.url).subscribe((result: Data[]) => {  
      result.forEach(x => {  
        this.Player.push(x.PlayerName);  
        this.Run.push(x.Run);  
      });  
      this  
      this.Linechart = new Chart('canvas', {  
        type: 'line',  
        data: {  
          labels: this.Player,  

          datasets: [  
            {  
              data: this.Run,  
              borderColor: '#3cb371',  
              backgroundColor: "#0000FF",  
            }  
          ]  
        },  
        options: {  
          legend: {  
            display: false  
          },  
          scales: {  
            xAxes: [{  
              display: true  
            }],  
            yAxes: [{  
              display: true  
            }],  
          }  
        }  
      });  
    });  
  }  
}  

Creating line chart

Now, open linechart.component.html file and add the following HTML.

<div class="chart-container" style="position: relative; height:40vh; width:70vw">    
  <canvas id="canvas">{{ Linechart }}</canvas>    
</div>  

Step 6 – Bar Chart

Open barchart.component.ts file and add the following code.

import { Component, OnInit } from '@angular/core';  
import { Chart } from 'chart.js';  
import { HttpClient } from '@angular/common/http';  
import { Data } from '../../app/Data';  
@Component({  
  selector: 'app-barchart',  
  templateUrl: './barchart.component.html',  
  styleUrls: ['./barchart.component.css']  
})  
export class BarchartComponent implements OnInit {  
  data: Data[];  
  url = 'http://localhost:58617/API/Charts/GetCharts';  
  Player = [];  
  Run = [];  
  barchart = [];  
  constructor(private http: HttpClient) { }  

  ngOnInit() {  
    this.http.get(this.url).subscribe((result: Data[]) => {  
      result.forEach(x => {  
        this.Player.push(x.PlayerName);  
        this.Run.push(x.Run);  
      });  
      this  
      this.barchart = new Chart('canvas', {  
        type: 'bar',  
        data: {  
          labels: this.Player,  
          datasets: [  
            {  
              data: this.Run,  
              borderColor: '#3cba9f',  
              backgroundColor: [  
                "#3cb371",  
                "#0000FF",  
                "#9966FF",  
                "#4C4CFF",  
                "#00FFFF",  
                "#f990a7",  
                "#aad2ed",  
                "#FF00FF",  
                "Blue",  
                "Red",  
                "Blue"  
              ],  
              fill: true  
            }  
          ]  
        },  
        options: {  
          legend: {  
            display: false  
          },  
          scales: {  
            xAxes: [{  
              display: true  
            }],  
            yAxes: [{  
              display: true  
            }],  
          }  
        }  
      });  
    });  
  }  
}  

Open the barchart.component.html file and add the following HTML.

<div class="chart-container" style="position: relative; height:40vh; width:70vw">    
  <canvas id="canvas"></canvas>    
</div> 


Step 7 – Pie Chart

Open the piechart.component.ts file and add the following code.

import { Component, OnInit } from '@angular/core';  
import { Chart } from 'chart.js';  
import { HttpClient } from '@angular/common/http';  
import { Data } from '../../app/Data';  
@Component({  
  selector: 'app-piechart',  
  templateUrl: './piechart.component.html',  
  styleUrls: ['./piechart.component.css']  
})  
export class PiechartComponent implements OnInit {  
    title = 'app';  
    data: Data[];  
    url = 'http://localhost:58617/API/Charts/GetCharts';  
    Player = [];  
    Run = [];  
    chart = [];  
    constructor(private httpClient: HttpClient) { }  

    ngOnInit() {  
      this.httpClient.get(this.url).subscribe((result: Data[]) => {  
        result.forEach(x => {  
          this.Player.push(x.PlayerName);  
          this.Run.push(x.Run);  
        });  
        this  
        this.chart = new Chart('canvas', {  
          type: 'pie',  
          data: {  
            labels: this.Player,  
            datasets: [  
              {  
                data: this.Run,  
                borderColor: '#3cba9f',  
                backgroundColor: [  
                  "#3cb371",  
                  "#0000FF",  
                  "#9966FF",  
                  "#4C4CFF",  
                  "#00FFFF",  
                  "#f990a7",  
                  "#aad2ed",  
                  "#FF00FF",  
                  "Blue",  
                  "Red",  
                  "Blue"  
                ],  
                fill: true  
              }  
            ]  
          },  
          options: {  
            legend: {  
              display: true  
            },  
            scales: {  
              xAxes: [{  
                display: true  
              }],  
              yAxes: [{  
                display: true  
              }],  
            }  
          }  
        });  
      });  
    }  
  }  

Open the piechart.component.html file and add the following HTML.

<div class="chart-container" style="position: relative; height:40vh; width:70vw">    
  <canvas id="canvas"></canvas>    
</div> 

Step 8 – Doughnut Chart

Open the doughnut.component.ts file and add the following code.

import { Component, OnInit } from '@angular/core';  
import { Chart } from 'chart.js';  
import { HttpClient } from '@angular/common/http';  
import { Data } from '../../app/Data';  
@Component({  
  selector: 'app-doughnut',  
  templateUrl: './doughnut.component.html',  
  styleUrls: ['./doughnut.component.css']  
})  
export class DoughnutComponent implements OnInit {  
    data: Data[];  
    url = 'http://localhost:58617/API/Charts/GetCharts';  
    Player = [];  
    Run = [];  
    chart = [];  
    constructor(private httpClient: HttpClient) { }  
    ngOnInit() {  
      this.httpClient.get(this.url).subscribe((result: Data[]) => {  
        result.forEach(x => {  
          this.Player.push(x.PlayerName);  
          this.Run.push(x.Run);  
        });  
        this  
        this.chart = new Chart('canvas', {  
          type: 'doughnut',  
          data: {  
            labels: this.Player,  
            datasets: [  
              {  
                data: this.Run,  
                borderColor: '#3cba9f',  
                backgroundColor: [  
                  "#3cb371",  
                  "#0000FF",  
                  "#9966FF",  
                  "#4C4CFF",  
                  "#00FFFF",  
                  "#f990a7",  
                  "#aad2ed",  
                  "#FF00FF",  
                  "Blue",  
                  "Red",  
                  "Blue"  
                ],  
                fill: true  
              }  
            ]  
          },  
          options: {  
            legend: {  
              display: true  
            },  
            scales: {  
              xAxes: [{  
                display: false  
              }],  
              yAxes: [{  
                display: true  
              }],  
            }  
          }  
        });  
      });  
    }  
  }  

Open the doughnut.component.html file and add the following HTML.

<div class="chart-container" style="position: relative; height:40vh; width:70vw">    
  <canvas id="canvas"></canvas>    
</div> 

Step 9 – Polararea Chart

Open the polararea.component.ts file and add the following code.

import { Component, OnInit } from '@angular/core';  
import { Chart } from 'chart.js';  
import { HttpClient } from '@angular/common/http';  
import { Data } from '../../app/Data';  
@Component({  
  selector: 'app-polararea',  
  templateUrl: './polararea.component.html',  
  styleUrls: ['./polararea.component.css']  
})  
export class PolarareaComponent implements OnInit {  

    url = 'http://localhost:58617/API/Charts/GetCharts';  
    data: Data[];  
    Player = [];  
    Run = [];  
    Linechart = [];  
    constructor(private httpClient: HttpClient) { }  

    ngOnInit() {  
      this.httpClient.get(this.url).subscribe((result: Data[]) => {  
        result.forEach(x => {  
          this.Player.push(x.PlayerName);  
          this.Run.push(x.Run);  
        });  
        this  
        this.Linechart = new Chart('canvas', {  
          type: 'polarArea',  
          data: {  
            labels: this.Player,  

            datasets: [  
              {  
                data: this.Run,  
                borderColor: '#3cb371',  
                backgroundColor: [  
                  "#3cb371",  
                  "#0000FF",  
                  "#9966FF",  
                  "#4C4CFF",  
                  "#00FFFF",  
                  "#f990a7",  
                  "#aad2ed",  
                  "#FF00FF",  
                  "Blue",  
                  "Red",  
                  "Blue"  
                ],  
              }  
            ],  
          },  
          options: {  
            legend: {  
              display: false  
            },  
            scales: {  
              xAxes: [{  
                display: false  
              }],  
              yAxes: [{  
                display: true  
              }],  
            }  
          }  
        });  
      });  
    }  
  }  

Open the polararea.component.html file and add the following HTML.

<div class="chart-container" style="position: relative; height:40vh; width:70vw">    
    <canvas id="canvas"></canvas>    
  </div>  

Step 10

Now, open the app-routing.module.ts file and add the following lines to create routing.

import { NgModule } from '@angular/core';  
import { Routes, RouterModule } from '@angular/router';  
import { BarchartComponent } from "./barchart/barchart.component";  
import { LinechartComponent } from "./linechart/linechart.component";  
import { PiechartComponent } from "./piechart/piechart.component";  
import { DoughnutComponent } from "./doughnut/doughnut.component";  
const routes: Routes = [  
  {  
    path: 'LineChart', component: LinechartComponent  

  },  
  {  
    path: 'BarChart', component: BarchartComponent  
  },  
  {  
    path: 'PieChart', component: PiechartComponent  
  },  
  {  
    path: 'DoughnutChart', component: DoughnutComponent  
  },  
   { path:'Polarchart',component:PolarareaComponent }

];  

@NgModule({  
  imports: [RouterModule.forRoot(routes)],  
  exports: [RouterModule]  
})  
export class AppRoutingModule { }  

Step 11

Open the app.component.html file and add the following HTML.

<div>  
  <div class="row">  
    <div class="col-sm-12 btn btn-primary">  
      Batsman Performance Analysis  
    </div>  
  </div>  
  <div class="row" style="margin-top:10px;margin-bottom: 10px;">  
    <div class="col-sm-2">  
      <button class="btn btn-success" routerLink="/LineChart">Line Chart</button>  
    </div>  
    <div class="col-sm-2">  
      <button class="btn btn-success" routerLink="/BarChart">Bar Chart</button>  
    </div>  
    <div class="col-sm-2">  
      <button class="btn btn-success" routerLink="/PieChart">Pie Chart</button>  
    </div>  
    <div class="col-sm-2">  
      <button class="btn btn-success" routerLink="/DoughnutChart">Doughnut Chart</button>  
    </div>  
    <div class="col-sm-2">  
      <button class="btn btn-success" routerLink="/Polarchart">Polar Area</button>  
    </div>  
    <div class="col-sm-2">  
    </div>  

  </div>  
</div>  
<hr style="background-color:black" />  

<router-outlet></router-outlet>  

Step 12

Now, open the app.module.ts file and add the following code.

import { BrowserModule } from '@angular/platform-browser';  
import { NgModule } from '@angular/core';  
import { HttpClientModule } from '@angular/common/http';  
import { AppRoutingModule } from './app-routing.module';  
import { AppComponent } from './app.component';  
import { LinechartComponent } from './linechart/linechart.component';  
import { BarchartComponent } from './barchart/barchart.component';  
import { PiechartComponent } from './piechart/piechart.component';  
import { DoughnutComponent } from './doughnut/doughnut.component';  
import { PolarareaComponent } from './polararea/polararea.component';  
@NgModule({  
  declarations: [  
    AppComponent,  
    LinechartComponent,  
    BarchartComponent,  
    PiechartComponent,  
    DoughnutComponent,  
    PolarareaComponent,  
  ],  
  imports: [  
    BrowserModule,  
    AppRoutingModule,  
    AppRoutingModule,  
    HttpClientModule  
  ],  
  providers: [],  
  bootstrap: [AppComponent]  
})  
export class AppModule { }  

Step 13

Now, run the project, click on the buttons and check the result.

Line Chart

Create Charts In Angular 7 Application Using Chart.js

Bar Chart

Create Charts In Angular 7 Application Using Chart.js

Doughnut Chart

Create Charts In Angular 7 Application Using Chart.js

Polararea Chart

Create Charts In Angular 7 Application Using Chart.js

Summary

In this article, we learned about Chart.js and how we add chart.js in an Angular application to create Charts. In this article, we discussed the line chart, bar chart, pie chart, doughnut chart, and polar area chart.

Further Reading



Source link

The Fastest Way to Create an Event Sign-up System
Strategy

The Fastest Way to Create an Event Sign-up System


In this post, I’m going to show you how to create a simple event sign up system. Since one of the goals is to create something quickly, we are going to use Corvid to build the application.

Corvid is a development platform from Wix, which allows you to concentrate on the logic of the application using JavaScript and not spend time on writing HTML/CSS to create the UI. Corvid is focused on helping teams dramatically decrease time spent on development and ship products faster.

You can find the complete documentation, tutorial videos, and examples here: www.wix.com/corvid

Creating the UI

First of all, we’re going to create a layout for our future page. Fun fact: it will take you from 10 to 25 minutes, depending on your familiarity with the platform.

Let’s assume we have the following user flow:

  • A user signs up for the event by filling out the form =>
  • A unique QR-code is generated based on their user id =>
  • The QR-code can be either saved as a picture or sent to email =>
  • On the day of the event, a user shows the QR-code at the entrance =>
  • Event administrators scan the code and submit the attendance

In the Wix Editor, login and choose to create a new site (“+Create New Site” in the upper right corner of the account dashboard). In this example, I’ve used a blank template, but you can choose any and customize it according to your own preferences.

You may also like:
Modeling Domain Events.

You’ll also need to enable Corvid Developer Tools to rename and manage your elements. If you feel confused about how to do this, check out this link: 

https://support.wix.com/en/article/wix-code-enabling-developer-tools.

We’ll need to create two pages: the first one will be public (for users to sign in), and another one is for admins to submit guests’ attendance. I’ve also created two lightboxes (pop-ups) to show success messages after completing the form and attendance submission. You can learn more about how to create pages and lightboxes here: https://support.wix.com/en/article/adding-a-pop-up

At this point, your Site Structure should look pretty much like this:

Site structure

Site structure
Let’s create a basic layout for our sign up
“HOME” page. We’ll need to create three user inputs: 
#name,
#email#phoneNumber, and a 
#signUpButton. I’ve put all three inputs in the 
#signInBox to make these elements easier to collapse. (You’ll see it later in the code.)

We’ll also add a default image, #qrCodeImage, for our future QR-code and a #sendToEmailButton button to the same page to avoid redirect (you still can put these elements on the other page if you have too many of them, but choose what works better for your project’s performance). Both #qrCodeImage and #sendToEmailButton are collapsed on load and shown to users only when they successfully sign up with the registration form.

In the end, your page should look something like this:

Sample output

Sample output

In the upper right corner, you can see the checkmark in the “Collapsed on load” field. That’s how we collapse #qrCodeImage and #sendToEmailButton when users first loads the page.

Note: there is a difference between “hide” and “collapse.” A collapsed element shifts all elements that are below it up when not visible, and a hidden one doesn’t affect the neighbor elements and reserves place for itself no matter if it’s visible or not. 

Now, when we’re done with our “HOME” page, let’s design the admin page. It will only have two elements: #guestName and #submitButton (nothing fancy).

Note: I’m keeping it simple in this example, but feel free to play around with the page design.

Don’t forget to add success messages to your lightboxes.

Adding a Database

To store our users’ data, we will use a built-in database. Let’s create one and call it “Participants” (the naming is up to you). The database needs to have six columns:

  1. title: (fieldType: Text).
  2. phone: (fieldType: Number).
  3. attended: (fieldType: Boolean).
  4. userId: (fieldType: Text).
  5. qrCodeLink: (fieldType: Url).
  6. email: (fieldType: Text).

If you’re not sure about how to create a database, check out this documentation page.

Writing Code

And now we’re coming to the most fun part: coding. We’re going to use the Corvid API and some custom JavaScript code to describe logics for our site. All API references and examples can be found here: https://www.wix.com/corvid/reference/.

I’m going to break it into several feature-based parts:

  1. Signing up.
  2. Generating a QR-code.
  3. Submitting data to the database.
  4. Showing the QR-code to the user.
  5. Sending it to a user’s email.
  6. Attendance submission.

Signing Up

Let’s add an event to our #signUpButton. In this example, I’m adding all events inside the $w.onReady() function. First of all, I’m importing four built-in modules, which I’ll use to process data: uuid (to generate unique user id), wixData (to submit data to the database), wixLocation (for passing url to QRCode generator function), and wixWindow (to open the lightbox).

I’m also creating a new object with user data that will be passed from the inputs later and an obligatory _id field.

Generating QR-Code

Corvid supports some built-in npm packages which can be installed right from the editor. The complete list of currently supported modules and how to add them to your project can be found here (more modules will be added in the nearest future): https://www.wix.com/corvid/npm-modules.

I’m using the module named “qrcode,” which makes it super easy to convert URLs to QR. The documentation for this module is on Github: https://github.com/soldair/node-qrcode.

We must import all the npm modules to the backend, so, in the backend section of the project, I’ve created a jsw-module called “createUrl.jsw”.

Quick update on the site structure:

Updated file structure

Updated file structure

In this module, I import the npm-package and return the QR-code URL:

Submitting Data to the Database

Now, let’s receive the actual user’s data and on “Sign up” button click submit it to the database.

Showing the QR-Code to the User

Let’s get back to our “HOME” code. The wixData.save() API returns a promise, so chain .then() methods to process the result returned. I’m waiting until the end of database submission, passing the received URL as a source to #qrCodeImage, collapsing the form, and expanding the #qrCodeImage and #sendToEmailButton. Finally, I’m cleaning all the form’s values.

Sending a QR-Code to the User’s Email

The last thing we are going to finish before going to the admin’s page is sending a success email with a QR-code to the user. In Corvid, you can easily create triggered emails by adding your email template to the “Email marketing” tab in the Dashboard. 

To learn more, check out this link: https://support.wix.com/en/article/about-triggered-emails.

Response email

Response email

For this triggered email, I’ve created two variables: ${userName} and ${qrCodeLink} to pass custom data. 

Corvid provides you with ready-to-go snippets after clicking on the Save & Publish button. Let’s copy it to our code inside the Send to email button event:

Note: There is no Wix login required in this example, so before sending the email, we need to create a contact in the Wix CRM system.

I also open a lightbox with a success message and return the page to initial state after the email is sent.

Attendance Submission

The last part of this user journey will happen on the day of the actual event. A user shows the downloaded QR-code at the entrance, gets it scanned, and their attendance is submitted. 

Let’s add the following logic to the Attendance Admin page:

A unique userId is passed as a query in the URL from the QRcode, so we need to receive it using  wixLocation.query.userId.

After this id is received, we are able to receive the user’s data from the database, pass their name to the text field, #guestName on the page, and submit refreshed data with a changed “attended” field value back to the database.

Note: don’t forget to change permissions of the Attendance Admin page to make it only visible to admins. To learn more follow this link: https://support.wix.com/en/article/applying-page-permissions.

Further Reading



Source link

article image
Strategy

Automated Solar Arrays Could Help Incinerate Global Warming


Plenty of days, temperatures in California’s Mojave Desert climb above 120 degrees Fahrenheit. A measly figure. These 400 silvered glass panels, tucked into the western edge of that hot, hot desert, are there to generate heat 15 times that amount. And, ideally, to help cool the planet too.

Assembled by the Pasadena-based company Heliogen, each 16-square-foot freckle, a heliostat, reflects a kilowatt of sunlight to the top of a five-story tower, where it’s absorbed by a silicon carbide receiver. As the little black plate glows white, it exceeds 1,800 degrees. That’s hot enough to begin manufacturing cement and other industrial products—processes that typically rely on burning fossil fuels—and to potentially cut up to 10 percent of global greenhouse gas emissions.

Heliogen CEO Bill Gross has dreamed of harnessing the sun since the 1973 energy crisis, when he sold DIY solar panels. Those sales helped put him through college. When oil prices plummeted, he took a detour to build software—you can thank him for inventing pay-per-click ads—before he founded Heliogen in 2013, with funding from Bill Gates. Last fall, the company fired up this first array. “It was a bit like watching a lunar landing,” Gross says.

article image

The WIRED Guide to Climate Change

The world is getting warmer, the weather is getting worse. Here’s everything you need to know about what humans can do to stop wrecking the planet.

Similar arrays have been used to make electricity and tasty SunChips, and even drill for oil. But those peak around 1,000 degrees, because each heliostat has to be individually calibrated and can fall out of alignment over time. With Heliogen, cameras atop the tower scan the sky, and image analysis software computes the optimal position for each mirror, which can rotate in increments smaller than 1/160 of a degree. Gross says such efficiency can deliver heat 20 percent more cheaply than fossil fuels can.

As proof of concept, Heliogen has mounted a kiln atop the tower to directly heat limestone, a key step in making cement. This year the company plans to link with commercial partners that have the ample shadowless land required. Gross is also building a receiver that can handle temperatures above 2,700 degrees. That kind of hellfire can create synthetic hydrogen, which could replace oil-based fuels. “Civilization depends on cement and steel—our roads, travel, everything,” Gross says. “We’ve found a way to clean it up.”


Laura Mallonee (@LauraMallonee) writes about photography for WIRED.

This article appears in the February issue. Subscribe now.


More Great WIRED Stories





Source link