teleren/devto huggingface dataset:
How to change the type of output object for a .filter()
Tags: typescript
Published: 2021-01-31 10:55:18

---
title: How to change the type of output object for a .filter()
published: true
date: 2021-01-30 17:12:33 UTC
tags: #typescript
canonical_url: https://darraghoriordan.com/2021/01/30/typing-output-of-a-property-filter-typescript/
---

If you have an iterable filter on a property in typescript you might have a slightly different model coming out of the filter based on the filter condition.

By setting the types correctly you can potentially save having to add manual typing hints in whatever follows the filter.

It’s easier to show this with code so see below!

Thanks to one of my colleagues for suggesting this one in a code review.

<!-- end excerpt -->
## The problem

```typescript 
type Car = {
  brand: string,
  color: string,
  tireWidth: number.
  spareTire?: SpareTire // note this is optional
}

// If we have this filter where we filter out the items where a property is undefined.
// Then we know that the property must be defined in the map. But the typescript type will still
// be undefined so we have to supply a hint ("!") to tell typsctipt our property is present
 const spareTireInfo = myCars
            .filter(
                (car) =>
car.spareTire !== undefined
            )
            .map(
                (car) =>
                    ({
                        spareTireAge: car.spareTire!.age //here we have to hint the undefined property is present
                        tireWidth: car.tireWidth
                    } )
            );
```

This isn’t too bad here with just one property being accessed but it would be tedious if you had more. It’s also an issue if you use eslint and warn on unnecessary type assertions (like ”!”). If you do that you have to add an ignore for each property.

We can prevent this by specifying the type expected from the filter.

```typescript
type Car = {
  brand: string,
  color: string,
  tireWidth: number.
  spareTire?: SpareTire // note this is optional
}

type WithSpareTire = {
    spareTire: SpareTire; // note this is not optional anymore
};

const spareTireInfo = myCars
            .filter(
                (car): car is Car & WithSpareTire => // here we hint the output type
car.spareTire !== undefined
            )
            .map(
                (car) =>
                    ({
                        spareTireAge: car.spareTire.age // now we don't have to provide the "!" hint anymore
                        tireWidth: car.tireWidth
                    } )
            );
```

Hope it helps!
Rounded edges on table rows
Tags: beginners, codenewbie, css, tip
Published: 2021-01-30 17:11:01

To add border radius to a table row `tr`, you have to specifically target the first table data `td` on the row and the last.

```css
tr{
  border-radius: 10px
}
```
This wont work..

Instead do this: 
```css
// Set border-radius on the top-left and bottom-left of the first table data on the table row
td:first-child,
th:first-child {
  border-radius: 10px 0 0 10px;
}

// Set border-radius on the top-right and bottom-right of the last table data on the table row
td:last-child,
th:last-child {
  border-radius: 0 10px 10px 0;
}
```

