teleren/devto huggingface dataset:
Extraindo Constantes de Números Mágicos
Tags: ruby, refactoring, braziliandevs
Published: 2022-06-25 18:48:01

---
title: Extraindo Constantes de Números Mágicos
published: true
description: Neste artigo você vai aprender a como extrair constantes de números mágicos
series: Refatoração
tags: #ruby #refactoring #braziliandevs
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

Olá, esse é o meu primeiro post da série refatoração, no qual vou mostrar o que estou aprendendo com o curso Refactoring do [Refactoring Guru](https://refactoring.guru/)

O primeiro post vai ser sobre extrair constantes de números mágicos.

Imagine que você tem o seguinte cenário:

```rb
def potential_energy(mass, height)
  mass * height * 9.81
end
```

Não sei se você aprendeu sobre energia potencial gravitacional na escola, mas concorda comigo que não está nada explícito o que representa 9.81?

Vamos refatorar seguindo o "Extraindo Constantes de Números Mágicos"

```rb
GRAVITATIONAL_CONSTANT = 9.81

def potential_energy(mass, height)
  mass * height * GRAVITATIONAL_CONSTANT 
end
```
![Mind Blowing](https://c.tenor.com/3eIvVsG3yPYAAAAd/the-universe-tim-and-eric-mind-blown.gif)
Uau! Agora sim! Agora ficou explícito que o valor de 9.81 é a constante gravitacional

É isso que diz o "Extraindo Constantes de Números Mágicos", ele diz que "Um número mágico é um valor numérico encontrado no código que não tem significado óbvio". Este 'anti-pattern' torna mais difícil entender o programa e refatorar o código"

Os benefícios dessa técnica são inúmeros, entre eles podemos destacar:
- As constantes podem servir como uma documentação.
- É muito fácil mudar o valor de uma constante do que buscar por esse número em todo o código, sem o risco de acidentalmente mudar o mesmo número usado para outro propósito.

É isso pessoal! Eu espero que esse artigo os ajude! E se sim, me deixe saber! Até a próxima!
First article in Profiles in Software series
Tags: beginners, career, codenewbie, programming
Published: 2022-06-25 18:34:40

I published my first article in the series I've started for [Profiles in Software](https://newsletter.attainable.engineer/p/profiles-in-software). I really enjoyed my time with Charity Majors. 

{% embed https://newsletter.attainable.engineer/p/a-book-by-its-cover %}
Yamlless Infrastructure as Code
Tags: aws, devops, cloud, yaml
Published: 2022-06-25 18:30:11

If Yaml had a tech CV, recuiters would kill to place it. Just look at some of projects it's been a key part of across its star studded career:

✅️ Kubernetes 
✅️ AWS CloudFormation 
✅️ Ansible 
✅️ GitHub Actions 
✅️ Azure DevOps 

Or in slightly more sensible terms; pretty much every single DevOps tool has own configuration language, and many are based on YAML. These languages usually express a great deal fairly simply, so the initial learning curve isn't too steep. However, the problem arises when you start trying to express high levels of complexity with them. Simple things that you'd take for granted in a normal programming language like conditional statements, loops, and text operations, may exist in some form, but quality varies a lot,  they aren't necessarily particularly easy to understand or discover, and the result can be an alphabet soup that's near impossible for humans to parse without deep subject knowledge.

However, at least in Infrastructure as Code, you can actually use general purpose programming languages. This is by no means a cure all but for some people,  like me, it might well be a more pleasant option. There are two options that I'm aware of; AWS Cloud Development Kit (which comes in three variants for: AWS only, Terraform and Kubernetes) and Pulumi, which seems to be Terraform based, not an AWS person, there are other options too; there are variants of it for Kubernetes and Terriform and a completely different project called Pulumi, which seems to be Terraform based. I've honestly only worked with the AWS only version of the CDK, so I'll fcus on that, but the other three options should be much the same. Love to hear from anyone who's used the other versions.


The way it works internally is really intresting; they wrote a whole framework for translating between languages so they can have just one codebase and support TypeScript, JavaScript, Python, Java, C# or Go with  modules in each programming language, and the end result actually gets written out as CloudFormation Yaml, so you can use that directly if you have to.

This approach to Infrastructure as Code obviously has its own complexities, and you need to know one of those languages already to get the best out of it. The one problem that I mainly encountered with the CDK  was that the documentation isn't necessarily the best, but IDE completion is available, the code is opensource and the team are super helpful if you raise a GitHub issue. It's not necessarily for everyone, but is well worth checking out if you relate to my little rant about Yaml and friends. 

First blog post in a while, I'm trying to take this a bit more seriously than before so feedback is welcome :)
Edit Image in NodeJS Using Sharp
Tags: node, express, react, angular
Published: 2022-06-25 18:07:21

sometimes need to edit image properties and filter in nodejs. when their is no any image editor in frontend side then we use backend as image editor library **sharp**. sharp is best package in npm to edit image.

## install package 

npm i sharp

## server.js

```
const express = require('express')
const app = express()
const multer  = require('multer');
const path= require('path');
const sharp = require('sharp');
const UserModel=require('./user.model');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/uploads')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, file.fieldname + '-' + uniqueSuffix)
  }
})

const upload = multer(
{ storage: storage ,
    fileFilter: function (req, file, callback) {
        var ext = path.extname(file.originalname);
        if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
            return callback(new Error('Only images are allowed'))
        }
        callback(null, true)
    },
    limits:{
        fileSize: 1024 * 1024
    }
})

app.post('/profile', upload.single('profile'),async function (req, res, next) {
  // req.file contains the file fields

  try {
    await sharp("./uploads/"+req.file.filename)
      .resize({
        width: 150,
        height: 97
      })
      .toFile("./resize-uploads/"+req.file.filename);
    let user=await UserModel({name:req.body.name,avatar:req.file.filename}).save();

res.send(user);
  } catch (error) {
    console.log(error);
  }
})
```
 
here first upload file in original directory image then resize image and save resize image into another directory. 
also we add many functionality in sharp package to use like.

```
//filter image to grayscale
await sharp("./uploads/"+req.file.filename)
      .extract({ width: 400, height: 320, left: 120, top: 70 })
      .grayscale()
      .toFile("./resize-uploads/"+req.file.filename);

//rotate image 
await sharp("./uploads/"+req.file.filename)
      .rotate(40, { background: { r: 0, g: 0, b: 0, alpha: 0 } })
      .toFile("./resize-uploads/"+req.file.filename);

//blur image

    await sharp("./uploads/"+req.file.filename)
      .rotate(40, { background: { r: 0, g: 0, b: 0, alpha: 0 } })
      .blur(4)
      .toFile("./resize-uploads/"+req.file.filename);
```

## index.html

```
<form action="/profile" enctype="multipart/form-data" method="post">
  <div class="form-group">
    <input type="file" class="form-control-file" name="profile" accept="/image">
    <input type="text" class="form-control" placeholder="Enter Name" name="name">
    <input type="submit" value="Get me the stats!" class="btn btn-default">            
  </div>
</form>
```
 that is enough for this explore on sharp package to add many filter. thank you everyone.
How to validate custom React component prop using proptype
Published: 2022-06-25 17:43:08

Day 7 of #100daysofcode
Today we will learn how to validate custom React component props with proptype. Our initial code will be :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sc4de4o7d7gosw70bzip.png)
When you create a React component, others may want to use it and may not utilize it correctly. As you can see, we have a react function component that takes `firstname` and `lastname` as input and returns the result. As you've seen, we gave false as an input to our `firstname` and nothing to our `lastname` in the `const element`, but we want both `firstname` and `lastname` as strings. We will utilize a feature proptype to evaluate how props given to the component are used.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/en8j5qklt582lkruq4xt.png)
Here we have a function that checks whether or not our `propName` is a string. If not, an `error` message is displayed. If you want the same thing for `lastname`, we must repeat what we did for `firstname`. Instead, we can create a variable like :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/thb5vig4fca9a7bhf4in.png)
This is so popular that the react team created a package on npm that you can use with this :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/78sp6ro7tzvswgbth94b.png)
You can also use this to determine whether your prop is a string, boolean, array, or something else. More information can be found [here](https://www.npmjs.com/package/prop-types).
Our finished code should look something like this :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n9ry4twtmsrqkx3aasg0.png)
That's all there is to toady.
I made a simple click winner game with javascript.
Tags: javascript, webdev, programming, beginners
Published: 2022-06-25 17:07:28

