teleren/devto huggingface dataset:
Understanding Unit Test From The Best Book On The Topic
Tags: testing, books
Published: 2022-01-06 13:36:20

Learning to write good and effective unit tests is very hard. Because of it, I used to tell myself that if I follow best practices, adopt good software architecture and patterns, break code into manageable and straightforward code pieces, I don't need tests and could produce the same quality software. It's a lie. Writing good tests is the only thing that can lead us to best practices, to suitable architectures and patterns.

I now religiously believe that it is a good test suite that defines the quality of any software. What is a good test? To answer this question, we must break the question into two questions: What is a unit test? What makes a test a good test?

There are many answers out there. The best answers are below, from the book "UNIT TESTING: PRINCIPLES, PRACTICES, AND PATTERNS" by Vladimir Khorikov.

**What is a unit test?**

 A unit test is a test that
* Verifies a single unit of behaviour,
* Does it quickly,
* And in isolation from other tests.

**What makes a test good?**

 A good unit test has the following four attributes
* Protection against regressions
* Resistance to refactoring
* Fast feedback
* Maintainability

There we have it. A unit test verifies a single unit of behaviour, not a single piece of code, not a single class, not a single function etc., but a single unit of behaviour.

To do this, we must be mindful of the following:

1. Try to get as close to an actual business use case as possible and as far as possible from implementation details. Mimic user actions and assert user expectations. Never assert what the code should do internally. It is worth to mention that for JavaScript, the library `@testing-library` embraces and enforces this principle.

1. Isolate business logic to pure functions/methods (without side effects, given the same input, they always return the same output). Use pure functions anywhere when possible because Input/Output based tests are the best tests.

1. If one behaviour is too complicated to test, break it up. Ok, I tried my best, but it is still not easy to test? There is more room for improvement. Keep trying until they are easily testable.

1. Only mock external unmanaged dependencies if possible. If not, do not assert against managed dependencies

1. If it's not a behaviour, don't test it.

**Beware, bad tests are worse than no tests!** 

If tests verify a single piece of code and assert what they do internally, they are pinning down the implementations. It is the worst thing that could happen to a project. They don't help deliver what the software is supposed to do for its users. They make the code base impossible to refactor hance hinder the team's ability to improve the software and add/change features. It is a waste of time to write them. It is worse than no tests at all.
Hover on Duration on Gradients? | TailwindCSS
Tags: tailwindcss, question, issued
Published: 2022-01-06 14:48:04

