teleren/devto huggingface dataset:
Create a custom eslint rule with typescript
Tags: eslint, typescript, tutorial, npm
Published: 2021-04-02 04:06:47

Creating custom eslint rules can often come handy. I enjoy using typescript, so I decided I'd share a way how to use its superpowers to create custom eslint rules.

## Step one

Create a repo and initialise an npm package in it:

```bash
mkdir my-awesome-eslint-rule && cd my-awesome-eslint-rule && npm init -y
```

Make sure your package name starts with `eslint-plugin-`, 'cos _this is the way_, i.e.:

```json
{
    "name": "eslint-plugin-my-awesome-rule",
    ...
```

Install the dependencies (we won't touch @types/estree in this tutorial, but it's quite handy for types when writing eslint rules, so I keep it here):

```bash
npm i -D  @types/eslint @types/estree @types/node tsup typescript
```

Basically we're installing three packages with types definitions, typescript and a _the simplest and fastest way to bundle your TypeScript libraries_ :)

## Step two

We'll be seriously developing, so we'll have a `src` and `dist` folders, for the source and produced output respectively, so let's configure our `package.json` accordingly:

```json
{
    "name": "eslint-plugin-my-awesome-rule",
    "main": "./dist/index.js",
    "files": [
    "dist/**"
    ],
    ...
```

Now let's create the `src` folder with an `index.ts` file as the entry point to our future rule:

```typescript
module.exports = {
    rules: {
        // our rules will go here
    },
};
```

## Step three

Let's create a ~~silly~~ simple rule in our `src` folder. Note, that a rule is a function that accepts `context` and returns rule listener. Both these types we can get from the `eslint`.
For the sake of demonstration let's create a rule that questions every import:

```typescript
// ./src/my-awesome-rule.ts
import { Rule } from "eslint";

export function myAwesomeRule(context: Rule.RuleContext): Rule.RuleListener {
    return {
        ImportDeclaration(node) {
            context.report({
                node,
                message: 'Are you sure about this?'
            })
        }
    }
}
```

Now let's import it into our entry file and plug it in:

```typescript
// ./src/index.ts
import { myAwesomeRule } from './my-awesome-rule';

module.exports = {
    rules: {
      'my-silly-rule': {
        create: myAwesomeRule,
      },
    },
};
```

## Step four

Let's transpile it to js to make it usable. Add a build command to the scripts section in the `package.json` file. We'll be using tsup, which is absolutely awesome for this:

```json
...
"scripts": {
    "build": "tsup src/index.ts --no-splitting --minify"
},
...
```

Run the command to get a minified tiny version of your rule in `dist` folder.

## Step five

Install and enjoy, you can install it directly from the `dist` folder, run `npm pack` to create an archive with your new rule or publish it to npm with `npm publish`.
After installing, don't forget to plug it into your `.eslintrc`, by adding it to the plugins section and activating its rule:

```json
{
    "plugins": ["my-awesome-rule"],
    "rules": {
      "my-awesome-rule/my-silly-rule": "warn"
    }
  ...
  
```

Have fun :)
April 1st, 2021: What did you learn this week?
Tags: weeklylearn, discuss, weeklyretro
Published: 2021-04-02 03:11:46

No it's not an April Fool's joke folks.

<center>

