teleren/devto huggingface dataset:
¿Cómo crear mi primer proyecto en Spring boot?
Published: 2023-01-23 21:42:05

## Requisitos

* JDK de java, 8+
* Maven
* Ide intelliJ IDEA o VSCode

---

## 1) Iniciar el proyecto

Aunque es un tema aparentemente trivial, para los usuarios que se inician o iniciarán en el desarrollo de aplicaciones con Spring Boot resulta importante conocer esta utilidad que reduce drásticamente el tiempo inicial de crear y configurar las dependencias de un nuevo proyecto. 

Hablaremos de Spring Initializr que es una API que permite la generación de proyectos con sus dependencias permitiendo simplificar esta etapa inicial de arranque de nuevos proyectos.

Spring Initializer nos ofrece 2 alternativas:

- API: Interfaz que permite la integración con IDEs y entornos como Intellij IDEA, Eclipse, otros.

![Interfaz API en Intellij IDEA](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pnbdhuoc494f73ut4j0q.png)

- WEB: Interfaz web que permite directamente desde el navegador generar un proyecto, visualizar y descargarlo para luego cargarlo en nuestro entorno de desarrolllo. Esta web está disponible en https://start.spring.io/

![Interfaz web](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/swqmxi4r8lsvd1ovrc7v.png)

### 1.1) Contenido de Spring Initializer


**- Project:**
El apartado de proyecto nos permite elegir el gestor de dependencias que queremos usar en nuestro proyecto. Los gestores de dependencias más usados son: Maven y Gradle.

**- Lenguaje:**
Este apartado nos permite elegir el lenguaje en el que queremos trabajar: Java, Kotlin o Groove.

**- Versión de Springboot:**
Podremos elegir la versión de Spring boot con la que queremos trabajar. (Podremos modificarla posteriormente)

**- Metadata:**
Datos sobre el nombre del paquete y la arquitectura de carpetas y paquetes.

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

**- Empaquetado y versión de Java: **
Tipo de empaquetado que queremos tener en nuestra aplicación:
* JAR (Java ARchive)
* WAR (Web Application Archive)

y Versión de Java que se quiere utilizar.

**- Dependencias**

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

En esta interfaz podremos seleccionar las bibliotecas que queremos usar en nuestro proyecto según sean el conjunto de funcionalidades que queremos que este tenga.


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

Librerías seleccionadas para crear un pequeño CRUD que se conectará a una base de datos postgres que explicaremos en un siguiente artículo.

### 2) Generar proyecto

Para generar el proyecto pulsaremos en el botón "Generar" que nos descargará un archivo .zip que contendrá la arquitectura del proyecto que construimos.


![Arquitectura descargada](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iwe4z2t10chb6mr6gck1.png)
10 Secrets to Boosting Your Productivity as a Developer - #7 Will Shock You!
Published: 2023-01-23 21:34:41

As developers, we all know how important it is to be productive. With so many tasks to juggle and deadlines to meet, it can be easy to get overwhelmed. But what if I told you that there are secrets to boosting your productivity as a developer?

1. **Prioritize your tasks**
Make sure you are working on the most important tasks first.

2. **Use keyboard shortcuts**
Keyboard shortcuts can save you a lot of time in the long run.

3. **Keep your workspace clean**
A cluttered workspace can lead to a cluttered mind

4. **Take regular breaks**
Sitting in front of a computer all day can be tiring. Make sure to take regular breaks to refresh your mind.

5. **Use a timer**
Set a timer for specific tasks to keep yourself on track.

6. **Use an app to block distractions**
There are many apps available that can block distracting websites and apps.

7. **Try the Pomodoro Technique**
This technique can help you to increase focus and productivity by taking short breaks after 25 minutes of work.

8. **Automate repetitive tasks**
Use tools or scripts to automate repetitive tasks.

9. **Learn to say no**
Don’t be afraid to say no to tasks that are not a priority.

10. **Get enough sleep**
A well-rested brain is a productive brain.