I have created a website and those containers that are in **gradients** when it's hovered. The `duration-300` just doesn't apply to it. Here is the website [Website](https://zytha.ml) 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lavqhfqhwi2nu77vvnkx.png)
Remove Vim Tab Characters
Tags: vim, linux, todayilearned
Published: 2022-01-06 14:43:56

---
canonical_url: https://waylonwalker.com/til/remove-vim-tab-characters/
cover_image: https://images.waylonwalker.com/til/remove-vim-tab-characters.png
published: true
tags:
- vim
- linux
- til
title: Remove Vim Tab Characters
series: til
---

I've been stuck many times looking at a vim buffer with little question marks at the beginning of each line and trying to get rid of them.  for so long I didn't know what they were so trying to get rid of them was impossible.

![example of what the tab character renders as in my editor](https://images.waylonwalker.com/vim-tab-characters.png)

It turns out they are tabs, and you can get rid of the little leading question marks with this substitution command.

``` vim
:%s/\t/    /g
```

---

This is a til (today I learned) I'm posting them on my [website](https://waylonwalker.com/til/) and to twitter's [#100daysoftils](https://twitter.com/hashtag/100daysoftils)
CSS Shorts: Lets Build a Custom Scroll bar
Tags: webdev
Published: 2022-01-06 14:42:43

Lets face it. We as developers and designers spends hours on designing the webpage that should looks good, feels good and drive sales/convert customer. We spends hours on micro-animations. Then Why not design the scroll too.  In this artile I'll show you how to do that. 

The scrollbar has basically 2 components. That is `scrollbar-track` and `scrollbar-thumb`. 
And we need to tweek `::-webkit-scrollbar` pseudo element to modify the look of the browser's scrollbar. 

Here the code that you need to design a simple scrollbar which has a width of 10px, A black trackbar and a red thumb. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k6e06t3irmdwy6cb6nj0.png)
 
```css
::-webkit-scrollbar {
    width: 10px;
  }
  
  ::-webkit-scrollbar-track {
    background: #ff2b2b;
  }
  
  ::-webkit-scrollbar-thumb {
    background: #ff5252;
  }
```

That's it? Well you can use `vertical-scroll::-webkit-scrollbar-track {}` to design the horizontal scrollbar. 
You can use other css properties `background`, `border-radius`, `box-shadow` and similar.
11ty: Inject SVG code using Shortcodes
Tags: 100daysofcode, webdev, javascript, tutorial
Published: 2022-01-06 14:33:59

Create a `{% svg %}` shortcode to inject SVG icons, images, or illustration directly into your template.

Open the `.eleventy.js` config file and add the following code at the top of the page:

```js
const fs = require('fs');
```

Inside the Eleventy config create a new function that will get the SVG contents:

```js
function eleventyConfig(config) {
   let getSvgContent = function (file) {
      let relativeFilePath = `./src/svg/${file}.svg`;
      let data = fs.readFileSync(relativeFilePath, 
      function(err, contents) {
         if (err) return err
         return contents
      });

      return data.toString('utf8');
   }
}
```

Next, create the new shortcode using the `addShortcode` function, like so:

```js
config.addShortcode("svg", getSvgContent);
```

Create a new folder in the `src` folder, name it: `svg`, and add a new vector file with the `.svg` extension.

To use it in your templates, simply add the new shortcode tag and the file path:

```html
{% svg "myfile" %}
```

If you want to use subfolders:

```html
{% svg "subfolder/myfile" %}
```

Notice, we are only using the subfolder and file name, without any extension. That is because in our function we are doing this automatically.

That's it!

---

### The full code

```js
const fs = require('fs');

function eleventyConfig(config) {
   let getSvgContent = function (file) {
      let relativeFilePath = `./src/svg/${file}.svg`;
      let data = fs.readFileSync(relativeFilePath, 
      function(err, contents) {
         if (err) return err
         return contents
      });

      return data.toString('utf8');
   }
   
   config.addShortcode("svg", getSvgContent);
}

module.exports = eleventyConfig;
```

### Thanks for reading

Feel free to change it however you need. Don't forget to like, share, and comment ✌️
How to Find a Windows 10 Product Key
Published: 2022-01-06 14:29:33



First, press the Windows key, search for "cmd", and click on "Run as administrator":

```
`wmic path softwarelicensingservice get OA3xOriginalProductKey`
```


Reference   
https://www.freecodecamp.org/news/how-to-find-a-windows-10-product-key/
Fundamentos de TypeScript 🦆| #4: Tuplas
Tags: typescript, webdev, spanish, beginners
Published: 2022-01-06 14:28:57

Las tuplas en esencia **son arreglos**, pero **arreglos limitados a cierta cantidad de elementos y a ciertos tipos de datos**.

## **Sintaxis**

```js
const nombreVariable:[tipoDato1, tipoDato2, ...tipoDatoN] = [valor1, valor2, ... valorN];
```
## **Funcionamiento**
Por ejemplo, podríamos tener una tupla `temperatura` de 2 posiciones, que contega la temperatura y su unidad de medida:

```ts
const temperatura:[number, string] = [20,"C"];
```

Esta tupla solo puede contener 2 elementos, el primero un `number`, y el segundo un `string`, exactamente en ese orden.
Si tuvieramos la tupla invertida tendríamos un error:

```ts
const temperatura:[number, string] = ["C", 20];
```
Estamos tratando de asignar un tipo `string` a un tipo `number`, por ello nos arroja una advertencia como la siguiente:

> *Type 'string' is not assignable to type 'number'.*

Ahora, si intentamos agregar más de 2 elementos al ejemplo anterior, por más que sean del tipo de dato permitido, este arrojará un error:

```ts
const temperatura:[number, string] = [20, "C", 23, "F"];
```

> *Type '[number, string, number, string]' is not assignable to type '[number, string]'.
Source has 4 element(s) but target allows only 2.*

Para solucionarlo tendremos que añadir más tipos, de la siguiente manera:

```js
const temperatura:[number, string, number, string] = [20, "C", 23, "F"];
```

## **Caso especial**
¿Qué pasaría si intentamos usar un `push` en una tupla?
¿Debería dar un error no es verdad?
Pues no lo hace.

```ts
const temperatura:[number, string, number, string] = [20, "C", 23, "F"];

temperatura.push(30)
//salida: [20, "C", 23, "F", 30];
```

Este ejemplo es totalmente válido.

---

## **Conclusiones**
- Las tuplas son arreglos pero son datos específicos.
- Permiten crear arreglos con valores concretos y tipos exactos en cuanto a posiciones se refiere.
- Son más rápidos que los arreglos tradicionales.

## **Referencias**


{% youtube BwuLxPH8IDs %}
Python challenge_13
Tags: python, beginners, programming, tutorial
Published: 2022-01-06 14:28:38

##Consecutive zeros

The goal of this challenge is to analyze a binary string consisting of 
only zeros and ones.

Your code should find the biggest number of consecutive zeros in the string.

###For example:
 
given the string "1001101000110" The biggest number of consecutive zeros is 3.

Define a function named consecutive_zeros that takes a single parameter, 
which is the string of zeros and ones.

Your function should return the number described above.
All the best to you.


####My Solution
```
def consecutive_zeros(binary_string):
    binary_list = binary_string.split('1') # ['', '00', '', '0', '000', '', '0']
    biggest_number = max(map(len, binary_list))
    return biggest_number
print(consecutive_zeros("1001101000110"))

```

####Aother solution
```
def consecutive_zeros(bin_str):
    result = 0
    streak = 0
    for letter in bin_str:
        if letter == "0":
            streak += 1
        else:
            streak = 0
        result = max(result, streak)
    return result
```

####shorter solution
```
def consecutive_zeros(bin_str):
    return max([len(string) for string in bin_str.split("1")])
```

All the best to you.
🎬Top 10 CSS & JavaScript Projects🙌
Tags: html, css, beginners, javascript
Published: 2022-01-06 14:25:38

**Top 10 CSS & JavaScript Projects** that will help you test your knowledge and use muscle memory in creating them.

***

{% youtube xhaq1YhelIw %}

***

  We will see from the simple HTML (markup) as well as its presentation layer, adding beauty to your pages, going beyond that adding effects such as hover effects and others.

  Lastly we have more intermediate projects, we'll see how to manipulate CSS at our leisure using Javascript, making our sites really interactive.
Tech conferences list: how to find the next tech conference?
Tags: dev, github
Published: 2022-01-06 14:20:23

---
title: Tech conferences list: how to find the next tech conference?
published: true
description: All the tech and developers conferences list and agenda (CFP)
tags: Dev, GitHub
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fwoovj9qm3qngl7i0r2r.png
---

As an organizer, speaker, attendee or sponsor, have you ever ask when and where the next tech conferences will be happen?
And as a speaker maybe you want to submit your last talk, but where and when?

In 2017, several years back!, I created a Git repository on GitHub titled ["Developers Conferences Agenda/List"](https://github.com/scraly/developers-conferences-agenda/).

{% github scraly/developers-conferences-agenda no-readme %}

## Goal

The goal of this repository was to: "list a maximum of conferences date in order to help conferences organizers/speakers/sponsors/attendees.

As a conference organizer, we always ask us what will be the perfect date for the event?

A data to take in account is the date of others events, but how to find this?

As a developer, a technical lover, an attendee, we want to have a calendar, we want to know when will be the next event.

And as a speaker, do you ask yourself what are the dates of the next CFP (Call For Paper)? What is the date and place of the next conferences?

![CFP](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p3kgr1k1okn9mb1wtoh4.png)

I propose to you this GitHub repository in order to list all conferences for developers in France, Europe and world."

## Want to contribute?

I try to maintain and continually update this repository, but if you find any missing conferences you can easily contribute. Just add an event or your event. For that, just do a [Pull Request (PR)](https://github.com/scraly/developers-conferences-agenda/pulls) in order to update this developers conferences agenda.

If everybody contribute to this repository, it can really help conferences organizer. If they don't know your conference they can't buy a ticket and come to it 😏. It can also help sponsor: thanks to this tech conferences agenda, they can know which conferences to sponsor. 

## The repository

{% github scraly/developers-conferences-agenda no-readme %}

## Conclusion

In order to help developers and tech lifetime it can be easy. No need to create the future Javascript framework, no need to understand all the concepts of Kubernetes and Docker.

But the power is in your hands, you can add a star to this simple repository, share it, contribute it and create your own repositories and projects :-).
Access Localhost from Smartphone with help of VS Code and Live Server
Tags: webdev
Published: 2022-01-06 14:09:36

Responsive Web design, well I know the developer console is a greater tool for debugging. and it gives you an option to check the responsiveness of your webpage. but checking it on a real device is always better.
So how to do it without too much hassle? The simple answer is with help of VS Code and Extensions called Live Server.

Before proceeding make sure your laptop and mobile device are connected to the same wifi.

For this, you need to install VS Code from [here](https://code.visualstudio.com/). And Live Server Extensions by Ritwick Dey from [here](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer).

After installing open your project folder on VS Code. You can do it by "drag-and-drop" or by navigating to "`File > Open Folder`".

Then open `index.html` and right-click on Editor, from the "Explorer Window" choose "Open with Live Server". 

![vs-code-open-with-live-server.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cm9tzw70odf2o5gssuds.jpg)
 
Remember the port, on which the live server is running. 

![live-server-ip-address.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4g1yqech1wb19osgmoot.jpg) 

 
Now open "Command Prompt" on windows and type `ipconfig` hit Enter. Check the IP Address. 


 
Now open your favorite browser on your smartphone and on the address bar enter the IP Address of your Computer and port of the local server. after that file name. like `http://ip_address:port/filename` for example, mine would be: `http://196.168.43.14:5500/index.html`

![live-server-mobile-preview.jpeg](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uagr1oghtr63qv0fcitz.jpeg)
Plutónio – Tirar Bilhete 
Published: 2022-01-06 13:58:26

O Músico Luso-moçambicano Plútónio acaba de lançar mais uma bomba no mercado. A mesma intitula-se "Tirar Bilhete".



A música foi lançada no final do ano passado, em parceria com o DJ Dadda. 



O jovem rapper voltou a não decepcionar. Aliás ele já nos acostumou a cantar músicas que facilmente vão parar na boca do povo e dificilmente saem.



Amúsica "Tirar Bilhete" já tem um vídeo clipe lançado no Youtube. Segundo fontes o mesmo foi gravado no bairro mais perigoso de Badajoz (Espanha), que faz fronteira com Elvas (no sul de Portugal).


Consigo, o artista levou toda a “sua tropa”, incluíndo a Pluma, que realizou o vídeo.


O artigo [Plutónio – Tirar Bilhete (Download mp3 2021)](mozmassokomusic.com/plutonio-tirar-bilhete-download-mp3-2021/), apareceu primeiro no site [Moz Massoko Music](mozmassokomusic.com).
Fixing Next.js router query param returning undefined on initial render

Tags: javascript, nextjs, react, webdev
Published: 2022-01-06 13:47:40

---
canonical_url: https://dpnkr.in/blog/nextjs-router-query-undefined
description: If you're getting undefined query params in nextjs on the first render and want to fix it then this blog is for you.
---

While building a React application using next.js, I stumbled upon an issue that kept me stuck for a good amount of time. I don't want people to do the same therefore I would be covering the fix in this blog. Feel free to [skip to fix](#fix) if you want to.

## Issue

First, let's just try to reproduce this issue. You might encounter some cases where you need access to query params of a route. Nextjs makes it easy to deal with routes by using the [`useRouter`](https://nextjs.org/docs/api-reference/next/router) hook. Here's an example code that you can place inside the `/pages` directory to try it out.

```tsx
import { useRouter } from 'next/router';
import React from 'react';

const Test = () => {
  const router = useRouter();
  console.log(router.query);
  return <div>Hello World</div>;
};

export default Test;
```

Now let's visit the router with some param and see the logs. In my case, I visited `/test?name=Deepankar`.

```bash
{}
{name: 'Deepankar'}
```

As you can see in the 1st render we don't have the access to the param. So how do we know when the router fields are updated client-side and ready for use?. Now let's look into the fix.

## Fix

`useRouter` hook returns `isReady` field which is a boolean value that denotes if the router fields are updated client-side and ready for use. Accessing `isReady` field should be done inside of `useEffect` methods and not for conditionally rendering on the server.

```tsx
import { useRouter } from 'next/router';
import React from 'react';

const Test = () => {
  const router = useRouter();
  React.useEffect(() => {
    if (router.isReady) {
      // Code using query
      console.log(router.query);
    }
  }, [router.isReady]);
  return <div>Hello World</div>;
};

export default Test;
```

## Reason

Pages that are statically optimized by Automatic Static Optimization will be hydrated without their route parameters provided, i.e `query` will be an empty object (`{}`).

After hydration, Next.js will trigger an update to your application to provide the route parameters in the `query` object.

## References:

- [Next router docs](https://nextjs.org/docs/api-reference/next/router)
- [Dynamic routes caveats](https://nextjs.org/docs/routing/dynamic-routes#caveats)
Comparing text files with diff command
Tags: diff, git, linux, tutorial
Published: 2022-01-06 13:38:03

How would you check the difference between two files with same code? open both files at the same time in editor and look at the each line of code and looking for differences! Maybe you can spot the differences but its not super obvious. its complex and super-prone.
Here is a command called diff which compare the contents of files and write to the standard output the list of changes necessary to convert one file into the other. diff stands for difference and is a Unix base operating system command.
To compare two files, use the following syntax:
`diff [option] file1 file2`
Now lets take a look at 2 Python files using cat command:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tv3xdxa1sbnndp9ahj5t.png) 
Can you find the difference? Lets use diff command to find difference:
`diff file1.py file2.py`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6oaprocdtk4i9w1i5afl.png)
The less than and greater than symbol tells about removed and added to file.
‘c’ means changed. if you saw ‘a’ it means added and ‘d’ stands for delete.
You can use ‘-u’ flag to show the differences in unified format:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c4l03e42rl4kvwklarbc.png)
using the minus sign to mark lines that were removed and the plus sign to mark lines that were added.
There are many tools to compare files, diff is the most popular one. you may also use wdiff, meld KDiff3 or vimdiff.
Migrating Helmet for Express.js from v4.x to v5.x
Tags: helmet, security, express, javascript
Published: 2022-01-06 13:34:58

A routine I have is to go through my (most important) projects I maintain and update the node dependencies to be up to date, this is to ensure that I don't have software running on deprecated and unsecure dependencies.
I also do this quite often as it keeps the upgrade process to a minimum and if something break, it's easier to find what's the cause.
And today, while doing this maintenance, I had a migration issue with a security package I use on all my node.js projects: [Helmet](https://github.com/helmetjs/helmet).

If you don't know what Helmet is, in short, is a package that protects your node server from common http attacks. It's not the only solution you should have and it doesn't shield you from every attack, but it's a good starting point.

In my case I had a problem with an application, which lives in a subdomain, and it needs to access to some scripts from the parent domain.

In version 4.x we had a couple of security features that you had to enable manually, which updated [the headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy) preventing your site to access to any resources outside your current domain.
By default in this version you only needed to disable the `contentSecurityPolicy` with this version to allow your domain to access to CDN content or resources outside your domain.

As I didn't set this feature in my code, no such header was sent and so my site could access to resources from the main domain.

But in version 5.x, now these security features, `helmet.crossOriginEmbedderPolicy()` and `helmet.crossOriginResourcePolicy()` are enable by default, this means that every requests from the Express.js server will return the following headers:

```
"Cross-Origin-Embedder-Policy: require-corp"
"Cross-Origin-Resource-Policy: same-origin"
```

This will prevent any communication between my subdomain and the parent domain or any CDN I need, like Google Fonts for example.

To allow external resources to be allowed from my server, I had to update my Helmet configuration on my server from this:

```javascript
/**
 * Add helmet to prevent XSS attacks
 */
 server.use(helmet({
  contentSecurityPolicy: false,
}));
```

To this:

```javascript
/**
 * Add helmet to prevent XSS attacks
 */
 server.use(helmet({
  contentSecurityPolicy: false,
  crossOriginEmbedderPolicy: false,
}));
```

Essentially what this will do is to set the `Cross-Origin-Embedder-Policy` header to be the default value `unsafe-none`.

Again, if you do not need to access to any resources outside your domain, it's better to enable this security feature.

But if you like in my situation, unless somebody can propose a better solution, the above configuration will let you application to work as before.