Checkout the codepen below
{% codepen https://codepen.io/temmietope/pen/RwoNbQb default-tab=js,result %}
Launched a new theme for VSCode today
Tags: showdev, vscode, theme
Published: 2021-01-30 17:08:23

---
title: Launched a new theme for VSCode today
published: true
description: Launched a new theme for VSCode
tags: showdev, vscode, theme
cover_image: https://static.crucialhuman.com/images/vscode-theme-banner.png
---

Hello everyone! I launched a VSCode theme that my team uses internally. I've had several people ask about it in the past and finally got around to making it available to the public.

I launched it on Product Hunt today and it would be awesome if you checked it out and tried it out yourself! -> [Crucial Human Theme for VSCode](https://www.producthunt.com/posts/crucial-human-theme-for-vscode)

Here's some previews and I hope you enjoy it! 😎

###JavaScript
![Crucial Human Theme for VSCode](https://static.crucialhuman.com/images/crucialhuman-vscode-shadow.png)

###CSS
![Crucial Human Theme for VSCode](https://static.crucialhuman.com/images/crucialhuman-vscode-css-shadow.png)

_Font used in previews is Fira Code_
How to co-install composer 1 and composer 2
Tags: composer, drupal, docker, php
Published: 2021-01-30 17:03:28

If you followed the steps at [How to set-up a Drupal or WordPress site locally using Docker](https://dev.to/davo20019/how-to-set-up-a-drupal-or-wordpress-site-locally-using-docker-edi) to set-up a local Drupal 8 site using docker, you will find that the PHP container has composer2 and that Drupal 8 is not compatible with it.

The easiest way to get composer 1 up and running when one already has composer 2 installed is by running this command: `composer self-update --1` It will replace composer 2 completely though.

If for some reason you need to have both composer 1 and composer 2 co-installed you can run these simple commands in the terminal (Assuming you have composer 2 already working):

```
sudo cp `which composer` /usr/local/bin/composer1 && sudo composer1 self-update --1

sudo composer self-update --2 && sudo ln -s `which composer` /usr/local/bin/composer2

```
After running the commands above you should be able to run `composer1` or `composer2` instead of just composer, based on one's needs.

Example to use composer 1:

```
composer1 install
```

Example to use composer 2:

```
composer2 install
```
#100DaysOfCode (Todo App React Hooks & REDUX)
Tags: 100daysofcode, react, redux, javascript
Published: 2021-01-30 16:52:22

today is the day 41 of my challenge #100DaysOfCode 😍

Todo List App Using React Hooksn Redux, Styled Components, SweetAlert2 & LocalStorage 😎

Demo : https://react-js-todos.netlify.app/
Repo: https://github.com/saidMounaim/100DaysOfCode/tree/main/Day41

#100DaysOfCode Challenge Repo : https://github.com/saidMounaim/100DaysOfCode
Qui est Angel?
Tags: fr
Published: 2021-01-30 16:49:21

## **Angel Ismael Rodríguez Arévalo**
[Porfolio Personnel](https://angelprojects.ca/)

## Bonjour à vous
Bienvenu à mon premier post sur `Dev.to`. Ce post sera uniquement une présentation de qui je suis, d’où je viens, qu'est-ce que j'en deviens, etc. Enjoy!

## Mes débuts
J'ai débuté en informatique environ à l'age de 6 ans quand j'ai connu Ubuntu avec mes cousins (maintenant devenus des ingénieurs informatiques). J'ai commencé à apprendre les distro Linux _"inside-out"_
> Ubuntu, Lubuntu, Xubuntu, Fedora, etc.

![test](https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fsabza.org%2Fwp-content%2Fuploads%2F2008%2F03%2Fubuntu-hardyheron-screenshot.png&f=1&nofb=1)

Dans les années qui ont suivi, j'ai continué ma découverte des nouveautés dans l'informatique tel que le site Web pas très connu à l'époque **Facebook**, m’emmenant a créer un compte en 2008.

La même année, le film Iron Man sort et me donne encore une plus grande passion envers la technologie, j'avais envie de construire mon propre JARVIS.

#### En 2010, je déménage avec ma famille nucléaire pour nous installer a Montréal.
3 années après j'apprends à programmer en LUA.

## Ma formation
En 2018, je débute une formation technique en développement au cégep de Rosemont ce qui me permets d'apprendre l'algorithmie de base, la planification de développement et des différents langages de programmation tels que:
* Python
* Java
* C#
* Javascript
* TypeScript
* PHP

## Projets en développement
A part les projets académiques, je développe aussi:
- Un système de reconnaissance vocal et visuelle, de chatbot, d'automatisation de la maison ansi que de synthèse vocale. Une sphère qui me fait sortir de ma zone de confort en raison de mon peu de connaissances dans le sujet du `Machine Learning`
- Une solution informatique pour le système de la santé dans mon pays d'origine (développé conjointement avec des ingénieurs informatiques)

## Intérêts
Mes intérêts les plus grands sont dans:
- L'automatisation (peu importe les tâches à automatiser)
- La collecte d'informations
- La sécurité informatique
- L'apprentissage en continu

En raison de mes intérêts et la grande nuisance que la combinaison de ces trois premiers peuvent être envers la vie privée, il est essentiel que
1. Je fasse excellente preuve d'une bonne moralité et des bons choix éthiques
2. Que je travaille pour une entreprise qui peut légitimer et légaliser ces actions 

## Mot de fin
Quoique mes plus grands intérêts sont listés, ceci ne veut pas dire que je n'ai des yeux que pour celles-ci. En informatique il est important de garder une vision périphérique. Par conséquent, attendez-vous à n'importe quoi **d’intéressant** pour mes futurs posts.
Avoid distractions with Flow and Forest App
Tags: zen, productivity, webdev
Published: 2021-01-30 16:38:27

## Flow

Flow is a minimalistic pomodoro based focus timer with simple design and can block apps or websites to prevent distractions.

![Alt Text](https://flowapp.info/wp-content/uploads/2020/01/Flow-App-MacOS.svg)

![Alt Text](https://flowapp.info/wp-content/uploads/2020/08/App-Blocker.svg)

Link : [https://flowapp.info/](https://flowapp.info/)

## Forest App

Forest is an app helping you stay away from your smartphone and stay focused on your work.

![Alt Text](https://www.forestapp.cc/img/og/en.png)

![Alt Text](https://i0.wp.com/www.botany.one/wp-content/uploads/2019/01/Forest-Development.jpg?ssl=1)

Link : [https://www.forestapp.cc/](https://www.forestapp.cc/)
Lazy loading image
Tags: javascript, react
Published: 2021-01-30 16:35:17

---
title: Lazy loading image
published: true
description: 
tags: javascript,react
cover_image: https://images.unsplash.com/photo-1580894896813-652ff5aa8146?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80
---

Have you ever wondered what type of magic shows in the platform like [Medium](https://medium.com/) to render the image

First, the image is blurred and after sometime image, the whole image is loaded

How this is happing ????

Two images are being rendered the first one with low-resolution but with the exact width and height of the original image, and in parallel, we are loading the original image with full resolution and when the images are loaded, the low-resolution image is replaced with the full resolution image

TADA...

but let's hold for a sec how we can achieve this one in code

```js
import { useEffect, useState } from 'react'

const useLazyImage = (src: string): useLazyImageProps => {
  const [sourceLoaded, setSourceLoaded] = useState<string | null>(
    null,
  )
  const [loading, setLoading] = useState<boolean>(true)

  useEffect(() => {
    const img = new Image()
    img.src = src
    img.onload = () => {
      setLoading(false)
      setSourceLoaded(src)
    }

    return () => {
      img.remove()
    }
  }, [src])

  return {
    loading,
    src: sourceLoaded,
  }
}

interface useLazyImageProps {
  loading: boolean
  src: null | string
}

export default useLazyImage
```

there are a hell of a lot of things that are going on here let go through one by one 

`useLazyImage` is a hook that accepts the address of the full resolution image and returns the loading true/false and src 

while mounting the component it creates the img element with the address of the image and when the image finishes it loading we set the loading to false via onLoad event and remove the img node on un-mounting the node.

is-it simple 

Let me know down in the comments
20 Days of CSS animation post💪
Tags: css, html, beginners
Published: 2021-01-30 16:26:25

Hey, Folks, I have just started learning CSS Animation from [Scrimba](https://scrimba.com/learn/cssanimations) and the instructor is so good named Jad Khalili. The course is absolutely free and next few days I will learn whatever in this course, I'll share with you. And one biggest reason for sharing this learning with you guy's that I have read somewhere that when we share our knowledge with another person it will store in your mind in a better way.

So I'll share everything here with you :)
How javascript code is executed
Tags: javascript
Published: 2021-01-30 16:24:39

Everything in JavaScript happens inside an "**Execution Context**”. Whenever a JavaScript program is run an execution context is created.

```javascript
var number=10; 	//line1	
function add(n)	//line2
{		        //line3
var result=n+n;	//line4
return result;	//line5
} 

var result1=add(4);	//line6
```

when we run the above code, a **global execution context (GEC)** is created. It is created in two phases:

**1)Creation Phase or Memory Creation**

In this phase, javascript allocates the memory to all the variables and functions present in the program. The variables are stored with the value *undefined* and the function is stored with all the code present in that particular function. For the above code, the variable number is stored with the value *undefined* and the function add is stored with value b/w the {...} curly braces. The result1 is also a variable so it is stored with the value *undefined*. 

**2)Code Execution Phase**

In this phase the main execution takes place and the javascript runs through the code line by line. Now the *number* value is changed from *undefined* to *10*. Then it moves to the next line as there is nothing to execute it moves to line 5. In line 5 function invocation takes place. When a new function is invoked a new execution context is created within the GEC.

Now the again above process is repeated with the two phases but for only the add function. After the function is executed completely, the execution context created for that particular function will get deleted automatically.

Now, when the whole javascript program is executed completely the GEC will also get deleted. 

A **Call stack** is also maintained by javascript. Call stack maintains the **"Order of execution of execution contexts"**. It works similarly as a stack whenever a new function invoked its execution context is pushed into the call stack.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/836mfeh1nyfu7j2me73b.png)
The GEC is at the bottom of the call stack as it is created at the starting of the program and all the new execution context is pushed on top of it. So when a function's execution gets finished its execution context is also removed from the call stack.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/836mfeh1nyfu7j2me73b.png)


I hope you would have found this article beneficial.
Thank you for reading through this article.
Create a Word and Character counter using HTML CSS  Tailwind JavaScript
Tags: html, javascript, css, codenewbie
Published: 2021-01-30 16:23:59

Create a Word and Character counter using HTML CSS  Tailwind JavaScript
<img src="https://i.postimg.cc/BQftbNbn/screenshot-codepen-io-2021-01-30-21-10-26-621.png">

Source Code ==> https://codepen.io/Bilal1909/pen/KKNKjWB

Fully responsive.
Scales with its container.
Separate settings per breakpoint
Uses CSS3$ Tailwind & Javascript when available.
Fully functional when not.
Check it out 
Tags: cartoon, animation, codepen, css
Published: 2021-01-30 16:18:14

Could you guys like my codepen and follow me. I promise I am gonna make you happy with my new codepens! ❤❤❤❤❤❤❤❤❤❤❤❤❤

https://codepen.io/ahmed364051/pen/MWbgReK

Thanks a lot!)
Roadmap to improving your Agile QA Toolkit
Tags: testing, beginners, career
Published: 2021-01-30 16:10:11

An Agile QA does more than write test cases or execute them. They participate in activities such as "Estimating Stories" and "Backlog Grooming", interact with developers, attend daily scrum and sprint-planning sessions and they AUTOMATE. 

QA's are expected to be knowledgeable on the different tools and methodologies used, find the root cause, bringing fresh ideas and perspectives while still ensuring that releases are sent out on time. 

How do you set yourself up for success or make an impact? An Agile QA toolkit will allow you to be knowledgeable in the right areas, think quickly on your feet, be ready to grasp promotion and opportunities for growth as well as be confident and efficient in carrying out tasks. You will gain applicable knowledge about automation tools, testing concepts and approaches as well as be able to better handle challenges, be more prepared and empowered for change.

Join me as I walk you through my journey to being an impactful QA as well as give you a guide on how you can create your toolkit to be impactful.

You will take the following from the talk: 
1. Being ready for change and applying lessons from past projects to future projects.
2. Testing tools and approaches needed for a consultant toolkit (Getting Started and improving on what you have)
3. Be prepared to grab opportunities and grow as a QA Consultant

{% youtube opYugfaD2WY %}
How to install Tailwind CSS with your react project
Tags: react, javascript, css, tailwindcss
Published: 2021-01-30 16:00:10

**Introduction**: Tailwind CSS is a class-based UI CSS framework to design your websites, the way you want within shortage amount of time. I found that it is pretty tricky to embedded with react project.
Now we will see how we can install Tailwind CSS in your project by following some steps. So let’s get started…

I will add a [link](https://github.com/CsAlkemy/react-tailwind-starter) to the GitHub repository of the ReactJs & tailwind starter. You can clone and start without the hassle of setup.
*Just make sure you have installed Node.Js 12+ and React CLI.*

####1. Create React App
We will start by creating React project By create-react-app and cd into the newly-created directory. If you have already done this you can skip it.
```bash
$ npx create-react-app my-project
$ cd my-project
```
####2. Install Tailwind
**Install Tailwind via npm** (node package manager)
*You will need Node.js 12 or higher.*

Install tailwind with other dependencies using
```bash
$ npm install tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
```
*As react doesn’t support postcss8 so we will install postcss7.*

**Install CRACO**
CRACO is Create React App Configuration Override, an easy and comprehensible configuration layer for create-react-app. Craco is used for override PostCSS
```bash
$ npm install @craco/craco
```
Once it’s installed, update your ‘scripts’ as below in package.json e

```json
"scripts": {
   "start": "craco start",
   "build": "craco build",
   "test": "craco test",
   "eject": "react-scripts eject"
 },
```
Next, create a ‘craco.config.js’ at the root of our project and add those line:
```javascript
module.exports = {
   style: {
     postcss: {
       plugins: [
         require('tailwindcss'),
         require('autoprefixer'),
       ],
     },
   },
 }
```

**Generate Tailwind config file:**
*Now, Let’s generate your `tailwind.config.js` file:*
```bash
npx tailwindcss init
```
*This command will create the tailwind config file in your root directory.*
And replace this line to remove unused style in production:
```javascript
module.exports = {
 purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
 darkMode: false, // or 'media' or 'class'
 theme: {
   extend: {},
 },
 variants: {
   extend: {},
 },
 plugins: [],
}
```

*Installing is done! Let’s find out, how we can use tailwind classes in your project.*

####Use of Tailwind CSS

**Include Tailwind in your CSS**
Now open your `index.css` and replace it with importing tailwind base, components, utilities

```javascript
@tailwind base;
@tailwind components;
@tailwind utilities;
```


Include index.css.
Make sure you include or import `index.css` in your parent index.js file. 
```javascript
import './index.css';
```
*We are finished now. Create a component using Tailwind CSS and add it to your `index.js` for test.* 
Run your project using 
```bash 
`npm run start`
```

I hope you find this article helpful. This is my very first writing experience in dev.to.

Happy Coding!
How to become an effective programmer?
Tags: discuss, watercooler, codenewbie, beginners
Published: 2021-01-30 15:43:44

**How to become an effective programmer?**

I know many of has have this question in our minds especially students and people who are new to coding. Now just like any other skill, coding doesn't have a right or wrong way of learning. This is one of the reasons it's easy to get misguided as a beginner. 

So what it actually takes to be an **effective programmer?**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/d4tvukbt5mra37cvwklk.gif)

# My take on this

---

Here are few tips which have helped me to improve both as a dev & as a student:

- Start learning about Data Structures & Algorithms early (start with basics)
- Don't skip the maths (knowing basics can go a long way)
- Start building things (learn as you go)
- Collaborate & Code
- Participate in coding competitions & hackathons
- Build an online presence with a developer profile

# Discuss

---

Feel free to share your own tips which have helped you to improve as a developer in the **discussion/comments**.
Web Monetization serves as a new revenue model for content creators and software developers.
Published: 2021-01-30 15:35:59

If you are a content creator looking for the convenient and most effective way to grow your revenue on the web then you must understand Web Monetization and how it can assist you to make a fair amount of money.

Web Monetization is an API that allows websites to request a small amount of payments from users facilitated by the browser and the user's Web Monetization provider. It is a new revenue collection model for the content creators which considered and saves users time and headache, of having to deal with so many subscriptions, whenever they visit the website or block in order to consume the content and it also helps by removing the unnecessary ads, which does not form part of the content the user needs, meaning the users get value for their money by consuming the quality content.

To take advantage of this amazing emerging technology and receive payment for the work you have done, one needs to have a digital wallet that supports the Interleger Protocol (ILP). Currently there are only two options which are Uphold and Gatehub, but in near future hopefully there will be more options. There is no need to register for both wallets, you only need to choose one that you prefer and after registering you will get a payment pointer, which serves as your unique address for all your payments.

What is even more interesting about this technology is that all the transactions on both sides of the user and the content creators are processed and handled automatically by the web monetization provider which makes payment on behalf to the user and web monetization receiver which receives payments on behalf of the website, without any user interaction. Web monetization is still at an early stage of adaptation but due to many benefits that it offers to both content creators and users it is believed that in the coming near future it is going to dominate and take over the web industry.

What is even more interesting about this technology is that all the transactions in both side of the user and the content creators are processed and handled automatically by the web monetization provider which makes payment on behalf to the user and web monetization receiver which receives payments on behalf of the website, without any user interaction. Web monetization is still at early stage of adaption but due to many benefits that is offering to both content creators and users it is believed that in the coming near future it is going to dominate and take over the web industry.