teleren/devto huggingface dataset:
Creating blur placeholder images using Next JS 12 and Plaiceholder
Tags: nextjs, react, tutorial, blur
Published: 2022-06-18 21:39:10

Image load without placeholder makes like something an error on the website. We want the user to know that image is still fetching on the server and provide some feedback as soon as possible when the page is not fully loaded. Some websites, such as  Unsplash, have blur image placeholders, which adds some aesthetic to the website.
 

###1.Install Plaiceholder
I assume that you have already created a new next app using `npx create next-app` then install plaiceholder dependecy: 
```nodejs
npm i plaiceholder @plaiceholder/next sharp
```
&nbsp;
###2.Setup the Image assets
You can get the image assets from local or remote. In this tutorial, I use data I get from [Pixabay](https://pixabay.com/api/docs/)API to simulate the network download process. 
&nbsp;
###3.Config Next Js
This config ensures that all Plaiceholder functions start in the main thread and be able to run the function on the *getStaticProps* function. Don't forget to define of image provider domains that you want to be served from the Next.js Image Optimization API. 
```javascript
const { withPlaiceholder } = require("@plaiceholder/next");

module.exports = withPlaiceholder({
    images: {
        domains: ["pixabay.com"],
    },
});
```
&nbsp;
###3. Generates the Static HTML pages with *getStaticProps*
The code that wrote inside getStaticProps never runs on the browser. So we can run node js environment function like getPlaiceHolder as it runs on the server. We can also access our database using ORMs like Prisma inside this function.
```javascript
export async function getStaticProps() {
  const { hits } = await axios
    .get("https://pixabay.com/api/", {
      params: {
        key: "your_api_key",
        q: "cat",
        image_type: "photo",
      },
    })
    .then((res) => {
      return res.data;
    });

  const images_data = await Promise.all(
    hits.slice(0, 6).map(async (data, index) => {
      const { base64, img } = await getPlaiceholder(data.largeImageURL);
      return {
        ...img,
        base64: base64,
      };
    })
  ).then((value) => value);

  return {
    props: {
      images_data,
    },
  };
}
```
###4. Render to the Page Component
Pass the `props` property with the data that you want to provide to the page component.
```javascript
export default function NextBlurImage({ images_data }) {
   //The rest of the code..
      {images_data.map((data) => {
           return (
               <Image
                  src={data.src}
                  layout="fill"
                  alt=""
                  blurDataURL={data.base64}
                  placeholder="blur"
               />
           );
      })}
  //The rest of the code..
}
```

###5. Result
As you can see the result that the blurred image will appear before the original image. This also applies lazy loading, which loads the image when the user is in the viewport.

<img width="100%" style="width:100%" src="https://media.giphy.com/media/5QS6KC8SoaQjMTtgrP/giphy.gif">
Prime Arrangements
Tags: leetcode, dsa, theabbie
Published: 2022-06-18 21:30:38

Return the number of permutations of 1 to `n` so that prime numbers are at prime indices (1-indexed.)

_(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)_

Since the answer may be large, return the answer **modulo `10^9 + 7`**.

**Example 1:**

**Input:** n = 5
**Output:** 12
**Explanation:** For example \[1,2,5,4,3\] is a valid permutation, but \[5,2,3,4,1\] is not because the prime number 5 is at index 1.

**Example 2:**

**Input:** n = 100
**Output:** 682289015

**Constraints:**

*   `1 <= n <= 100`

**SOLUTION:**

    import math
    
    class Solution:
        def isPrime(self, n):
            if n <= 1:
                return False
            if n == 2:
                return True
            if n % 2 == 0:
                return False
            for i in range(3, int(math.sqrt(n)) + 1, 2):
                if n % i == 0:
                    return False
            return True
    
        def factorial(self, n):
            if n <= 1:
                return 1
            return n * self.factorial(n - 1)
    
        def numPrimeArrangements(self, n: int) -> int:
            numPrimes = 0
            for i in range(1, n + 1):
                if self.isPrime(i):
                    numPrimes += 1
            return (self.factorial(numPrimes) * self.factorial(n - numPrimes)) % (10 ** 9 + 7)
Short note: gradual union progress in tech with CODE-CWA
Tags: labor, laborunion
Published: 2022-06-18 21:01:27

The Communications Workers of America have a campaign that has been slowly winning some unionization efforts:

https://www.code-cwa.org/

Overall union efforts:

Alphabet (Alphabet Workers Union)
Mapbox (Mapbox Workers Union)
Medium (Medium Workers Union)
Activision Blizzard (ABK Workers Alliance)
NPM (failed effort)
Kickstarter (Kickstarter United)
New York Times Tech (New York Times Tech Guild)
NPR Digital Media Division (Digital Media United)
Vodeo Games (Vodeo Workers United)
Raven Software (Game Workers Alliance)
Glitch
Voltage Entertainment
Blue Stage Digital (Blue State Union)
Mobilize (Mobilize Union)
Catalist (Catalist Union)
Change.org (Solidarity @ Change)
EveryAction (EveryAction Workers Union)

https://en.m.wikipedia.org/wiki/CODE-CWA
Matrix Cells in Distance Order
Tags: leetcode, dsa, theabbie
Published: 2022-06-18 21:00:46

You are given four integers `row`, `cols`, `rCenter`, and `cCenter`. There is a `rows x cols` matrix and you are on the cell with the coordinates `(rCenter, cCenter)`.

Return _the coordinates of all cells in the matrix, sorted by their **distance** from_ `(rCenter, cCenter)` _from the smallest distance to the largest distance_. You may return the answer in **any order** that satisfies this condition.

The **distance** between two cells `(r1, c1)` and `(r2, c2)` is `|r1 - r2| + |c1 - c2|`.

**Example 1:**

**Input:** rows = 1, cols = 2, rCenter = 0, cCenter = 0
**Output:** \[\[0,0\],\[0,1\]\]
**Explanation:** The distances from (0, 0) to other cells are: \[0,1\]

**Example 2:**

**Input:** rows = 2, cols = 2, rCenter = 0, cCenter = 1
**Output:** \[\[0,1\],\[0,0\],\[1,1\],\[1,0\]\]
**Explanation:** The distances from (0, 1) to other cells are: \[0,1,1,2\]
The answer \[\[0,1\],\[1,1\],\[0,0\],\[1,0\]\] would also be accepted as correct.

**Example 3:**

**Input:** rows = 2, cols = 3, rCenter = 1, cCenter = 2
**Output:** \[\[1,2\],\[0,2\],\[1,1\],\[0,1\],\[1,0\],\[0,0\]\]
**Explanation:** The distances from (1, 2) to other cells are: \[0,1,1,2,2,3\]
There are other answers that would also be accepted as correct, such as \[\[1,2\],\[1,1\],\[0,2\],\[1,0\],\[0,1\],\[0,0\]\].

**Constraints:**

*   `1 <= rows, cols <= 100`
*   `0 <= rCenter < rows`
*   `0 <= cCenter < cols`

**SOLUTION:**

    class Solution:
        def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
            return sorted([[i, j] for i in range(rows) for j in range(cols)], key = lambda p: abs(p[0] - rCenter) + abs(p[1] - cCenter))
¿Por qué React 18 llama dos veces a useEffect?🙄
Tags: javascript, webdev, react
Published: 2022-06-18 20:53:53

React planea agregar una característica que permite agregar o remover secciones de la interfaz, preservando el estado.
En la documentación hay ejemplo de tabs, cuando usuario se mueve a una determinada tab y vuelve a la anterior. React debe mostrar inmediatamente  el anterior Tab, para que esto sea posible  React admite volver a montar el árbol del componente, reutilizando el mismo estado usado antes de que se desmonte de la interfaz

Con esta característica React tendrá un mejor rendimiento, todo esto sería manejado internamente por React, pero para hacer esto posible, necesita que los componentes sean resistentes a los efectos que se montan y se desmontan varias veces. Los desarrolladores tendrían que tener consideración esto al escribir código, asegurarnos de cualquier código que este dentro del efecto no cause fugas de  memoria o comportamientos no deseados cuando el componente se vuelva montar reutilizando el estado, por ejemplo, tener una suscripción doble a una misma fuente o timers que no se han limpiado.


Esto puede ser un poco confuso para las personas que recién empiezan a utilizar React, porque normalmente se dice que el array de dependencias vacío, solo sucederá una vez, ahora esto no es del todo cierto, ya que en ciertos casos el componente se va a montar dos o más veces utilizando el mismo estado como el caso de los tabs por ejemplo.


Para ayudar a afrontar estos problemas, [React Strict Mode](https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects)  ahora tiene una nueva validación que monta y 
desmonta el componente automáticamente después de montarse por primera vez, restaurando el primer
estado en la segunda vez ayudando a detectar efectos secundarios inesperados.


Una pregunta que se me vino a la mente cuando me encontré con esto, fue, ¿las peticiones a la Red, se harán múltiples veces?. Y la  la respuesta es que en desarrollo esto siempre sucederá (con el modo estricto) y en producción sucederá en casos  como el mencionado anteriormente, de todas maneras deberíamos evitar de usar el patrón de hacer peticiones durante el ciclo de eventos de React (fetch-on-render) o similares y utilizar los nuevos métodos empleados en librerías como `react-query` que proveen una mejor manera de hacer peticiones a la red y además se integran con `Suspense`.

## Si quieres saber más acerca de esto, puedes visitar los siguientes enlaces.

- https://www.youtube.com/watch?v=j8s01ThR7bQ&ab_channel=JackHerrington

- https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state

- https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state
Shuffle String
Tags: leetcode, dsa, theabbie
Published: 2022-06-18 20:30:37

You are given a string `s` and an integer array `indices` of the **same length**. The string `s` will be shuffled such that the character at the `ith` position moves to `indices[i]` in the shuffled string.

Return _the shuffled string_.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/07/09/q1.jpg)

