teleren/devto huggingface dataset:
Crear modal de diálogo nativo con HTML
Tags: html, webdev, tutorial, spanish
Published: 2023-03-08 16:00:00

Generalmente para crear un modal se utiliza JavaScript, pero actualmente se puede crear un modal de diálogo nativo utilizando solo HTML, por lo que resulta interesante conocerlo.

La estructura del elemento `dialog` es la siguiente, considerando que puede tener un estado que indica si esta abierto o no.

```html
<dialog open>
	<p>Hola!</p>
</dialog>
```

El código anterior renderiza el modal de diálogo con el texto "Hola! Soy un modal de diálogo" y el estado abierto por defecto.

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

## Abrir dinámicamente el modal

Usualmente un modal se abre con una determinada acción, por ejemplo un clic en un botón. Para esto el elemento `dialog` tiene una API de JavaScript que nos permite abrirlo de forma dinámica. Solo es necesario asignarle un identificador.

```html
<dialog id="mydialog">
	<p>Hola! Solo me muestro con un clic</p>
</dialog>
```

Asignado el identificador podemos abrirlo de la siguiente forma.

```js
window.mydialog.show();
```

Asi mismo, se puede abrir de una manera más explicita utilizando el método `showModal()`. Este método abre el modal de diálogo de forma modal, y permite tener un fondo y centrar el modal de diálogo.

```js
window.mydialog.showModal();
```

Hasta aquí puede resultar raro mostrar el modal de diálogo directamente, por lo que se puede agregar un botón para esta acción.

```html
<button onclick="window.mydialog.showModal();">Mostrar modal</button>
<dialog id="mydialog">
	<p>Hola! Solo me muestro con un clic</p>
</dialog>
```

## Cerrar el modal

Hay dos maneras de cerrar el modal de diálogo, la primera es utilizando el método `close()` de la API de JavaScript.

```js
<button onclick='window.mydialog.close();'>Cerrar modal</button>
```

Mientras que la segunda manera es utilizando un formulario con el método `dialog` dentro del elemento `dialog`, tal y como se muestra a continuación.

```html
<form method="dialog">
	<button>Cerrar</button>
</form>
```

## Personalizar el modal

El elemento `dialog` tiene una serie de atributos que nos permiten personalizar el modal de diálogo, como el tamaño, el color de fondo, el color de texto, etc.

A continuación se agrega un estilo para modificar el color de fondo utilizando el pseudo-elemento `::backdrop`.

```css
dialog::backdrop {
  background: rgba(255, 255, 0, 0.1);
}
```

Ahora se debería ver de la siguiente manera.

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