#7 is a game changer and will shock you! Try the Pomodoro Technique and see the difference it makes in your productivity. Give it a shot and let me know in the comments how it worked for you!
I wold like creat search engine whit React/php
Tags: react
Published: 2023-01-23 21:32:39

Hello every body! Il french and sory for my rough english. I creat now a search engine whit React and php but they are nothing  result, and nothing message for error exept "Firefox cannot establish a connection to the server at ws://localhost:3000/ws." in a console. 

This is my App for react:

```
import React from 'react'
import Turnstone from 'turnstone'

const styles = {
  input: 'border p-2 bg-white w-full',
  listbox: 'border p-2 bg-white w-full'
}

// Set up listbox contents.
const listbox = {
  
  data: (query) =>
    fetch(`http://essai/mr/query.php?query=${encodeURIComponent(query)}`)
      .then(res => res.json())
}




console.log(listbox);

export default function BasicExample() {
  return <Turnstone id="autocomplete" listbox={listbox} styles={styles} typeahead={false} />
}
```
And this is my PHP is name query in my Wamp. 

```
<?php


header('Access-Control-Allow-Origin: http://localhost:3000');


 header("Content-Type: application/json");

$nbr = 0;

$data = array();
 
$output = '';
 
$name = $_GET['query'];

 


//fetch.php
$connect = mysqli_connect("localhost", "root", "", "immoffre");
$output = '';
if(isset($name))
{
 $search = mysqli_real_escape_string($connect, $name);
 $query =  "
 SELECT * FROM villes_france 
 WHERE ville_nom LIKE '%" . $search . "%'
 OR ville_slug LIKE '%" . $search . "%' 
 OR ville_code_postal LIKE '%" . $search . "%' 
 LIMIT 5
";
}
else
{
 $query = "
  SELECT * FROM tbl_customer ORDER BY CustomerID
 ";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
 
 while($row = mysqli_fetch_array($result))
 {


    $nbr++;
    $data[$nbr]   =   $row["ville_nom"];
 


 
 }
 
}
 