This game is very simple and easy to understand. I have build just now and posted here. If you are beginner on HTML, CSS and Javascript this game will teach you a lot. 


## Step 1: Lets create html file now:
click_winner/index.html

```
<!DOCTYPE html>
<html>
<head>
<title>Shooter Ball</title>

<link rel="stylesheet" href="css/style.css"/>
</head>
<body>

<div class="floor">
<div id="time"></div>
<div id="score-box">Score: <strong id="score">0</strong></div>
<div id="plane" disabled>Click Me</div>
</div>

<script src="js/script.js"></script>

</body>
</html>
```



## Step 2:
Create CSS file on css folder now
click_winner/css/style.css
```.floor{
  width:500px;
  margin:auto;
  background:green;
  height:100vh;
}

#time, #score-box{
color:#fff;
padding:5px 10px;
} 

#plane{
border-radius: 50%;
padding: 10px;
height:50px;
width: 50px;
background:red;
text-align:center;
color:#fff;
box-shadow: 10px 10px 60px 0px rgba(0,0,0,0.75);
-webkit-box-shadow: 10px 10px 60px 0px rgba(0,0,0,0.75);
-moz-box-shadow: 10px 10px 60px 0px rgba(0,0,0,0.75);

 -webkit-user-select: none;  
  -moz-user-select: none;    
  -ms-user-select: none;      
  user-select: none;
  
cursor:pointer;  

}
```



