teleren/devto huggingface dataset:
How to test current time with jest and react-testing-library
Tags: jest, reacttestinglibrary, react, testing
Published: 2022-02-05 19:34:40

You have a frontend app that shows current time. I mean - you built a clock. Pretty simple, working fine. But how to test it properly?

If you new to testing, you may not see the problem. What's the issue, right? You check what time is it in the system, then you check in test if UI shows the same thing. Not really...

This approach won't work cause time may be different when you check it is the system and then (after a while) check it in your test. Your goal needs to be different - you need to control system time in tests and check things based on that.

Let's assume we have really simple React component, the only thing it does is showing hours and minutes (we don't care if this shows '02' when it 2 o'clock, let's make if super simple). The component looks like this: 


```jsx
import React from 'react';
import styled from 'styled-components';

const Wrapper = styled.div`
    text-align: center;
`;

const Time = () => {
    const today = new Date();

    return (
        <Wrapper>
            <h2>Current time is: {today.getHours()}:{today.getMinutes()}</h2>
        </Wrapper>
    );
}

export default Time;
```

Now, let's write a unit test for it. We will be using [jest](https://jestjs.io/) and [React Testing Library](https://testing-library.com/docs/react-testing-library/intro/). If we want to test anything related to time, we shouldn't use real time methods (no `setTimeout` and things like this) cause they rely on real time. We need fake time here. So first we want to tell `jest` to do that before our test start executing. We can achieve it by using `jest.useFakeTimers()` . Having that we can set system time we want. And now test the UI! Just don't forget to go back to real timers after all tests that needed fake ones.

This is how the test may look like:


```jsx
import { render, screen } from '@testing-library/react';
import Time from './Time';

describe('Time component', () => {
    beforeAll(() => {
        jest.useFakeTimers();
        jest.setSystemTime(new Date('20 Aug 2020 02:12:00 GMT').getTime())
      });

      afterAll(() => {
        jest.useRealTimers();
      });

    test('renders current time', () => {
        render(<Time />);

        expect(screen.getByText(/current time is/i)).toBeInTheDocument();
        expect(screen.getByText(/2/i)).toBeInTheDocument();
        expect(screen.getByText(/12/i)).toBeInTheDocument();
    })
});
```

I hope you got the idea :) Happy coding and testing!
🌟 Converting Roman Numerals to Integer n vice-versa
Tags: typescript, javascript, tutorial
Published: 2022-02-05 19:23:01


