teleren/devto huggingface dataset:
Composition and Inheritance: From Cars to Cars
Tags: webdev, python, programming, tutorial
Published: 2023-08-28 23:35:44

Hello and welcome! A while back, I tackled a real-world problem through Forage, and the company at the center was [Lyft](https://www.lyft.com/). While much of the material covered wasn't entirely new, what intrigued me were the concepts of _composition_ and _inheritance_. These concepts played a central role in shaping Lyft's backend infrastructure and I thought to share my newfound knowledge with you. Stay tuned.

### Composition: Assembling a Car
Let's say we are putting together a car. A car is made up of lots of different parts, and instead of making the whole car all at once, we start by making smaller pieces. Then, we fit these pieces together to build the complete car. This way of building things is called _composition_. It's a helpful approach because it gives our car flexibility. We can easily add or remove pieces as needed. This makes our finished car more versatile.

Let's see an example:
```python
class Engine:
    def start(self):
        pass

class Wheels:
    def rotate(self):
        pass

class Car:
    def __init__(self, brand):
        self.brand = brand
        self.engine = Engine()
        self.wheels = Wheels()
```
Here, we are defining three classes: `Engine`, `Wheels`, and `Car`. Engine and Wheels represent parts of a car while the Car class brings together an engine and wheels to construct a complete car.

We see that each part has its own functionality with specific responsibilities. The engine starts, the wheels rotate and the car cars (I thought that would come out right).

### Inheritance: Family Traits Passed On
Inheritance is in the name, we inherit traits from our parents. Same applies here as our classes inherit characteristics from their base class. We can create new things based on existing things and pass down their characteristics. This approach makes us more efficient as we do not need to create things from the start.

Let's see an example:
```python
class Vehicle:
    def __init__(self, brand):
        self.brand = brand

class Car(Vehicle):
    pass

# Creating an instance of Car
my_car = Car("Toyota")
print(f"My car's brand is {my_car.brand}")
```
The `Car` class inherits the `brand` attribute from the `Vehicle` class without needing to redefine the `__init__` method. The Car class inherits all attributes and methods from the Vehicle class while also retaining the ability to redefine and implement its own variations.

You could use both composition and inheritance together to get the best out of your application. If you'd like to explore how I employed both to address the Lyft challenge, you can find the code [here](https://github.com/ajipelumi/forage-lyft-starter-repo/tree/main).

If you've got stories about using composition and inheritance, I would love to hear them. Drop a comment below and share your experiences!
How to Create a Draughts Game Board with HTML, CSS, and JavaScript
Published: 2023-08-28 22:55:49

Otherwise known as Checkers, draughts "is a group of strategy board games for two players which involve diagonal moves of uniform game pieces and mandatory captures by jumping over opponent pieces."

You can create an amazing draughts game board with HTML, CSS, and JavaScript. 

**HTML Session**

In the HTML section, create the board's skeleton with the table tag and its elements. 

The draughts board consists of 64 cells with alternating black and white colors. 

 <table id = "game-board">

    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>

    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>

    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>

    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>

    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>

    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>

      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>

      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>

  </table>

**CSS Section**

Define the draught's properties such as the board size, cells, and color in this section. 

table {
      border-collapse: collapse;
    }

    td {
      border: 1px solid black;
      padding: 3px 5px;
      width: 50px; 
      height: 50px;
    }

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background-color: #f0f0f0;
}

.game-board {
  border-collapse: collapse;
  border: 2px solid #000;
}

.cell {
  width: 50px;
  height: 50px;
  text-align: center;
  vertical-align: middle;
  font-size: 24px;
  cursor: pointer;
}

.black {
  background-color: #000;
  color: #fff;
}

**JavaScript Section**

Here is where you define the alternating black and white colors. 

let table = document.getElementById("game-board");

let rows = table.getElementsByTagName("tr");

for (let i = 0; i < rows.length; i++) {
  let cells = rows[i].getElementsByTagName("td");
  
  for (let j = 0; j < cells.length; j++) {
    if ((i + j) % 2 === 0) {
      cells[j].style.backgroundColor = "black";
    } else {
      cells[j].style.backgroundColor = "white";
    }
  }
}