## Step 3:
Create a script file as well now in javascript.
click_winner/js/script.js

``` 
var pl = document.getElementById('plane');


//make a gravity for Plane;

var x =0;
var y=0;
var score = 0;


var timer_start = setInterval(makeMove, 10);

function makeMove(){
 x++;
 y++;


pl.style.transform = "translate("+ x +"px"+","+ y+"px)";


if(y >= 200){
  x = Math.floor(Math.random()*300);
  y = Math.floor(Math.random()*300);
  
 }
}



pl.onclick = ()=>{
score++

document.getElementById('score').innerHTML = score;
}

var time = 0;
setInterval(()=>{
time++;
document.getElementById('time').innerHTML = time + " Seconds left";

if(time == 60){
clearInterval(timer_start);
alert("Time Off. Restart the game again..")
}

}, 1000);

```




## Conclusion

I hope you guys enjoyed my simple game. If you learned something new today. You can check out the source code <a href="https://github.com/pt67/click_winner">here</a>.

Thank you!
WordCamp MontClair: The WordPress all-women and non-binary release squad: contributing to WordPress and more
Tags: speaking, wordpress
Published: 2022-12-01 19:03:59

---
title: WordCamp MontClair: The WordPress all-women and non-binary release squad: contributing to WordPress and more
published: true
date: 2022-06-25 16:49:52 UTC
tags: Speaking,WordPress
canonical_url: https://courtneyr.dev/2022/06/25/wordcamp-montclair-the-wordpress-all-women-and-non-binary-release-squad-contributing-to-wordpress-and-more/
---