**Input:** s = "codeleet", `indices` = \[4,5,6,7,0,2,1,3\]
**Output:** "leetcode"
**Explanation:** As shown, "codeleet" becomes "leetcode" after shuffling.

**Example 2:**

**Input:** s = "abc", `indices` = \[0,1,2\]
**Output:** "abc"
**Explanation:** After shuffling, each character remains in its position.

**Constraints:**

*   `s.length == indices.length == n`
*   `1 <= n <= 100`
*   `s` consists of only lowercase English letters.
*   `0 <= indices[i] < n`
*   All values of `indices` are **unique**.

**SOLUTION:**

    class Solution:
        def restoreString(self, s: str, indices: List[int]) -> str:
            n = len(s)
            op = " " * n
            for i in range(n):
                op = op[: indices[i]] + s[i] + op[indices[i] + 1 :]
            return op
Sort Array By Parity II
Tags: leetcode, dsa, theabbie
Published: 2022-06-18 19:30:49

Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**.

Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**.

Return _any answer array that satisfies this condition_.

**Example 1:**

**Input:** nums = \[4,2,5,7\]
**Output:** \[4,5,2,7\]
**Explanation:** \[4,7,2,5\], \[2,5,4,7\], \[2,7,4,5\] would also have been accepted.

**Example 2:**