echo json_encode($data);

 
?>
```
Thank you for your consideration!
Facts no one knows about programmers
Tags: programmer, beginners, career, computerscience
Published: 2023-01-23 21:24:14

Here are a few fun facts about coders or programmers that you may not know about:

1. Many early computer programmers were women: During the 1950s and 1960s, when computers were first being developed, many of the programmers were women. This is because computers were seen as more of a "girl's job," and many women were hired to work as "computers" (people who did calculations by hand) before computers were even invented.

2. The first computer programmer was a woman: Ada Lovelace, an English mathematician and writer, is considered to be the world's first computer programmer for her work on Charles Babbage's Analytical Engine in the 19th century. She wrote the first algorithm intended to be processed by the machine.

3. Some programmers use "rubber duck debugging": This is a technique where a programmer explains their code, line by line, to a rubber duck or any other inanimate object. The act of explaining the code helps the programmer to find the errors or bugs in their code.

4. The term "debugging" comes from an actual bug: In the early days of computing, bugs were not just a metaphorical term for errors in the code, but actual bugs that would crawl into the computer and cause problems. The term "debugging" comes from the practice of physically removing bugs from the computer.

5. The first computer virus was created by a 15-year-old: In 1986, a 15-year-old boy named Rich Skrenta created the first computer virus, called Elk Cloner. He wrote it as a joke and distributed it on floppy disks to his friends.

6. The first computer game was written by a programmer: The first computer game was written in 1958 by William Higinbotham, a physicist and programmer, called Tennis for Two. It was a simple game that used an oscilloscope as a display and was played on an analog computer.

7. The term "hacker" was originally a compliment: In the early days of computing, a "hacker" was someone who was skilled and clever with computers. The term has since taken on a negative connotation, but it originally was a compliment.
Understanding :has() selector in CSS.
Tags: css, webdev, programming, tutorial
Published: 2023-01-23 21:21:33

While working on CSS problems I have come across a situation multiple times where I need to **apply styles to parent element only if it has a specific type of child element**.
For example - 

```
/* Selects an h1 heading with a
paragraph element that immediately follows
the h1 and applies the style to h1 */
```

The solution to above problem is using **:has()** pseudo-class which is also commonly known as **parent selector**. If we had to do vice versa where styles need to applied to paragraph element(child) we can use `>` selector.

## Let's understand this more in detail with the help of an example.

Suppose we are working on an application which has a page containing multiple figures with and without captions. Let's say we have to apply styles to the figures with captions.

Here we can make use of `:has()` selector which will help us to identify figure with caption and apply to it.

Syntax for `:has()` selector is -
```css
:has( <relative-selector-list> )
```

{% codepen https://codepen.io/jasmin_virdi/pen/OJwQMOq %}

In order to select the figure element with figcaption I used the following code on css.

```css
figure:has(figcaption){
  apply styles here...
}
```

Point to note about **`:has()` selector is supported in Firefox behind the `layout.css.has-selector.enabled` flag.**

In order to check the browser compatibility of the `:has()` selector I have used [`@supports`](https://developer.mozilla.org/en-US/docs/Web/CSS/@supports) CSS at-rule to specify the declaration on browser support for this feature.

For this I have wrapped my code around - 
```css
@supports(selector(:has(*))) {
    figure:has(figcaption) {
       apply styles here...
    }
}
```

A fallback logic is a good to have in case if this does not work in any browser due to compatibility issues. We can use JS to select the parent element and apply styles to it after checking the CSS support of `:has()` feature in the browser.

```js
if (!CSS.supports('selector(:has())')) {
    const galleryFigures = document.querySelectorAll("figure")

    // loop over each HTML figure element to find if figcaption is present
    for (let figure of galleryFigures) {
        console.log(figure.children.length)
        if (figure.children.length === 2) {
            figure.style.height = '18rem';
            figure.style.borderRadius = '10px';
            figure.style.background = 'linear-gradient(to right, #935116, #FAE5D3)'
            figure.style.color = 'white';
            figure.style.backgroundSize = '400% 400%';
        }
    }
}
```
## Conclusion
In this article we have seen the usage of `:has()` property along with some interesting examples. We also covered its browser compatibility and a fallback logic in case of missing support. Feel free to add more points to this article. 


Happy Learning! 👩🏻‍💻
Better Alternatives to React's useState Hook
Tags: webdev, javascript, react, reactnative
Published: 2023-01-23 21:07:17

React's way to declare state is interesting, the useState Hook returns you an array of the state and a function to change the state.

The question is, how many times do you need those two elements seperately ?

I mean you always need both, you wouldn't declare the state only to have the setter function, or just the state itself without setter right? If no, why on earth would you do something like that?

Anyway, in this post I want to present two different way to declare the state: I call it the vue-like way and the solid-like way, just because they share some similarities.

## The vue-like way

For this let's design the useBetterState() hook:

```javascript
const useBetterState = (value) => {
  const [state, setState] = useState(value)
  return {
    get value() {
      return state
    },
    set value(v) {
      setState(v)
    }
  }
}
```
Now that it is defined, we can use it like this

```javascript
const Counter = () => {
  const count = useBetterState(0)

  const increment = () => {
    count.value++
  }

  return (
    <>
      <div>{count.value}</div>
      <button onClick={increment}>+</button>
    </>
   )
}
```
So much better Right ?

## The solid-like way

I know solid also have a both the state and it's setter separately, but the similarity is in the use of a function to display the state.
```javascript
const useSuperState = (value) => {
  const [state, setState] = useState(value)
  return function(v) {
    if (v != null) {
      setState(v)
    }
    return state
  }
}
```
And we can use it this way:
```javascript
const Counter = () => {
  const count = useSuperState(0)

  const increment = () => {
    count(count() + 1)
  }

  return (
    <>
      <div>{count()}</div>
      <button onClick={increment}>+</button>
    </>
   )
}
```
As you can see, the whole idea of this experiment is to use one variable instead of two to manage a state.

Now before you scream blasphemy, remember this is just an experiment.
And before you write a comment think of me as a violent criminal who knows where you live lol :).

Let me know you thoughts though, I am really curious.
Refactoring RATOM: Day 1
Tags: email, htmx, django, react
Published: 2023-01-23 20:55:00

### Where to start?

Whelp, as it often is... the best laid plans. 

I thought I would spend the day spinning up the system, so I could refresh myself as to the site structure from a UI/UX perspective, but instead I got caught up in getting testing and CI to work.

The moral of this story...

### Tech Debt Is Everywhere

[Jade-truffle](https://github.com/JeremyGibson/jade-truffle) the cookiecutter template that I used to bring up the skeleton of the application, has been pretty well maintained, and I took some pains when designing it, to create the most up to date site possible. No versions of anything are pinned in the pip-tools `.in` files, and the requirements are resolved at the time the cookiecutter is run.

Even so, other places that I hadn't thought to look had rotted away:
* pre-commit.config.yml was out of date with many of its revs.
* flake8 started failing because of changes in a major version
* An initiative to add accessibility testing into jade-truffle had some quirks that I missed on the initial PR.

I had to fix all of those to go from angry red x's on my repo to happy green ticks.

On to tomorrow.

[Previous Post](https://dev.to/jeremygibson/refactoring-ratom-with-htmx-586g)

[Next Post](https://dev.to/jeremygibson/refactoring-ratom-day-3-5gm1)
🌶️ Hot tip - Use snapshots in React Testing Library to debug faster ⚙️
Tags: react, testing, javascript
Published: 2023-01-23 21:06:53

So you have this test that is already spitting out something big and complex to DOM and it's failing to find the expected element. You see the usual error message `TestingLibraryElementError: Unable to find an element with the text: ...` and absolutely have no idea where things might have gone wrong. Inline errors are nice, however, you can't see the problem. 🙈

![Usual error message for failing test](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lhgdtwn1r8782gda6u3a.png)

🍀 To solve this we will leverage snapshot testing! 🍀

Modify your test to get the `container` out of render, then make a snapshot with `expect(container).toMatchSnapshot()` 🪄. Notice, this trick can be applied regardless of the complexity of your test.

![Create a snapshot file to better understand your DOM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/byqmnxtr7f1m1wx7rho0.png)

Re-run your test you'll see the snapshot file 🎉 (`App.test.tsx.snap`), which is now totally under your control. 

You can easily spot the problem and search your way through. It's pretty printed and already formatted as your IDE knows this stuff. Feel free to look around and close/open tags **to see what is the actual DOM content at this point of the test**.

![Navigable snapshot of your DOM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fp9ldwaolqfuiofrc8vn.png)


Okay, we've found the problem, we missed some additional characters inside. Now we can fix our test. We can rerun and see it's all green 💚.

![Test fixed](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/thll5kzbyfma5p0a7tjg.png)

🚨 Also, make sure you remove the `*.snap` file and the related `toMatchSnapshot` line to avoid having unexpected snapshot tests later.

💡 This technique is especially useful when your component is rendering a huge markup (maybe a composite component already) and you can't find out why your test is not finding an element.

💡 Also useful to apply this technique if you just want to know the DOM state at a given step. If you are testing a loader with async data, you'll be able to make a snapshot before and after the async data have been loaded.

Let me know if you find this useful 😊

Hungry for more RTL tips 🍽️ ? See my previous post ➡️ [Top 3 React Testing Library mistakes I should have spotted earlier 🚀](https://dev.to/jozsefdevs/top-3-react-testing-library-mistakes-i-should-have-spotted-earlier-9hd)

Happy testing!
Cap XII: Todo está en la UI, El libro negro del programador. 💻
Tags: productivity, books, programming, spanish
Published: 2023-01-23 21:06:34

## **Todo está en la UI**

---

> **He aquí uno de los grandes problemas de los desarrolladores web: lo que creamos es intangible y por ende difícil de valorar el esfuerzo que costó crear, diseñar e implementar una solución.**

---

* Al ver un producto como un vehículo, un teléfono, un electrodoméstico; no es posible imaginar que dicho producto fue creado por una sola persona. Hubo un equipo de trabajo detrás.

* En software el cliente no puede ver la enorme complejidad que hay por detrás que hace que el software funcione, como mucho el cliente solo puede ver la UI.

* No se ve claramente el esfuerzo del trabajo realizado, no se puede imaginar el esfuerzo y dedicación del producto.

* Se menosprecia el hecho de que un cliente pueda valorar injustamente el esfuerzo y dedicación.

* Debemos ofrecer al usuario aplicaciones sencillas de usar que escondan la complejidad del sistema.

* Google es visualmente solo un input con un botón de búsqueda, pero por detrás hay todo un conjunto de algoritmos optimizados y una infraestructura de hardware que hacen que funcione de tal forma que parece magia.

* Ofrecer funcionalidad de la manera más sencilla posible es un reto de diseño y usabilidad.

* Se va a valorar la calidad de nuestro trabajo por la calidad de UI que podamos desarrollar.

* La UI es lo único que se ve, lo único que el cliente percibe.

* Por más que tengamos un mega software que funcione de maravilla, si no se ve bien el usuario no querrá usarlo.

* **No solo hay que ser bueno, sino parecerlo.**

* La impresión que podemos causar con solo desarrollar una UI llamativa es muy importante.

* Al usuario final no le interesa lo que hemos sufrido para crear un diseño simple y elegante, ni la metodología ágil que hemos usado, ni la disposición que tenemos a refactorizar todo de manera continua, o las pruebas automáticas que ejecutamos.

* Lo que le interesa es que la solución dada le aporte valor y mejore de manera sustancial su negocio.

* La UI es el peaje de la app.

---

Te dejo el link gratuito de [*El libro negro de programador*](https://underpost.net/ir/pdf/cy3/el-libro-negro-del-programador.pdf) por si te intesa leerlo, o dale click a la imagen:


[![libro](https://www.digitalskillsinstitute.com/assets/media/books/5541eba31b4b42b5bb021dc77c70d658-480.jpg)](https://underpost.net/ir/pdf/cy3/el-libro-negro-del-programador.pdf)
SRE book notes: Simplicity
Tags: sre, books
Published: 2023-01-23 21:06:33

These are the notes from [Chapter 9: Simplicity](https://sre.google/sre-book/simplicity/) from the book [Site Reliability Engineering, How Google Runs Production Systems](https://sre.google/sre-book/table-of-contents/).

This is a post of a series. The previous post can be seen here:

{% embed https://dev.to/bitmaybewise/sre-book-notes-release-engineering-244c %}

---

> “The price of reliability is the pursuit of the utmost simplicity.” — C.A.R. Hoare, Turing Award lecture

---

> A software system can only be perfectly stable if it exists in a vacuum.

---

> Unlike just about everything else in life, "boring" is actually a positive attribute when it comes to software! We don’t want our programs to be spontaneous and interesting; we want them to stick to the script and predictably accomplish their business goals.

“Boring” is not always a pejorative word. We should consider that a blessing in software engineering.

I never heard anyone complaining about maintaining “boring“ software. XD

---

> when you consider a web service that’s expected to be available 24/7, to some extent, every new line of code written is a liability

---

> French poet Antoine de Saint Exupery wrote, "perfection is finally attained not when there is no longer more to add, but when there is no longer anything to take away"

---

> A small, simple API is usually also a hallmark of a well-understood problem.

---

> It is much easier to measure and understand the impact of a single change rather than a batch of changes released simultaneously.

---

If you liked this post, consider subscribing to my newsletter [Bit Maybe Wise](http://bitmaybewise.com/).

You can also follow me on [Twitter](https://twitter.com/bitmaybewise) and [Mastodon](https://mastodon.online/@bitmaybewise).

---

Photo by [Андрей Сизов](https://unsplash.com/@alpridephoto) on Unsplash