Conclusion
You can effortlessly create the a checkers board with the above code
When Lost, Choose All.
Tags: django, webdev, programming, productivity
Published: 2023-08-28 22:28:51

##Dev Journey #6
Hello Fella LinkedIn-istas, today I’m back with another update on my web-development journey. 
Ever since the post I put out last week, I’ve been so lost. 


- Should I continue to learn Django Rest Framework?
- Should I start learning JavaScript since it’s required in every web development job ever?
- Should I stop thinking ahead of myself and just focus on creating new projects to add to my portfolio ? 
- How should I go about my journey? 


It felt like I was driving on a highway really fast and I couldn't find an exit to continue driving to my destination. A couple of reddit posts, dev talks and YouTube tutorials later, I got it all figured out! 

I decided that I should do everything I mentioned above and more. The trick lies within the order. As a person who loves Depth-First-Search strategies, I’ll start with making a couple more Django projects that serve different areas of life in general.


 **Currently** I’m working on a company landing page for my game development team (**StageRibbon**), next up I’ll try to make a database website, where you can store data and view them in a variety of ways (charts, spreadsheets and more.. ) just to sharpen my skills in building **CRUD**(Create, Read, Update, Delete) functionalities, viewing different types of data and manipulating them with a simple user interface and in securing a website’s data flow.

- Once I finish my next project, I’ll hop on learning DRF (Django Rest Framework).
- Once I’m comfortable with that I’ll then go ahead and start to build some real frontend skills with JavaScript.

And since I know that learning a new programming language is a long journey and I really need a job as soon as possible, I decided to take a rough turn and try freelancing.
_Now, I know that you are probably thinking that it isn’t going to work and it’s a total waste of time, and that’s what I myself heard when I went asking for people's views on freelancing._ 

## BUT
, what pushed me to that corner is that most of the stuff required on websites like **Fiverr **are simple and doesn't require a lot of complicated work, that, and the fact that I’m not limiting my work there with web-development.

I just posted my first service (Called Gig there) and I offered nearly free music production for multiple purposes (songs, games, videos, trailers and such).
And I’ll just sit and wait for the results. I’m not hoping for anything to happen, but if it did, **it’ll motivate me** to grow my skills even more and seek new limits for myself.

 I’m posting about this dilemma that I faced recently to encourage any developer stuck in a place like the one I’m at to seek people’s advice and to try different things even if they are kind of frowned upon by the majority of the community.

> Because I believe in trial and error. I also believe that nobody knows nothing about anything until he/she realize that he/she knows nothing about it. And this journey to explore beyond the norm is our mission as humans to discover the unknown.

## Until next time people !
Step by step guide to becoming a Data Scientist in 2023
Published: 2023-08-28 22:14:41

## AI and Data Science Roadmap

I have noticed a consistent demand from our dear learners for some sort of roadmap that can assist them in their learning journey. In response to this, i recognize the importance of providing a clear and comprehensive guide to aid learners in achieving their educational goals.

## The Learning Sea
Navigating the path of learning can often be a daunting task, especially in today's fast-paced world where information is abundant and diverse. With so many options available, it's understandable that learners seek a structured approach to their learning process. I think that a roadmap serves as a valuable tool, offering a step-by-step plan that outlines the key milestones and resources needed to progress efficiently.

## Keep going
Furthermore, a roadmap serves as a source of accountability. As learners check off milestones and achievements, they experience a sense of accomplishment that propels them forward. In moments of uncertainty, the roadmap acts as a guiding light, reminding learners of their purpose and encouraging them to persevere.

## A testimony
At the beginning of my learning journey I felt very lost, and I didn't know how to organize my studies in order to feel some progress in my learning, that's when I found a roadmap platform. Today they released a roadmap dedicated to data science and strongly recommending DeepLearning.AI


