teleren/devto huggingface dataset:
ECharts: La librería para generar gráficas
Tags: webdev, javascript, beginners, spanish
Published: 2023-08-02 21:25:28

Apache ECharts es una librería de JavaScript muy útil e interesante a la hora de crear graficas, hay una gran variedad tipos y formas de configurarlas. #javascript
Lo mas interesante de todo esto es que tienes disponible de manera automática la descarga de la gráfica. cuando esta implementada.


![Diferentes graficas](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d5ha8kjh484h64a7nrfl.png)

Tienes disponible desde las gráficas básicas de toda la vida de barras hasta gráficas para población, datasets, calendarios, arboles, etc.

La instalación de ECharts se puede realizar fácilmente a través de npm con el siguiente comando.


![Comando de instalación](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z310j8vy8kz48e1213u4.png)

Cuando seleccionas una gráficas te despliega un demo de la misma, la cual la puedes manipular para agregar o quitar cosas que no creas necesarias. Pero no solo eso sino que también las puedes abrir en CodePen o CodeSandbox. Se puede jugar con el modo oscuro si es que lo necesitas y además puedes probar con las diferentes versiones de la librería disponible.


![Grafica de ejemplo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/key51x87jud5u30p310c.png)

Y lo mas increíble de todo si es que por alguna razón necesitas un estilo diferentes al que viene predeterminado, hay un sección en donde puedes elegir el estilo personalizarlo e integrarlo a tu proyecto. ECharts es una de las librerías mas robustas y mejor documentada que he visto y probado. Los ejemplos son muy buenos y los puedes tomar como base para no empezar a hacer la gráfica que quieres completamente de cero.


![Personalizar gráfica](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ngg5ltucp3yld28ueejj.png)
Master Image Resize Modes in HTML/CSS with object-fit
Tags: html, css, beginners, tutorial
Published: 2023-08-02 21:17:13


---
title: Master Image Resize Modes in HTML/CSS with object-fit
tags: html,css,beginners,tutorial
---



Hello everyone, today I'm going to explain how to resize images in HTML and CSS. By using the `object-fit` property, you can freely control images. In this post, I will introduce how to use and remember it.

