teleren/devto huggingface dataset:
Server Side Rendering, Prisma + Next.js  + TypeScript
Tags: typescript, nextjs, react, javascript
Published: 2021-12-25 07:24:10

I've been working on a new project recently ([CodeComponents](https://code-components.vercel.app) if you wanna check it out) and struggled a little bit figuring out server side rendering because typescript wants to know what is being passed to the pages so I wanted to share how to do it.

---

so lets say we have a helper function that just returns all posts from the database

```typescript
const prisma = new PrismaClient()
async function getPosts() {
    const posts = await prisma.post.findMany()
    return posts
}
```


## Static Site Generation

```typescript

export const getStaticProps: GetStaticProps<{
    posts: Prisma.PromiseReturnType<typeof getPosts>
}> = async () => {
    const posts = await getPosts()
    return {
        props: {
            posts
        }
    }
}

const Home: NextPage<InferGetStaticPropsType<typeof getStaticProps>> = (
  props: InferGetStaticPropsType<typeof getStaticProps>
) => {
    return (
        <div>
            ...
            {/* do whatever with posts here */}
        </div>
    )
}

export default Home;

```

## Server Side Rendering

Server Side rendering is pretty similar we just have to change the type of props passed to page function

```typescript
export const getServerSideProps: GetServerSideProps<{
    posts: Prisma.PromiseReturnType<typeof getPosts>
}> = async () => {
    const posts = await getPosts()
    return {
        props: {
            posts
        }
    }
}

const Home: NextPage<InferGetServerSidePropsType<typeof getServerSideProps>> = (
  props: InferGetServerSidePropsType<typeof getServerSideProps>
) => {
    return (
        <div>
            ...
            {/* do whatever with posts here */}
        </div>
    )
}

export default Home;

```

Hope this was helpful
Write these C/C++ Program before going to Interview.
Tags: programming, cpp, interview, beginners
Published: 2021-12-25 06:30:37

### While-loop

1. WAP - To check string is Palindrome or not
2. WAP - To check number is Armstrong or not.
3. WAP - To check number is perfect or not.
4. WAP  - To check number is prime or not 

---

1. WAP - To find number Factorial.
2. WAP - To find number Factorial or not
3. WAP - To print Fibonacci & and Tribonacci.
4. WAP - To find prime number between the number rang
5. WAP - To calculate area of circle, (Square, rectangle and triangle )
6. WAP - To  check Leap year or not.
7. WAP - To swap to numbers.
8. WAP - To swap to numbers without using third variable.

### Array

1. WAP - To sort array element in ascending and descending order.
2. WAP - To insert element at beginning, ending and any position of array.
3. WAP - To print array element in reverse order.
4. WAP - To find maximum and minimum element of array (smallest, largest)
5. WAP - To print 2d array matrix transport matrix.
6. WAP - To print mirror matrix
7. WAP - To swap two matrix.

---

1. WAP - To print palindrome string
2. WAP - To convert temperature Celsius to Fahrenheit and vice-versa
3. WAP - To add two number using pointer.
4. WAP - To print 5 student records suing structure and union.
5. WAP - To calculate total and average marks of 5 subjects (struct)
6. WAP - to calculate tax 
    
    Conditions : if ≤1000 then “No Tax”
    
    if > 1000 && ≤ 100000 then “10%” tax
    
    if > 100000  then “25%” tax
    
7. WAP - To add every element from array.
8. WAP - To search array elements with appropriate location

---

 

# Patterns

1. Pattern 1

```c
*
* *
* * *
* * * *
* * * * *
```

1. Pattern 2.

```c
* * * * * * 
* * * * * * 
* * * * * * 
* * * * * * 

```

1. Pattern 3

```c
	       *
         *   *
       *   *   *
     *   *   *   *
   *  *    *   *   *
 *   *   *   *   *   *
```

1. Pattern 4

```c
1 
2 3
4 5 6
7 8 9 10
11 12 13 14
```

1. Pattern 5.

```c
* * * * * * * * *
  * * * * * * *
    * * * * *
      * * *
        *
```

1. Pattern 6: half pyramid of alphabets

```c
A
B B
C C C
D D D D
E E E E E
```
Position Sticky With CSS Grid, Conditional Border Radius In CSS, Custom Scrollbars In CSS
Tags: css, html, javascript, react
Published: 2021-12-25 06:20:00


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

CSS Blogs

Position Sticky With CSS Grid
Have I ever come across a case where the sticky position isn’t working as expected with a child of a grid container? A few days ago, I was helping youtube in fixing that exact problem and wanted to finally write about it.