![Rick Astley singing "Never gonna give you up"](https://media.giphy.com/media/kFgzrTt798d2w/giphy.gif)

</center>

It's that time of the week again. So wonderful devs, what did you learn this week? It could be programming tips, career advice etc.

<center>

![Information flowing through your brain](https://media.giphy.com/media/qKltgF7Aw515K/giphy.gif)
</center>

Feel free to comment with what you learnt and/or reference your TIL post to give it some more exposure.

{%tag todayilearned %}

<!--
And remember, if something you learnt was a big win for you, then you know where to drop it as well.👇👇🏻👇🏼👇🏽👇🏾👇🏿

{% link https://dev.to/devteam/what-was-your-win-this-week-145j %}

<center>

![Price is Right contestant celebrating](https://media.giphy.com/media/gF29UEqBhSoDY8LHKg/giphy.gif)
</center>
-->
Code Smell 65 - Variables Named After Types
Tags: codenewbie, codesmells, oop, webdev
Published: 2021-04-02 03:05:47

*Names should always indicate role.*

# Problems

- Declarative

- Design for Change

- Coupling to accidental implementation

# Solutions

1.  Rename your variable according to the role.

# Sample Code

## Wrong

{% gist https://gist.github.com/mcsee/00c30c369fe7339e28d50f858392cf4c %}

## Right

{% gist https://gist.github.com/mcsee/91e3a3f2b1351fa0e09fb8c56a5c2779 %}

# Detection

This is a semantic rule. We can instruct our linters to warn us from using names related to existing classes, types o reserved words since they are too implementative.

# Tags

- Declarative

# Conclusion

The first name we can across is related to an accidental point of view. It takes time to build a theory on the models we are building using our [MAPPERS](https://maximilianocontieri.com/the-one-and-only-software-design-principle). Once we get there, we must rename our variables-

# Relations

{% post https://dev.to/mcsee/code-smell-38-abstract-names-34ng %}

# More info

{% post https://dev.to/mcsee/what-exactly-is-a-name-part-i-the-quest-61k %}

[XUnitPatterns](http://xunitpatterns.com/Intent%20Revealing%20Name.html)

# Credits

Photo by <a href="https://unsplash.com/@sxy_selia">Sangga Rima Roman Selia</a> on <a href="https://unsplash.com/s/photos/name">Unsplash</a>
  
This idea came from this tweet

{% twitter 1377522389312008193 %}


* * *

> Types are essentially assertions about a program.  And I think it’s valuable to have things be as absolutely simple as possible, including not even saying what the types are.

_Dan Ingalls_
You no longer need to import React from 'react'
Tags: javascript, react, jsx
Published: 2021-04-02 03:05:38

---
title: You no longer need to import React from 'react'
published: true
description: If you use React, import React from 'react' is the first thing that you write in your code.
tags: Javascript, React, JSX
//cover_image: https://direct_url_to_image.jpg
---

If you use React, `import React from 'react'` is the first thing that you write in your code but if you have created a new react app using *creat-react-app* recently, you might have noticed that there is no import React statement at the top and your code works just fine. So, How's that working?

Well, previously you had to import React because the JSX is converted into regular Javascript that use react's `React.createElement` method.
![JSX conversion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oql3gz9vcrdh0sdili1v.jpg)
But, React has introduced a new JSX transform with the release of React 17 which automatically transforms JSX without using `React.createElement`. This allows us to not import React, however, you'll need to import React to use Hooks and other exports that React provides. But if you have a simple component, you no longer need to import React. All the JSX conversion is handled by React without you having to import or add anything.

This new JSX transform is also supported in older versions of React so you can start using them even if you don't use React 17.

Read the official [React doc](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) to learn more.
Next.js with TypeScript, tailwindcss, ESLint, Prettier boilerplate
Tags: nextjs, typescript, tailwindcss
Published: 2021-04-02 03:03:30

I created Next.js with TypeScript, tailwindcss, ESLint, Prettier boilerplate.
https://github.com/otashun/nextjs-typescript-tailwindcss-eslint-prettier

Getting started
```
git clone git@github.com:otashun/nextjs-typescript-tailwindcss-eslint-prettier.git
cd nextjs-typescript-tailwindcss-eslint-prettier
docker-compose up -d && docker-compose exec app bash
npm install
npm run dev
```
Motorola Moto G60 and Moto G20 render leaked the design and specs
Tags: mobile, android
Published: 2021-04-02 03:02:59

Recently, Motorola Moto G60 and Motorola Moto G20 render leak the design. Although, it was a rumor a lot of G series smartphones are coming soon. We will disclose the design photos and some key specifications below. Please read it carefully and drop your opinion... more https://www.mobiledokan.co/motorola-moto-g60-and-moto-g20-render-leaked-the-design-and-specs/
The beginner's brief guide to Usability Testing
Tags: webdev, ux, codenewbie, beginners
Published: 2021-04-02 02:38:56


According to the industry expert Jacob Nielsen from Nielsen Norman Group, 85% of issue associated with the UX are often detected by performing an usability test of 5 users.

I think that it is an amazing reason, why to conduct usability testing session. Most often I use unmoderated screen recordings. Let's see five main steps to do it💪!

---

### Set Goals and Metrics

This is the first and probably **crucial step** influencing all the next steps of the usability testing process! See the following examples of those goals: 

- Do benchmark comparison
- Identify usability problems
- Improve time to complete task
- Get knowledge of how users feel about the interface
- Get knowledge of how users understand key interface functionality

---

### Scenario and Questions

Give to users a **clear overview of the context** they use your platform(prototype). It's important for them to set the right mindset during testing sessions. 
Questions and tasks should be clear and they shohuld be in alignment with your goals!

---

### Prepare Prototype

It's important to modify the prototype based on your tasks and scenario to are sure, that users are able to complete your tasks and questions clearly. 


--- 

### Find respondents

There three main options for finding respondents for your usability testing sessions. 

- Use an external platform
- Find your own respondents
- Ask current customers/users


---

### Analyze and Iterate

After successful testing sessions, you just need to analyze main metrics and do iterations on your product. 
Don't forget to try your test on the pilot to make sure, that everything will work well. 


---

Thank You For Reading 😉
Medium Style Image Blur-Up Loading with Gatsby-Image
Tags: gatsby, performance, react, jamstack
Published: 2021-04-02 02:07:13

Although the subscription wall can be annoying, I think it fair to say Medium is a pretty great blogging platform. It's simple to use, feature loaded, but most importantly its really fast. 

A lot of different things go into making a website fast ([Check Web.Dev for more tips](https://web.dev/fast/)) but one thing that Medium does especially well is Progressive Image Loading.

Progressive Image Loading, also known as the Low Quality Image Placeholder(LQIP) pattern, is simply the technique of loading a low quality version of your image first, and then lazy loading a full size version once the main page content has loaded. 


The effect this has is a bit similar to using skeleton content, and it can do wonders for the perceived performance of your website and help cut on the first contentful paint (FCP) time. With GatsbyJS LQIP comes out-of-the-box with the Gatsby-Image plugin though if you want to use it ouside of Gatsby feel free to check-out [lazysizes](https://github.com/aFarkas/lazysizes#lqipblurry-image-placeholderblur-up-image-technique). 


In Gatsby though, blur up isn't actually enabled by default, and ends up being all too often overlooked. Because of this a lot of sites will show a not so pretty pixelated or compressed version of the image instead of a nice blurred version. Thanks to the `placeholderStyle` attribute though, fixing this is actually as easy as a single extra line of JSX.

```typescript
import Img from "gatsby-image";

<Img
    fluid={someFluidSrcImage}
    title={imageTitle}
    placeholderStyle={{ filter: `blur(1.5rem)` }}
  />
```

By adding the `placeholderStyle` attribute we can apply styles to the image that gets loaded in as a placeholder, and Gatsby handles the rest! Add a blur, pixilation or any other kind of CSS filter you like. Here's what the end result looks like for me.
![The end result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vdaj6srojexoom3t9ynn.gif)

Let me know if you have any questions, and hope you found this useful!

*Originally published on my blog at [maxphillips.dev](https://www.maxphillips.dev)*
What to do when your programming project gets canceled
Tags: programming, project, work
Published: 2021-04-02 01:52:15

---
title: What to do when your programming project gets canceled
published: true
date: 2021-04-02 01:50:51 UTC
tags: Programming,project,work
canonical_url: https://phoenixtrap.com/2021/04/01/what-to-do-when-your-programming-project-gets-canceled/?utm_source=rss&utm_medium=rss&utm_campaign=what-to-do-when-your-programming-project-gets-canceled
---

This week my main task for this [sprint](https://www.scrum.org/resources/what-is-a-sprint-in-scrum) was canceled. While not as momentous as the cancellation of an entire project _(I’ve been there too)_, deleting the past week’s work still stung. This isn’t the first time, though, so I know that there are a few things to keep in mind:

## You didn’t waste your time

Bottom line: Were you paid for your work? Then your employer still sees it as valuable, if only to make sure that a given line of development was sufficiently explored before determining it wasn’t worth continuing. Developing a product or service often means saying “no” to things, and sometimes that means cutting losses before the [sunk cost](https://en.wikipedia.org/wiki/Sunk_cost) fallacy takes hold.

## You probably learned something

Over the past week’s work, I learned about [managing TLS connections](https://metacpan.org/pod/IO::Socket::SSL) (including supporting ciphers that are no longer considered secure), [parameter validation](https://metacpan.org/pod/Type::Params), and [XML namespace support in XPath](https://metacpan.org/pod/XML::LibXML::XPathContext). You probably learned a lot more if your project extended longer, and you can use that knowledge further on in your career. Put it on your résumé or CV, and you may get an opportunity to work on the same things in the future.

## You could continue if you want

Okay, maybe you’re not going to [sneak into the office for months](https://www.pacifict.com/Story/) to finish things. But as long as you have the time and inclination, you could continue to work on your project, especially if you think it could be valuable to the company later on. Consider this carefully, though—you don’t want off-the-books work taking time and energy away from your main job.

## There’s no shame

Lastly, you shouldn’t feel ashamed about being part of a canceled project. They happen all the time, and probably should happen more—history is littered with [failed software projects](https://en.wikipedia.org/wiki/List_of_failed_and_overbudget_custom_software_projects) that likely could have cost less if only their problems were recognized earlier. By its nature, software development is exploratory and difficult, and not every idea pans out. As long as you can find something new to work on, you’ll be fine.
Sherif Awad-Film Critic-Egypt
Published: 2021-04-02 01:43:57

Born in Cairo, Sherif Awad is an art/film/video curator who worked as a programmer, communications attaché and editor of film publications since 1990. Now online entrepreneur.
https://www.sherifawad-filmcritic.com/
https://www.meetingvenus.com/
https://comics-bd-universes.com/
#Day12 - Anonymous Functions in Python
Tags: python, programming, 100daysofcode, codenewbie
Published: 2021-04-02 01:06:03

Today, we will be talking about anonymous functions in Python. Anonymous functions are also known as lambda functions. They are one-liners and look elegant. Below is the syntax
```
lambda parameters: expression
```
Since they have no names, they are called anonymous functions. However, to actually use them, we need to assign them to a variable
```
variable = lambda parameters: expression
```
To call a lambda function, we just call the variable and pass the parameters
```
variable(parameters)
```
Let's look at an example and compare a function written as a normal function and as a lambda function

#### Normal
```
def square(x):
    result = x*x
    return result

ans = square(5)
print(and)
```
#### Lambda
```
square = lambda x: x*x
ans = square(5)
print(and)
```
Both print the same result. However, the lambda expression looks cleaner. 

#### Lambda functions with multiple parameters
```
add = lambda x,y: x+y
print(add(5,4))
```

### Using lambda functions with the sorted function
```
pairs = [(1,2) , (3,14) , (5,26) , (10,20) ]

sorted_pairs = sorted(pairs, key = lambda pair: max(pair[0],pair[1]))
print(sorted_pairs)
```
We have a list of tuples and want to sort it in ascending order based on the maximum number in the pair.

### Parameterless lambda function
```
func = lambda : return "String"
print(func())
```

#### Lambda Function without variable name
```
print( (lambda x,y: x+y)(4,5))
```
DOM - Document Object Model
Published: 2021-04-02 00:38:34

Chegamos a mais um post da minha [saga de estudos](https://dev.to/inando85/bem-vindo-de-novo-javascript-1b48) em JavaScript.

No post de hoje irei falar sobre o DOM.


### DOM

`DOM` é a abreviação de Document Object Model, é o coração de qualquer modificação em uma webpage.

O `DOM` é criado pelo browser, ele não faz parte do JavaScript em si.

Quando o HTML é carregado no browser, o próprio browser cria o `DOM`, para que a gente consiga interagir com o documento HTML através do nosso código JavaScript.

Através do `DOM` podemos por exemplo: criar, remover e editar elementos através do código em JavaScript.

Uma vez que o documento HTML é carregado no browser, o browser cria um objeto que modela este documento, este objeto se chama `document`.

Este objeto `document` possui diversas propriedades e métodos que podem ser usados para manipular o documento HTML.

Com isso, fica claro, que para fazer uma manipulação qualquer em uma página, tipo remover um elemento ou responder ao clique de um botão, isso é feito através do objeto `document`.

```js
console.log(document)
```

No exemplo acima, o output desse `console.log` será uma representação do elemento HTML.

#### Alguns exemplos de propriedades e métodos

Como o `document` é um objeto, iremos utilizar a anotação de ponto `.` para acessar as propriedades e métodos.

###### Location

Irá retornar um objeto com informações sobre a URL do documento.

```js
console.log(document.location)

// Output
Location {ancestorOrigins: DOMStringList, href: "http://127.0.0.1:5500/etapa-05-o-document-object-m…el-dom/aula-01/aula-01-06-o-que-eh-dom/index.html", origin: "http://127.0.0.1:5500", protocol: "http:", host: "127.0.0.1:5500", …}
```

###### URL

Irá retornar apenas a URL do documento.

```js
console.log(document.URL)

// Output
http://127.0.0.1:5500/etapa-05-o-document-object-model-dom/aula-01/aula-01-06-o-que-eh-dom/index.html
```

#### Estrutura de Árvore

O `DOM` vê o nosso HTML como uma estrutura de árvore, em forma de nós (nodes em ingês), e cada um dos elementos é considerado um nó (node em inglês).

A tag raiz do documento é a tag HTML, chamada de `root node`.

![Estrutura do DOM](https://capitalcode.com.br/admin/uploadsPost/8d009efa8e8abc5bd370d6a42b6aa97b.jpg)

Acima estrutura em forma de árvore, para exemplificar como o `DOM` enxerga o elemento HTML.

Vou deixar um link da MDN para mais detalhes sobre o [Document Object Model](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model)

________________________________________________________________

Esse foi mais um post da minha saga de estudos em JavaScript Vanilla. Espero que estejam gostando!

Qualquer dúvida ou sugestão, vocês me encontram nas minhas redes sociais:

[LinkedIn](https://linkedin.com/in/inando85)
[GIthub](https://github.com/inando85)
[Twitter](https://twitter.com/inando85)
International Women's Day 19
Tags: iwd19, womentechmakers, actionsongoogle, googlecloudplatform
Published: 2021-04-02 00:09:25

GDG the Google Cloud London meetup

 {% youtube 50hWIqDzOWs %}

Kubra and myself, alongside the support of handful of GDG Cloud organisers, Googlers and Eddie Jaoude took the [Karaoke Action Workshop] (https://karaokeaction.netlify.app) I created to the next level.

It wasn't simply a workshop on coding. We also also had karaoke in addition to dancing and a fine dinner.

{% twitter 1117927506252902400 %}

The event was held at Google's offices at Kings Cross London the meetup was focused on Actions on Google.

We brought the community together to not celebrate such an important date. But to hone their tech skills and and to have fun!

{% twitter 1200685490007138304 %}

The food was fantastic and we were happy with the feedback the participants gave to our planning and how the event was a success!

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5xex9n32z8l9v346tue3.png)
 

At the end we invited some of the attendees if they'd like to practice their public speaking, as there was only maybe a handful of people maybe if they wanted get up on stage and practice your public speaking in front of a few people therefore in the future you could potentially give a talk.

It was an experience I'll never forget, it has really impacted my life positively.
Send webhooks with your Laravel application
Published: 2021-04-01 23:36:53

Laravel webhook allows businesses to send webhooks to their merchants/clients with ease. This package also introduces a
new artisan command to generate a webhook class.

## Requirement

- Composer v1.0/2.0
- Php (7.3 and above)
- Laravel (6 and above).

## Installation

You can install the package via composer:

```bash
composer require bencoderus/laravel-webhook
```

## Setup

Publish basic components. (migrations and configuration files)

``` php
php artisan webhook:install
```

Run migrations

```bash
php artisan migrate
```

## Basic usage

Create a new webhook class

```bash
php artisan make:webhook PaymentWebhook
```

Creates a new webhook class in App\Http\Webhooks

You can format your webhook payload like a resource.

```php
public function data(): array
    {
        return [
            'status' => $this->status,
            'amount' => $this->amount,
            'currency' => 'USD',
        ];
    }
```

Sending a webhook.

```php
$transaction = Transaction::first();

$webhook = new PaymentWebhook($transaction);
$webhook->url('https://httpbin.com')->send();
```

Sending with an encrypted signature

```php
$transaction = Transaction::first();

$webhook = new PaymentWebhook($transaction);
$webhook->url('https://httpbin.com')
        ->withSignature('x-key', 'value_to_hash')
        ->send();
```

The default hashing algorithm is sha512 you can change it by passing a different hashing algorithm as the third
parameter for the withSignature method. PHP currently supports over 50 hashing algorithms.

Sending webhooks without using a Queue.
By default, all webhooks are dispatched using a queue to facilitate webhook retrial after failure. You can also send
webhooks without using a Queue by passing false to the send method.

```php
$transaction = Transaction::first();

$webhook = new PaymentWebhook($transaction);
$webhook->URL("https://httpbin.com")->send(false);
```

<br/>
Find package on Github.
https://github.com/bencoderus/laravel-webhook