teleren/devto huggingface dataset:
Visual Gherkin Manager - devlog#2
Tags: devlog, qa, react, automation
Published: 2022-11-27 23:54:33

I have been working in this project since the last post, and today I will show you a first result. 

The first feature implemented was the canvas to model the test flow using a visual diagram that seems like an activity diagram. In the last post I was thinking something like the following:

![desired-model-diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trdytt0ahiaooy30x4j8.png)

After a lot of effort, using React with TypeScript and the library [react-diagrams](https://github.com/projectstorm/react-diagrams) the following result was achieved:

![achievied-model-diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rfjle88xlh7a471voxyo.png)

I was a long time without writing some frontend code with React and most of the effort was remember the necessary structure and concepts. 

The library [react-diagrams](https://github.com/projectstorm/react-diagrams) is very extensive, allowing easy customization of all necessary components styles and behaviors. For example, It were necessary to create custom node and label components to contemplate the desired needs.

![simple-components-explanation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/crayy3cryy1zk36hn9bo.png)

A important point is the lack of diagram validations. I am mapping possible rules that are required to avoid unexpected errors/behaviors and maintain some level of consistency. All the rules will be implemented soon.

I am working in the test case generation (Gherkin format), that is the second main part of the project. In the next post I will share with you the results.

---

The application was deployed on Netlify, you can visit [here](https://quality-flow-tool.netlify.app/) to evaluate.
Pogress on my study
Tags: node, javascript, beginners, webdev
Published: 2022-11-27 23:48:04

in my #Twitter , i´m postting my progress on my way like backend developer node.js in #platzi  and is a 11 day :D

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k47ktqrotu6bf0om47mv.png)
TRX Stake and Earn on Huobi Exchange
Tags: trx, tron, huobi, crypto
Published: 2022-11-27 22:41:03

[Huobi Exchange](https://justyy.com/out/huobi) has Stake and Earn (DeFi) and I noticed that you can stake TRX and earn roughly 3.36% APY.

![image.png](https://cdn.steemitimages.com/DQmaJ3L2YfbaRoYBhfNdW4BducAd51QKegLCaRiMSUxn5Y7/image.png)

So, is this better than [Stake](https://helloacm.com/automate-freeze-balance-on-tron-blockchain-using-nodejs-with-tronweb-trongrid/), Vote Super Representives, and [Claim Rewards](https://helloacm.com/how-to-claim-the-witness-super-representative-voting-rewards-on-tron-blockchain-using-node-js-javascript/) yourself?

I have staked roughly 150K TRX in my own wallet, 


![image.png](https://cdn.steemitimages.com/DQmNUr7ExmaLXvNQQogtDWVDXDHecJnw6McooCiefvNZdAn/image.png)

and on average, my daily return is 18 TRX.
![image.png](https://cdn.steemitimages.com/DQmPwmx2KQf6rc1txC2YebZfq2NydUsnDXzCdZ95tn6Vy9B/image.png)

This is roughly 18*365/150000=4.38% TRX

And if you stake TRX on [Huobi Exchange](https://justyy.com/out/huobi), you will get slightly less 3.36% APR
![image.png](https://cdn.steemitimages.com/DQmV4UgN2tAuZNqGenj1U9o4uB6eDLqaGHbbGdwXZRVnzgR/image.png)


Staking rules of [Huobi Exchange](https://justyy.com/out/huobi):
1. Staking is a chain contract service. Huobi only offers technical channels.
2. Tokens will be locked in your Huobi Exchange account after staking and cannot be used to trade.
3. The revenue comes from validator rewards. APY will fluctuate according to actual income.
4. The delay between unstaking and unlocking is based on rules of the chain. No earnings will be generated in the period.
5. Earnings will start to accumulate on T+1 and be distributed on T+2.
6. Stakes can only be unstaked after the expiry time.

Of course, if you stake and earn TRX on [Huobi Exchange](https://justyy.com/out/huobi), you don't need to vote the Super Representatives and claim the rewards yourself.

<hr/>

## [Steem](https://steemyy.com) to the Moon!
Code Smell 182 - Over Generalization
Tags: webdev, beginners, programming, tutorial
Published: 2022-11-27 22:32:48

*We are refactoring fans. Sometimes we need to stop and think.*

> TL;DR: Don't make generalizations beyond real knowledge.

# Problems

- Overgeneralization

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

# Solutions

1. Think before making structural generalizations

# Context

Refactoring is not just looking at structural code. 

We need to refactor behavior and check if it needs an abstraction.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/2b7734f1f6c0ab46a88a71b37464ceeb)
```rust
fn validate_size(value: i32) {
    validate_integer(value);
}

fn validate_years(value: i32) {
    validate_integer(value);
}

fn validate_integer(value: i32) {
    validate_type(value, :integer);
    validate_min_integer(value, 0);
}
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/1eca09d9bb13cea966bcbe2eda95021c)
```rust
fn validate_size(value: i32) {
    validate_type(value, Type::Integer);
    validate_min_integer(value, 0);
}
	
fn validate_years(value: i32) {
    validate_type(value, Type::Integer);
    validate_min_integer(value, 0);
}
	
// Duplication is accidental, therefore we should not abstract it	
```

# Detection

[X] Manual

This is a semantic smell.

 # Tags

- Duplication

# Conclusion

Software development is a thinking activity. 

We have automated tools to help and assist us. We need to be in charge.

# Relations

{% post https://dev.to/mcsee/code-smell-46-repeated-code-4iib %}

# More Info

- [DRY—The Evils of Duplication](https://en.wikipedia.org/wiki/The_Pragmatic_Programmer)

# Disclaimer

Code Smells are just my [opinion](https://dev.to/mcsee/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned-1n3a).

# Credits

Photo by [Matthew Henry](https://unsplash.com/@matthewhenry) on [Unsplash](https://unsplash.com/s/photos/duplicate)  
  
* * *

> Duplication is far cheaper than the wrong abstraction.

_Sandi Metz_
 
{% 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 %}
6 Techniques to manage your time effectively.
Tags: productivity, management, motivation
Published: 2022-11-27 21:53:44

Time management is one of the most skills demanded now. It's essential for everyone from students to bosses. There are many strategies and techniques that keep you master this skill.

**1. Create a list.**
Create a list, it's important to know all tasks and activities you want to make them. So the first step is making a list which should be collected all your tasks. you can use paper and pen, a calendar, an application or a tool mobile.

**2. Prioritize tasks.** 
Prioritize tasks, when writing your tasks, always prioritize what's important to you. Decide which activities are urgent and which have the most impact on yourself and your work. There will be some taches which are urgent and can be done quickly. While other urgent jobs may be bigger and need a long time to achieve them. Having a list of tasks is useful to keep focused and make sure nothing is missed. Besides, it's a good feeling when you ticked off your taches as completed.

**3. Delegate the no-important tasks.**
Delegate the no-important tasks, sometimes we can't do all things that are required, because it can be damaging and create stress and anxiety so, you should delegate no-important taches to another person to help you and also support your work development.

**4. keep focused and stop distractions.**
keep focused and stop distractions, there are many things that distract us every moment such as email alerts, social media notifications, and phone messages. All those things waste our time a lot. Staying focused can be difficult, however, there are a few things we can do to help, for example, put the phone away, and turn off social media notifications.

**5. Time Blocking.**
Time Blocking, sometimes we want to make several tasks at one time but, we fail to finish any one. the solution to this situation is to keep focused on one task at a time until completed and go to the second task.

**6. Take a break.**
Take a break, for our health and well-being, it's essential to plan into your daytime for regular breaks. these should be away from your work to recharge and clean your mind. Those breaks should include healthy food and drinks besides, chatting or making contact with other people.

In short, creating a list, prioritising and delegating tasks, keeping focused,  time blocking, and taking a break are the essential techniques to manage your time effectively.

Do you have other techniques?
Using Docker & Installing a Linux Distro. + cURL
Tags: docker, showdev, beginners, tutorial
Published: 2022-11-27 21:49:20

## Goal
The goal of this project is to use Docker to setup a Linux distribution and check the cURL version. This should be a fairly quick tutorial since Docker is awesome and can do everything in a few commands.

<img width="100%" style="width:100%" src="https://media.giphy.com/media/61AizO23LGHJLyOjjn/giphy.gif">

### Prereqs
📍Docker Engine & CLI installed
📍Internet connection

#### Let's Get Started!
The first thing that we need to do is install the Linux distribution of our choice. I'm using Ubuntu 22.04. We're also going to install bash alongside the installation so that we can immediately start doing the commands we need to once inside.

`docker container run --name ubuntu --rm -it ubuntu:22.04 bash`

![successful installation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cu63aa0rbuazlcskudk3.png)

#####Breaking It Down
- `--rm` makes cleaning up easier. Once I exit the container, the container will be wiped clean and removed rather than just stopped.
- `--it` is actually two commands that are combined.
- `-i` actually is `-interactive` shortened and allows us to input directly into the container.
- `-t` stands for `-tty` which allows us to interact with the shell within the container.

![ubuntu logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ffbgt5i1vutli9xdiozd.png)
You don't have to use Ubuntu, but the commands in the next section are Ubuntu specific. If you're using a different Linux distribution, check the docs for your distro on how to download cURL.

---

###See If cURL Works
At this point you should be in your Ubuntu instance. Let's try to run `curl --version` and see if we're all set!

![curl not installed](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jr6fpzi7djabh4tbc7gg.png)

It turns out that curl isn't installed by default in the Ubuntu 22.04 image. No problem, let's download it!

`apt-get update && apt-get install curl` 

#####Breaking It Down
- `apt-get update` updates the system's repositories so that everything will work correctly when calling `apt-get install`
- `&& apt-get install curl -y` runs the cURL installation right after apt-get update finishes

---
###See If cURL Works... Now?

`curl --version`
![version of curl](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qqomwdtz749fj790drzi.png)

`curl google.com`
![checking google with curl](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ga087u3yfitctxz7j9dd.png)

Woohoo, time to celebrate!

<img width="100%" style="width:100%" src="https://media.giphy.com/media/VPT5cqgHBpfHO/giphy.gif">

---
###Wrap Up
In this quick demo, I've shown how to use Docker to download and install cURL on a containerized Linux distribution. I am really coming to appreciate how quick and easy it is to work with Docker and am interested in seeing how I can utilize userdata with EC2 instances to make software installation a breeze.

<img width="100%" style="width:100%" src="https://media.giphy.com/media/4N5ddOOJJ7gtKTgNac/giphy.gif">
React Context with React Router v6.4
Published: 2022-11-27 21:16:51

I searched for a while to find how to use the Context API with `createBrowserRouter`. What I found is that you can use [layout routes](https://reactrouter.com/en/main/start/concepts#layout-routes) to wrap your components with the provider:

```
import { Outlet } from 'react-router-dom';
export default function ContextLayout() {
  return (
    <ContextProvider>
      <Outlet />
    </ContextProvider>
  );
};
```

Then, you can create a `RouteObject` without a path that renders that layout route with the children as the components you want to wrap in the provider.

```
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
const router = createBrowserRouter([
  {
    element: <ContextLayout />,
    children: [
      {
        path: '/some/path',
        element: <SomeContextConsumer />
      }
    ]
  },
  ...
]);

export default () => {
  const rootElement = document.getElementById('root');
  const root = createRoot(rootElement!);
  root.render(
    <RouterProvider router={router} />
  );
};
```

That's it! Hopefully this saves someone the time it took me to figure this out.
What is JSON with padding?
Tags: javascript, webdev, json, hacking
Published: 2022-11-27 21:11:50

JSONP (JSON with padding) is a tricky way to send cross-site GET requests by getting around the browser’s same-origin policy. The modern browsers follow the CORS rules when sending XHR (XMLHttpRequest) requests, but JSONP bypasses it due to the way how it sends requests.

JSONP isn’t an XHR request; it’s a script load on the page but returns a function call. This is what JSONP data looks like:

```javascript
callback({
	data: {
		id: 1
	}
})
```

_But, what does it do exactly?_

Let’s assume your web page has functions from the app.js file that loads on the page with script tags. As the page opens, the script tag will send a request for the app.js and loads it, the definition of functions will be processed onto the page, and the functions will be ready to call. This is how JavaScript files are processed.

![Taken from https://stackoverflow.com/a/43835381/8574166](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ekjdt7op8edgb23wr0vy.png)

But, if you put an endpoint URL into the script tag with a callback parameter, the server would return only a JSONP object ready-to-call on the client if the returning function is defined on the client right after the page resolves the script tag.

![Taken from https://stackoverflow.com/a/43835381/8574166](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iqij5ur92ktzd78hl7i0.png)

### Dynamic JSONP requests
Instead of sending the requests when the page initiates, requests can be sent dynamically by injecting a script element into the DOM within a function.

```javascript
function requestServerCall(url) {
  var head = document.head;
  var script = document.createElement("script");

  script.setAttribute("src", url);
  head.appendChild(script);
  head.removeChild(script);
}

function myCallback(data){
	// process your data here
}

requestServerCall("URL?callback=myCallback")
```

### Is it safe?

Well, no. It’s just a basic hack to make cross-domain requests, and sites that use JSONP services are prone to CSRF; well, that’s why XHR request methods have CORS policies: to keep safe client users.

An attack that prepared for potential XSS vulnerabilities, such as stealing user cookies, can also be demonstrated for JSONP. The provider of JSONP data must be trustable and ensure that it doesn’t return any malicious JavaScript code and try to run a different callback than given.

## Conclusion

JSONP is an old-fashioned and hacky way, but not safe, to send GET requests to the client. XHR requests, such as ajax and fetch, are restricted to sending cross-site requests, but it is still possible to send with JSONP.

Plus, it is not that useful to use it in JavaScript applications due to no callback functions are provided to handle potential errors, even though some libraries like jQuery and Angular implemented a native way to send JSONP requests.

So, there is no need to use it.

_This blog post was published on [here](https://www.samet.codes/what-is-json-with-padding)._
How to find your Mastodon account ID
Tags: mastodon
Published: 2022-11-27 21:00:38

---
title: How to find your Mastodon account ID
published: true
tags: mastodon
canonical_url: https://khendrikse.netlify.app/blog/find-your-mastodon-account-id/
description: Here's a simple way to find your Mastodon account ID.
---

**If you're trying to set something up with the public [Mastodon API](https://docs.joinmastodon.org/client/public/), you might need your account ID. This is one of the ways you can find your ID.**

You can find your mastodon account ID by doing a call to the following URL.
Replace `INSTANCE` with the name of the server you are on. If you're on mastodon.online for example, it will be `mastodon.online`.

Replace `USERNAME` with your username.

```
https://INSTANCE/api/v1/accounts/lookup?acct=USERNAME
```

Now you can either visit that URL in the browser, or use curl in your terminal:

```bash
curl https://INSTANCE/api/v1/accounts/lookup?acct=USERNAME
```

Both will return an object holding your `id`.

```json
{
  "id": "1",
  "username": "fakename",
  "acct": "fakename",
  "display_name": "A fake name",
  "locked": false
  // ...
}
```

If you want to know more about this endpoint. Check out [the documentation](https://docs.joinmastodon.org/methods/accounts/#lookup). Hopefully this can help people to quickly find their account ID.
OWASP API Security Top 10 API4:2019 Lack of Resources & Rate Limiting With an Example
Tags: security, api, webdev, opensource
Published: 2022-11-27 19:18:42

Improper configuration of resources and rate limiting can lead to attackers being able to overload a system with re``quests, causing APIs to fail or become unresponsive. Rate and resource limiting are measures that can be taken to help mitigate this risk. It involves limiting the number of requests that a user can make in a given period of time. This can prevent attackers from being able to send a large number of requests and overwhelm the system.

In this blog, I have explained about the OWASP API Security Top 10 API4:2019 Lack of Resources & Rate Limiting With an Example.

{% embed https://blogs.appsecworld.com/2022/11/owasp-api-security-top-10-api-2019-lack-of-resources-and-rate-limiting.html %}
APIs del DOM
Tags: javascript, beginners, programming
Published: 2022-11-27 19:10:09

Estas son algunas de las APIs más utilizadas que ya vienen integradas en JavaScript.

## Fetch
Fetch es una evolución de XMLHttpRequest. Las peticiones AJAX permitieron en su tiempo hacer peticiones asíncronas al servidor sin tener que detener la carga de la página. Hoy en día se utiliza la función fetch para esto.

```javascript
const getPokemons = async () => {
  return const pokemons = await fetch('https://pokeapi.co/api/v2/pokemon?limit=50')
}
```

## IntersectionObserver
Sirve para observar elementos y si cruzan un umbral que nosotros definimos nos lo va a notificar para tomar acción. El umbral se define por el porcentaje que tiene intersección con el viewport, con la parte visible de nuestra página.

```javascript
const observer = new IntersectionObserver(callback, options)
```
Le pasamos un callback para que se ejecute cuando el límite o el umbral(threshold) sea cruzado en una u otra dirección.

## VisibilityChange
El visibilityChange forma parte del API del DOM llamado Page Visibility y nos deja saber si el elemento es visible, pude ser usado para ejecutar una acción cuando cambiamos de pestaña. Así podemos ahorrar batería y mejorar la UX.
La API de visibilidad de página ofrece eventos que puedes escuchar para saber cuando un documento se convierte en visible o en oculto.

```javascript
document.addEventListener('visibilitychange', callback)
```

Cuando el usuario minimiza la ventana o cambia de pestaña, la API manda un evento de visibilitychange para que los listeners sepan que el estado de la página ha cambiado.

**VisibilityState**
Para saber el estado de visibilidad actual del documento utilizamos VisibilityState este estado se nos indica a través de una cadena de texto.

```javascript
//El contenido de la pagina esta visible para el usuario
document.visibilityState === 'visible'
//El contenido de la pagina no es visible para el usuario ya sea por que esta en otra pestaña o ventana
document.visibilityState === 'hidden'
//El contenido de la pagina se esta procesando y no es visible por el usuario
document.visibilityState === 'prerender'
```

Si quieres conocer más APIs y funcionalidades que disponemos a la hora de desarrollar un sitio web visita el siguiente [enlace](https://developer.mozilla.org/en-US/docs/Web/API).
Tips: Object Destructuring in JavaScript ES6
Tags: javascript, beginners, tutorial, programming
Published: 2022-11-27 19:05:04

Suppose you have a `person` object with TWO prperties:

```javascript
let person = {
   firstName: 'Devv',
   lastName: 'Sakib'
}
```

Before **ES6**, when you want to assign the variables to the properties of the `person` object, you typically do like this:

```js
let firstName = person.firstName
let lastName = person.lastName
```

But but but, ES6 make it more easier! There are an alternative way to assign properties of an object. Let's see

```js
let { firstName: fName, lastName: lName } = person
```

Here, `firstName` and `lastName` prop are assgined to `fName` and `lName` variables.

Syntax:

```js
let { 
    property: variable, 
    property: variable 
    } = object
```

Notice that the property name is always on the left whether it is object literal or object **destructuring** syntax.

TO KNOW: If the variables have the same name as the properies of the object, you can make the code more concise as follows:

```js
let { firstName, lastName } = person

console.log(firstName) // "Sakib"
console.log(lastName) // "Smith"
```

In this examples, we declared two variables `firstName` and `lastName`, and assigned the properties of the object to the variables in the same statement.

When you assign a property that does not exist to a variable using the object destructuring, the variable is set to `undefined`.

Example:
```js
let { firstName, lastName, middleName } = person

console.log(firstName) // "Sakib"
console.log(lastName) // "Smith"
console.log(middleName) // undefined
```

The `middleName` property does not exist in the `person` object, that's why `middleName` is **`undefined`**

### Default Values

You are able to assign a default value of the variable when the property of an object doesn't exist.

Example:
```javascript
let person = {
   firstName: 'Devv',
   lastName: 'Sakib'
}

let { 
    firstName, 
    lastName, 
    middleName = ''
    } = person

console.log(middleName) // ''
```

In this example, we assigned empty string to the `middleName` variable when the `person` object doesn't have the `middleName` property.

However, when the **person** object has `middleName` property, the assignment works as usual:

Example:
```javascript
let person = {
   firstName: 'Devv',
   lastName: 'Sakib',
   middleName: 'IDK'
}

let { 
    firstName, 
    lastName, 
    middleName = ''
    } = person

console.log(middleName) // 'IDK'
```

### Destructuring a null object
If you know, a function may return an object or null in some case.
```js
const person = () => {
   return null
}

let { fname } = person()

```
But you can't destructure an **null** object. The code will throw a `TypeError`

```js
TypeError: Cannot destructure property 'fname' of 'person()' as it is null.
```
To solve this, you can use the `OR`(||) operator to fallback the `null` object t an empty object.
```js
let { fname } = person() || {}
```
Now, fname will be `undefined`


There are so many destructuring, will write later. See yaa
JS equivalent for pydantic or dataclasses in python?
Tags: help, javascript, python, webdev
Published: 2022-11-27 18:54:54

I am just getting into the JS ecosystem and I have 4 years of experience in the python ecosystem.

I wanted to know if there is a direct equivalent of pydantic or dataclasses equivalent in JS (not typescript).

I am aware that json schema would be a worthy replacement but wanted class based capabilities if possible.