**Input:** nums = \[2,3\]
**Output:** \[2,3\]

**Constraints:**

*   `2 <= nums.length <= 2 * 104`
*   `nums.length` is even.
*   Half of the integers in `nums` are even.
*   `0 <= nums[i] <= 1000`

**Follow Up:** Could you solve it in-place?

**SOLUTION:**

    class Solution:
        def sortArrayByParityII(self, nums: List[int]) -> List[int]:
            n = len(nums)
            odds = []
            evens = []
            for i in range(n - 1, -1, -1):
                if nums[i] & 1:
                    odds.append(nums[i])
                else:
                    evens.append(nums[i])
            for i in range(n):
                if i & 1:
                    nums[i] = odds.pop()
                else:
                    nums[i] = evens.pop()
            return nums
Adding Startup.cs back to .NET 6 Project
Tags: csharp, programming, dotnet
Published: 2022-06-18 19:23:41

When `NET 6` was released, the first big change was the lack of `Startup.cs`. This is very nice and all. But sometimes we just want it back, and here is how.

First, create a new file called `Startup.cs` at the root of your project with the following content - don't forget the namespace.

```csharp
public class Startup
{
    readonly IConfiguration configuration;

    public Startup(IConfiguration configuration)
    {
        this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
        });
    }
}
```