![wcmontclair jpg](https://courtneyr.dev/wp-content/uploads/2022/10/wcmontclair-jpg.webp "WordCamp MontClair: The WordPress all-women and non-binary release squad: contributing to WordPress and more 58")

![wcmontclair jpg](https://courtneyr.dev/wp-content/uploads/2022/10/wcmontclair-jpg.webp "WordCamp MontClair: The WordPress all-women and non-binary release squad: contributing to WordPress and more 57")

<!-- wp:embed {"url":"https://videopress.com/v/6cnjGmW3","type":"video","providerNameSlug":"videopress","responsive":true,"align":"wide","className":"wp-embed-aspect-16-9 wp-has-aspect-ratio"} -->

https://videopress.com/v/6cnjGmW3

<!-- /wp:embed -->

This article first appeared on:  
 ![](https://courtneyr.dev/wp-content/uploads/2022/10/wcmontclair.jpg)  
[Courtney Robertson -](https://courtneyr.dev)  
by [<span class='p-author h-card'>Courtney Robertson</span>](https://courtneyr.dev/author/courane01/)
Svelte Origins: A JavaScript Documentary
Tags: svelte, javascript, typescript, webdev
Published: 2022-06-25 16:46:39

Svelte Origins: The Documentary tells the story of how Svelte came to be, what makes Svelte different, and how it changes the game as a JavaScript framework. Filmed in locations throughout Europe and the US, it features Svelte’s creator Rich Harris and members from the core community who contributed to making Svelte what it is today.

Svelte Origins was filmed in late 2021, produced by **OfferZen** and directed by Dewald Brand, with shoots in the USA, the UK, Ireland, Sweden and Germany.

<br />
**OfferZen** is a developer job platform helping developers find jobs they love in positions they deserve. Want to know more about OfferZen?. [Dev Jobs](https://bit.ly/dev-jobs-sdo)

Connect with OfferZen:
[Youtube](https://www.youtube.com/c/OfferZenOrigins) [Twitter](https://twitter.com/offerZen/) [Instagram](https://www.instagram.com/offerzen/) [Facebook](https://www.facebook.com/offerzen/) [LinkedIn](https://www.linkedin.com/company/offe...)
Control Version de una base de datos Oracle
Tags: oracle, ci, backend
Published: 2022-06-25 16:41:46

Podemos mencionar dos proyectos que nos ayudarán con el control de versiones de nuestra base de datos: Flyway y Liquibase.

Dada la integración de SQLcl y Liquibase, este ejemplo nos da una solución para podemos emplear entre distintos equipos.

---

La primera recomendación es usar **GIT**. Tener un repositorio único, permite el seguimiento de cada cambio en la base de datos.

Como segunda recomendación, tener _scripts_ tan atómicos como sea posible. Ello nos da la agilidad de remover o reemplazar los cambios.

Finalmente, usen un formato estandarizado para nombrar los archivos:

```
{YYYYMMDD}_{TEAM}_{SSS}_{DESC}.sql 
```
---
1.- Todos los _scripts_ los almacenamos en una carpeta específica:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/269il9256wgrjhd8rpzc.png)

2.- Usar un archivo _controller.xml_ el cual hace referencia a los _scripts_, abstraemos a los programadores de darles formato.
```xml
<?xml version="1.0" encoding="UTF-8"?> 
<databaseChangeLog
  xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:n0="http://www.oracle.com/xml/ns/dbchangelog-ext"
  xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
                      http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.3.xsd">
  <changeSet id="20220623_TRED_001_VM1" author="erios" labels="q3s1">
     <n0:runOracleScript objectName="20220623_TRED_001_VM1" ownerName="PTOVENTA" sourceType="FILE">
         <n0:source><![CDATA[20220623_TRED_001_VM1.sql]]></n0:source>
     </n0:runOracleScript>
  </changeSet>
  <changeSet id="20220623_TRED_002_VM2" author="erios" labels="q3s1">
     <n0:runOracleScript objectName="20220623_TRED_002_VM2" ownerName="PTOVENTA" sourceType="FILE">
         <n0:source><![CDATA[20220623_TRED_002_VM2.sql]]></n0:source>
     </n0:runOracleScript>
  </changeSet>
``` 

3.- Ejecutamos la actualización:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4o8852unrxewq0hp0udi.png)

4.- Verificamos la ejecución histórica:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h0iaiformpq2yux6jobs.png)

--- 
## Documentación
https://docs.oracle.com/en/database/oracle/sql-developer-command-line/22.2/sqcug/using-liquibase.html
Hello Testing... 1,2,3
Tags: javascript, beginners, tutorial, programming
Published: 2022-06-25 15:24:01

## This is a heading

![Cat](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x8l2ebqsdgu6kt6ct9io.jpg)

1. **Order List**

2. [Facebook](https://facebook.com)
Why frameworks should not be progressive?
Tags: webdev, beginners, programming, tutorial
Published: 2022-06-25 15:14:08

## What makes a framework?

A framework is an abstraction of its main purpose.
It is determined before it is created.
It is frequently reused for all projects based on it.
Its core value can be very easily verified.
Its main ideas are permanent and will never change.

## Why there should be no progressive framework?

A progressive framework is telling you that it is under consideration and maybe false abstracted.

It would do harm to all projects that base on it.
And it is anti the reason why a framework should exist.

If a framework changes every time, it should never be called a framework. It is just a program.

## What can be progressive?

Even a framework should never be progressive, the development process will always be progressive.

When the framework goals reached, a framework comes to its life cycle stage called maintenance.
And the progressive process ended.

## Conclusion

If you decide to write a new framework, you should verify if the framework is definite and finalized, and it will be frequently reused. If not, you just start a new program not a framework.
10 Piriformis Stretches To Get Rid Of Sciatica, Hip, And Lower Back Pain
Tags: discuss, opensource, news, architecture
Published: 2022-06-25 15:13:39

The human body is incredibly complex. If there is just one tiny structure that isn’t doing its job, we can experience devastating consequences.

This is true of all parts of the body. For example:

A tear of the minuscule supraspinatus muscle in the shoulder can make it difficult to use the arm.
Damage to the 1.5-inch ACL in the knee can prevent many athletes from ever returning to high-level competition.
Any muscles that press even slightly on the sciatic nerve in the leg can cause debilitating pain and weakness.
For the purposes of this article, we are most concerned with the third bullet point above. 

Specifically, how a small muscle known as the piriformis can pinch the sciatic nerve. And how that leads to numbness, pain, and weakness throughout the entire leg. [READ MORE](https://www.emon.eu.org/2022/05/10-piriformis-stretches-to-get-rid-of.html)
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Health Care, Health Insurance, Health (India), Health Care Technology, Health Care (Canada), World Health Organization, Health Care (India), Public Health, Mental Health, Healthy Eating, Healthy Recipes, Health Records, Health Care Law, Health Care (Australia), Digital Health, eHealth, Medical Technology, Health Information, Nutrition, Diabetes, Fraser Health, Vitamins, Vitamin C, Vitamin D, Vitamin B, Vitamin E, Vitamin A, Antioxidants, B Vitamins, Calcium, Free Radicals, Diets, Wellness, Dermatology, WorkoutsExercise Science, Sports Science, Aerobic Exercise, Bodyweight Exercise, Strength Training, Home Workouts, Kinesiology, Interval Training, HIIT, Weight Training, Pilates, Sports Medicine, Kettlebell Exercises, Running Workouts, Sports Nutrition, Full Body Workouts, Resistance Training, Sports Psychology, Chest Workouts,
Code Smell 144 - Fungible Objects
Tags: webdev, beginners, programming, tutorial
Published: 2022-06-25 14:59:38

*We have heard a lot about NFTs. Now we master the Fungible concept*

> TL;DR: Respect the [MAPPER](https://dev.to/mcsee/what-is-wrong-with-software-5pa). Make fungible what is Fungible in real-world and vice-versa.

# Problems

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

- Over Design

# Solutions

1. Identify fungible elements on your domains

2. Model them as interchangeable

# Context

According to [Wikipedia](https://en.wikipedia.org/wiki/Fungibility)

> Fungibility is the property of a good or a commodity whose individual units are essentially interchangeable and each of whose parts is indistinguishable from another part.

In software, we can replace fungible objects with others.

When [mapping](https://dev.to/mcsee/what-is-wrong-with-software-5pa) our objects with real ones, we sometimes forget about the *partial* model and build over design. 

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

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/3fc2c7089aa88088a73138ee6b62e675)
```java
public class Person implements Serializable {
    private final String firstName;
    private final String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

shoppingQueueSystem.queue(new Person('John', 'Doe'));
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/97a8fd4467d51b6769f7ba63210dddee)
```java
public class Person  { 
} 

shoppingQueueSystem.queue(new Person());
// The identity is irrelevant for queue simulation 
```

# Detection

[X] Manual

This is a semantic smell.

We need to understand the model to check whether it is right or not.

# Tags

- Over Design

# Conclusion

Make fungible what is fungible and vice-versa.

Sounds easy but requires design skills and avoiding accidental complexity.

# Credits

Photo by [Andrey Metelev](https://unsplash.com/@metelevan) on [Unsplash](https://unsplash.com/s/photos/nft)
  
* * *

> People think that computer science is the art of geniuses but the actual reality is the opposite, just many people doing things that build on each other, like a wall of mini stones.

_Donald Knuth_
 
{% 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 %}
Paracetamol.js💊| #153: Explica este código JavaScript
Tags: javascript, spanish, webdev, programming
Published: 2022-06-25 14:56:59

## **<center>¿Qué nomenclatura de importaciones representa el siguiente código?</center>**
#### <center>**Dificultad:** <mark>Intermedio</mark></center>
Se asume que ambos archivos, `index.js` y `operaciones.js` están en el mismo directorio.

```js
//index.js
module.exports = {
  suma(a, b) {
    return a + b;
  }
};

//operaciones.js
const calculadora = require("./index.js");
const { suma } = calculadora;
```

A. `Módulos ES6`
B. `IIFE`
C. `CommonJS`
D. `Ninguna de las anteriores`

Respuesta en el primer comentario.

---