HTML__:
     <div class="wrapper">
    <aside></aside>
    <main></main>
</div>

CSS__:
            
     .wrapper {
    display: grid;
    grid-template-columns: 250px minmax(10px, 1fr);
    grid-gap: 1rem;
}

Conditional Border Radius In CSS
We have a card component with a border-radius of 8px. When the card doesn’t have margin or is taking the full viewport width, we want to flip the border-radius to 0.

CSS__:

     @media (min-width: 700px) {
    .card {
        border-radius: 8px;    
    }
}

Custom Scrollbars In CSS

First, we need to define the size of the scrollbar. This can be the width for vertical scrollbars, and the height for horizontal ones.
CSS__:
.section::-webkit-scrollbar {
    width: 10px;

}

CSS Scroll Snap
To create a scrolling container, here are the basic things that you will need:
Using the overflow with a value other than visible.A way to display the items next to each other inline.
HTML__:
<div class="section">
  <div class="section__item">Item 1</div>
  <div class="section__item">Item 2</div>
  <div class="section__item">Item 3</div>
  <div class="section__item">Item 4</div>
  <div class="section__item">Item 5</div>
</div>

CSS__:
.section {
  white-space: nowrap;
  overflow-x: auto;
}
React JS CRUD operations using Local Storage
Tags: javascript, react, typescript, webdev
Published: 2021-12-25 06:15:28

many developers using localStorage for learning or some operation
like add to cart and store token or user information into the browser.

## What is local Storage?
local storage is type of memory in our browser to save our data.
local storage storage limit is 5 MB.

local storage is our browser memory so we can store everything in our browser using javascript or ReactJS.

## In HTML

```
<script>
localStorage.setItem("key","value");
localStorage.getItem("key");
localStorage.removeItem("key");
console.log(localStorage)
</script>
```

## In ReactJS

```
function App(){
localStorage.setItem("key","value");
const store=localStorage.getItem("key");
localStorage.removeItem("key");
console.log(localStorage)

return(
<div>
{store}
</div>

)}

```

In many users questions how we store array of object in localStorage. here is the solution.

```
const data={
name:"Deepak",
address:"Allahabad"
}
localStorage.setItem("user",JSON.stringify(data))

const user=JSON.parse(localStorage.getItem("user"))

console.log(user)
//it return {name :"Deepak", address :"Allahabad"}

```
Reasons Why You Should Not Ignore AWS Cloud Services  
Published: 2021-12-25 05:38:53

AWS cloud services provide various computing services that directly or indirectly help different industries to grow and earn more. When a business is facing a problem, the overall analysis of activities is done by taking everything in mind.  

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

While business analysis is not a piece of cake. Intelligent database tools or services are required for better management and analysis. To put everything under control, businesses take benefits of AWS Cloud. This AWS cloud is a secret ingredient to boost your business growth. Let’s take a look. 