El elemento `dialog` tiene un soporte muy bueno, por lo que no debería haber problemas para utilizarlo. Se puede consultar en el sitio [caniuse.com](https://caniuse.com/#feat=dialog).

En general resulta interesante conocer este elemento, ya que permite crear un modal de diálogo nativo utilizando solo HTML sin la necesidad de utilizar JavaScript, además de que puede ser personalizado.
NEXTJS 13. Needed SS and SC component example
Tags: nextjs
Published: 2023-03-08 15:54:22

Hello

I am  new to react and nextjs/13 in particular and need a help with short example of how to combine static and client rendering in one component.
I am trying to build interactive side bar that from one side is reactive and will shrink by client UI, from the other side I need it to contain list of links added statically by server reading them from some file on a server. 

Thank you very much
Alex
Join the WeCoded Virtual Meetup 🌟
Tags: wecoded, meta
Published: 2023-03-08 15:51:24

We’re hosting a virtual WeCoded meetup on the [WeCoded Discord](https://discord.gg/dMBZfa2Ube) at **3pm ET / 12pm PST / 8pm UTC on Friday, March 10, 2023**. We’d love for you to join us!

The conversation will be a roundtable discussion on topics related to gender equity, diversity, and inclusion in the tech and software development industries. It will be moderated by a panel of excellent DEV Team members: @devencourt (they/them), @caroline (she/her), and @rachelfazio (they/them).

The Discord is open, so join us! We can’t wait to chat, connect, and celebrate together.

{% embed https://discord.gg/dMBZfa2Ube %}

Please review the rules upon joining! The [DEV Code of Conduct](https://dev.to/code-of-conduct) applies to conduct in the Discord, and your actions in the WeCoded Discord may have repercussions on your DEV account status as well.
Maximum subarray
Tags: algorithms, javascript, tutorial
Published: 2023-03-08 15:25:47

I will be talking about the maximum subarray leetCode problem.

Let`s set up the problem.

At first it was a little hard for me to understand how to actually do it cause i did not understand what was being asked and i was over engineering it, so it is really important to understand what we have to do before start coding.

We are being asked to find the subarray with the largest sum.

Examples given by leetCode:

**Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.**

**Input: nums = [5,4,-1,7,8]
Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23**


We will have to define two main variables, one to store the value that should always be smaller that the actual value we have to check and in order to do that we will have to use "Infinity" which in positive will always be greater than any other value and in negative will be the opposite.


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

Next we will have to make two loops that will over the array, will re-define the currSum and if it is greater than maxSum we sill re-define maxSum with the currSum value.


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

On the last for loop we will make an if statement that will check if maxSum is smallet than currSum and if it is, we will re define maxSum with the currSum value.

Finally the code will look like this.


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


If you have any further questions, i will happy to help you out.

Hope someone found it helpful.

Lautaro.
Ontario Digital Service is HIRING for Sr. Developers and Lead DevOps professionals!
Tags: career, devops, react, drupal
Published: 2023-03-08 15:42:56

The Ontario Digital Service is hiring! 
We are hiring **Senior Developers(React/Python/Drupal) AND Lead DevOps** professionals! 
We’re looking for user-centric individuals to collaborate on solving challenging problems. 
Do you have _5+ years of experience_ in the required tech and live in _**Ontario**_ then we are looking forward to speak with you! 
Please send in your resume and cover letter to **ODS.Tech.Talent@ontario.ca**
Polymorphism in C# — When to Use and When to Avoid
Published: 2023-03-08 15:35:32

In Object-Oriented Programming, polymorphism is an essential part that allows you to define behavior shared by multiple classes while changing it independently for each class. To demonstrate how to reduce code complexity, I would like to share something from my experience.

Polymorphism can be useful for reusing code and maintaining maintainability. Coding becomes easier. As with any programming method, polymorphism has its limitations.


![https://unsplash.com/photos/Fi-GJaLRGKc](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k4hv8taqn5n2ui9ndgkr.png)

[Read more...](https://admirlive.medium.com/polymorphism-in-c-when-to-use-and-when-to-avoid-3bb39c65c22)
Self Organizing Maps (SOMs)
Tags: deeplearning, unsupervised, maps, algorithms
Published: 2023-03-08 15:19:44

- **Self Organizing Map** or **Kohonen Map** or **SOM** is a type of Artificial Neural Network which is also inspired by biological models of neural systems.
- It follows an unsupervised learning approach and trained its network through a competitive learning algorithm. 
- SOM is used for clustering and mapping (dimensionality reduction) techniques to map multidimensional data onto lower-dimensional which allows people to reduce complex problems for easy interpretation. 
- SOM has two layers one is the **Input layer** and the other one is the **Output layer**.


### How do SOM works?
`wij = wij(old) + alpha(t) *  (xik - wij(old))`

- alpha is a learning rate at time t
- j denotes the winning vector
- i denotes the ith feature of training example 
- k denotes the kth training example from the input data

After training the SOM network, trained weights are used for clustering new examples. A new example falls in the cluster of winning vectors. 

### Train the algorithm

1. Initialize the weights wij random value may be assumed. Initialize the learning rate α.
2. Calculate squared Euclidean distance.

    `D(j) = Σ (wij – xi)^2`
     - i=1 to n  
     - j=1 to m

3. Find index J, when D(j) is minimum that will be considered as winning index.

4. For each j within a specific neighborhood of j and for all i, calculate the new weight.

    `wij(new)=wij(old) + α[xi – wij(old)]`

5. Update the learning rule 

    `α(t+1) = 0.5 * t`

6. Test the Stopping Condition.
Comparing ReactJS and Laravel: Understanding the Differences in Purpose and Functionality
Tags: react, laravel, javascript, php
Published: 2023-03-08 15:06:22

ReactJS and Laravel are two popular technologies in the web development world, but they serve different purposes. ReactJS is a JavaScript library for building user interfaces, while Laravel is a PHP web application framework.

ReactJS is focused on building interactive user interfaces using a component-based approach. It allows developers to create reusable UI components, which can be easily managed and updated. React uses a virtual DOM, which improves performance by only updating the necessary components when the state of the application changes. It is commonly used in conjunction with other JavaScript libraries or frameworks such as Redux or MobX to manage application state.

On the other hand, Laravel is a framework for building web applications with PHP. It provides a set of tools and features to help developers build robust and maintainable applications. Laravel follows the Model-View-Controller (MVC) architectural pattern, which separates the application logic into different components, making it easier to understand and maintain. Additionally, Laravel provides features such as routing, middleware, and an ORM (Object-Relational Mapper) which makes it easier to interact with databases.

In summary, ReactJS is a library for building user interfaces, while Laravel is a framework for building web applications. Both technologies are powerful and widely used in the web development industry, but they serve different purposes and can be used together to build complete web applications.
Parallel Class in .NET ! – Part 2
Tags: dotnet, csharp, parallelism, performance
Published: 2023-03-08 14:51:53


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

In the first part, I have talked about the Parallel class in .NET and then Parallel.For has been explained with some examples. 

You can find the first part link here : https://dev.to/alikolahdoozan/parallel-class-in-net-part-1-2hc7

In this article, I am going to continue by explaining Parallel.ForEach and Parallel.ForEachAsync as the second and third items that I have mentioned in part 1. 
Since I have already gone through the theory side of the concept in Part 1, let’s start some examples, but before doing that, please have a look at the below pic. 

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

I have created a region for Parallel.For and commented everything related to then I created a new region as well for Parallel.ForEach so things won’t be such a mess in the source code. 

First of all, I create a simple Array of String like below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5tirk3u4ko0l2tiqpcoz.png)
If I want to make any processing through this area in a parallel, I can use Parallel.Foreach like below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ja2v9nt5guc5nl7xbigk.png)
As you can see, the first parameter is the array that we want to process and the second is the item that we can use from the loop at each iteration. This one also does not give you a sequential result since everything is done in parallel. 

Let’s create a small Async function like below. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fktzrao4ukpjz1b07mao.png)
I want to use this method in my ForEach Loop so since my method is an Async method, better to use ForEachAsync like what I have done in the below screen shoot, but please pay attention, we need to add one more parameter that is Cancellationtoken to the loop parameters.

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

So if I run, you will see something like this:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3p6t3aundzh93atane4n.png)
The next and last part is showing you how to use Parallel.Invoke very fast with some small examples. 


Lazy to write 3-5 line of simple code ?. I have provided the Github link for you :

https://github.com/AliCharper/ParallelClassExercise

Wish you all the best...
We ❤️ .NET !
Ali
Read and Write JSON in Python Requests from API
Tags: python, programming, tutorial, beginners
Published: 2023-03-08 14:35:17

Python requests module allows you to send HTTP requests, The response from the HTTP request will have content, status, header meta details.

Using the requests package we can make a get request to a API which will return a JSON response it will be [parse as python dictionary data](https://www.programdoc.com/python/dictionaries).

getData function is used to make api call and parse data, we can check the response status by checking the status_code from response. And function writeData is used to write the response as json to local storage.
```py
import json
import requests

def getData():
    url = "https://dummyjson.com/products/1"
    r = requests.get(url)
    print("Status:", r.status_code)
    
    return r.json()


def writeData(data):
    with open("jsonfile.json", "w") as file:
        json.dump(data, file, indent=4)


data = getData()

writeData(data)
```

![python requests get method data from response](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yls6blsz7fmtqnvil2o3.jpg)




### Explore Other Related Articles
[Read and Write Python Json](https://dev.to/max24816/read-and-write-python-json-h6i)
[How to combine two dictionaries in python using different methods](https://dev.to/max24816/how-to-combine-two-dictionaries-in-python-using-different-methods-3hcc)
[How to check if a key exists in a dictionary python](https://dev.to/max24816/how-to-check-if-a-key-exists-in-a-dictionary-python-132i)
[Python try exception tutorial](https://dev.to/max24816/python-try-exception-tutorial-2nlp)
[Python classes and objects tutorial](https://dev.to/max24816/python-class-and-objects-21k6)
[Python Recursion Function Tutorial](https://dev.to/max24816/python-recursion-function-tutorial-3jmo)
Why It's high time for developers to understand the importance of Web Accessibility?
Tags: a11y, wedev, wcag, programming
Published: 2023-03-08 14:23:04



[![Webforeveryone](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e2nlggciq18m71zdfuim.png)](https://www.youtube.com/@webforeveryone)

Hello Devs,

As a developer why it's a high time for us to think to create a more inclusive web so everyone can able to access what we're creating and think Why it's our social responsibility?

Recent data shows that there are over **61 million **adults with disabilities in the US and over **14.1 million** disabled people in the UK, and this number is increasing. The spending power of UK families with at least one disabled person is estimated at **£274** billion per year. Additionally, **71%** of disabled people abandon websites that present access barriers. Almost everyone experiences temporary or situational impairments (e.g., noise, poor lighting, distractions), and these people benefit from web accessibility. It's clear that accessibility is not only a legal requirement but also an ethical and social responsibility.

Secondly, by making your website accessible to everyone, you're ensuring that people with disabilities can access your website's information and services on an equal basis with others. This promotes inclusivity and diversity, making the web a more accessible and fair space for all.

Thirdly, there are significant business benefits to having an accessible website. An accessible website can increase your audience and customer base, especially as people with disabilities represent a large and growing market segment. Additionally, accessible websites can improve your search engine rankings and user experience, leading to increased traffic and sales.

Fourthly, making your website accessible can future-proof it against new technologies and devices. By making your website and applications compliant to WCGA standards you're increasing your website/ applications longevity and relevance.

So, as a developer, it's imperative to prioritize web accessibility in your code to create a more inclusive and accessible digital world for everyone. You can visit [webforeveyone](https://www.youtube.com/@webforeveryone) to get more details.

Thanks
Como usar error cause no Javascript e no Typescript
Tags: javascript, typescript, node
Published: 2023-03-08 14:11:09

Tratar erros nunca é uma tarefa divertida, principalmente no ecossistema Javascript onde precisamos tratar vários tipos de erros; HTTP, Node, milhares de bibliotecas...

Uma proposta relativamente recente me chamou bastante à atenção em relação ao tratamento de erros. Se trata da [proposal-error-cause](https://github.com/tc39/proposal-error-cause), já disponível nas versões mais atualizadas dos navegadores e do Node 16.9.0. De forma resumida, ela traz a razão, a causalidade de um erro específico.

Sabe quando precisamos fazer um fetch em uma API e precisamos tratar diversos erros como a própria falha da rota, bug em nossa implementação ou até mesmo um erro terceiro, que não previmos ainda? É uma loucura tratar isso tudo da forma tradicional, mas usando um exemplo descrito na própria proposta, podemos ver como esse tal error.cause pode nos ajudar:

```ts
async function doJob() {
  const rawResource = await fetch('//domain/resource-a')
    .catch(err => {
      throw new Error('Download raw resource failed', { cause: err })
    })

  const jobResult = doComputationalHeavyJob(rawResource)
  await fetch('//domain/upload', { method: 'POST', body: jobResult })
    .catch(err => {
      throw new Error('Upload job result failed', { cause: err })
    })
}

try {
  await doJob()
} catch (e) {
  console.log(e)
  console.log('Caused by', e.cause)
}
// Error: Upload job result failed
// Caused by TypeError: Failed to fetch
```

Além dos nossos logs tratados, recebemos exatamente a causa daquele erro estar sendo levantado. Isso resolve aquele problema de tentar encapsular erros em mensagens bonitinhas e acabar tirando um pouco da transparência que facilita um bom _debugging_.

Agora, tudo parece muito fácil, certo? Só começar a aplicar isso ao seu código e ser feliz. Na verdade, ainda não temos uma implementação dessa propriedade no Typescript até o momento (02/2023).

Se você tentar acessar a propriedade, receberá um erro dizendo que tal propriedade não existe na classe Error.

Isso porque o Typescript trabalha em cima de versões novas do ES e Node. Como essa proposta foi aprovada e adicionada à versão 16.9.0 do Node, e o time do Typescript adicionou essa mudança algum tempo depois, precisamos atualizar nosso tsconfig.

Veja o exemplo abaixo:

```json
{
  "compilerOptions": {
    "lib": ["es2022"],
    ...
  },
```

Atualizando o compilerOptions.lib para ES2022, os erros em relação ao error.cause irão desaparecer e você irá poder usurfruir dessa ferramenta poderosíssima.

Para referência, a compatibilidade da proposta:
-   Chrome, released on 93,
-   Firefox, released on 91,
-   Safari, released on 15,
-   Node.js, released on [v16.9.0](https://nodejs.org/en/blog/release/v16.9.0/#error-cause).
Is there a simpler way?
Tags: career, azure, architecture, dotnet
Published: 2023-03-08 13:52:20

I recently saved a company 𝗮 𝘄𝗵𝗼𝗽𝗽𝗶𝗻𝗴 £𝟭𝟵,𝟮𝟬𝟬 𝗽𝗲𝗿 𝘆𝗲𝗮𝗿 by reviewing their caching strategy. 

👉 Here's how I did it...

---

First, I planned a comprehensive approach to review the company's caching strategy. 

This involved assessing their current suite of applications to determine how they were currently caching, the blast radius of any change, and whether they needed to cache at all.

Next, I would document the possible caching strategies available and explain why they would or wouldn't be suitable for their needs. 

After narrowing down the options, I'd recommend a change to the strategy based on suitability, simplicity, blast radius, and development effort.

I was eager to get my hands on the code, but there was much anxiety around code changes of this nature due to some recent production issues... and I was new to the code base...

👉 I asked myself - "Is there a simpler way to achieve this?"

I needed some more information:

👉 What was the current load on the system?
👉 What was the future expected load on the system?
👉 How equipped was the current infrastructure to handle this?

To cut a long story short:

👉 There was no clever caching strategy implementation.
👉 There was no exceptionally performant code - in fact, no code was changed at all. 

It turns out the infrastructure was extremely well equipped, so much so that reducing the tiers to bring it in line with the reality of the load on the system and future expectations was enough to achieve these savings...

It's amazing how sometimes the simplest solutions can have the biggest impact. 

That infrastructure may or may not have been configured that way for the previous 12 months... 🤷‍♂️
lightdm script
Tags: lightdm, greeter, lightdmgreeter, boot
Published: 2023-03-08 13:46:16

Hello guys 
I'm trying to run a script at boot on Ubuntu 22 OS that will check if the device is connected to the internet or not. If it isn't, the script will run the "armbian-config" command to open a system configuration screen and edit the network configuration, the script is running fine but i can't execute it to run automatically at boot.
i tried : 
`$ sudo nano /usr/share/check_network.sh`

```
#!/bin/bash
ping -c 1 google.com
if [ $? -ne 0 ]; then

  echo "configure your network" | bash -c "read; armbian-config"
fi
```
`$ sudo nano /etc/lightdm/lightdm.conf`

```
[Seat:*]
display-setup-script=/usr/share/check_network.sh
```
i also tried 
`$ sudo nano /usr/share/xgreeters/slick-greeter.desktop`

```
Exec=/bin/bash /usr/share/check_network.sh
```
any idea would be appreciated..