## Table of Contents
1. [Introduction](#introduction)
2. [What is the `object-fit` property?](#object-fit)
3. [Values of `object-fit` and their meanings](#object-fit-values)
4. [How to use `object-fit`](#object-fit-usage)
5. [Conclusion](#summary)

---

<a name="introduction"></a>
## 1. Introduction

In HTML, the size of an image is usually specified using the `width` and `height` attributes of the `<img>` tag. However, you can also perform more advanced resize operations using CSS. For that, you use the CSS `object-fit` property.

---

<a name="object-fit"></a>
## 2. What is the `object-fit` property?

The `object-fit` property controls how the contents of a replaced element, such as an image, fit into the specified width and height. There are five values for this property.

---

<a name="object-fit-values"></a>
## 3. Values of `object-fit` and their meanings

Here are the values of `object-fit` and their meanings:

- `fill`: The content of the element is stretched to fit the specified size. The original aspect ratio is not retained.
- `contain`: The content of the element is reduced or enlarged to fit within the specified size. The original aspect ratio is retained.
- `cover`: The content of the element is reduced or enlarged to cover the specified size. The original aspect ratio is retained, but some content may be trimmed.
- `none`: The content of the element is not resized and the original size is used as is.
- `scale-down`: The smaller behavior of `none` or `contain` is applied.

---

<a name="object-fit-usage"></a>
## 4. How to use `object-fit`

Now, let's see how to resize images using each value of `object-fit`.

### `fill`

```html
<img src="image.jpg" style="object-fit: fill; width: 300px; height: 200px;">
```

### `contain`

```html
<img src="image.jpg" style="object-fit: contain; width: 300px; height: 200px;">
```

### `cover`

```html
<img src="image.jpg" style="object-fit: cover; width: 300px; height: 200px;">
```

### `none`

```html
<img src="image.jpg" style="object-fit: none; width: 300px; height: 200px;">
```

### `scale-down`

```html
<img src="image.jpg" style="object-fit: scale-down; width: 300px; height: 200px;">
```

---

<a name="summary"></a>
## 5. Conclusion

As you can see, you can easily resize images using HTML and CSS. With the `object-fit` property, you can choose the way to resize images as needed.

Remembering how each value of `object-fit` works will help you choose the best image resizing method for your web pages. So, Happy Coding!

---

That's it for now. I hope you find this article helpful. If you have any questions, please let me know in the comments. And if you think this article was useful, please give it a thumbs up!

---
Inside the MongoDB findById Method: Understanding the Efficiency of Searching for Unique IDs
Published: 2023-08-02 21:16:12

**In MongoDB**, when you use the findById method, whether through the Mongoose library or the native MongoDB library, essential processes occur that make this operation efficient and powerful.

Firstly, MongoDB receives the request as soon as you call findById, and the MongoDB library (Mongoose) creates a specific query for the database.

Next, Mongoose converts the ID to the appropriate format used by MongoDB. IDs are typically represented as hexadecimal strings or ObjectId objects. This step is essential to ensure that the search is done correctly.

Then, MongoDB comes into action and performs the query on the database to find the document associated with the provided ID. To expedite this process, MongoDB uses an automatically created index structure for the _id field. This optimized data structure, known as a binary search tree (B-tree), allows MongoDB to quickly locate the document corresponding to the requested ID without having to go through all the documents in the collection. This makes the search extremely efficient, even for large volumes of data.

Once the document is found, Mongoose comes into play again and uses the corresponding model (Schema) you defined to construct a model object, which is an instance of the model representing the retrieved document from the database.

Finally, Mongoose returns the model object representing the document found in the database, or null if no document matches the provided ID.

It's worth noting that the findById method is an abstraction provided by Mongoose, specifically designed to facilitate the search for documents by their unique ID in MongoDB. Through this abstraction, developers are spared the intricate details of the query, ID conversion, and model object construction, making the process simpler and more efficient.

**Is this search done through a loop?**

The answer to this question is no. MongoDB uses its index structure and the optimization of the binary search tree to avoid loops and quickly locate the documents corresponding to the ID. This approach ensures that the search is performed swiftly and efficiently, even in collections with a significant amount of data.

In summary, the findById method of MongoDB is a powerful tool for searching by unique IDs, and understanding its internal workings is essential to maximize its potential. By using an optimized and efficient process, you ensure smoother and faster database queries, providing a superior experience in your application.
password generator using javascript
Tags: javascript, beginners, webdev
Published: 2023-08-02 21:15:19

Below is a simple implementation of a password generator using `JavaScript`:

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

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

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

## Javascript

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

This simple password generator allows the user to specify the length of the password (between 8 and 20 characters) and generates a random password that includes uppercase letters, lowercase letters, numbers, and symbols.

When the user clicks the "**Generate Password**" button, the JavaScript function `generatePassword()` is called. It validates the password length, generates a random password, and displays it in the output field.

Feel free to customize the character sets or add more complex password generation logic based on your requirements. Happy coding! 🔐🚀📝
Como criar interfaces para React Native com o Motif
Tags: reactnative, ui, typescript, motif
Published: 2023-08-02 21:11:08

E aí pessoal,

o desenvolvimento mobile sempre chamou muito a minha atenção, me lembro que eu gostava muito das aulas de Android na faculdade. Existem diversas opções no mercado e dentre essas a que mais me chamou a atenção foi o React Native. React Native é uma ótima opção por dois motivos: é cross-platform e usa as mesmas tecnologias da web. Hoje eu me sinto muito produtivo e feliz criando estilos pra web usando o Tailwind, mas sempre achei muito penoso criar e manter os estilos para React Native. E depois de sofrer por um tempo com o Styled-component eu decidi criar minha própria biblioteca de estilo: [Motif](https://github.com/gideaoms/react-native-motif).

Com o Motif é fácil e divertido criar componentes reutilizáveis e manuteníveis.

#### Criando o tema
Crie um arquivo na pasta src (aqui eu vou chama-lo de _motif.tsx_) e adicione os estilos do tema
```tsx
import { createTheme } from 'react-native-motif'

export const { theme, ThemeProvider } = createTheme({
  colors: {
    blue: '#476C9B',
    red: '#984447',
    white: '#fff',
  },
})
```

#### Adicionando o provider
Essa parte é necessária caso você queira acessar o tema através do hook _useTheme_

```tsx
import { ThemeProvider } from './motif'

export default function App() {
  return (
    <ThemeProvider>
      ...
    </ThemeProvider>
  )
}

```

#### Criando um componente
Crie um arquivo chamado title.tsx e adicione o seguinte código:
```tsx
import { ReactNode } from "react";
import { Text } from "react-native";
import { VariantProps, styled } from "react-native-motif";
import { theme } from "./motif";

const color = styled({
  primary: {
    color: theme.colors.primary,
  },
  secondary: {
    color: theme.colors.secondary,
  },
});

const fontSize = styled({
  sm: {
    fontSize: 20,
  },
  md: {
    fontSize: 30,
  },
});

const uppercase = styled({
  true: {
    textTransform: "uppercase",
  },
});

type TitleProps = TitleVariants & {
  children: ReactNode;
  color?: VariantProps<typeof color>;
  fontSize?: VariantProps<typeof fontSize>;
  uppercase?: VariantProps<typeof uppercase>;
};

export function Title(props: TitleProps) {
  return (
    <Text
      style={[
        color.get(props.color) ?? color.primary,
        fontSize.get(props.fontSize),
        uppercase.get(props.uppercase),
      ]}
    >
      {props.children}
    </Text>
  );
}
```
Como você pode ter notado, a biblioteca permite criar variantes, o que é muito útil quando o componente possui diversas formas de apresentação. A inspiração para essa abordagem veio do projeto [Stitches](https://stitches.dev/).

#### Usando o componente
```tsx
import { Title } from './title'

export default function App() {
  return (
    <Title
      uppercase
      fontSize="md"
    >
      Hello world
    </Title>
  )
}
```

É isso aí pessoal, espero que vocês tenham gostado da biblioteca [Motif](https://github.com/gideaoms/react-native-motif), qualquer dúvida ou sugestão fiquem à vontade nos comentários. E não esqueçam de dar uma estrela para o projeto lá no Github.
What's New in Tower 10
Tags: git, github, news
Published: 2023-08-02 20:59:54

The much-anticipated version 10 of our Git client has been released, and it's our most colorful update yet.

Why? Because we've introduced Syntax Coloring to every file and diff view!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0wd4uhiske4abk44rprv.jpg)

With support for nearly 200 languages, your Git repository's code is now more readable than ever! We also took the opportunity to add two other customization options that have been highly requested:
- The possibility to show or hide invisible characters.
- The ability to configure the preferred tab width (the default is 4).

It looks beautiful in dark mode, too! 😍

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

Tower's themes have also been fully updated to support the new Syntax Highlighting feature. That said, you can still modify them to your liking or create new ones from scratch.

You can [download a 30-day trial for free](https://www.git-tower.com/) to try it out! No registration or email is required.

P.S. This is the first of many exciting features that are on [our roadmap](https://www.git-tower.com/blog/coming-up-on-the-roadmap-2023/) for the upcoming months. Keep an eye out for what's to come! 🔥
Powershell - Delete files by Size & Telegram Notification
Tags: powershell, script, notification, telegram
Published: 2023-08-02 20:53:27

This script, you can **delete** files more than **specific size** and send **notification** by Telegram.

```
# First, we specify the details of the Telegram account and the chat ID

#Variables Region
$botToken = Get-Content -Path  Env:\botToken
$chatId =   Get-Content -Path  Env:\chatId 

$directory = "YOUR_PATH" 
$sizeFile = 2GB #100MB
$directoryLOG = YOUR_PATH

# We get a list of files in the directory that are greater than size specify
$filesBig = Get-ChildItem $directory -Recurse | Where-Object { $_.Length -cge $sizeFile } | Select-Object Name,";",Directory,@{n='GB';e={"{0:N2}" -F ($_.length/ 1GB)}} 

# If not files that meet the criteria, we end the execution of the script
if ($filesBig.Count -eq 0) {
    Write-Host "No files larger than $($sizeFile/1GB)GB."
    return
}

# If are files that find the criteria, generate the message that will be sent by Telegram.
$message = "$(Get-Date -Format "yyyyMMdd_HH:mm:ss") ;" 

foreach ($files in $filesBig) {
    
    $message += "$($files.Name) ;$($files.GB)GB; $($files.Directory) ;files more than $($sizeFile/1GB)GB `n"
    # Save LOG
    Add-Content -Path $directoryLOG $message
    # Remove items
    Get-ChildItem $directory -Recurse | Where-Object { $_.Length -cge $sizeFile } | Remove-Item -Force 
}

# Send the message via Telegram
$message = [System.Web.HttpUtility]::UrlEncode($message)
$uri = "https://api.telegram.org/bot$botToken/sendMessage?chat_id=$chatId&text=$message"
Invoke-WebRequest -Uri $uri 
```

Note: you can schedule task for automate this script.


Thanks for read!

- [**Redhcp Page**](https://redhcp.me/)
- [**Redhcp Github**](https://github.com/redhcp)
- [**More Posts**](https://dev.to/redhcp)
React Custom Hooks (useWindowResize)
Tags: react, reacthooks, customhook
Published: 2023-08-02 20:51:40

## INTRO
Hello World! 👋
Now onwards I want to start a new series named `React Custom Hooks`. In this series I want to post different ReactJS custom hooks, their coding and their use cases.

Today's Custom Hook is `useWindowResize`.

## USAGE
This hook is very helpful to the developers when they want to know browser screen width and height. As a frontend developer I am always have to check the screen width to test web responsiveness. We know that we have `media queries` in `css` to handle responsiveness but sometimes have to handle from `JavaScript` side also. That time this hook will very helpful to handle page layouts or design changes based on screen width what we get from this hook.

## CODE
```javascript
import { useEffect, useState } from "react";

export const useWindowResize = () => {
  const [width, setWidth] = useState(0);
  const [height, setHeight] = useState(0);
  const handleResize = () => {
    setWidth(window.innerWidth);
    setHeight(window.innerHeight);
  };
  useEffect(() => {
    window.addEventListener("resize", handleResize);
    handleResize();

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return { width, height };
};
```

## USE CASE

```javascript
import { useWindowResize } from "./useWindowResize";

function LogoComponent() {
  const { width } = useResize();

  const getLogo = () => {
    if (width <= 480) {
      return "mobile logo";
    } else if (width <= 768 && width >= 480) {
      return "tablet logo";
    } else {
      return "desktop logo";
    }
  };
  return getLogo();
}

export default LogoComponent;
```

## OUTPUT

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/29k92g0txg0cs7s6h2tx.gif)

I hope you people understand the `useWindowResize` hook. We will meet with another hook in another post.

Peace 🙂.
A review of WeAreDevelopers 2023
Tags: conferences, career, community, developers
Published: 2023-08-02 20:48:57

Tech conferences usually fall into one of two categories: vendor-centric and user-centric.   

Vendor-centric conferences are about showing what's new with the product and providing a place for their partner and customer ecosystems to co-mingle. User-centric conferences are gatherings for sharing ideas and learning from others; this format attracts the people who are doing the work and creating the innovation. In this case, it's Developers.  

In July of 2023, I attended WeAreDevelopers in Berlin, supporting Appdome where I work as a Senior Product Manager. In my time there, three things stood out to me that positioned WeAreDevelopers as a user-centric conference that has succeeded in attracting an innovative, curious, engaged and talented group of attendees, speakers and sponsors at an epic scale. 

Working the booth gave me a great position to talk to dozens of people over the course of a few days. What I noticed immediately is the wide range of people there from so many different countries, cultures, backgrounds, skill levels, and specializations. Each person I spoke to shared unique challenges in the development, user base, market fit, or some other aspect of their projects. From mobile developers in Kazakhstan to recent grads from Bulgaria to a CTO from Poland, every conversation was a quick glimpse into a new and unexpected context, even just standing in the booth, it was impossible to be bored.     


![StackOverflow Presentation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mocctfmfy5n94vebkyx1.png)

Second was the range of topics being presented; I'm a car guy, and I loved hearing how Rimac overcame the challenges of designing a software architecture from scratch for a technology-focused hypercar. As a developer, StackOverflow has bailed me out of a technical jam more times than I can count, so sitting in on Joel Spolsky's session about the Past Present and Future of StackOverflow was an interesting and insightful peek behind the curtain on one of my favorite tools. And yes, I'm a bit biased, but Appdome co-creator Tom Tovar's talk on how to make money from cyber attacks and cheats, offered a unique approach to an old problem from a new voice you may not have heard from before, and is worth listening to.  

Beyond the things I saw and people I met, what impacted me the most was the sense of community around building and creating new things with technology. Everyone there was motivated to broaden or deepen their skillset, learn from others in the field, and  get exposed to new tools and techniques. The overall vibe was one of excitement and curiosity. 

From what I could tell, Appdome was the only mobile-centric sponsor; we talked to so many mobile devs who were excited to see something specifically for them that makes their jobs easier and the apps more secure. It would be great to see more mobile dev tools and sessions at next year's event.  

Looking forward to meeting you there in 2024. 

![Appdome team at our booth](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0clldtnst7ewweya6q5k.jpeg)
Indices of the two numbers such that they add up to a specific target
Tags: javascript, beginners, programming, interview
Published: 2023-08-02 20:14:52


Good morning! Here's your coding interview problem for today.

## This problem was asked by Amazon.

**Given an array of integers, return indices of the two numbers such that they add up to a specific target.**

You may assume that each input would have exactly one solution, and you may not use the same element twice.

```
Example
const twoSum = (nums, target) => {

};
  
console.log(twoSum([2, 7, 11, 15], 9))  // [0, 1]
// nums[0] + nums[1] = 2 + 7 = 9
```

**Solution**

```
const twoSum = (nums, target) => {
  const obj = {};
  for (let i = 0; i < nums.length; i++) {
    const num = nums[i];
    const diff = target - num;
    if (obj[diff]) return [+obj[diff], i];
    obj[num] = i.toString();
  }
  return [-1, -1];
};
```

**Explanation**

- Iterate through the nums array
- Calculate the complement that would sum to target
- Check if complement already exists in map
- If so, return the indices
- Otherwise, store num as key and index as value in map
Talking to containerd GRPC services using .NET
Tags: containerd, grpc, protoc
Published: 2023-08-02 20:01:44

---
title: Talking to containerd GRPC services using .NET
published: true
description: 
tags: containerd, grpc, protoc
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-08-02 16:06 +0000
---

I have been wanting to explore the containerd service APIs on the Windows platform from .NET and almost found the end of internet looking for how to do it.

Thankfully following the below articles I was able to put together a client library which is shared here https://tinyurl.com/mry73kvx

https://tinyurl.com/5n7u93fs

https://tinyurl.com/mr4aumad

The solution generates C# wrappers from protocol buffer specification for the respective containerd service. Hope that someone will find this useful.
find the majority element
Tags: javascript, programming, beginners, interview
Published: 2023-08-02 19:56:16


Good morning! Here's your coding interview problem for today.

### Given an array of size n, find the majority element. The majority element is the element that appears more than [n/2] times.

You may assume that the array is non-empty and the majority element always exist in the array.

**Example**

```
const majorityElement = nums => {

};

console.log(majorityElement([2,2,1,1,1,2,2]))  // 2
```

**Solution**

```
function majorityElement(nums) {
  const obj = {};
  for (const num of nums) {
    obj[num] = (obj[num] || 0) + 1;
    if (obj[num] > nums.length / 2) return num;
  }
}
```

**Explanation**

- Iterate through the array and count the frequency of each number in a hash map.
- If any number's frequency is greater than n/2, return that number immediately.
- Otherwise, return the majority number after full iteration.
Summary of its ranges
Tags: programming, javascript, beginners, interview
Published: 2023-08-02 19:50:19

## Given a sorted integer array without duplicates, return the summary of its ranges.

```
Example
const summaryRanges = nums => {

};

console.log(summaryRanges([0,2,3,4,6,8,9])) 
// ["0","2->4","6","8->9"]
```

**Solution**

```
function summaryRanges(arr) {
  let i = 0;
  const result = [];
  while (i < arr.length) {
    let j = i + 1;
    while (j < arr.length && arr[j] === arr[j - 1] + 1) j++;
    const val = arr[j - 1];
    result.push(i === j-1 ? val.toString() : `${arr[i]}->${val}`);
    i = j;
  }
  return result;
}
```

**Explanation**

The summaryRanges function iterates through an array using a while loop. It uses a nested while loop to identify contiguous ranges of numbers. For each range, it constructs a string representing that range and pushes it to a result array. After fully iterating the array, it returns the result array containing the summarized ranges.