**[AWS cloud maintenance services](https://www.zehncloud.com/24-7-aws-cloud-support-and-maintenance-services/)** provide 24/7 support and maintenance. By adding numerous benefits to the list like removing unnecessary access, enhancing server performance (with frontend and backend also), scalability, reliability, elasticity, improving quality like a fast response, providing complete security, etc. **[AWS managed cloud services](https://www.zehncloud.com/aws-managed-cloud-services/)** can give you quality assurance with multiple uses of services and tools at affordable prices. 

This also allows pay-as-you-go services for the users. In this, you can use the services and tools when you need them and stop when you’ve done. With this, you can reduce costs and grow your business with fewer expenditures.  

## Conclusion 

By taking everything in mind, you can leverage business growth by migrating the business workload to the AWS cloud. This will help you in multiple ways and lets you focus on the business rather than on the complex management.  

[YOUTUBE](https://www.youtube.com/channel/UCKXN4AYEe4OsUv2ph-7R9fw) – [INSTAGRAM](https://www.instagram.com/zehncloudhq/) – [FACEBOOK](https://www.facebook.com/zehncloudHQ/)
E-commerce website with a powerful search engine equipped with autocomplete
Tags: atlashackathon, webdev, javascript
Published: 2021-12-25 05:08:06

[Instructions]: # (To submit to the MongoDB Atlas Hackathon on DEV, please fill out all sections.)


### Overview of My Submission
hassly in an e-commerce website with tailor made search engine specifically designed for e-commerce. The website includes autocomplete, search relevancy, will return you the results you wanted even if there are errors (such as typos) in your search.
Uses mongodb atlas search.
See github readme for more


### Submission Category: 

E-commerce creation


### Link to Code

https://github.com/irshad4250/hassly_public 

### Additional Resources / Info

website demo: https://hassly.herokuapp.com/

> The github readme will tell you everything you need to know

Built with:
EJS, HTML, CSS, javascript, Node JS, Express JS
Mongodb, Mongodb Atlas Search, Mongoose
Animate on click with Javascript!
Tags: javascript, beginners, html, css
Published: 2021-12-25 05:06:17

```
<p>Hello</p>
<p>Merry Christmas</p>
```

Previous Chapter [Chapter 2 (Part 2)](https://inform-our-world.github.io/Saqha/CH%202.2)

Inform Our World [Link here](https://inform-our-world.github.io/)

[My Portfolio](https://subhransuindia.github.io/Subhransu%20Patra.html)

Animation with js? Not too much tough but if you are new to javascript, like me, then at first it would be a  little bit difficult but with time, you would be coping up with it. So, lets start the topic of 'Animate on click with Javascript!'

First create a HTML file...

```
<!DOCTYPE html>
<html lang="en">
<head>
<title>Animate on click with Javascript!</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
  margin: 0;
}
</style>
</head>
<body>

</body>
</html>
```

Then add any tag such as `<a>` or `<p>`. It is upto you which tag you will use to animate...

```
<p>Hello World!</p>
```

Here I used `<p>` tag. Then create an `id=""` for it. Let's name it animate. You can use anything...

```
<p id="animate">Hello World!</p>
```

Then we need a button so that if we clicked on it, it would animate as per our needs...

```
<button>Click to Animate</button>
```

then in the `<button>` tag add `onclick=""`. It is very much essential for onclick animation.

```
<button onclick="beyblade()">Click to Animate</button>
```
I have put `beyblade()` in `onclick=""`. `()` is very much essential...

Then add `<script>` in the body...

```
<script>

</script>
```

and in that add 

```
<script>
function beyblade() {

}
</script>
```
The text after `function` will be the one you have written in `onclick=""` i.e. I have written `onclick="beyblade()"`, the same I will write after `function` i.e. 
```
function beyblade() {
}
```
So, let's take the element that we take be `x`. So to do this, implement..

```
<script>
function beyblade() {
let x = document.getElementById("animate")
}
</script>
```

then add the following component...

```
<script>
function beyblade() {
let x = document.getElementById("animate")
x.style.marginLeft = "300px"
x.style.transition = "1s"
}
</script>
```
`x.style.transition` will create transitions and `1s` will create timing for it. 

You can implement any css component in place of `marginLeft` such as `x.style.color = red` it will change the text color to red and `x.style.backgroundColor = blue` will change the background color to blue.  

It  helps  us to create a hamburger menu also.

So, this is for today. I hope you liked the article and if you, then please notify me. 

Full Code..

```
<!DOCTYPE html>
<html lang="en">
<head>
<title>Animate on click with Javascript!</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
  margin: 0;
}
</style>
</head>
<body>

<p id="animate">Hello World!</p>

<button onclick="beyblade()">Click to Animate</button>

<script>
function beyblade() {
let x = document.getElementById("animate")
x.style.marginLeft = "300px"
x.style.transition = "1s"
}
</script>

</body>
</html>
```

Thanks for your time. 😺
Upload image to Cloudinary with Node js
Tags: javascript, webdev, programming
Published: 2021-12-25 04:14:46

_**install package**_

> express

> cloudinary

> dotenv

> multer

**Express**
Create _app.js_

```
const express = require('express');
const port = 3200;
const App = express();



App.listen(port,()=>{
   console.log(`Running on {port}` )
})
```
**Cloudinary**
Create _cloudinary.js_

```
const cloudinary = require('cloudinary').v2
cloudinary.config({
    cloud_name: 'CLOUD_YOUR_NAME',
    api_key: "API_KEY_YOUR_CLOUDINARY",
    api_secret: "API_SECRET_YOUR_CLOUDINARY",
    secure: true
})




```
Custom cursors using data-uri
Tags: codepen
Published: 2021-12-25 04:13:23

<p>The option to use Base64 encoded images inline in your CSS stretches also into the custom cursors. So you can embed your own custom cursors in the CSS file. Here you can see how it is done through an example. </p>

{% codepen https://codepen.io/harunpehlivan/pen/WNZXpPg %}
Jira Link Auto Commenter
Tags: githubactions, bot, projectmanagement, jira
Published: 2021-12-25 03:42:28

---
title: Jira Link Auto Commenter
published: true
description: This Github action auto comments in pull request with Jira link to it. 

tags: githubactions, bot, projectmanagement, jira,
cover_image: https://user-images.githubusercontent.com/11685953/147376660-50957431-f9a8-4317-b10a-9fcce82e7b42.png
---
Migrating from bitbucket to Github made me lack only one feature. The link that navigates to its related Jira ticket from pull request.

This is why I created this tool for my project.
This Github action auto comments in pull request with Jira link to it. This tool is helpful for devs who use consistent PR summary like `Ticket-1234: This is PR summary`.
It grabs the ticket number using regex and comments on the PR by making a JIRA link. If it can't find the ticket number, it will fail silently and won't fail the whole workflow.

### How to use:
Create a workflow file in root of your project.
`.github/workflows/main.yml`

Input:
* `custom-comment`(optional): If you want to add your own comments before Jira link. Default is `Thank you for your contributions. Jira link:`
* `jira-project-url`: you can figure our this URL by going to any of your JIRA ticket in new tab and checking the URI box.
* `GITHUB_TOKEN`: is auto generated

```yaml
on: pull_request

jobs:
  example_comment_pr:
    runs-on: ubuntu-latest
    name: Auto jira link commenter
    steps:
      - name: Checkout
        uses: actions/checkout@v1

      - name: Comment PR
        uses: sbimochan/jira-link-commenter@v2.4
        
        with:
          jira-project-url: https://jira.atlassian.net/browse
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          custom-comment: 'Thank you for your contribution!!! :confetti_ball:'
```

Hope you will find it useful for your project. 

### Links:
[Marketplace](https://github.com/marketplace/actions/auto-ticket-link-commenter)
[Github Repo](https://github.com/sbimochan/jira-link-commenter)
How I built SetProgress - Part 3 Automation
Tags: nextjs, sideprojects, webdev, twitter
Published: 2021-12-25 03:18:32

In the previous post, I explained how I built SetProgress.

In this post, I am going to explain how I automated progress updates. 

Automation was not part of my initial plan. I just wanted to create a simple app which allows a user to design & push a progress bar to Twitter.

[Sumudu Siriwardana](https://twitter.com/sumusiriwardana) asked me if the app could calculate & update progress for her #100DaysOfCode challenge.

I thought about it, and I realized that the app doesn't offer much automation. User has to update their progress manually everyday or every week. 

### Automating #100DaysOfCode

Let me give you a bit of context on [100DaysOfCode](https://www.100daysofcode.com/).

**It has 2 rules**

1. Code minimum an hour every day for the next 100 days.
2. Tweet your progress every day with the #100DaysOfCode hashtag. 

Anyone who is doing this challenge will tweet everyday tagging 100DaysOfCode and a little bit about what they did that day. 

**Solution**

We can fetch all the tweets of a user and check if any one of those have the hashtag 100DaysOfCode. 

I used the [Twitter search tweets API](https://developer.twitter.com/en/docs/twitter-api/v1/tweets/search/api-reference/get-search-tweets) to get the tweets of a user containing a specific hashtag and in a given date range.

This is how the request looks.
```
https://api.twitter.com/1.1/search/tweets.json?q=from%3Asdinesh91%20since%3A2021-12-24%20until%3A2021-12-25%20#100DaysOfCode%20-filter%3Aretweets
```

These are the query parameters I used

```
from:sdinesh91 since:2021-12-24 until:2021-12-25 #100DaysOfCode -filter:retweets
```

This query returns tweets of a specific user, tweeted within a specific date range and having the specified hashtag. We also don't need to fetch the retweets, so I filter them out.

We don't have to count multiple tweets containing the hastag in a single day. 100DaysOfCode is progress made in days and not in the number of times tweeted.

Having fetched the tweets it is very simple to count the progress. If I find a tweet for any given day, I increment the count. Once I have the count, I update the progress in the database and push the new progress bar to Twitter.

One important aspect of writing a backend job like this, is to make it **Idempotent**. Being idempotent, ensures that we obtain the same result irrespective of the number of times we run the code. This is critical as backend jobs might fail or timeout. In such cases, we should be able to just rerun the job and things should work as expected.

To make tracker job idempotent, I store the tracker's last run date to each user's config. This allows the tracker to resume processing from where it last left by comparing the last run date.

### Tech

I have hosted the tracker on [Netlify](netlify.com) as a function. I also use [EasyCron](https://www.easycron.com/) to trigger the tracker function every day.
Public Solving: Earth, Fire, Snow game
Tags: javascript
Published: 2021-12-25 02:55:14

The elves love making up games, and they have their own version of Rock, Paper, Scissor. 

Their version includes Earth, Fire, and Snow.
Let me quickly tell you how you can win with this game:

- Fire melts snow
- Snow covers earth
- Earth extinguishes fire

Alright, let's get right into coding this fun game for the elves 👏

[Click here to view the puzzle.](https://github.com/devadvent/puzzle-14)

## Thinking about a solution

I think it's safe to say there are only three options that win for this game.

Then there is a tie (both the same)

That's actually all there is, and it makes our program a bit easier to create.

Let me show you how:

## Building the earth, fire, snow game in JavaScript

Let's first define an object with the winning combinations.

```js
const winMatchUp = {
  fire: 'snow',
  snow: 'earth',
  earth: 'fire',
};
```

There is no need to define the other way around as we can abstract it, seeing we only have two players.

First, let's look at a draw. This means both players picked the same element.

```js
export const selectWinner = (user1, user2) => {
  if (user1.choice === user2.choice) return null;
};
```

Then we can check if user1's choice match up is equal to user2's choice. This would mean user 1 one.

Let's me check an example to explain a bit more:

- user one picked snow
- user two picked earth

We then query our match-up table and say give us the matchup object for `snow`. This will return `earth`.

So if we now compare this to user two choice, we won!

In our code we can do it like so:

```js
if (winMatchUp[user1.choice] === user2.choice) return user1;
```

This automatically means, if user 1 did not win, user 2 must have won!

```js
export const selectWinner = (user1, user2) => {
  if (user1.choice === user2.choice) return null;
  if (winMatchUp[user1.choice] === user2.choice) return user1;
  return user2;
};
```

And there you go!

A super simple game, but yet so much fun.

I've run the test as a sanity check, and they turn green ✅.

![All test green](https://cdn.hashnode.com/res/hashnode/image/upload/v1639507909269/SgCLLxFAz.png)

Let me know what you think of my solution and how you would do differently.

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
Why branching over multiple types is a disaster
Tags: functional, programming, haskell, scala
Published: 2021-12-25 02:50:35

**Warning: This article presumes at least a cursory knowledge of HM type systems**

Anyone using a static, strongly-typed programming language (like Haskell) is familiar with the idea of functional types. And any programmer is also familiar with the idea of error handling. 

Let's say we have a function that returns the square root plus one of a number:
`f = x -> sqrt x + 1`

However, disaster strikes when you pass a negative number into the function (assuming we're operating in the real numbers):
`f (-1) // => error`

We need some way to handle this! Perhaps we can introduce some sort of branching into the function:
`f = x -> if x >= 0 then sqrt x + 1 else "Invalid input"`

Aha! We have successfully created a function that can handle all of the real numbers. What could go wrong?
`f 4 // => 3`
`f 0 // => 1`
`f (-2) // => "Invalid input"`

Let's try passing this into another function:
`double = x -> 2 * x`
`g = x -> double f x`

Now let's test this out:
`g 1 // => 4`
`g 9 // => 8`
`g (-1) // => type error`

We receive a nasty type error on the same values we thought we "fixed," since we tried passing a string to a function between numbers:
`double : Number -> Number`

Speaking of, what even is `f`'s type? It can output both a number and a string, no?
`f : Number -> ??? // string + number perhaps?`

This is why most functional languages do not allow for branching across multiple types. What happens when you pass those values to a different function? Some of them will go through, some of them won't. In fact, the original implementation of `f` would *not* be valid!

To represent this possibility of multiple types being returned by a branched expression, we would need a special type that indicates the sum of all of the types in each branch:
`data Either a b = [Left : a -> Either a b, Right : b -> Either a b]`

`f` could then be rewritten as:
`f : Number -> Either Number String`
`f = x -> if x >= 0 then Left sqrt x + 1 else Right "Invalid input"`

However, `g` would still not work since we're trying to input a value that could either be a number or a string into a function that only accepts a number:
`Either Number String != Number`

We would have to find a way to convert this to a number value:
`both_to_num : Either Number String -> Number`
`both_to_num = x -> match x [Left n -> n, Right str -> 0]`

Here, we had to make a function that takes in a value that is either a number or a string and matches it to a number. We can then pass this value into other functions

`f (-1) // => "Invalid input"`
`both_to_num f (-1) // => 0`

Finally! We have made it so that we can pass `f` into `double` and implement `g` without any type errors.
`g : Number -> Number`