Then at Program.cs change to the following.

```csharp
//add necessary usings

var builder = WebApplication.CreateBuilder(args);

//create new instance of Startup
var startup = new Startup(builder.Configuration);

//configure all services
startup.ConfigureServices(builder.Services);

var app = builder.Build();

//configure the pipeline
startup.Configure(app, builder.Environment);

//run
app.Run();
```

The simplest solution is the better!

That is it. Enjoy.
Day 71: Hello Docker!
Published: 2022-06-18 19:19:50

Hi!
so today I got started with The research about Docker with the main search being "What is Docker" I have found good resources and walked through  lot of documentation but I think there still a lot to cover but so far is a good start. I got a chance to help a friend about his GraphQl project and we completed it successfully which was great and I started the show "Family Guy" the first season which I will be watching for relaxation in the upcoming days. overall it was a good day. Tomorrow I will not do much it's my free day so I will find something else to do maybe look into designs later in the evening as preparation  for the next week.
That's about it

signing off...
Long Pressed Name
Tags: leetcode, dsa, theabbie
Published: 2022-06-18 19:00:52

Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times.

You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly none) being long pressed.

**Example 1:**

**Input:** name = "alex", typed = "aaleex"
**Output:** true
**Explanation:** 'a' and 'e' in 'alex' were long pressed.

**Example 2:**

**Input:** name = "saeed", typed = "ssaaedd"
**Output:** false
**Explanation:** 'e' must have been pressed twice, but it was not in the typed output.

**Constraints:**

*   `1 <= name.length, typed.length <= 1000`
*   `name` and `typed` consist of only lowercase English letters.

**SOLUTION:**

    class Solution:
        def getRLE(self, string):
            n = len(string)
            i = 0
            op = []
            while i <= n - 1:
                ctr = 1
                while i < n - 1 and string[i] == string[i + 1]:
                    ctr += 1
                    i += 1
                i += 1
                op.append((string[i - 1], ctr))
            return op
        
        def isLongPressedName(self, name: str, typed: str) -> bool:
            namelist = self.getRLE(name)
            typedlist = self.getRLE(typed)
            m = len(namelist) 
            n = len(typedlist)
            if m == n:
                for i in range(m):
                    if namelist[i][0] != typedlist[i][0]:
                        return False
                    if namelist[i][1] > typedlist[i][1]:
                        return False
                return True
            return False
What is data Binding in Angular 12
Tags: javascript, angular, webdev, programming
Published: 2022-06-18 18:58:22

**Data Binding is communication between typescript code of your component and the template (html) the user see.**

_Data Binding === Communication_

We get different ways of communication.

Let's say we want to output data from our Typescript code in html template. **We can use String Interpolation for that.**

**Syntax for String Interpolation**

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

You put it inside double curly braces.

So in your ts file you have a property name of string type and set to 'deepa'

**Example of String Interpolation**

**In your ts file:**

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

**Now in your html you will use it like this:**

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

So it will print 'My name is Deepa'

Now suppose you have a button to submit the form or some other task. It must be enabled only if you're admin. Whether you're admin or not buisness logic will be handled on your ts file.

- In this case what you can use is **Property Binding**

- The native property [disabled] of html file will get bind to a boolean value that will come from ts file .

**Example of Property Binding**

**In  ts file:**

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

**I have defined a property isAdmin like this and set it to true. Now in my html file**

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

- Now if user is **not admin** ,then  **button will be disabled** otherwise it's enabled.
- As we are having **isAdmin **set to true so it's **enabled**.

**Event Binding** 

It allows your component to react to user's actions such as button clicks ,key strokes and many more.

**Like Property Binding use [] Square Brackets**