These problems appeared in leecode and featured in various blogs, i have just summarised and included them using [ts-problems](https://devpost.hashnode.dev/solving-with-typescript) deck.


### :bookmark: Roman Numerals to Integer conversion

Numbers generally increase in a roman numeral notation from right to left, any subtractive number must also be smaller than our current `res`.

So we can avoid the need for an extra variable here. We do run into the case of repeated numerals causing an issue `III`, but we can clear that by multiplying `num` by any number between 2 and 4 before comparing it to `res`, since the numerals jump in value by 5x.

Once we know how to properly identify a subtractive numeral, it's a simple matter to just iterate in reverse through given numeral to find and return the `res`.

```typescript
function romanToInt(s: string): number {
  let res: number = 0;
  const symbols = {
    I: 1,
    V: 5,
    X: 10,
    L: 50,
    C: 100,
    D: 500,
    M: 1000,
  };
  s.split("")
    .reverse()
    .forEach((char) => {
      let val: number = parseInt(symbols[char]);
      if (res > 4 * val) {
        res -= val;
      } else {
        res += val;
      }
    });
  return res;
}
```

###  :bookmark: Integer to Roman Numerals conversion 

This solution uses a lookup table composed which can help in easier conversion and much simple compared to the above one.

```typescript
function intToRoman(num: number): string {
  let res:string = "";
  const value:number [] = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
  const numerals:string [] = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
  for (let i = 0; num; i++)
    while (num >= value[i]){
        res += numerals[i];
         num -= value[i];
    }
  return res;
}
```

Here I have tried to solve them in typescript using [ts-problems](https://devpost.hashnode.dev/solving-with-typescript) repo.


:repeat: original post at :link: [Dev Post](https://devpost.hashnode.dev/converting-roman-numerals-to-integer-n-vice-versa)


Thanks for supporting! 🙏

Would be really great if you like to [:coffee: Buy Me a Coffee](https://www.buymeacoffee.com/AravindVCyber), to help boost my efforts.

<a href="https://www.buymeacoffee.com/AravindVCyber"><img src="https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=AravindVCyber&button_colour=BD5FFF&font_colour=ffffff&font_family=Cookie&outline_colour=000000&coffee_colour=FFDD00" /></a>
What is Front-End Development and why React?
Tags: javascript, react, java, webdev
Published: 2022-02-05 19:14:30

**Front-end development** refers to what the end-user (also commonly referred to as the "**client**") can see. In the most basic forms, front-end development consists of HTML, CSS, JavaScript.

As a developer, you will find that it is very easy for your front-end (website, web application, etc.) to become very complex and have a lot of different moving parts.
It makes solving problems much more difficult when you have to go through a maze of code to find the issue.

Eventually, developers decided that there must be a better way to manage all of that code, so they created libraries that could make life easier. **React** was one of those libraries.

## **Why React?**

**React** is one of the most popular JavaScript libraries for front-end web applications.

Here are some of the advantages of React:

**Speed**
Interactive websites need to update the <u>DOM</u> (Document Object Model) each time a change happens. This process is generally resourceful and slow.
Compared to other libraries that manipulate the <u>DOM</u>, React uses a **Virtual <u>DOM</u>**, allowing to update only the parts of the website that have changed. This increases the speed of updates dramatically, as modern web applications may contain thousands of elements.

**Ease of Use**
React allows developers to group related code, thereby making building and maintaining large-scale applications much less complex.

**Support**
React has an amazing large community and is open source. it is maintained by Facebook and the community.

**Declarative**
React allows you to control flow and state in your application by saying "It should look like this". An imperative style turns that around and allows you to control your application by saying "This is what you should do".

The benefit of declarative is that you don't get bogged down in the implementation details of representing the state. you're delegating the organizational component of keeping your application views consistent so you just have to worry about the state.
Dev mindset - how to really own the process?
Tags: career, devmindset, ownership, mindset
Published: 2022-02-05 19:07:00

"Ownership" and "owning the process" show up a lot in IT industry, especially when you read job offers. What does it really mean to own the process when you work as a software developer? For me a recipe for the ownership is pretty simple.

**You care**

It's not just about getting assigned task done and moving to another one. You don't take things as granted. You ask questions if something is not clear. You speak up if something doesn't feel right. Your goal is to understand the reason behind the things you are asked to do. It's not just about coding, it's more about contributing. Sometimes, after long (and painful) discussion this means dropping the feature or not coding things at all. 

It's not just about coding but also proper testing. You don't drop you task after it's merged. You check with QA, you check with Product owner, you check the metrics. You see how the thing you built behaves and you even may have some ideas how to improve it. 

**You see things that are not strictly in your scope**

 When you want to own what you do, you need to think of the product you build and people you work with. You consider how your task would impact the users. You think if your change may interfere with your or other team members work. You can see dots in various places and you know how to link them. 

 You are proactive and jump in the different roles when needed. You take care of the tasks without your manager micro managing you and asking about the progress every two hours. You know how to handle problems that show up or you know who to ask for help. 
 
**You have knowledge or you know where to get it**

You have not only technical knowledge but also domain knowledge. You know why things are built the way they are. You know how to go with the existing flow. While thinking of implementing a feature, you already have an idea on what changes in other places are required. Or you know who to ask to get these pieces of information. 

These things may sound simple but in reality they are hard. You need to change the way you think about the work to really get the ownership going. It's not like you ask one or two questions and - done - an ownership badge shows up. Owning something requires constant learning. You always have more to discover.

So why you should care? Can't you just code the task based on 3 requirements you see in the ticket description? And if something it not clear, can't you just do it your way and hope that this doesn't comes back to you? Of course you can. But would it give you satisfaction, better salary and a promotion? That is a question you need to reply by yourself. 


_Photo from [kaboompics](https://kaboompics.com/)_
Deploying NextJS on Netlify - Starter Template
Published: 2022-03-13 15:53:47

---
title: Deploying NextJS on Netlify - Starter Template
published: true
date: 2022-02-05 19:00:46 UTC
tags: 
canonical_url: https://chrisdevcode.hashnode.dev/deploying-nextjs-on-netlify-starter-template
---

# Deploying NextJS to production

By default, [NextJS](https://nextjs.org/) applications are easily deployable on [Vercel](https://vercel.com/) with zero configurations. That doesn't mean you shouldn't explore what other platforms have to offer.

To deploy a NextJS application, simply follow the steps below. If you want to start straight up without the hustle, use the button below:

[![Deploy on Netlfiy](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/achingachris/next-netlify-starter)

## Create a Netlify Account

On your browser, go to https://app.netlify.com/signup to create your Netlify account.

![Creating a Netlify Account](https://cdn.hashnode.com/res/hashnode/image/upload/v1644080613728/s27NP3fJY.png)

Choose a method that works best with you(I would use GitHub)

## Set Your Next project Ready

Install `@netlify/plugin-nextjs` dependency on your project:

```
npm i @netlify/plugin-nextjs

```

On the root of your NextJS project, create a `netlify.toml` file and the following code in the file:

```
[build]
  command = "npm run build"
  publish = ".next"

[[plugins]]
  package = "@netlify/plugin-nextjs"

```

> Ensure to update and commit changes on GitHub

## Deploy on Netlify

To deploy, head over to your Netlify dashboard, https://app.netlify.com/ and create on the `Add New Site` button in the `Site` tab.

![addnew](https://cdn.hashnode.com/res/hashnode/image/upload/v1644082441537/hYhIpMP6B.png)

From the dropdown, select `Import an Existing Project`.

![create-dropdown.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644082852674/JQrAOg-uD.png)

You'll be taken to a new page and asked to pick a Git provider, I will use GitHub.

![pick-git.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644083397211/PSMnVT4zF.png)

Choose the repository with your project in it and proceed to deploy the site. Do not change anything under the `Basic build settings`.

![build.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644083552224/rtND2bWdb.png)

Click on the `Deploy Site` button and wait for it to complete.

Once the deployment is successful, you are ready to go!

> Netlify offers automatic deploys once you push a commit, and provides a preview link for the build! That is very useful!

View The demo site: https://nextnetlifystarter.netlify.app/

View The Source: https://github.com/achingachris/next-netlify-starter

![next-on-netlify.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644087308025/otfRPzknj.png)

### You Got This
Deployment of ML and Data Science Apps
Tags: webdev, machinelearning, datascience, beginners
Published: 2022-02-05 18:41:23

### So here comes the most awaited part of the most talked about yet the most undisclosed knowledge in the field of ML or Data Science. ###
Well that is the deployment of the applications as web app and other integrated forms. Now Python being the programming tool for both the communities has a lot to play here. As we mentioned that Tableau and Excel are some platforms to perform data science, they holdback in terms of deployment as an application or something that can hold its own as a standalone web app. 

[Streamlit](https://streamlit.io/) is the best and the most easy to implement framework for web deployment for data scientists with a little kink for coding. You can customize the UI but its still limited and you need to force in some hybrid frontend tech stack to do so. 

[Flask](https://flask.palletsprojects.com/) on the other hand can help you get the best out of the UI part. Both the libraries are easy to be implemented and a lot fun to be used. 

Here, I will link some projects of the same genre that I had posted. 

[Movie Recommendation System - Flask](https://github.com/Souvik1406/SouviksMovieRecommendationSystem)

[Laptop Price Predictor](https://github.com/Souvik1406/newLaptopPricePredictor)

[Data Science Classifier App](https://github.com/Souvik1406/BasicMLDataScienceClassifierApp)

Well all the things that you need to add and maintain are there, mentioned in the repositories. 

Here is a link to one blog that can help you further. 

https://towardsdatascience.com/3-ways-to-deploy-machine-learning-models-in-production-cdba15b00e#:~:text=The%20simplest%20way%20to%20deploy,classifier%20built%20with%20scikit%2Dlearn.

https://towardsdatascience.com/building-a-machine-learning-web-application-using-flask-29fa9ea11dac


Now, I have also created a PWA that has all the major ML apps available for viewing the code and the deployed versions. 

[Streamlit - Hub](https://streamlithubbysouvikroy.netlify.app/)

The above app also showcases the wonders that Streamlit library can do. However, that topic requires a dedicated blog that is soon to be released. 
Recently there has been another method added to the arsenal. 

Read about this thing called : Mercury

Read about it here : 
https://towardsdatascience.com/create-a-web-app-from-your-jupyter-notebook-with-mercury-21239b7abb37

**Those who are willing to learn ML and Data Science in depth, I have some good news to share, my book on the same topic is releasing in two months**

***Stay-Tuned***
Prisma - Backup System
Tags: prisma, typescript, database, postgres
Published: 2022-02-05 18:30:28

<center>// start</center>

Hi everyone! 
[GitHub of the Project](https://github.com/DaxSoft/prisma-backup)

-----

Use this module to create a backup measure for your project that uses Prisma. You can either backup the information, or use them to migrate to another database, or just to reset the database.
Example: Let's say that you need to change a unique key (email) to another like (code). You can backup first,
then change the schema.prisma, and use this module to inject the old information.


-----

<center>// How To Use</center>

Basic example using the Prisma, let's imagine that we have two models, User & Post. And the Post model is related to the User model.



```ts
import { PrismaClient } from '@prisma/client';
import { backup } from '@vorlefan/prisma-backup';

const prisma = new PrismaClient();

void (async function () {
    const [user, post] = await prisma.$transaction([prisma.user.findMany({}), prisma.post.findMany({})]);

    // w/out encrypt

    await backup({
        models: {
            user,
        },
    });

    // encrypting the models

    await backup({
        models: {
            user,
        },
        encrypt: true,
        password: 'pwd123',
        backupFolderName: 'encrypted'
    });
})();
```

-----

<center>// End</center>

There a lot of feature that I'm planning for this module, then if you want to, please contribute or follow up the news xD
A lambda that sends daily AWS bill notifications
Tags: aws, lambda, tutorial, python
Published: 2022-02-05 18:19:04

The SMS/Email will be as below.

> AWS Account
> Yesterday Usage : Kshs. 730
> Month To Date Bill : Kshs. 12,640
> Forecasted Bill : Kshs. 20,479

The code is on [github](https://github.com/leroykayanda/AWS/tree/master/Bill%20Notifications).

This helps you keep track of your AWS spending in order to avoid surprises at the end of the month

**How it works**
It uses cost explorer APIs to get your bill details and then sends them using SNS.

**IAM permissions required for the lambda role**
cost explorer
sns

**How to set it up**
Create a python lambda function
Initialize the environment variables
Schedule the lambda function to run periodically using CloudWatch events

**Lambda Environment Variables**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hqzulla3cpv0v969z50n.png)

currency : name of your local currency e.g kshs
dollar_exchange_rate : the function converts from dollars to your local currency
sns_topic : arn of your sns topic
subject : subject of the message that is sent
A CICD pipeline that pushes code to cpanel or any other server via FTP or SSH
Published: 2022-02-05 18:23:17


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a495w6befohjpphuz2jp.jpg)

The code is on [github](https://github.com/leroykayanda/AWS/tree/master/CICD%20to%20cpanel%20and%20other%20servers).

 1. Set up codebuild to build your code once a commit is made to your repository. You can also use codebuild to run your tests. When building is complete, the code is stored in s3
 2. Create a codepipeline that will trigger automatically when you push a commit to your repository ( bitbucket, github, codecommit etc). The first stage will be your code source and the second stage will be codebuild.
 3. When you push a commit, the pipeline will run. The code will be built and stored in S3. You can set up an S3 lifecyle rule to delete old code artifacts. You can also set up a CloudWatch event rule that will inform you via SNS of the state of the pipeline execution ( successful or failed ).
 4. The code now needs to be pushed to cpanel. Set up an S3 event that monitors for new object creation. When code is pushed, set the event should invoke a lambda function.
 5. The Lambda will fetch the code from S3 and store it in its /tmp directory which is limited to 512 mb. The lambda will unzip the code and push it to cpanel using FTP. FTP credentials are fetched from the AWS Parameter Store. Lambda can then inform you via SNS when the code has been successfully pushed. Lambda has a maximum running time of 15 minutes. 

***codepipeline_cpanel_push_lambda.py***

**IAM Permissions Required**
 - cloudwatch
 - S3
 - SNS
 - SSM

**Lambda Environment Variables**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zu6i0w317e2uxt2xa0xi.png)

 - bucket: bucket name for bucket that stores codepipeline artifacts
 - ftp_hostname
 - sns_topic : arn of sns topic to send you a notification when code has been pushed to cpanel
 - region
 - ftp_directory: where files will be pushed to
 - ftp_hostname: hostname of the cpanel server

The function named `codepipeline_ssh_push_lambda.py` is for the case where code is pushed to a server via SSH, which offers increased security as the data between the lambda function and the server will be encrypted.

Lambda environment variables in this case.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l1hzm3srnrkbcf828ema.png)

**target_host**: IP address of the server.
**zipped_src**: path in /tmp directory of lamba temporary storage where the zipped code downloaded from S3 will be stored eg /tmp/zipped.
**unzipped_src**: path in /tmp directory of lamba temporary storage where the unzipped code will be stored e.g /tmp/unzipped.
Divide Two integers Leetcode python
Tags: leetcode, leetcodesolutions, dividetwointegers, pythonsolutions
Published: 2022-02-05 17:59:10

LeetCode has a Medium coding Problem in Its’ Algorithm Section “Divide Two integers Leetcode python”. Today We are going to solve this problem. LeetCode Link of the Problem is HERE


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/witbgbfjpgbubdjljgcz.jpg)
Divide Two integers Leetcode python

Question
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.

The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2.


 
Return the quotient after dividing dividend by divisor.


 
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.

Examples

Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = 3.33333.. which is truncated to 3.
Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7/-3 = -2.33333.. which is truncated to -2.
Constraints:

-231 <= dividend, divisor <= 231 - 1
divisor != 0
Solution to Divide Two integers Leetcode python
https://hecodesit.com/divide-two-integers-leetcode-python/
Solution 
https://hecodesit.com/divide-two-integers-leetcode-python/