<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dilina Hirantha on Medium]]></title>
        <description><![CDATA[Stories by Dilina Hirantha on Medium]]></description>
        <link>https://medium.com/@dilinahirantha?source=rss-7afc02975a3b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PWlewmItLZN7rZVKT6EAXA.jpeg</url>
            <title>Stories by Dilina Hirantha on Medium</title>
            <link>https://medium.com/@dilinahirantha?source=rss-7afc02975a3b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 20:58:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dilinahirantha/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[.NET Core AutoMapper]]></title>
            <link>https://dilinahirantha.medium.com/net-core-automapper-ed2e304cafda?source=rss-7afc02975a3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed2e304cafda</guid>
            <category><![CDATA[object-mapping]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[xunit]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[automapper]]></category>
            <dc:creator><![CDATA[Dilina Hirantha]]></dc:creator>
            <pubDate>Sat, 04 Jan 2025 20:07:35 GMT</pubDate>
            <atom:updated>2025-01-13T17:00:16.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VyqNaFhldzN7RUrwtQn2Sw.png" /></figure><p>AutoMapper is a dependency injection tool that simplifies mapping between object types. Before AutoMapper, manually mapping properties between view and domain models was time-consuming and error-prone. AutoMapper solves this by automating the mapping process, reducing boilerplate code, and ensuring consistency. It is beneficial for tasks like transforming database data into models for APIs, business logic, or converting data between ViewModels and domain models in MVC applications.</p><p><strong>below is the overview of the article</strong>,</p><ul><li>Installing AutoMapper</li><li>Setup AutoMapper</li><li>Create Model Classes and AutoMapper profile</li><li>Unit Test with AutoMapper</li></ul><blockquote><strong>Installing AutoMapper</strong></blockquote><p>To install AutoMapper, you can either run the following command in the NuGet Package Manager Console:</p><pre>Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection</pre><p>or search for AutoMapper.Extensions.Microsoft.DependencyInjection install it in Visual Studio&#39;s <strong>NuGet Package Manager</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*n3nU1AakbfpNHl5WvmoKNQ.png" /></figure><blockquote><strong>Setup AutoMapper</strong></blockquote><p>After installing the AutoMapper NuGet package, the next step is to register the service in the ConfigureServices method within the Startup.cs class.</p><pre>public void ConfigureServices(IServiceCollection services) {<br>    services.AddAutoMapper(typeof(Startup));<br>    services.AddControllers();<br>}</pre><p>Now, We have completed the AutoMapper configuration parts.</p><blockquote><strong>Create Model Classes and AutoMapper Profile</strong></blockquote><p>To use AutoMapper for data mapping, create a custom class that inherits from the Profile class. This class is used to define and configure mappings between source and destination objects.</p><p>Before that, let’s define two classes to represent the source and destination objects. First, the data model (Database),</p><pre>public class UserModel<br>{<br>    public int Id { get; set; }<br>    public string FirstName { get; set; }<br>    public string LastName { get; set; }<br>    public string ContactNo { get; set; }<br>    public string Email { get; set; }<br>    public Address Address { get; set; }<br>}</pre><pre>public class Address<br>{<br>    public string Street { get; set; }<br>    public string City { get; set; }<br>    public string State { get; set; }<br>    public string PostalCode { get; set; }<br>}</pre><p>Below are the view model classes that are used to represent the view in UI,</p><pre>public class UserViewModel<br>{<br>    public int Id { get; set; }<br>    public string FullName { get; set; }<br>    public string ContactNumber { get; set; }<br>    public string Email { get; set; }<br>    public Address Address { get; set; }<br>}</pre><pre>public class AddressViewModel<br>{<br>    public string Street { get; set; }<br>    public string City { get; set; }<br>    public string State { get; set; }<br>    public string PostalCode { get; set; }<br>}</pre><p>After creating source and destination classes, we should create a UserPofile class by inheriting the Profile class. Inside that, we can map UserModel to UserViewModel.</p><pre>using AutoMapper;<br><br>public class UserProfile : Profile<br>{<br>    public UserProfile()<br>    {<br>        // Mapping UserModel to UserViewModel<br>        CreateMap&lt;UserModel, UserViewModel&gt;()<br>            .ForMember(dest =&gt; dest.FullName, opt =&gt; opt.MapFrom(src =&gt; $&quot;{src.FirstName} {src.LastName}&quot;))<br>            .ForMember(dest =&gt; dest.ContactNumber, opt =&gt; opt.MapFrom(src =&gt; src.ContactNo))<br>            .ReverseMap();<br>           <br>        // Mapping Address to AddressViewModel<br>        CreateMap&lt;Address, AddressViewModel&gt;().ReverseMap(); // Mapping Address object<br>    }<br>}</pre><p>Let&#39;s break the above mappings which explain the features of AutoMapper,</p><ul><li>CreateMap&lt;UserModel, UserViewModel&gt; configuration maps the UserModel to the UserViewModel</li><li>We explicitly do not need to map the UserModel Email to the UserViewModel Email, since <strong>object property names are not different</strong>. But, mapping between the ContactNo and ContactNum is necessary.</li><li>We can use custom mappings along with AutoMapper. As an example the FullName property in UserViewModel is generated by combining FirstName and LastName from the UserModel.</li></ul><p>Additionally, as an example, if you have a requirement to <strong>map between two data types</strong> such as <strong>int and string</strong>, we can achieve it using custom mapping like the one below,</p><pre>CreateMap&lt;UseModel, UserViewModel&gt;()<br>            .ForMember(dest =&gt; dest.ContactNumber, opt =&gt; opt.MapFrom(src =&gt; src.ContactNo.ToString()));</pre><ul><li>For complex objects like a model containing another model (e.g., UserModel with an Address), AutoMapper automatically handles nested mappings. You <strong>only need to define mappings for the parent and nested objects</strong>, and AutoMapper will easily map the inner objects without extra configuration.</li><li>The .ReverseMap() method in AutoMapper creates a two-way mapping between source and destination types. Here we map UserModel to UserViewModel, by calling .ReverseMap() will automatically create a mapping from UserViewModel back to UserModel.</li></ul><blockquote><strong>Unit Test with AutoMapper</strong></blockquote><p>We can write unit tests for the AutoMapper using the xUnit by following the below steps.</p><ul><li>As a prerequisite, in addition to the AutoMapper, you should have installed the NuGet packages for xUnit.</li></ul><p>Following is the code snippet for the unit test class of UserProfileTests.</p><pre>using AutoMapper;<br>using Xunit;<br><br>public class UserProfileTests<br>{<br>    private readonly IMapper _mapper;<br><br>    public UserProfileTests()<br>    {<br>        // Set up AutoMapper using MapperConfiguration<br>        var configuration = new MapperConfiguration(cfg =&gt;<br>        {<br>            cfg.AddProfile(new UserProfile()); // AutoMapper profile class<br>        });<br><br>        _mapper = configuration.CreateMapper();<br>    }<br><br>    [Fact]<br>    public void Should_Map_UserModel_To_UserViewModel_Correctly()<br>    {<br>        // Arrange<br>        var userModel = new UserModel<br>        {<br>            Id = 1,<br>            FirstName = &quot;John&quot;,<br>            LastName = &quot;Doe&quot;,<br>            ContactNo = &quot;61-2-1234 5678&quot;,<br>            Email = &quot;John@gmail.com&quot;,<br>            Address = new Address<br>            {<br>                Street = &quot;123 Main St&quot;,<br>                City = &quot;Somewhere&quot;,<br>                State = &quot;CA&quot;,<br>                PostalCode = &quot;12345&quot;<br>            }<br>        };<br><br>        // Act<br>        var userViewModel = _mapper.Map&lt;UserViewModel&gt;(userModel);<br><br>        // Assert<br>        Assert.Equal(userModel.Id, userViewModel.Id);<br>        Assert.Equal(&quot;John Doe&quot;, userViewModel.FullName);<br>        Assert.Equal(userModel.ContactNo, userViewModel.ContactNumber);<br>        Assert.Equal(userModel.Email, userViewModel.Email);<br>        Assert.Equal(userModel.Address.Street, userViewModel.Address.Street);<br>        Assert.Equal(userModel.Address.City, userViewModel.Address.City);<br>        Assert.Equal(userModel.Address.State, userViewModel.Address.State);<br>        Assert.Equal(userModel.Address.PostalCode, userViewModel.Address.PostalCode);<br>    }<br><br>    [Fact]<br>    public void Should_Map_UserViewModel_To_UserModel_Correctly()<br>    {<br>        // Arrange<br>        var userViewModel = new UserViewModel<br>        {<br>            Id = 1,<br>            FullName = &quot;John Doe&quot;,<br>            ContactNumber = &quot;61-2-1234 5678&quot;,<br>            Email = &quot;John@gmail.com&quot;,<br>            Address = new AddressViewModel<br>            {<br>                Street = &quot;123 Main St&quot;,<br>                City = &quot;Somewhere&quot;,<br>                State = &quot;CA&quot;,<br>                PostalCode = &quot;12345&quot;<br>            }<br>        };<br><br>        // Act<br>        var userModel = _mapper.Map&lt;UserModel&gt;(userViewModel);<br><br>        // Assert<br>        Assert.Equal(userViewModel.Id, userModel.Id);<br>        Assert.Equal(&quot;John&quot;, userModel.FirstName);<br>        Assert.Equal(&quot;Doe&quot;, userModel.LastName);<br>        Assert.Equal(userViewModel.ContactNumber, userModel.ContactNo);<br>        Assert.Equal(userViewModel.Email, userModel.Email);<br>        Assert.Equal(userViewModel.Address.Street, userModel.Address.Street);<br>        Assert.Equal(userViewModel.Address.City, userModel.Address.City);<br>        Assert.Equal(userViewModel.Address.State, userModel.Address.State);<br>        Assert.Equal(userViewModel.Address.PostalCode, userModel.Address.PostalCode);<br>    }<br>}</pre><p>As we reach the end of this article, I trust it has been valuable and useful in helping you gain a better understanding of how <em>AutoMapper</em> can streamline the mapping between models and view models in your applications.</p><p>You can further explore using the AutoMapper official documentation <a href="https://docs.automapper.org/en/stable/index.html">documentation</a>. Happy Coding!</p><p>Let’s continue sharing valuable knowledge like this &amp; feel free to follow <strong>👉 </strong><a href="https://medium.com/@dilinahirantha"><strong>Dilina Hirantha</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed2e304cafda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Observable using Behavior Subject in Angular]]></title>
            <link>https://javascript.plainenglish.io/creating-observable-using-behavior-subject-in-angular-93a949f54d18?source=rss-7afc02975a3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/93a949f54d18</guid>
            <category><![CDATA[observables]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Dilina Hirantha]]></dc:creator>
            <pubDate>Thu, 02 Dec 2021 15:46:24 GMT</pubDate>
            <atom:updated>2024-08-28T12:24:00.358Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ce_QCjhgmm41Iq7lyhAAOw.jpeg" /></figure><h3><strong>Observable</strong></h3><p>Observable, also known as ReactiveX library, comes from RxJS<em> </em>and it’s really useful to handle events, and, more particularly, to subscribe to them. As an example, Angular uses observables as an interface for its core functionalities such as:</p><ul><li>Define custom events to send outputs data from child component to parent component.</li><li>Handle AJAX requests and responses through HTTP modules.</li><li>Listen and respond to user-input events in the Angular Router and Form modules.</li></ul><p>In Angular, RxJS provides 4 types of subjects to create an observable. Those 4 types are <em>Subject</em>, <em>BehaviorSubject</em>, <em>ReplaySubject </em>and <em>AsyncSubject</em>. They can be distinguished from each other by looking at how they react to <em>subscribe</em>. But, in this article, we are going to discuss the way of implementing the <em>BehaviorSubject </em>which is one of the most common subjects in Angular.</p><h3>BehaviorSubject</h3><p>First of all, you need to have basic knowledge of how the Subject works. When you subscribe to the Subject, you will get every event emitted from the Subject <strong>after</strong> you subscribed to it. Refer to <a href="https://www.youtube.com/watch?v=_5n9p_2Ajvo&amp;t=1s">this</a> video.</p><p>But in the BehaviorSubject, it seems to work same as the Subject, except it receives the <strong>last event that occurred before</strong> the subscription. Refer to <a href="https://www.youtube.com/watch?v=ENluprrCpTU">this </a>video.</p><p>So, there are few reasons to prefer the BehaviorSubject over the Subject:</p><ul><li>It will always return the current value on subscription (Require initial value when initialization).</li><li>It has a <strong>getValue()</strong> function to get the current value.</li><li>It ensures that the component always receives the most recent data.</li></ul><p>We can illustrate the implementation of BehaviorSubject by using the example of data sharing between components.</p><p>First of all, we need to create a service using a private BehaviorSubject that will hold the <strong>current value</strong> of the message. We define a <em>currentMessage </em>variable to handle this data stream as an observable that will be used by the components. After that, we implement a function to call the <strong>next()</strong>function to change its value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d5c95b2e23ce1087db5881a0146a24b/href">https://medium.com/media/5d5c95b2e23ce1087db5881a0146a24b/href</a></iframe><blockquote><em>💡</em> <strong>Learn how to extend existing Angular schematics to add new functionality:</strong></blockquote><p><a href="https://differ.blog/inplainenglish/extending-angular-schematics-a-step-by-step-guide-9cf52f">Extending Angular Schematics: A Step-by-Step Guide</a></p><blockquote><em>👉</em> To read more such acrticles, <a href="https://differ.blog/"><strong>sign up for free on Differ</strong></a>.</blockquote><p>Next, let’s see how we can use this <em>DataService </em>inside both parent and child components.</p><p>In the parent component, inject the <em>DataService</em> in the constructor. Then subscribe to the <em>currentMessage </em>observable of the <em>DataService </em>to get value changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28b00b9acb836bd48decd010485b9518/href">https://medium.com/media/28b00b9acb836bd48decd010485b9518/href</a></iframe><p>Then, we create a <em>changeMessage </em>function inside the child component to assign a new value to the message. The important thing is, we can create a function in any component to change the message and it will automatically broadcast to all other components who are subscribed to the <em>DataService</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2778f73503613afec05fee00a1d88ae/href">https://medium.com/media/b2778f73503613afec05fee00a1d88ae/href</a></iframe><p>In the above code snippet, after the user clicks the New Message button, the <em>changeMessage </em>function is triggered and the <em>currentMessage </em>observable updates its value from the new value of the message through the <strong>next()</strong>function. Therefore, the parent component who is subscribed will receive the new message value. Also, not only the parent but also child, and sibling components who are subscribed receive the same treatment.</p><blockquote>BehaviorSubject is a very simple, easy to use, but powerful way of creating a observable. I hope this article will help you get a basic understanding of BehaviorSubject.</blockquote><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93a949f54d18" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/creating-observable-using-behavior-subject-in-angular-93a949f54d18">How to Create Observable using Behavior Subject in Angular</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Axios Vs. Fetch for HTTP Requests]]></title>
            <link>https://dilinahirantha.medium.com/axios-vs-fetch-for-http-requests-f11f98e719c1?source=rss-7afc02975a3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f11f98e719c1</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[fetch]]></category>
            <dc:creator><![CDATA[Dilina Hirantha]]></dc:creator>
            <pubDate>Fri, 17 Sep 2021 19:05:01 GMT</pubDate>
            <atom:updated>2021-09-21T09:19:02.725Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is the Best Method to Implement HTTP Requests</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*zkIfkZH3NplQMMEd5SsI3Q.png" /></figure><p>One of the basic tasks of any web application is to communicate with servers through the Hypertext Transfer Protocol (HTTP). This will be simply achieved with the use of Fetch or Axios. Fetch and Axios seem similar in the functionalities, but Some developers like Axios over Fetch for its easy use. Also, Fetch API is capable of reproducing the key options of Axios somehow. Therefore we should know which is better and where each should be used.</p><h3>Axios</h3><p>Axios is an easy-to-use API / promise-based HTTP client. Also, It is a third-party tool (Not <em>Vanilla </em>JavaScript) that can be used on both the client and server sides. However, one major aspect of Axios which it does not come as a native JavaScript API, so we will have to manually import it into our project.</p><h3>Fetch</h3><p>Fetch is a modern and cleaner way to make asynchronous requests and handles responses more smoothly and is now supported by most major browsers. Another benefit of Fetch is that it is <em>Vanilla </em>JavaScript, so there’s no need to install or import.</p><p>Next, let’s take a look at some of the different syntaxes and applicability of Fetch and Axios.</p><h3>1. JSON data transformation</h3><p>Axios automatically stringifies the data when sending requests. But you have to do it manually if you use fetch(). Compare,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/016c7652ca03e7387fbd9397bb2c8a59/href">https://medium.com/media/016c7652ca03e7387fbd9397bb2c8a59/href</a></iframe><p>In the above code snippet, when you use fetch(), first, we have to make the actual request fetch()and then we call the .json() method on the response as the second step.</p><h3>2. HTTP interceptors</h3><p>Another major capability of the Axios is to intercept the HTTP request. Intercepting means you can modify or change the value of the request or response. In deeply, You can use interceptors to transform the request (e.g., logging, authentication, etc.) <strong>before </strong>Axios sends it (request intercept) or transform the response <strong>before </strong>Axios returns the response(response intercept) to your code.</p><p>Axios has an <strong>in-build feature</strong> of intercept HTTP Requests while fetch()haven’t. Below is the simple Axios intercept to print the request and response.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f02f1836c1caab83940ad662d655cae4/href">https://medium.com/media/f02f1836c1caab83940ad662d655cae4/href</a></iframe><p>By default, fetch() does not provide a way to intercept HTTP requests. We can overwrite the global fetch() method and define our interceptor, like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/017b3014164eff9adec0e11fcc0771cd/href">https://medium.com/media/017b3014164eff9adec0e11fcc0771cd/href</a></iframe><h3>3. Response timeout</h3><p>Most of the developers prefer Axios over fetch(),due to the simplicity of setting the <strong>timeout </strong>option in the Axios. By the timeout property in the config object of the Axios, you can set a time in milliseconds, which is considered the time before the request is aborted. Using Axios,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce28fcd5da592f65ec193004d1481ac0/href">https://medium.com/media/ce28fcd5da592f65ec193004d1481ac0/href</a></iframe><p>Fetch() provides similar functionality through the AbortController interface. But it’s not as simple as the Axios.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32d52a863480dc61a3418ba222b47239/href">https://medium.com/media/32d52a863480dc61a3418ba222b47239/href</a></iframe><p>In the above snippet,</p><ul><li><strong>AbortController</strong> Interface provides the capability to abort the request.</li><li><strong>Signal </strong>property in options object provides the mean of communicating with the requestor abort it.</li></ul><p>If the server doesn’t respond within five seconds, the <strong>abort </strong>method will be called and the request aborted.</p><h3>4. Simultaneous requests</h3><p>Both Axios and fetch()are capable of accessing multiple simultaneous requests. Axios simply pass an array of requests to axios.all() method and use axios.spread() to assign the properties of the response array to separate variables as follow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2207da3381d78a479e5e7551824a9bd0/href">https://medium.com/media/2207da3381d78a479e5e7551824a9bd0/href</a></iframe><p>You can achieve the same results with fetch()by passing the array of requests to built-in Promise.all() method. Then response can handle using an async function,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e968b4edbd0ddecd2e186c0e967dd66/href">https://medium.com/media/7e968b4edbd0ddecd2e186c0e967dd66/href</a></iframe><p>After the above discussed majorly important points between Axios and fetch(),we can jump into another few comparisons as below.</p><h3>5. CSRF Protection</h3><p>Axios have in-build support of CSRF (Cross-site request forgery) to prevent cross-site requests while fetch()doesn’t support CSRF.</p><h3>6. Upload/Download Request Progress</h3><p>Axios provides <a href="https://github.com/rikmms/progress-bar-4-axios/">Axios Progress Bar</a> module to data transmission progress so developers can show the loading indicator while the user communicates with the server. But fetch() doesn’t have such a module.</p><p>In this blog, we have looked at <strong>Fetch </strong>and <strong>Axios </strong>and checked out some real-world operations. While most of the scenarios, <strong>Axios </strong>seems better than <strong>Fetch </strong>and also can use in the Node.js environment. On the other hand, <strong>Fetch </strong>has the added advantage of being readily available in all modern browsers.</p><p>I hope this blog will help you to choose the most suitable API for the next developments. Thanks for reading!</p><h3>Learn More</h3><ul><li><a href="https://enlear.academy/uri-vs-url-vs-urn-51b8167cafad">URI vs URL vs URN</a></li><li><a href="https://enlear.academy/http-vs-https-93c87cf51a20">HTTP vs HTTPS—Why HTTP Is Not Safe?</a></li><li><a href="https://enlear.academy/how-to-implement-a-customized-google-map-with-flutter-d6fb40534cda">How To Implement a Customized Google Map with Flutter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f11f98e719c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Query the DOM in Angular with Decorators]]></title>
            <link>https://dilinahirantha.medium.com/querying-the-dom-in-angular-using-decorators-fd3041bd4497?source=rss-7afc02975a3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd3041bd4497</guid>
            <category><![CDATA[viewchild]]></category>
            <category><![CDATA[contentchild]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[querying]]></category>
            <category><![CDATA[dom]]></category>
            <dc:creator><![CDATA[Dilina Hirantha]]></dc:creator>
            <pubDate>Sun, 08 Aug 2021 07:27:27 GMT</pubDate>
            <atom:updated>2021-09-14T03:04:58.417Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to Access DOM in Angular?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xX7P2MJpAUh-WoI82V0Fg.jpeg" /></figure><p>DOM stands for the <strong>D</strong>ocument <strong>O</strong>bject <strong>M</strong>odel. The logical structure of documents and the ways of accessing and manipulating documents are defined using DOM elements. On other hand, The DOM is the way <strong>JavaScript sees</strong> its containing pages’ data. It is an object that includes how the HTML/XHTML/XML is formatted, as well as the browser state and it defines events, methods, properties for all HTML elements as objects.</p><h3>DOM Queries</h3><p>Angular has provided two ways to query the different reference types within a component/ directive.</p><ul><li><strong>ViewChild/ViewChildren</strong></li><li><strong>ContentChild/ContentChildren</strong></li></ul><p>let’s look at how we can apply the above decorators for querying the DOM.</p><h3>What is ViewChild/ViewChildren?</h3><p>The <em>@ViewChild</em> decorator is used to query a reference for a single DOM element from the DOM tree while <em>@ViewChildren </em>is used to returns a list of references in the form of a query list. (Here after use ViewChildren without @ Sign)</p><h4>ViewChild</h4><p>below shows the syntax for the <em>ViewChild </em>decorator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c44e7817d5e29f23e84b4b1c783cff9e/href">https://medium.com/media/c44e7817d5e29f23e84b4b1c783cff9e/href</a></iframe><p>There are three main parameters that can be identified in the above syntax,</p><ul><li><strong><em>Selector</em></strong>: The selector of the element to query and it can be a string, a type, or a function that returns a string or type.</li><li><strong><em>read</em></strong>: This is one of the options given. It reads a different token from the queried elements.</li><li><strong><em>static</em></strong>: Determines when the query is resolved. True is when the view is initialized (before the first change detection) for the first time. False if you want it to be resolved after every change detection.</li></ul><p>Next, we are moving to the example of the <em>ViewChild</em>,</p><p>For that, we need to create a new Angular component and here I named it as the <strong>childcomponent</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*FrKW5KX3hpl83mm1OzLISQ.png" /></figure><p>Below shows the template of the <strong>childcomponent</strong><em>,</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6b5ba5633d1b856b91f8927a4caf385/href">https://medium.com/media/c6b5ba5633d1b856b91f8927a4caf385/href</a></iframe><p>We use the <strong>childcomponent </strong>as the child component for the app component which is acts as the parent component. Therefore, we have used the local input variable, which is declared within the component class to print the value coming from the parent component. We use <em>@input</em> decorator for that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e62a64b8b58b2f61f2c8287503b836b3/href">https://medium.com/media/e62a64b8b58b2f61f2c8287503b836b3/href</a></iframe><p>After that, let us move into setup the app component. Here we used the selector of the child component in the <strong>app.component.html</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70c0cbb3567719011b031098754c62be/href">https://medium.com/media/70c0cbb3567719011b031098754c62be/href</a></iframe><p>In the first sight of view, you can notice we have used another property along with the child component’s selector as <strong>componentName. </strong>We use this property to access the name of the child component from the parent component as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f25c1560ef3ea8c2a2b63e6f9a802349/href">https://medium.com/media/f25c1560ef3ea8c2a2b63e6f9a802349/href</a></iframe><p>You can use the variable <em>demo </em>to direct access the property of the child component.</p><p>I think you have doubts about the usage of the AfterViewInit<strong><em> </em></strong>lifecycle hook in here. The child element may not be loaded completely until the application loads. If we access it at the same time, it returns undefined. Therefore we use AfterViewInit what is called after Angular has fully initialized a component’s views.</p><p>Also, we can use <em>ViewChild</em> to access the elements without reference to the whole component as below. This is <strong>app.component.html</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff85f914da740096cb302d53de7131de/href">https://medium.com/media/ff85f914da740096cb302d53de7131de/href</a></iframe><p>Here, to access the native element (button), we can use <strong>ElementRef</strong>, which returns the native HTML element. It can be accessed from the component like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec79b7c614fc126f52eda9d4e200888b/href">https://medium.com/media/ec79b7c614fc126f52eda9d4e200888b/href</a></iframe><h3>ViewChildren</h3><p>The point of difference between <em>ViewChild </em>and<em> ViewChildren </em>is, <em>ViewChildren </em>returns multiple references in form of a query list.</p><p>The below example shows how it works by using a child component named <strong>demochild</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74b5aae7851c1440db2ec898297685cf/href">https://medium.com/media/74b5aae7851c1440db2ec898297685cf/href</a></iframe><p><strong>demochild </strong>component class as below,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95a6d3f3208b086c399ea34c7edd5b7a/href">https://medium.com/media/95a6d3f3208b086c399ea34c7edd5b7a/href</a></iframe><p>Next, we set up the app component as like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbe74774a24d1c748c0969f27b35a13a/href">https://medium.com/media/dbe74774a24d1c748c0969f27b35a13a/href</a></iframe><p>By looking this, you can clearly understand that we have used the child component’s selector in three times along with the <strong>name </strong>property. Therefore, we require to access multiple child references.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/304f6bab11591e444b8cc225f07b6b06/href">https://medium.com/media/304f6bab11591e444b8cc225f07b6b06/href</a></iframe><p>You can access the query list through the given children variable and for better visualization, you can convert it to an array using <strong>toArray </strong>method.</p><h3>What is ContentChild/ContentChildren ?</h3><p>Both ContentChild and ContentChildren are very similar to the <em>ViewChild </em>and <em>ViewChildren</em>, but there is a difference between them.</p><p><em>“ViewChild or ViewChildren can access any DOM element, component, or directive. But it cannot be used to access the </em><strong><em>projected content</em></strong><em>. While ContentChild or ContentChildren can access only the projected content, but cannot be used to access any other content.”</em></p><ul><li>Here<strong><em> content projection</em></strong> is a way to pass the <strong><em>HTML content</em></strong> from the parent component to the child component and the child component will display the template in a<strong> <em>designated spot</em></strong>. We use the <strong>ng-content</strong> element to designate a spot for the template in the template of the child component. Also <strong>ng-content</strong> allows us to create multiple slots using the <strong>selector </strong>attribute. Therefore, parents can send different content to each of those slots.</li></ul><h3>ContentChild</h3><p>Below show the syntax of the <em>ContentChild </em>and it seems similar to the syntax of <em>ViewChild</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1996612d74cb581ca393d1a338c8cae5/href">https://medium.com/media/1996612d74cb581ca393d1a338c8cae5/href</a></iframe><p>Let’s get a clear understand of it using an example.</p><p>First of all, we create a <em>card </em>component that acts like a child component used to create a single card.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54db8c50907ddbac1f6eb3e0cc380f5f/href">https://medium.com/media/54db8c50907ddbac1f6eb3e0cc380f5f/href</a></iframe><p>In the card component, we have used three <strong>ng-content </strong>elements separately. Next, we are going to pass HTML content to the header of the card using the <em>header </em>selector. As well as you can pass any HTML content to other card components if you want.</p><p>For that, we use <em>cardlist </em>component as the parent component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1253e093e19a78b0139bb4b506e1ef62/href">https://medium.com/media/1253e093e19a78b0139bb4b506e1ef62/href</a></iframe><p>If you look carefully, you can see we have accessed the header using the <strong>header </strong>property inside the <strong>h </strong>tags.</p><p>Next, we go back to the card component and modify it to use the <em>ContentChild</em>.</p><p>First, we import <em>ContentChild </em>from the @angular/core.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f8788f0d7cd4e9d95bf9d8adb0645ed/href">https://medium.com/media/8f8788f0d7cd4e9d95bf9d8adb0645ed/href</a></iframe><p>Then we can add below code snippets to the card component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bae76d116ac5afc91a1a525229d7f272/href">https://medium.com/media/bae76d116ac5afc91a1a525229d7f272/href</a></iframe><p>Here, <strong>headerContent </strong>is the variable. We apply the <em>ContentChild </em>decorator on that variable. The <strong>header </strong>is the template variable, that we want to read. Since it is applied on <strong>h the </strong>tag, it is going to return the <strong>ElementRef</strong>.</p><p>Also, we use AfterContentInit hook. Hence the <em>headerContent </em>is available to use only after the AfterContentInit hook. Eventually, <a href="http://renderor2/"><em>renderor2</em></a><em> was </em>used to style the header element.</p><h3>ContentChildren</h3><p><em>ContentChildren is </em>similar to <em>ContentChild </em>but it always returns a <strong>list of element references</strong> from the projected content. If there are multiple elements the <em>ContentChild </em>returns the first matching element.</p><p>Thank you for reading this piece. I hope you have found it useful. Be sure to let me know your thoughts in the comments.</p><h3>Learn More</h3><ul><li><a href="https://enlear.academy/routes-access-controlled-by-angular-guards-63000283c017">Access Controlled by Angular Route Guards</a></li><li><a href="https://enlear.academy/angular-for-every-one-resolver-c900c8f7672a">Using Angular Resolver to Pre Load Data</a></li><li><a href="https://enlear.academy/angular-for-everyone-simplified-scss-files-imports-25539a134dc0">Simplifying SCSS File Imports in Angular</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd3041bd4497" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis Caching with Node.js]]></title>
            <link>https://javascript.plainenglish.io/guide-to-redis-caching-with-node-js-e50356b06c1c?source=rss-7afc02975a3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e50356b06c1c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dilina Hirantha]]></dc:creator>
            <pubDate>Fri, 23 Jul 2021 07:40:48 GMT</pubDate>
            <atom:updated>2021-07-23T07:56:03.244Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting Started with Redis Caching in Node.js</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HuwqQJWFNpomg28TRWPqBQ.jpeg" /></figure><p>Modern applications can’t process without a minimum amount of performances. As time goes on, this requirement gets increase as the complexity and amount of requests hitting applications increase exponentially. Therefor, caching came to the fore in response. <strong>Caching</strong> refers to the process of storing data in a temporary location so that the applications can access and retrieve data faster. The aim of caching is to reduce the cost of bandwidth of data sent over the network and the application’s response time by speeding up data access operations.</p><h4>What is Redis?</h4><p>Redis is a powerful and versatile in-memory caching mechanism which is incredibly super fast. We called it “versatile” because it is a perfect choice for handle caching, database-like features, session management, real-time analytics, event streaming, queue management etc.</p><h4>Installing Redis</h4><p>Here, we will walkthrough step by step to build <em>Redis </em>cache with a Node.js application.</p><p>First of all, we need to download the binaries for <em>Redis </em>into your directory and compile using a following commands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*Wu-5d77ccJtH_7g6PDn3Ww.png" /></figure><p>After installing use the following command to start the <em>redis </em>server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*w7LW8xhX6Ms6yG-UqbOiNw.png" /></figure><p>Also you can test whether connections is still alive by using the below command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*0xF_52jUQzqcDY8MMOHD1A.png" /></figure><p>For above command response should be received as <strong><em>pong </em></strong>and that means our <em>Redis </em>server is running successfully.</p><p>For further details read the <a href="https://redis.io/topics/quickstart">official quick start guide</a> .</p><h4>Setup Node.js application</h4><p>In this tutorial we use <strong>axios </strong>to access the data form the external API. Also we use <strong>redis </strong>which is the standard Redis client for Node. We can install above two packages as following using the <strong>npm</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13b34c5fdfb45b5b1744961112200a3a/href">https://medium.com/media/13b34c5fdfb45b5b1744961112200a3a/href</a></iframe><p>We can setup the node server using below code snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a526b6d09ec8258a639ec59d4fbad30/href">https://medium.com/media/9a526b6d09ec8258a639ec59d4fbad30/href</a></iframe><p>After that, we use a open public API from the <a href="https://openweathermap.org/">https://openweathermap.org</a> to get the weather details of any given city.</p><p>You can pass a any city name as a string which you are looking for to the API and retrieve an array of weather details in a json format. A sample request to the API looks like this. Here replace your API key with xxx for use.</p><p><a href="https://api.openweathermap.org/data/2.5/weather?q=London&amp;appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">https://api.openweathermap.org/data/2.5/weather?q=London&amp;appid=xxx</a></p><p>Above our Node application, we define a route named /weather, which retrieves weather details for any city from the API and send them back to the client. Here we have used axios<strong> </strong><em>GET</em> request for this purpose.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9a81242e6b0d622e06f61ced332926f/href">https://medium.com/media/f9a81242e6b0d622e06f61ced332926f/href</a></iframe><h4>Caching with Redis</h4><p>Now let’s move on to the most important part where to apply the <em>redis </em>cache to the application. First of all, we need to connect to the <em>redis </em>server through our Node application. We can accomplish it as below,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fdc890c2a6f41b55942d2341dc0a379/href">https://medium.com/media/7fdc890c2a6f41b55942d2341dc0a379/href</a></iframe><p>Here, need to mention that <strong>6379 </strong>is the <em>default port number</em> for the <em>Redis </em>server. After that we can use above created <em>Redis client </em>to handle the caching in our Node application.</p><p>First we need to extract the city name from the request query parameters. Then we need to pass that city name as a <strong><em>key</em></strong> into the cache to check whether weather details already in it.</p><p>Here need to mention that, <em>Redis </em>cache store the data as <strong><em>key value pairs</em></strong>. Therefore you need a key to retrieve the related value. Since the Redis package doesn’t have native support for promises, we have to pass a callback to process the retrieved data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdc59a489fd939a55e994cb5048d13d0/href">https://medium.com/media/fdc59a489fd939a55e994cb5048d13d0/href</a></iframe><p>How we can know whether the <em>Redis </em>cache has the weather details related to the passed city name?</p><p>If the value returned from <em>Redis </em>is <strong><em>not null</em></strong>, it means the related data exists in the cache, so it’s easy to return that data in the response. Just make sure you cast back the string to JSON.</p><p>Otherwise, if the returned value was <strong><em>null</em></strong>, we have to send a request to the external API to retrieve relevant weather data. After getting the weather data from API, we store it in the cache so that next time the same request is sent to the Node server, it can respond with data stored in the cache instead of requesting them from the API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32d3f9a408be1d20f409583a2b076ef3/href">https://medium.com/media/32d3f9a408be1d20f409583a2b076ef3/href</a></iframe><p>Here we have used <strong>setex </strong>function instead of usual <strong>set </strong>function, because we can set an<strong><em> expiration time</em></strong> to the stored key-value pair. After we set a value for expiration time, <em>Redis </em>will automatically remove that key-value pair from the cache when the elapsed time expires.</p><p>Complete source code for above implementations as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f9d4ca261eb00ee324d18583940aac3/href">https://medium.com/media/6f9d4ca261eb00ee324d18583940aac3/href</a></iframe><p>Now, we have completed the mainly focused topics of this article. But I would like to give brief facts about the <strong>Redis<em> </em></strong>cache.</p><p>Redis cache have few operations which we can use to work easy with it as follow.</p><ul><li><strong><em>Check key exist</em></strong>: This method use to check if a key already exists and proceed accordingly. To do so, you can use <strong>exists</strong>() function.</li><li><strong><em>Delete key from any value</em></strong>: At times, you’ll need to clear some keys and reinitialize them. To clear the keys, you can use the <strong>del </strong>command.</li></ul><p>Also need to mention that <em>Redis </em>support different data types rather than using a strings such as <strong><em>hashes, lists </em>and <em>sets</em></strong>. You can use those types to store the data into R<em>edis </em>cache.</p><h4>Conclusion</h4><p>In this article, We have covered how to implement caching on a Node.js REST API using external API as our data source and <strong>Redis </strong>as our cache. Hope you will grab your knowledge through this.</p><p>Happy coding!</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e50356b06c1c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/guide-to-redis-caching-with-node-js-e50356b06c1c">Redis Caching with Node.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Task Scheduling with NodeJS]]></title>
            <link>https://dilinahirantha.medium.com/task-scheduling-with-node-js-20a3d46a86d6?source=rss-7afc02975a3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/20a3d46a86d6</guid>
            <category><![CDATA[scheduled-tasks]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Dilina Hirantha]]></dc:creator>
            <pubDate>Mon, 12 Jul 2021 17:52:09 GMT</pubDate>
            <atom:updated>2021-08-16T12:40:17.340Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to Create a Cron Job with NodeJS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*4uyZekxRkkZBOGdxvJhM2A.jpeg" /></figure><p>When building web applications and APIs using Node.js, we sometimes encounter tasks that need to be repeatedly done, such as email notifications, file downloads, database backups, etc. Depending on the task, this can be at a specific time every day, month, or even year.</p><p>First of all, we are going to schedule a job in Node.js using the <em>node-cron</em>. After that, we hope to compare the <strong><em>node-cron</em></strong> against <strong><em>node-scheduler, </em></strong>which is the most popular package currently.</p><h3>Introduction to Node-cron</h3><p><em>Node-cron</em> is an <a href="https://www.npmjs.com/package/package">npm package</a> written for <a href="https://nodejs.dev/">node</a> in pure JavaScript, and it is based on <a href="https://www.gnu.org/software/mcron/manual/html_node/Crontab-file.html">GNU crontab</a> syntax. Therefore our first step is based on the learning <em>node-cron</em> and <em>cron-syntaxes</em>.</p><h3><strong><em>Node-cron syntaxes</em></strong></h3><p>The actions of cron are driven by a <a href="https://www.gnu.org/software/mcron/manual/html_node/Crontab-file.html">crontab</a> (cron table) file, a configuration file that contains instructions to the cron daemon. Cron daemon is a system-manage executable that runs in the memory, which may use to schedule tasks. The following shows the crontab syntaxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*Zp9JiYwIdCYMb8yPZd96Iw.png" /></figure><h3>Using Node-cron in Practice</h3><p>Install <em>node-cron</em> using npm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f964a963d34045b7101b4c7a8b28606/href">https://medium.com/media/6f964a963d34045b7101b4c7a8b28606/href</a></iframe><p>The syntax for job scheduling:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d2b983427537aafa23d5215fc59a22e/href">https://medium.com/media/5d2b983427537aafa23d5215fc59a22e/href</a></iframe><p>Here, as options:</p><ul><li><strong>scheduled</strong>: Boolean is set for task scheduled or not. The default value is <em>true</em>.</li><li><strong>timezone</strong>: Time zone used for job scheduling. Default, use server’s define time zone.</li></ul><p>Following job scheduled to run at every 2nd minute of an hour.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bca145c3976150a0541211f253062dd/href">https://medium.com/media/5bca145c3976150a0541211f253062dd/href</a></iframe><p>In the above example, The asterisks (*) in positions, one, three, four, five, and six of the time specification are like file <strong><em>wildcards</em></strong>. That implies “<em>every second, every hour, every day, every month and day of the week” </em>individually.</p><p>Another example as below shows that cron job which runs in every day at 5.30 am,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86413802c335fec3501464e8968e01b6/href">https://medium.com/media/86413802c335fec3501464e8968e01b6/href</a></iframe><p>Next, let&#39;s move into some <strong><em>special cases</em></strong> such,</p><p>if we want to schedule a job that executes every first day of a quarter in a year, we can do it below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad6029613faf87cc495105d1f3c9c61e/href">https://medium.com/media/ad6029613faf87cc495105d1f3c9c61e/href</a></iframe><p>Here you can see, we have used a special character (/) other than usual asterisks. Just like that, few special characters have been introduced into the cron job scheduling, and we can represent them below.</p><ul><li><strong>Comma</strong>: Commas can use to separate the few values. For example, every 2 and 5 minutes, we can represent it as 2,5.</li><li><strong>Hyphen</strong>: Hyphen (-) use to provide the range of values such as Monday-Friday.</li><li><strong>Slash: </strong>Slash is used to providing step values such as for every 5 seconds, we can represent it as */5.</li></ul><p>Below is another example, which can schedule a job to execute every day from Monday to Friday (only weekdays) at 4.00 pm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9eb7e179b09b3595c5d29427ec6b7a53/href">https://medium.com/media/9eb7e179b09b3595c5d29427ec6b7a53/href</a></iframe><p>Another example shows that a job which executes every 15 minutes in between 5 am to 7 am.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4f4bfe512854ecd472f8a2721ff276c/href">https://medium.com/media/b4f4bfe512854ecd472f8a2721ff276c/href</a></iframe><h3>Methods use in NodeJS job scheduling.</h3><h4><strong>Starting a schedule</strong>:</h4><p>In the initialization, if you set the cron option as False, the scheduled job will not execute even the scheduled time reached. Therefore, if you need to start that job, you need to call the <strong><em>start</em></strong> method below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c4fedd7d26153668d4c46d6f6521bf6/href">https://medium.com/media/2c4fedd7d26153668d4c46d6f6521bf6/href</a></iframe><h4><strong>Stopping a schedule</strong>:</h4><p>If you need to stop any schedule which is executing, you should use the <strong><em>stop </em></strong>method. The schedule will not execute even if it is restarted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6d6ce488414abb37984dc446c85e3dc/href">https://medium.com/media/f6d6ce488414abb37984dc446c85e3dc/href</a></iframe><h4><strong>Destroying a schedule</strong>:</h4><p>You can use <strong><em>destroy </em></strong>method to destroy the schedule forever.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5ed706d16423f83bdf08efea6eb49d6/href">https://medium.com/media/c5ed706d16423f83bdf08efea6eb49d6/href</a></iframe><h4><strong>What is Node Schedule?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*bKCltWmKslwwlhYTvY2YPw.png" /></figure><p><strong><em>Node-schedule</em></strong> is the most popular flexible cron-like task scheduling library for Node.js. Both <em>node-schedule</em> and <em>node-cron</em> are functionality pretty similar.</p><p>The <em>node-schedule</em> is a time-based schedule, not an interval-based schedule, and it is designed for in-process scheduling. In-process scheduling means ‘<em>scheduled jobs will only fire as long as your script is running, and the schedule will disappear when execution completes</em>. If you need to schedule jobs that will persist even when your script <em>isn’t</em> running, consider using actual cron.</p><p>Also, <em>node-schedule</em> supports windows systems, unlike cron, which does not. Finally, you can use <a href="https://www.npmjs.com/package/node-schedule">npm</a> to get detailed knowledge about the <em>node-schedule</em> module.</p><h3>Conclusion</h3><p>This article covered most of the node-cron features you’ll need to schedule tedious tasks and a brief introduction to the node-schedule, which works much similar to the node-cron. I think this will help you implement your schedule at the right time, and it will free you up for more important and more fulfilling work.</p><h3>Learn More</h3><ul><li><a href="https://enlear.academy/nodejs-backpressuring-in-streams-52638f505e1b">NodeJS Backpressuring in Streams</a></li><li><a href="https://enlear.academy/all-about-high-order-component-and-render-props-patterns-60bc2492548b">React Higher-Order Components and Render Props Patterns</a></li><li><a href="https://enlear.academy/http-vs-https-93c87cf51a20">HTTP vs HTTPS—Why HTTP Is Not Safe?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20a3d46a86d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Custom Form Controls With Control Value Accessor]]></title>
            <link>https://javascript.plainenglish.io/angular-custom-form-controls-with-control-value-accessor-90869cdf100c?source=rss-7afc02975a3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/90869cdf100c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Dilina Hirantha]]></dc:creator>
            <pubDate>Sat, 03 Jul 2021 21:08:03 GMT</pubDate>
            <atom:updated>2021-08-09T05:00:38.585Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*5ScQi1M4Hj66xbiMgA-L6w.jpeg" /></figure><blockquote>In the development of complex Angular applications, developers tend to build large components that encompass the entire form and can make it challenging to re-use in efficient manner. In that situation the concept reusable/custom components come to forward. Custom form controls are a typical pattern in complex Angular applications. It’s common to want to encapsulate HTML, CSS, and accessibility in an input component to make it easier to use in forms throughout the application.</blockquote><p>In this article, we are going to explore the usage of the Angular custom components with reactive forms. For that purpose, we are going to observe the inbuilt Angular directive “<strong><em>control value accessor</em></strong>”.</p><p><strong><em>Control Value Accessor Directives</em></strong></p><p><em>Control Value Accessor is an inbuilt directive in Angular which will be responsible for tracking the value of the child field, and communicate it back to the parent form.</em></p><p>In the below example, we are going to build a custom numeric value counter which contains two buttons to increment or decrement the value. Also, we provide min and max value ranges for this counter where it’s valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*9laRzc1lvtOS77okkUie-g.gif" /></figure><p>First of all, we create a new Angular custom component named “custom counter” which acts as the parent component for this practice. Here is the implemented custom component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ecc3ddb6beae769e9f507beb512f1ec/href">https://medium.com/media/5ecc3ddb6beae769e9f507beb512f1ec/href</a></iframe><p>In the above snippet, you can see we have implemented <strong><em>onAdd</em> </strong>and <strong><em>onRemove</em> </strong>methods to increment and decrement the counter value. Also, the template of the custom counter component is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/029e87fd0e705cf0a7b65720d4fea426/href">https://medium.com/media/029e87fd0e705cf0a7b65720d4fea426/href</a></iframe><p>The next step is to implement the child component which utilizes the custom counter component. We named the child component as quantity form and added built-in validators to add the min and max range values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8aca7220215f09767aa67c7ddbbf546/href">https://medium.com/media/a8aca7220215f09767aa67c7ddbbf546/href</a></iframe><p>The template of the quantity form component as below,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d283cdedba95374e08012bc638f69b9/href">https://medium.com/media/9d283cdedba95374e08012bc638f69b9/href</a></iframe><p><strong><em>Understanding Control Value Accessor</em> I<em>nterface</em></strong></p><p>Still, we haven’t utilized the actual usage of the<strong> </strong><em>Control Value Accessor</em> <em>interface</em>. Therefore, the next step is to understand the applicability of the Control Value Accessor interface.</p><p>Control Value Accessor interface provides few methods and all those methods are meant to be called only by the Forms module at runtime, and they are meant to facilitate communication between our form control and the parent form.</p><ul><li><strong><em>writeValue</em></strong>: Forms module writes a value into a form control using this method.</li><li><strong><em>registerOnChange</em></strong>: If a form value changes due to user input, we need to report the value back to the parent form. This is done by calling a callback, that was initially registered with the control using the registerOnChange method.</li><li><strong><em>registerOnTouched</em></strong>: When the user first interacts with the form control, the control is considered to have the status touched, which is useful for styling. In order to report to the parent form that the control was touched, we need to use a callback registered using the registerOnToched method.</li><li><strong><em>setDisabledState</em></strong>: form controls can be enabled and disabled using the Forms API. This state can be transmitted to the form control via the setDisabledState method.</li></ul><p>As the next step, let’s discuss these methods one by one with their applicability.</p><p><strong><em>Implementation of writeValue</em></strong></p><p>This method is used in the Angular forms module whenever the parent component needs to set the value to the child control. We can do it as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/538e15c0f61866777fc5e01e630bd1c6/href">https://medium.com/media/538e15c0f61866777fc5e01e630bd1c6/href</a></iframe><p><strong><em>Implementation of registerOnChange</em></strong></p><p>Using the <strong><em>writeValue </em></strong>method, the parent component can set the value to the child control. But the critical situation is, when the counter value change by incrementing or decrementing, parent component need to aware of it to grab the changing values.</p><p>There, the child component can notify the parent about that new value using a <em>callback </em>function. For this purpose, the parent component needs to register the <em>callback </em>function using the <strong><em>registerOnChange</em></strong><em> method </em>as below<em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df04adac4bd55d61b64ff96af8db8b3f/href">https://medium.com/media/df04adac4bd55d61b64ff96af8db8b3f/href</a></iframe><p>When the <strong><em>registerOnChange </em></strong>method is called, the changed value will save into a <strong>onChange </strong>variable. In this implementation, we have declared the <strong>onChange </strong>variable as a function and initially, it has an empty body. This way, if the program for some reason calls the function before the <strong><em>registerOnChange </em></strong>call was made, it won&#39;t run into any errors.</p><p>When we increment or decrement the counter value, then we can notify the parent component by calling the <em>callback </em>function as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adf135774264468842356605fedba942/href">https://medium.com/media/adf135774264468842356605fedba942/href</a></iframe><p><strong><em>Implementation of registerOnTouched</em></strong></p><p>When the form is initialized, form controls are considered to be in the untouched status and the ng-untouched CSS class is applied to the form group and also to each of its individual child controls.</p><p>In the previous topics, we set and grab the value changes to the parent component. Also, we need to notify the form control has been touched by the user to the parent component. Therefore, we use the <strong><em>registerOnTouched </em></strong>method.</p><p>If the user does interact with the form control, then that implies the ng-untouched CSS class is going to be applied to the form control.</p><p>First of all, we need to register the callback function as the previous function as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fe05a61b3ab5406900b1dce15d4fa28/href">https://medium.com/media/0fe05a61b3ab5406900b1dce15d4fa28/href</a></iframe><p>Next, we need to call this callback in situations when counter value is incremented or decremented by the user. There, the status of the form control will be changed as the touched.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d92cde6849da9decc7966f8dff2a0389/href">https://medium.com/media/d92cde6849da9decc7966f8dff2a0389/href</a></iframe><p><strong><em>Implementation of setDisabledState</em></strong></p><p>We can use <strong><em>setDisabledState </em></strong>method to disable or enable the child form control. There we initialize a disable variable as false and change the value of it by calling the <strong><em>setDisabledState</em></strong><em> </em>method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4e81326d990c0c72bf214eaf8d69309/href">https://medium.com/media/a4e81326d990c0c72bf214eaf8d69309/href</a></iframe><p><strong><em>Configure ControlValueAccessor Interface</em></strong></p><p>This is the main step of this implementation, which is to register the custom counter component as a known value accessor in the dependency injection system using the <strong><em>ControlValueAccessor Interface</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d49537cb6ed14addecc5da4972b9b107/href">https://medium.com/media/d49537cb6ed14addecc5da4972b9b107/href</a></iframe><p>As the configurations, we provide <em>NG_VALUE_ACCESSOR </em>to register this component by adding to the list of known value accessors. Notice the multi flag set to true, this means that this dependency provides a list of values, and not only one value. Now our custom component is now capable of setting the value of a property in a form. Also our the component is now capable of participating in the form validation process with the in-built required and min, max validators.</p><p><strong><em>Furthermore, what if we need to set custom validation for the control?</em></strong></p><p>If the component needs to have its own built-in validation rules, there we need to implement custom counter class using the <strong><em>Validator interface</em></strong>. This interface contains two methods,</p><ul><li><strong>validate : </strong>This method is used to validate the current value of the form control. This method will be called whenever a new value is reported to the parent form. This method returns null if no errors are found.</li><li><strong>registerOnValidatorChange: </strong>This will register a callback that will allow us to trigger the validation of the custom control <strong>on demand</strong>. There we don’t need to trigger this method whenever new value input to the control but it is required if the form will decide to recall validations ( something changed outside, form initialized, etc.)</li></ul><p>For the explanation, let&#39;s think that we have removed the in-built min validator form the control and instead of we implement a custom validator to check the counter value is lower than zero. We can do it as below,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1eaa87d55aadad227918b2561bda197f/href">https://medium.com/media/1eaa87d55aadad227918b2561bda197f/href</a></iframe><p>In this code snippet, we have return the null if the counter value is valid, otherwise we return error object. For this purpose we don’t need <strong><em>registerOnValidatorChange </em></strong>method since we use only the current value of the control.</p><p>For completion of this implementation, we need to register our component as the <em>NG_VALIDATORS </em>injection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e43488438004d361f607a8c65145f77/href">https://medium.com/media/1e43488438004d361f607a8c65145f77/href</a></iframe><p>Now we have built fully functional custom control capable of both setting the value of a form property and participating in the form validation process. Finalized code as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b451cfc736414f0bce471abe95580ba/href">https://medium.com/media/5b451cfc736414f0bce471abe95580ba/href</a></iframe><h3>Summary</h3><ol><li>We have implemented a custom component with the <strong><em>Control Value Accessor</em> interface.</strong></li><li><em>Control Value Accessor</em> interface includes three methods as <strong><em>writeValue</em>, <em>registerOnChange</em>, <em>registerOnTouched</em> </strong>and <strong><em>setDisabledState</em>.</strong></li><li>Among these methods, <strong><em>writeValue </em></strong>method is used to set the value to the child control by the parent component. <strong><em>registerOnChange </em></strong>method is used to communicate between parent and child component when the input value changes. <strong><em>registerOnTouched </em></strong>method is used to notify the parent component whenever child form control is considered to be touched.</li><li>Then we implemented custom validation by using the <strong><em>Validator interface.</em></strong></li></ol><p>Thank you for reading! Hope you will use this article to cut out your doubts about Angular custom components.</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90869cdf100c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/angular-custom-form-controls-with-control-value-accessor-90869cdf100c">Angular Custom Form Controls With Control Value Accessor</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Analysis Using ARIMA Model With Python]]></title>
            <link>https://medium.com/geekculture/time-series-analysis-using-arima-model-with-python-afe4b41bbec8?source=rss-7afc02975a3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/afe4b41bbec8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[arima]]></category>
            <dc:creator><![CDATA[Dilina Hirantha]]></dc:creator>
            <pubDate>Sat, 05 Jun 2021 13:10:11 GMT</pubDate>
            <atom:updated>2021-06-12T07:08:44.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4acgmnLzaBfQukMWIN2BNQ.jpeg" /></figure><blockquote><strong><em>Time series</em></strong> is a sequence of time-based data points collected at specific intervals of a given phenomenon that undergoes changes over time. In other words, time series is a sequence taken at consecutive equally spaced points in the time period.</blockquote><p>As a example, we can present few time series data sets in different domains such as pollution levels, Birth rates, heart rate monitoring, global temperatures and Consumer Price Index etc. At the processing level, above datasets are tracked, monitored, down sampled, and aggregated over <strong>time.</strong></p><p>There are different kind of time series analysis techniques in the big data analytical field. Among them few are,</p><ul><li>Autoregression (AR)</li><li>Moving Average (MA)</li><li>Autoregressive Moving Average (ARMA)</li><li>Autoregressive Integrated Moving Average (ARIMA)</li><li>Seasonal Autoregressive Integrated Moving-Average (SARIMA)</li></ul><blockquote><strong>ARIMA Model</strong></blockquote><p>ARIMA Model is simple and flexible enough to capture relationship we would see in the data and It aims to explain the autocorrelation between the data points using past data. We can decompose the ARIMA model as follow to grab the key elements of it.</p><ul><li><strong>AR: <em>Auto regression. </em></strong>This is a model that uses the dependent relationship between the data and the lagged data.</li><li><strong>I:<em> Integrated. </em></strong>The use of differencing of raw observations (e.g. subtracting an observation from an observation at the previous time step) in order to make the time series stationary.</li><li><strong>MA: <em>Moving average. </em></strong>A model that uses the relationship between the observations and the residual error from the moving average model applied to lagged observations.</li></ul><blockquote><strong>Dataset Explanation</strong></blockquote><p>For this practice, the dataset have been downloaded form the <a href="https://www.kaggle.com/sudalairajkumar/daily-temperature-of-major-cities">https://www.kaggle.com/sudalairajkumar/daily-temperature-of-major-cities</a>. In this dataset, it includes daily average temperature values collected as Fahrenheit over different regions, countries, cities over the years from about 1995 to 2020.</p><p>For the preprocessing and further analytics of the dataset I have used <em>pandas. </em>Using <em>pandas, </em>we can explore, clean and process dataset by creating a pandas DataFrame.</p><p>In the preprocessing of the DataFrame we are done with few steps such as,</p><ul><li>I have added new column as <strong>Date</strong> by combining the Year, Month and Day columns. Then dropped the Year, Month, Day, City and Region columns individually from the dataset.</li><li>Remove duplicate and null value rows from the data frame.</li></ul><p>In this article I’m not focused to demonstrate the data preprocessing. Therefor let’s move into discussed a important fact of this observation.</p><p>In this preprocessed data frame, it has temperature values over long period for each country. So far it is so good! But, using the past temperature as far as old might not be a good indicator for today’s weather data, as there have been factors which impact to global temperature have been changing time to time.</p><p>Thus, it is <strong>better to analysis under recent influential factors</strong>, we would take only a subset of data from 2016 to 2020 for time series analysis. Also I have filtered the data frame for a specific country for the ease the analysis. Here, I have used country “Sri Lanka”.</p><blockquote><strong>Exploratory Analysis</strong></blockquote><p>First of all, you need to set the Date as the index for the data frame.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a000f16c6d0be04168711f03191d7246/href">https://medium.com/media/a000f16c6d0be04168711f03191d7246/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*CDR-OwprYrB1Ggpeky_f_g.png" /><figcaption>sample head records of data frame</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*XitQRdaCRCPao7M8qsA1gQ.png" /><figcaption>sample tail records of data frame</figcaption></figure><blockquote><strong>Data Visualization</strong></blockquote><p>Next step is to visualize the data frame as a time - series plot. The plot below shows how the temperature spread through period of 2016 to 2020 of Sri Lanka. For the plotting I have imported matplotlib.pylot.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5510aa46dcb3d4dca7c56c688a78ce66/href">https://medium.com/media/5510aa46dcb3d4dca7c56c688a78ce66/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Ijvw7FTVQXZJGKf-IgY5Q.png" /></figure><p>As you can see it is bit noisy to read the plot, because dataset contains daily temperature and plot visualize every day all over. Therefor we need to smooth the plot using proper technique.</p><p><strong>How we can smooth the graph?</strong></p><p>In the data science, smoothing techniques can be used to reduce or cancel the effect of these variations and noises. When properly applied, these techniques smooth out the fine-grained variation between time steps to improve the visualize and identifying of underlying trends. As example,</p><ul><li>Exponential Smoothing</li><li>Moving Average Smoothing</li></ul><p><em>Moving Average Smoothing </em>is a popular smoothing method frequently used in the time series analysis which is easy to apply and less prone to a lot of false signals.</p><p>Pandas has prebuilt method to easier the application of the Moving Average Smoothing as rolling(). Throughout this method you can provide specific time period as a window size. As a example window size 30 means, we use 30 days as a one window. Using this technique, we can get the mean of the dataset per window size in the period.</p><p>You can choose your window size according to your attenuation needs. In this example I used window size as 30.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20862ad888eb1794e39925a4a5b1db91/href">https://medium.com/media/20862ad888eb1794e39925a4a5b1db91/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a7GNETZhbszP0JbZecxilA.png" /></figure><p><strong><em>Time Series Decomposition</em></strong></p><p>Time series data can exhibit a variety of patterns, and it is often helpful to split a time series into several components, each representing an underlying pattern category.</p><p>If we consider above plots, there we can slightly see the common pattern in the daily average temperature in the each year. At the beginning and the end of the each year it seems like cold. But when it’s reaching to the middle of the year, temperature is getting increase gradually.</p><p>Time series decomposition have different components,</p><ul><li><strong><em>Seasonality </em></strong>: Repeated patterns occurs over a fixed and known period in the dataset.</li><li><strong><em>Trend</em></strong> : includes persistent increasing or decreasing direction in the data.</li><li><strong><em>Residual </em></strong>: terms after the seasonal and trend components of a time series have been estimated and removed. Data which are form short term fluctuations in the series which are neither systematic nor predictable.</li></ul><p>Here I have done additive decomposition the above three patterns.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c77c123b3bcce4aaf7ea39e1867176ca/href">https://medium.com/media/c77c123b3bcce4aaf7ea39e1867176ca/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oudiJSaUnX6tCRhhT98jVg.png" /></figure><blockquote><strong><em>Forecasting With SARIMA Model</em></strong></blockquote><p>The problem with plain ARIMA model is it does not support seasonality.</p><p>In this daily average dataset we could see seasonality pattern, therefore, we proceed with SARIMA model which uses seasonal differencing. Seasonal differencing is just similar to regular differencing, but, instead of subtracting successive terms, we subtract the value from previous season.</p><p>ARIMA model includes three main parameters as p, d and q.</p><ul><li><strong><em>p</em></strong>: The order of the autoregressive model.</li><li><strong><em>q</em></strong>: The order of the moving average model.</li><li><strong><em>d</em></strong>: The number of differences required to make the time series stationary.</li></ul><p>The <strong>SARIMA model builds upon the ARIMA</strong> model. It also includes the <em>p</em>, <em>q</em>, and <em>d</em> parameters, but also an extra set of parameters to account for time series seasonality.</p><p><strong><em>P</em></strong>: The order of the seasonal autoregressive model.</p><p><strong><em>Q</em></strong>: The order of the seasonal moving average model.</p><p><strong><em>D</em></strong>: The number of seasonal differences applied to the time series.</p><p>Therefor we can denote the notation of the SARIMA model as SARIMA(p,d,q)(P,D,Q,s). Here s denotes the seasonality of the year.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d2b13fc5d0a16c9ada6084fd6b66126/href">https://medium.com/media/0d2b13fc5d0a16c9ada6084fd6b66126/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*J6VcrfYcCc3RVBZK3SflWw.png" /></figure><p><strong><em>How we select suitable parameter combination to fit to SARIMA model ?</em></strong></p><p>Selecting the best ARIMA model configuration is usually an iterative process. For that, we can use a “grid search” to iteratively explore different combinations of parameters.</p><p>For each combination of parameters, we fit a new seasonal SARIMA model with the SARIMAX() function from the statsmodels module and calculate the AIC (Akaike information criterion). AIC is used to measure the relative quality of the statsmodels.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cf3a0af1a065ee547a6781021b169ec/href">https://medium.com/media/1cf3a0af1a065ee547a6781021b169ec/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*_WcglCe7RcgCl08yf9HR5Q.png" /><figcaption>sample of different combination of parameters with AIC values</figcaption></figure><p>considering the different combinations and their AIC values, we can choose a combination which have minimum value of AIC. By considering the all the values in this combinations, I could get the <em>minimum AIC (5281.62)</em> combination as <em>SARIMA(1, 1, 1)*(1, 1, 1, 12)12 </em>. The reason to select lower combination AIC because it will be the <strong>better</strong>-fit to the model.</p><p><strong><em>Fit the choose combination to SARIMA model</em></strong></p><p>Now we have figured out the combination. Then we can compose it to the SARIMA model as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3e2dbbf1e12a1421dca5ccf0ab19c15/href">https://medium.com/media/f3e2dbbf1e12a1421dca5ccf0ab19c15/href</a></iframe><blockquote><strong>Validating The SARIMA Model With Forecasting</strong></blockquote><p>We can forecast using to ways.</p><ul><li><strong><em>Non- Dynamic Forecasting (Static)</em></strong> : This method produce one-step-ahead forecasts, meaning that forecasts at each point are generated using the full history up to that point.</li></ul><p>In this example we mainly focused on the static forecasting where it will more suitable practice than dynamic forecasting for this daily average temperature example.</p><p>By this method We compare predicted values to actual values of the time series where we can assure the accuracy of out model. Below code snippet shows that we predict the daily average temperature as providing start date as 2018–05–01.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8109872d4a1364ae9b01906acbf717c8/href">https://medium.com/media/8109872d4a1364ae9b01906acbf717c8/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a7afb619db6f63ffcce847747d748e3/href">https://medium.com/media/2a7afb619db6f63ffcce847747d748e3/href</a></iframe><p>In above code snippet, we determined training time series period as 2016 to 2018. Therefore we forecast the temperature from starting 2018 to end of the 2020 period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdzg-ilG0H2GERj86oo_wA.png" /></figure><p>As visualized, at the first glance we can see forecasted daily average temperature behave along with the actual daily average temperature. We can quantify the accuracy of our forecast by evaluating the <strong>RMSE (Mean Squared Error)</strong>, in which for each predicted value, we compute its distance to the true value and square the result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf564bdf0719b50e2767f9e15a744343/href">https://medium.com/media/cf564bdf0719b50e2767f9e15a744343/href</a></iframe><p>Result : <strong>The RMSE error of forecast prediction is 1.32 </strong>for this SARIMA model which is very low means we have acquired high accuracy from this model. In the ideal scenario MSE should zero. but typically it is impossible.</p><ul><li><strong><em>Dynamic Forecasting</em></strong><em> :</em></li></ul><p>By the dynamic forecasting we only use information from the time series up to a certain point, and after that, forecasts are generated using values from previous forecasted time points.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e681a7fcbb0a783345269f7e2d17f129/href">https://medium.com/media/e681a7fcbb0a783345269f7e2d17f129/href</a></iframe><p>For the dynamic forecasting we also calculate the RMSE value as below,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f09abde22668fe9fc4d9fd8f20d38c3f/href">https://medium.com/media/f09abde22668fe9fc4d9fd8f20d38c3f/href</a></iframe><p>Result : <strong>The RMSE error of dynamic forecast prediction is 20.45 </strong>This is significantly higher than the one-step ahead. By considering the above prediction accuracy values, we can conclude that,</p><p><strong><em>STATIC forecast allow results of previous forecast to be done singly as a predictor of future inflation outcomes and this is very well tracked as the margin of error is quite small when compared to DYNAMIC forecast outcomes.</em></strong></p><blockquote><strong>By the way we have reached to end of this article on “ <em>Time Series Analysis Using ARIMA Model With Pandas</em>” eventually. Hope you will grab knowledge on the discussed topic whatever previous knowledge you have.</strong></blockquote><blockquote><strong>provide me a clap for motivation if you got this article. 👏</strong></blockquote><blockquote><strong>I’m winding this journey till we meet with another interesting topic.😊 🎉</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afe4b41bbec8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/time-series-analysis-using-arima-model-with-python-afe4b41bbec8">Time Series Analysis Using ARIMA Model With Python</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Reactive Forms With Validations And Custom Validations]]></title>
            <link>https://javascript.plainenglish.io/angular-reactive-forms-create-simple-form-with-validations-1dfff3d84fa6?source=rss-7afc02975a3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dfff3d84fa6</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Dilina Hirantha]]></dc:creator>
            <pubDate>Thu, 03 Jun 2021 08:31:49 GMT</pubDate>
            <atom:updated>2021-07-26T13:15:03.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MlQD4TC6Oyw2cXS3O7cnWg.png" /></figure><blockquote>A large category of frontend applications are very form-intensive, especially in the case of enterprise development. Many of these applications are basically just complex forms, having multiple tabs and dialogs and with different validation logics.</blockquote><p><strong><em>Angular</em></strong> presents a couple of alternative ways to create forms. <strong><em>Reactive forms</em></strong> (also known as Model-driven forms) and<strong> <em>template-driven forms</em></strong> are the frequently used methods to build Angular forms. Reactive forms are far better than template-driven forms where they are more powerful and provide easy testing because all the logic is composed into the component class.</p><p>In reactive forms, most of the heavy lifting for creating a form happens in the component class rather than the template.</p><h4><strong>First of all, we need to set up the module</strong></h4><p>In this step, we need to import <strong><em>ReactiveFormsModule </em></strong>from the <strong><em>@angular/forms </em></strong>to the the application module. To do this, I will be writing inside the <strong><em>AppComponent </em></strong>for simplicity. The below code snippet shows how to do it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ff77f2449ca088c91ce4832f2f05f86/href">https://medium.com/media/5ff77f2449ca088c91ce4832f2f05f86/href</a></iframe><h4>Next, we are going to <strong>create a reactive form</strong></h4><p>When creating a reactive form, we have to deal with two important concepts named <strong><em>form group</em></strong> and <strong><em>form controls</em></strong><em>. </em>Form controls<em> </em>are classes which can handle both data values and the validations status of any form element. <em>Form groups</em> wrap a collection of form controls. A form control could represent something like a user’s first name, last name, email or password, etc.</p><p>There are <strong>two ways</strong> to initiate a form group in the Angular reactive forms.</p><ul><li>For the<strong> first way</strong>, we start initiating a form group by passing a collection of child controls as a first argument. The <strong><em>key </em></strong>for that child control registers the name for the control and each control should be of object type of FormControl. The below snippet shows the implementation.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ff77f2449ca088c91ce4832f2f05f86/href">https://medium.com/media/5ff77f2449ca088c91ce4832f2f05f86/href</a></iframe><ul><li>The <strong>second way </strong>is useful when the form becomes more complex. In this, we inject the FormBuilder class and invoke the group method.</li></ul><p>As parameters to the group method, we pass <strong><em>keys</em></strong> to define control’s name and values as an empty array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db8aba1cdc0dace584c0fce151dbe034/href">https://medium.com/media/db8aba1cdc0dace584c0fce151dbe034/href</a></iframe><p>In special scenarios, we are required to provide default values to the form controls. As an example, if we want the default email as user@gmail.com, we can do it as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7851d19b6ba59b5f4adaadfa172d4112/href">https://medium.com/media/7851d19b6ba59b5f4adaadfa172d4112/href</a></iframe><h4>Next, let’s look at the <strong>usefulness of the <em>setValue </em>and <em>patchValue</em></strong><em> </em>methods</h4><p>In some situations, we need to set or patch default values into the form controls for a situation where the user is going to edit the details in the edit form.</p><p>For this purpose, we use setValue and patchValue methods. The difference between them is that when we use setValue(), we have to set all form controls in our FormGroup and when we use patchValue() then selected form control can be set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*ZU3yt6DAO_h6TkNlFElcuQ.png" /><figcaption>patchValue method</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*bIxm1nwGOTScWWtOIaHJTQ.png" /><figcaption>setValue method</figcaption></figure><p>So far, we are done with the basic steps for the component class. Next, we are moving on to the steps in the template.</p><p>In the template, you need to wrap the input fields which represent the form controls using a &lt;form&gt;. Thereafter add the FormGroup directive to the form tag and pass the instantiated form group in the component class.</p><p>After above steps, add FormControlName directive to input fields and pass the name of the form controls as strings which were used in the component class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*-eoIhJhcaO626R0ArTb1Ag.png" /></figure><p>Now we have covered all the basic implementations of the form without finalizing the submission.</p><h4>Let’s move on to form submission</h4><p>As our next step, we will add submit button which has a type as submit. Also, we need to add NgSubmit handler in the form tag.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b1b31b4cf8bb126e550347948d493e3/href">https://medium.com/media/2b1b31b4cf8bb126e550347948d493e3/href</a></iframe><p>When we consider the form submission, there are two possible ways we can spot it:</p><ul><li><strong><em>submit</em></strong>: It is an HTML default form submit an event, it will call an underlying method when the form gets submitted.</li><li><strong><em>ngSubmit</em></strong><em>: </em>This will prevent the form from being submitted if the handler code throws and causes an actual HTTP post request.</li></ul><h4>Validating form controls</h4><p>Processing input field values before validating can have serious consequences. You may end up storing invalid data like an invalid email, age, date, etc. In this situation, Angular has provided few in-built validators:</p><ul><li><strong>required</strong>- Validates that a form control must has a value and marks it as required.</li><li><strong>email</strong> - Validates that a form control has a valid e-mail address.</li><li><strong>minLength</strong> - Validates that the length of the text in a form control is greater than or equal to the value.</li><li><strong>maxLength </strong>- Validates that the length of the text in a form control is less than or equal to the value.</li><li><strong>Max</strong> - Validates that a number in a form control is less than or equal to the value.</li><li><strong>Min </strong>- Validates that a number in a form control is larger than the min or equal to the value.</li><li><strong>Pattern </strong>- Validates that text in a form control matches a specific regular expression.</li><li><strong>email</strong>- Validates the correctness and completeness of user-provided email addresses.</li></ul><p>Now let’s see how we can add validator to form control.</p><p>We need to import the Validators class from @angular/forms into the component class. As an example, here we are going to make the email and password fields as required and email control should have a valid email. We can do it by adding Validators.required to both controls’ array and only adding Validators.email to the email control’s array as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/656199db69be8f3a1c7a0c4d715cdcf9/href">https://medium.com/media/656199db69be8f3a1c7a0c4d715cdcf9/href</a></iframe><p>As shown in the above example, you can have multiple validators for one control.</p><p>The interesting part of the validation is that we can compose <strong><em>custom validators</em></strong> into our controls.</p><p>Let’s say that you want to set the default password for login as “admin123” and need to validate it against the user input. If the input password differs from the default password, the password field should be invalid. For this purpose, you have to write your own function and pass an object type of AbstractControl.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff729706a2fe9d85db99d8f4295994cf/href">https://medium.com/media/ff729706a2fe9d85db99d8f4295994cf/href</a></iframe><p>Then add the ValidatorPassword function to the password control’s array next to the required validator as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d33e3223cdca6bccd24cb14306a6f3f8/href">https://medium.com/media/d33e3223cdca6bccd24cb14306a6f3f8/href</a></iframe><p>Next, we look at how we can apply this custom validator to the template.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55642220a7eb9e46e8ccf8f635c67430/href">https://medium.com/media/55642220a7eb9e46e8ccf8f635c67430/href</a></iframe><p>Here I have used <strong><em>invalid-feedback</em> </strong>class in <strong><em>bootstrap</em></strong> to display validation error messages for the input fields<em>.</em> Alternatively, you can use the hasError method and there you need to pass the name of the error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44fe61165d1a43111d65f5f3c074c78f/href">https://medium.com/media/44fe61165d1a43111d65f5f3c074c78f/href</a></iframe><h4>Next, we advance to grab the knowledge about Form States</h4><p>Angular forms and their controls can have different states such as:</p><p>- <strong><em>Pristine</em></strong>: The user has not changed the values of the form control.</p><p>- <strong><em>Dirty</em></strong>: Opposite of pristine.</p><p>- <strong><em>Touched</em></strong>: The user has visited the form control and exited it.</p><p>- <strong><em>Untouched</em></strong>: Opposite of touched.</p><p>These states help you enhance the way your forms behave. The below example shows how we can apply the above states with a control.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c87aacc1211234ae5978fae59672691/href">https://medium.com/media/0c87aacc1211234ae5978fae59672691/href</a></iframe><p>Furthermore, we will discuss with detailed explanations how form states work in a separate article in the near future.</p><p>Here we have come to the destination of this article. I hope you enjoyed this article and made the most of it to improve your knowledge about <strong>Angular Reactive Forms</strong>.</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dfff3d84fa6" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/angular-reactive-forms-create-simple-form-with-validations-1dfff3d84fa6">Angular Reactive Forms With Validations And Custom Validations</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>