**Similarly Event Binding use () paranthesis.**

Let's say **If i click on a button 'Add' only then data will be binded to html template.**

You can use Event Binding here like this:

**In your ts file**

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

here you can see,initially name is not set to 'deepa' but inside onClick() method we are doing that.

**We'll call this method by event binding like this:**

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


  
Here in this case,**name will set to 'deepa' only after calling the method this is called event binding.**


_Thanks for reading,Please like share and save if it helped you :)_
LOVE WORK ANY TYPE OF COMPUTER RELATED
Tags: computerscience, design, webdev
Published: 2022-06-18 18:47:13

********
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/33k962e5itcl3yi8wfog.jpg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1h7m4z3k5xuanh1j2vdn.jpg)
Code Smell 141 - IEngine , AVehicle, ImplCar
Tags: webdev, javascript, beginners, programming
Published: 2022-06-18 18:34:05

*Have you ever seen an IEngine in the wild?*

> TL;DR: Don't prefix or suffix your classes

# Problems

- Readability

- [Bijection](https://dev.to/mcsee/the-one-and-only-software-design-principle-3086) Fault

- Implementative Names

# Solutions

1. Remove prefixes and suffixes

2. Name your objects after what they do

# Context

Some languages have cultural conventions related to data types, Abstract classes, or Interfaces.

These names load our models with cognitive translations hard to follow. 

We must [KISS](https://en.wikipedia.org/wiki/KISS_principle).

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/00b852bfb884a47c5d7adf0543ec3a61)
```java
public interface IEngine
{
    void Start();
}

public class ACar 
{

}

public class ImplCar 
{

}

public class CarImpl
{

}
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/4507889577dd937dda844b8119782a50)
```java
public interface Engine
{
    void Start();
}

public class Vehicle 
{

}

public class Car 
{

}
```

# Exceptions

In C# it's a common practice to put "I" in the name of an interface because without it, you can't tell whether it is an interface or a class.

This is a language smell.

# Detection

[X] Automatic  

If we have a Thesaurus we can point to awkward names.

# Tags

- Naming

# Conclusion

Use real names for your models.

# Relations

{% post https://dev.to/mcsee/code-smell-130-addressimpl-b46 %}

# More Info

- [What is in a name: Part II Rehab](https://dev.to/mcsee/what-exactly-is-a-name-part-ii-rehab-20gd)

# Credits

Photo by Tim Mossholder on Unsplash

* * *

>Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.

_Jamie Zawinski_
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
Minimum Domino Rotations For Equal Row
Tags: leetcode, dsa, theabbie
Published: 2022-06-18 18:30:38

In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)

We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values.

Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same.

If it cannot be done, return `-1`.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/05/14/domino.png)

**Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\]
**Output:** 2
**Explanation:** 
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.

**Example 2:**

**Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\]
**Output:** -1
**Explanation:** 
In this case, it is not possible to rotate the dominoes to make one row of values equal.

**Constraints:**

*   `2 <= tops.length <= 2 * 104`
*   `bottoms.length == tops.length`
*   `1 <= tops[i], bottoms[i] <= 6`

**SOLUTION:**

    class Solution:
        def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:
            n = len(tops)
            minSwaps = float('inf')
            for v in range(1, 7):
                pos = True
                currtopswaps = 0
                currbottomswaps = 0
                for i in range(n):
                    if tops[i] != v and bottoms[i] != v:
                        pos = False
                        break
                    else:
                        if tops[i] != v:
                            currtopswaps += 1
                        if bottoms[i] != v:
                            currbottomswaps += 1
                if pos:
                    minSwaps = min(minSwaps, currtopswaps, currbottomswaps)
            return minSwaps if minSwaps != float('inf') else -1
What’s your latest side project ?
Tags: discuss, java, webdev, career
Published: 2022-06-18 18:12:26

Tech and market has been changing crazy these days. What is your latest side hustle ? 

I will start with mine: 
Started a blog for tech and important interview tips.

https://tipseason.com/

Collecting top coding questions for interviews in one place:

https://tipseason.com/coding-interviews.html  

What’s yours ?