Keep in mind that it is a tool just like the other one, so, do not take this platform as a dogma in your learning, instead keep yourself updated and exploring new horizons

[Data Science Roadmap](https://roadmap.sh/ai-data-scientist)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f99y8vyhut4ixyq3w7hv.jpg)
  
I Hope this roadmap help you in your journey.

Best regards

Image Cover by <a href="https://unsplash.com/pt-br/@purzlbaum?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Claudio Schwarz</a> at <a href="https://unsplash.com/pt-br/fotografias/fyeOxvYvIyY?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
Photo by <a href="https://unsplash.com/@sambalye?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Sam Balye</a> on <a href="https://unsplash.com/photos/w1FwDvIreZU?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
Leveraging PostgreSQL Full Text Search for Enhanced Content Discovery in Content Management Systems
Tags: postgres
Published: 2023-08-28 21:02:53

CMS (information Management Systems) have become essential for properly managing and delivering digital information. However, as the volume of content expands, it might be difficult to identify useful information. PostgreSQL's Full Text Search (FTS) features shine here. In this post, we'll look at how PostgreSQL FTS may be used to provide robust search capabilities within CMS platforms.

## Example Scenario: Building a Blog Post Search

Consider a CMS that hosts a large number of blog articles. Traditional searches may focus on exact keyword matches, ignoring content that use similar phrases or synonyms. Let's have a look at how PostgreSQL FTS can enhance the search experience:

### Step 1: Creating a Full Text Search Index

To get started, create a full-text search index on the relevant columns of your database table. In this case, we'll index the title and content columns of the blog_posts table:
```sql
CREATE INDEX blog_posts_fts_idx
ON blog_posts
USING gin(to_tsvector('english', title || ' ' || content));
```

### Step 2: Implementing FTS Queries

Now, let's explore various FTS queries to enhance content discovery:

#### 1. Basic Text Search:

Retrieve all blog posts containing the word "technology":
```sql
SELECT id, title
FROM blog_posts
WHERE to_tsvector('english', title || ' ' || content) @@ to_tsquery('english', 'technology');

```
#### 2. Ranking Results:

Rank the results by relevance using the ts_rank function:
```sql
SELECT id, title, ts_rank(to_tsvector('english', title || ' ' || content), to_tsquery('english', 'technology')) AS rank
FROM blog_posts
WHERE to_tsvector('english', title || ' ' || content) @@ to_tsquery('english', 'technology')
ORDER BY rank DESC;
```

#### 3. Phrase Search:

Search for blog posts containing the phrase "machine learning":
```sql
SELECT id, title
FROM blog_posts
WHERE to_tsvector('english', title || ' ' || content) @@ phraseto_tsquery('english', 'machine learning');
```

#### 4. Synonyms and Stemming:

Consider synonyms and stemming for a broader search:

```sql
SELECT id, title
FROM blog_posts
WHERE to_tsvector('english', title || ' ' || content) @@ to_tsquery('english', 'analyzing | analysing');
```

#### 5. Highlighting Matched Words:

Highlight matched words using the ts_headline function:
```sql
SELECT id, title, ts_headline('english', title || ' ' || content, to_tsquery('english', 'database')) AS highlighted_text
FROM blog_posts
WHERE to_tsvector('english', title || ' ' || content) @@ to_tsquery('english', 'database');
```
React Custom Hook: useStateWithValidation
Tags: webdev, javascript, programming, react
Published: 2023-08-28 21:00:00

In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the "useStateWithValidation" hook, one of the many carefully crafted hooks available in the collection of React custom hooks.

Github: https://github.com/sergeyleschev/react-custom-hooks
```javascript
import { useState, useCallback } from "react"

export default function useStateWithValidation(validationFunc, initialValue) {
    const [state, setState] = useState(initialValue)
    const [isValid, setIsValid] = useState(() => validationFunc(state))
    const onChange = useCallback(
        nextState => {
            const value =
                typeof nextState === "function" ? nextState(state) : nextState
            setState(value)
            setIsValid(validationFunc(value))
        },
        [validationFunc]
    )
    return [state, onChange, isValid]
}
```
The **useStateWithValidation** hook combines the useState and useCallback hooks from React to provide an elegant solution. It takes two parameters: a validation function and an initial value. The validation function determines whether the current state is considered valid or not.

One of the key advantages of this custom hook is its flexibility. You can pass any validation function that suits your specific requirements. Whether it's checking the length of a string, ensuring a numeric value falls within a certain range, or performing more complex validations, useStateWithValidation has got you covered.
```javascript
import useStateWithValidation from "./useStateWithValidation"

export default function StateWithValidationComponent() {
    const [username, setUsername, isValid] = useStateWithValidation(
        name => name.length > 5,
        ""
    )
    return (
        <>
            <div>Valid: {isValid.toString()}</div>
            <input
                type="text"
                value={username}
                onChange={e => setUsername(e.target.value)}
            />
        </>
    )
}
```
In this example, the StateWithValidationComponent uses the _useStateWithValidation_ hook to manage the username state. The validation function checks if the length of the username is greater than 5 characters, and the isValid variable reflects the validity of the current input.

Full Version | React Custom Hooks:
https://dev.to/sergeyleschev/supercharge-your-react-projects-with-custom-hooks-pl4
Unleashing the Benefits: Why Embrace PostgreSQL Full Text Search
Tags: postgres
Published: 2023-08-28 20:58:11

PostgreSQL has proven to be a strong database system in the field of modern data management, acclaimed for its versatility and broad feature set. PostgreSQL Full Text Search (FTS) stands out as a fantastic tool for unleashing the entire potential of text-based data exploration among its features. This article explores the compelling reasons to use PostgreSQL FTS, emphasizing its benefits and real-world applications.


## Understanding PostgreSQL Full Text Search
Before we get into the benefits, let's go through what PostgreSQL Full Text Search is. FTS uses linguistic and semantic analysis to give contextually relevant search results, as opposed to traditional database search approaches that focus on exact word matching. This means that, rather than merely looking for a keyword, FTS takes into account word variants, synonyms, and word proximity to provide a more comprehensive and accurate search experience.

## Advantages of PostgreSQL Full Text Search

## Flexible Search Capabilities:
PostgreSQL FTS takes into account the intricacies of human language. Users can search for synonyms, similar terms, and even misspellings, allowing them to find content that might otherwise go unnoticed with typical searches.

### Ranking and Relevance:
FTS presents a ranking algorithm that ranks search results depending on their relevance. This means that users will get the most relevant content at the front of their search results, which will improve the user experience.

### Support for Complex Queries:
Advanced query options supported by FTS include phrase searches, boolean operators (AND, OR, NOT), proximity searches, and wildcard searches. This enables users to construct complex searches that capture unique needs.



### Efficiency and Performance:
The underlying indexing methods of PostgreSQL allow FTS to provide speedy search results even in databases with millions of records. Inverted indexing dramatically reduces search times while maintaining good performance.

### Language Support:
FTS is not restricted to English; it supports a diverse range of languages, enabling global applications without sacrificing accuracy.

### Integration with Other PostgreSQL Features:
PostgreSQL FTS works in tandem with other PostgreSQL functionalities. Combining FTS with normal SQL queries ensures consistency while also simplifies your development process.

## Conclusion
PostgreSQL Full Text Search is an amazing tool that completely changes the way we interact with text-based data. Its ability to understand language semantics and give contextually appropriate results enables organizations to design user-friendly search experiences. PostgreSQL FTS plays a critical role in enabling data exploration, boosting engagement, and ultimately contributing to the success of a wide range of applications, from e-commerce to CMS and beyond. Adopting PostgreSQL FTS is a strategic move that may propel your data-driven initiatives to new heights.
Client Side Rendering (CSR). ¿ReactJS es lento?
Tags: react, javascript, performance, typescript
Published: 2023-08-28 20:48:24

Para iniciar te recomiendo que leas mi [Post anterior](https://dev.to/wiar8/renderizados-en-la-web-para-que-sirven-11p)
en el que tendrás un poco más de contexto acerca del CSR y las otras estrategias de rendering.

Ahora sí, para comenzar, hay que hablar desde el inicio, de donde nace el CSR y por qué?

El CSR (Client Side Rendering) se originó como un enfoque de renderizado de aplicaciones web en el lado del cliente. Este enfoque comenzó a utilizarse ampliamente en el desarrollo web a medida que las aplicaciones web se volvieron más interactivas y dinámicas.

El CSR se popularizó en gran medida gracias al avance de las tecnologías JavaScript y los frameworks de desarrollo web como Angular, React y Vue.js. Estas tecnologías permiten que la lógica del cliente se ejecute en el navegador web del usuario, lo que significa que la renderización de la interfaz de usuario y la manipulación de datos se realizan en el lado del cliente.

El objetivo principal del CSR es mejorar la experiencia del usuario al cargar y usar una aplicación web. Al renderizar la interfaz de usuario en el lado del cliente, se pueden lograr interacciones más rápidas y fluidas, ya que no es necesario ejecutar solicitudes al servidor para obtener nuevas páginas o datos. En lugar de eso, la aplicación web se carga en su totalidad en el navegador y las actualizaciones posteriores se efectúan en el cliente.

Sin embargo, el CSR también tiene algunas desventajas. Debido a que la renderización se lleva a cabo en el lado del cliente, es posible que los usuarios tengan una experiencia inicial más lenta, ya que deben descargar todo el código de la aplicación antes de que esta se pueda cargar y ejecutar. Además, el CSR puede presentar desafíos en términos de SEO (Optimización para Motores de Búsqueda), puesto que los motores de búsqueda pueden tener dificultades para indexar y rastrear el contenido generado dinámicamente.

## Datos
En cuanto a las estadísticas, se ha demostrado que el CSR puede mejorar significativamente la experiencia del usuario. Según un estudio de Akamai, una empresa líder en servicios de distribución de contenido, la demora en la interacción de los usuarios se reduce en un 10% con el CSR en comparación con el server side rendering (SSR). Además, un informe de Google indicó que el CSR puede reducir el tiempo de renderizado en un 30% en comparación con el SSR.

Las empresas líderes en tecnología, como Facebook y Airbnb, han adoptado el CSR en sus aplicaciones web para mejorar el rendimiento y la experiencia del usuario. Además, frameworks populares como React y Angular brindan soporte para el CSR.

## Conclusión
En resumen, el CSR (Client Side Rendering) nació como una solución para mejorar la experiencia del usuario en aplicaciones web al realizar la renderización en el lado del cliente. Este enfoque se ha vuelto popular gracias a las tecnologías JavaScript y los frameworks de desarrollo web, y tiene como objetivo proporcionar interacciones rápidas y fluidas. Sin embargo, también presenta desafíos en términos de rendimiento inicial y SEO.
What is a Software Bill of Materials (SBOM)?
Tags: programming, cloudnative, cloudpractitioner, devops
Published: 2023-08-28 20:36:23



The harsh reality is that most companies cannot accurately summarize the software running on their systems. Hence...[SBOM](https://www.cisa.gov/sbom) has emerged as a key-part of the [security supply chain](https://medium.com/@dejanualex/security-supply-chain-101-a7889074bf45).


![https://xkcd.com/2347/](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4v4429hgc3ilfhpgsxhf.png)

- What is a Software Bill of Materials (SBOM)? 
It's a formal record containing the details and supply chain relationships of various components contained in the software.

- What artifacts may be documented in an SBOM? 
Libraries, modules, open-source components as well as proprietary components container in the software.


![Minimum elements in an SBOM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qr6kzitb9wu390uorsn5.png)

- What are the advantages of having an SBOM? 
Help identifying components with potential licensing issues or with **known** vulnerabilities.

Having the software metadata in a standardized software bill of materials (SBOM) can help organizations face the ever-green software vulnerability landscape. By generating an SBOM the organizations can efficiently tun analysis for security, licensing, and other use cases.