teleren/devto huggingface dataset:
DOM Element Observer
Tags: javascript, dom, observer, mutationobserver
Published: 2022-11-20 06:02:28

While developing a web application sometimes requires watching changes being made on the DOM element like when an attribute of a component changes or a new child element is added or removed.

How we can observe a DOM element in Javascript?

**MutationObserver** is the class that will help here to add a watcher on the DOM element. this watcher can observe changes for attributes or children elements as well. This MutationObserver API works asynchronously and similar to Promise uses a microtask queue while running their callbacks. In simple words, Promise / MutationObserver has more priority than setTimeout / setIntervals using the Task queue.

Let's see how to create this observer step by step.

First, create a configuration for what exactly you want to observe i.e. attributes or child nodes also both can observe at the same time.

```javascript
    const mutationConfig = { attributes: true, childList: true };
```

Second, create a callback function that will call when attributes or childList are modified.

```javascript
function onMutationChangeCallack(mutationConfigList) {
    for(const mutationConfig of mutationConfigList) {
        if(mutationConfig.type === 'attributes') {
            addLogs(`${mutationConfig.attributeName} attribute changed`);
        } else if(mutationConfig.type === 'childList') {
	    addLogs(`childList updated. new dom element added`);
        }
    }
}
```

Here inbuild attributes like a style or custom attributes like custom-data can be observed.
Third, create an object of MutationObserver class and pass onMutationChangeCallback to the constructor.

```javascript
   const observer = new MutationObserver(onMutationChangeCallack);
```


Then observe is the method that starts watching changes on the DOM element. Two mandatory parameters need to pass to observe method. One is the target DOM element that we need to watch and the configuration object created above.

```javascript
   let target = document.getElementById('playarea');
   observer.observe(target, mutationConfig);
```

There are other methods like disconnect which stops the observing functionality and a callback will not be called after that.

[For more information] (https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)

Please check below link of live of mutation observer api

[Live Example](https://jsexamples.netlify.app/mutationobserver/index.html)

![Mutation Observer Example](https://i.ibb.co/5Ldhv6J/Mutation-Observer-Example.gif)
Resumen: Ten cuidado con lo que pides - "The Clean Coder"
Published: 2022-11-20 05:41:53

Este es un breve resumen del libro de **Robert C. Martin "The Clean Coder"**, para compartir los conocimientos y mi percepción de este gran libro. Espero lo disfrutes y aprendas algo nuevo hoy.

😊 Let's do this!

Es fácil ser un no-profesional, poco comprometido e irresponsable por las acciones que ejecutas en tu trabajo.

**¿Cómo identificarlo?**

Aquí Robert nos da un ejemplo hipotético:
Que pasaría si un programador comete un error que le cuesta a la compañía $10,000.

- Un programador no-profesional diría: "Esas cosas pasan".
- Por el contrario uno comprometido, pagaría esa cantidad, Y sí. Se siente muy diferente cuando es tu propio dinero ¿verdad?

Pues así es como se siente el profesionalismo, es siempre tener ese sentido de responsabilidad y no es nada fácil, por eso; **Ten cuidado con lo que pides** y si decides hacerlo, sé un ejemplo de ello.
DNS Enumeration Part 1(HOST)
Tags: dnstool, dnsenumeration, host, reverselookup
Published: 2022-11-20 05:37:53

## Key Questions
What is DNS enumeration? How does it differ from more common forms of reconnaissance? What tools can you use to perform DNS (Domain Name Service) enumeration? I'll answer these questions and more in this article.

## Definition
While the Internet is much more robust than any other form of communication, there are some basic methods used to find out its structure and elements. While these methods also allow for gathering information about an organization, they can be used by attackers as well. 

DNS enumeration is one of these ways. The term 'DNS' stands for Domain Name System and in general, refers to the service responsible for translating hostnames (such as akarns.com) into IP addresses. For example, if your computer accesses akarns.com directly and asks the DNS server how to find this URL, it will return its address in an A record's name field. DNS server also has resources that let you know what type of record exists at a given point in time and whether changing it will affect something specific (to you).

## DNS Enumeration Tools
There are numerous tools used to perform DNS enumeration. However, the decision to use a particular tool solely depends on the attacker's preferences. Many prefer automated tools but in our discussion, I will try to explain manually available tools to better understand the working of different tools. This article covers the following tools: **Host**, **nslookup**, and **dig**.

## Host
The term host basically means a piece of software whose task is to parse DNS domain names, IP addresses, and query strings in a specific format. Host command can be used to convert domain names to IP addresses and IP back to domain names.

The syntax to perform host enumeration is:
`host domain_name`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xg54e0jibgjvecp81jcx.PNG)
Running the command above returned the IP address of the host domain.
_**Name servers**_
To find the name servers the domain run on you add the **-t** tag followed by **ns(name server)**. The **-t** denotes the type.
`host -t ns example.com`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hrnj77sxykv6o3r27vq.PNG)
**_Mail server_**
To get the mail server you add **mx** to the -t tag.
`host -t mx example.com`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kya0xxbo1csdf8c1gj6w.PNG)
_**Reverse lookup**_
In a scenario where you only have the IP address but you don't know the domain, the reverse lookup will be the best method to use. If the output doesn't present a domain then I will prefer using a web-based tool called shodan.io. 
`host ip_address`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bed01u0qyhwt09deeim8.PNG)

In the next article, I will cover **nslookup** and **dig** commands. 
Thanks for reading I look forward to your feedback.
Adding Tailwind CSS to Angular projects.
Tags: angular, tailwindcss
Published: 2022-11-20 05:27:42

**First need to Install Tailwind CSS using CLI command :**

```bash
npm install -D tailwindcss postcss autoprefixer
```

Next Run init command to generate  `tailwind.config.js`

```bash
npx tailwindcss init
```

**Configuring template paths :**

In `tailwind.config.js` 

```bash
/** @type {import('tailwindcss').Config} */
module.exports = {
	
	...

  content: [
    "./src/**/*.{html,ts}",
  ],

	...

}
```

Adding the Tailwind directives to your CSS :

In style.css

```bash
@tailwind base;
@tailwind components;
@tailwind utilities;
```
Reference : [Official Docs](https://tailwindcss.com/docs/guides/angular)
Resumen de Requisito Previo / Introducción de "The Clean Coder"
Published: 2022-11-20 05:25:50

Este es un breve resumen del libro de **Robert C. Martin "The Clean Coder"**, para compartir los conocimientos y mi percepción de este gran libro. Espero lo disfrutes y aprendas algo nuevo hoy.

😊 Let's do this!

En este capítulo el autor habla de varias experiencias que ha vivido como programador, todos sus errores y algunos logros, como un profesional debe actuar y que acciones debería evitar.

Robert C. Martin trabajó para una empresa en donde el y sus compañeros desarrollaron un proyecto, dicho proyecto se terminó y los dueños no les dieron ni el 3% de las utilidades de este. Esto sin duda alguna lo provocó a el y sus compañeros, entonces ellos decidieron renunciar de una manera agresiva, insultando y gritando a su jefe.
Robert quedó desempleado y no consiguió ningún empleo durante varios meses, entró en una "bajón" hasta que su madre le dijo que ya era hora de comer una gran rebanada de pastel de la humildad, es decir, pedir perdón por su comportamiento y suplicar a su ex jefe para regresar a su anterior empleo. 
Le hizo caso a su madre, le dieron su anterior empleo y pudo desarrollarse muy bien durante 8 meses más hasta que renunció y quedó en buenos términos con su ex empleador.

Sin duda alguna aquí nos habla de lo importante que es el **respeto** y la **gratitud** de tener un empleo, a veces no recibimos la mejor gratificación, sin embargo, hay que agradecer siempre en donde es que estamos parados. También una gran lección es, tener un plan y evitar actuar de manera emocional, usar siempre la cabeza y analizar la mayor cantidad de opciones que tenemos.

Sin duda alguna, una gran lección que Robert aprendió por las malas y gracias a su madre.
Reviewing code for peers
Published: 2022-11-20 05:22:06

Hi everyone,

This week I reviewed some code for some fellow peers in my course.

The [first review](https://github.com/Seneca-CDOT/telescope/pull/3763#issuecomment-1317621482) was for a PR that wanted to clarify the difference between a blog URL (HTML) and a blog feed URL (XML) during the sign-up process. I thought that it would've been a good idea to include an example of a blog URL vs a blog feed URL just for extra clarification.

The [second review](https://github.com/Seneca-CDOT/telescope/pull/3767#issuecomment-1320813665) was for a PR that fixed a link when clicking the "About" icon in the sidebar. The PR looked good after review, but the author was having similar trouble with rebasing like I did in my PR. So, I provided him the same instructions that someone else gave me.
Adding Bootstrap to Angular projects.
Tags: angular, bootstrap
Published: 2022-11-20 05:18:09

First Install bootstrap using CLI command :

```bash
npm install bootstrap
```

Next add these in `angular.json` :

```bash
"scripts": [
    "./node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
],
"styles": [
    "./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
```
224. Leetcode Solution in cpp
Tags: cpp
Published: 2022-11-20 05:14:52

```cpp
class Solution {
 public:
  int calculate(string s) {
    int ans = 0;
    int num = 0;
    int sign = 1;
    stack<int> stack{{sign}};  // stack.top(): current env's sign

    for (const char c : s)
      if (isdigit(c))
        num = num * 10 + (c - '0');
      else if (c == '(')
        stack.push(sign);
      else if (c == ')')
        stack.pop();
      else if (c == '+' || c == '-') {
        ans += sign * num;
        sign = (c == '+' ? 1 : -1) * stack.top();
        num = 0;
      }

    return ans + sign * num;
  }
};
```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/basic-calculator/
How to Upload Maven Artifacts to GitHub Packages
Tags: maven, github
Published: 2022-11-20 04:19:45

Learn how to deploy your Java Maven artifacts into GitHub packages using GitHub actions.

## 1. Introduction
GitHub is continuously upgrading its service offerings, and one of the latest that came out is the GitHub Packages. GitHub Packages is a platform for hosting and managing packages or artifacts. In a way, it's similar to Sonatype Nexus and can be used as the "maven central" for a private organization. In addition, it can also store containers like Docker images.

GitHub Actions is a CI/CD platform that will help us deploy and publish our Java project in GitHub Packages.

## 2. How do we use GitHub Packages?
Let's start with our use case, where we have a utility project logging referenced by all other services.

## 3. Utility Project - Logging
A Java maven project that contains all logging-related classes. This project is added as a dependency on all the organization's microservices.

Let's modify this project to:

### 3.1 Add distribution management in pom.xml.

```
<distributionManagement>
    <repository>
      <id>github</id>
      <name>GitHub Packages</name>
      <url>https://maven.pkg.github.com/your_org/common-logging</url>
    </repository>
  </distributionManagement>
```

### 3.2 Create a GitHub action that publishes our logging artifact into packages.

You can create an action by clicking the "Action" tab / New workflow.  https://docs.github.com/en/actions/quickstart

```
name: Publish the package to GitHub Packages
on:
  release:
    types: [created]
jobs:
  publish:
    runs-on: ubuntu-latest 
    permissions: 
      contents: read
      packages: write 
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-java@v3
        with:
          java-version: '11'
          distribution: 'adopt'
      - name: Publish package
        run: mvn --batch-mode deploy
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
```

Make sure to define a GITHUB_TOKEN under the project's or your organization's Secrets -> Actions.

## 4 Service Project
A random Java Maven project that needs a logging mechanism. Therefore, it is dependent on our logging project.

### 4.1  Add a repositories section pointing to your packages in pom.xml.

```
<repositories>
    <repository>
        <id>github</id>
        <url>https://maven.pkg.github.com/your_org/packages/</url>
    /repository>
</repositories>
```

### 4.2 Configure your maven's local settings.xml. Please make sure to add GitHub in the server section with your username and access token. This file is normally saved in %USER%/.m2/settings.xml.

```
<settings>
  <servers>
    <server>
      <id>github</id>
      <username>czetsuya</username>
      <password>xxx</password>
    </server>
  </servers>
</settings>
```

Create a personal access token https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token.
Creating more filters with OpenCV and Python
Tags: python, tutorial, beginners, datascience
Published: 2022-11-20 03:56:37

## Introduction

Hello! 😀

In this tutorial I will be showcasing some more filters using OpenCV and Python!
This is a continuation of my previous example which can be found here:
https://dev.to/ethand91/creating-various-filters-with-opencvpython-3077

I've already discussed how to create the virtual environment in previous tutorials so I will skip that part. 

Well lets get started creating some more filters! 🥳

---

## Vignette Filter

First we will create the vignette filter. The vignette filter is achieved by creating a broad 2D Gaussian kernel.

```python
def vignette(image, level = 2): 
    height, width = image.shape[:2]

    x_resultant_kernel = cv2.getGaussianKernel(width, width/level)
    y_resultant_kernel = cv2.getGaussianKernel(height, height/level)

    kernel = y_resultant_kernel * x_resultant_kernel.T
    mask = kernel / kernel.max()

    image_vignette = np.copy(image)

    for i in range(3):
        image_vignette[:,:,i] = image_vignette[:,:,i] * mask

    return image_vignette
```

Here we generate the vignette mask using Gaussian kernels, we then generate the result matrix and then apply the mask to each of the image's color channels.

![Vignette Filter](https://i.ibb.co/fCW34Fw/vignette.jpg)

---

## Embossed Filter

The next filter is the embossed filter:

```python
def embossed_edges(image):

    kernel = np.array([[0, -3, -3], [3, 0, -3], [3, 3, 0]])

    image_emboss = cv2.filter2D(image, -1, kernel = kernel)

    return image_emboss
```

Here we create an array for each of the channels and then apply it to the image via filter2D.

![Embossed Filter](https://i.ibb.co/zFwHybP/embossed.jpg)

---

## Outline Filter

The next filter is the outline filter:

```python
def outline(image, k = 9): 
    k = max(k, 9)
    kernel = np.array([[-1, -1, -1], [-1, k, -1], [-1, -1, -1]])

    image_outline = cv2.filter2D(image, ddepth = -1, kernel = kernel)

    return image_outline
```

Similar to the embossed filter but this time we increase the quality of the outlines.

![Outline Filter](https://i.ibb.co/8z78pMF/outline.jpg)

---

## Style Filter

The final filter is one of my personal favorites, the style filter.

```python
def style(image):
    image_blur = cv2.GaussianBlur(image, (5, 5), 0, 0)
    image_style = cv2.stylization(image_blur, sigma_s = 40, sigma_r = 0.1)

    return image_style
```

This filter is really cool IMO.
Before calling stylization it's best to blur the image a bit for better results.

![Style Filter](https://i.ibb.co/PQwRbg0/style.jpg)

---

## Conclusion

Here I have shown how to create more various filters with opencv/python. I hope this tutorial was useful to you.

If you have any cool filters please share them. 😎

The source code and the original image can be found via:
https://github.com/ethand91/python-opencv-filters

---

Like me work? I post about a variety of topics, if you would like to see more please like and follow me.
Also I love coffee. 

[![“Buy Me A Coffee”](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/ethand9999)
Xampp on Linux
Tags: php, xampp, webdev, beginners
Published: 2022-11-20 02:52:53

Olá devs, resolvi fazer um artigo com pequenas dicas de uso para quem está iniciando no Xampp, principalmente em ambientes Linux.

[Nesse artigo](https://www.arthurmaia.dev.br/2022/11/como-instalar-o-xampp.html) mostro um básico de realizar a instalação da ferremante e também os comados iniciais para gerenciar os serviços via terminal.

Em breve vou fazer uma segunda parte mostrando como alterar o CHMOD para os casos de erro de escrita
Working on Seneca's Open Source Projects
Published: 2022-11-20 02:00:48

This week I got to Explore Seneca's Open source Projects. I worked On Telescope which shows the blogs of Seneca students. And I looked into the Seneca vs-code extension.

# What I did for Telescope

My initial plan was to work on [Issue 3639](https://github.com/Seneca-CDOT/telescope/issues/3639). It seemed to be a lot of work so I asked another developer Tong Liu for help where we would each work on a bit of the Issue. However, we soon realized that both of us couldn't get telescope running locally. We both had the same issue and we were unable to progress until we found a solution. We were contacted by Tue Nguyen who is more experienced with Telescope than us and he offered to help us through our issues. We got into a call together and set up Telescope together so we can understand where we messed up. That's where we found out that the issue was that we modified the configuration file which caused the issues.

So that's what I decided to do I wanted to improve the environment-setup documentation to prevent further errors for new telescope developers. I made sure to tell people about the bug and how to fix it.

[Pull 3762](https://github.com/Seneca-CDOT/telescope/pull/3762)

My initial plan for the contribution was much larger but I think that supporting telescope and making it easier for new people to work on means that it will continuously improve.

# What I did for the vs-code extension 
[Issue 7](https://github.com/Seneca-CDOT/vscode-seneca-college/issues/7)

I was looking over some of the new projects and I stumbled on a new project that plans to create a vs-code extension for Seneca developers. The issue was asking to add gitpod support to the vs-code extension. Gitpod allows developers to easily work in a controlled environment the gitpod.yml can automatically install what needs to be installed and run what needs to be run and it allows developers to have an easier time contributing to projects.

[Pull 12](https://github.com/Seneca-CDOT/vscode-seneca-college/pull/12)

What this means is that I needed to read the setup doc where I researched how to set it up and how to use it for myself. I also looked at what the gitpod.yml file does and how to configure it to run a project and install the dependencies.
My first experience Doing code reviews for PRs
Published: 2022-11-20 01:59:33

My final goal for this week was to continue my participation for Seneca's open source repository's by Reviewing Pull requests. I participated in two different Pull requests

# First Review
[Review 1](https://github.com/Seneca-CDOT/telescope/pull/3764)

This was my first review I looked over the code and from what I tested it worked. Others however wanted their to be a new test to test the new feature.

# Second Review
[Review 2](https://github.com/Seneca-CDOT/telescope/pull/3767)

This was my second review again I looked over it and the code and the feature worked locally.

# What did I learn
My way of testing was not enough I need to continue my practice and look deeper into the code to make sure everything works. But I also need more practice writing a valid review my simple looks good comment should be replaced with some constructive criticism and maybe include some things that I think they did well. I'm going to continue to practice but next time I'm going to make sure that when I review something i really look into and consider the ways that i would've done it to make it better or more efficient. From the amount of reviews I had in my telescope PR I knew that the amount their could always be something to improve on or change.
Timeouts/Intervals vs Eventloops
Tags: javascript
Published: 2022-11-20 01:54:18

## Em qual ordem os consoles serão logados?

![Simples exemplo de operação com timeout](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8hm16nu61buuf2uavo42.png)

```
timeout executed
last call
finish code
```
ou
```
last call
finish code
timeout executed
```

- - -

Se você tem um nível mais intermediário ou sênior, certamente saberá a resposta e não achará grande coisa. Mas se você está começando agora, certamente pode pensar que é um pouco contraintuitivo.

- - -

Se você acredita que seja a segunda alternativa, então, meus parabéns, você está certo! Agora você sabe o porquê? 

- - - 

Isso ocorre por causa de uma _coisinha_ do JavaScript chamada de **Event Loop**.

De maneira bem simplista: o EventLoop é uma fila de mensagens que a runtime do JavaScript executa. Cada mensagem tem uma função associada que é executada no formato de fila (FIFO).

Por se tratar de uma fila, as mensagens mais antigas são processadas antes e, a próxima mensagem só é executada quando a mensagem corrente é finalizada.
- - -
Aí você pergunta: 

> _"Okay, mas eu sei também que o runtime interpreta o código na ordem em que é executado, por que mesmo com 0ms no segundo argumento, o 'timeout executed' aparece por último?"_

É justamente por isso! Pode parecer estranho, mas o JavaScript, em sua base, é síncrono. Já o setTimeout/setInterval é feito para manipular o EventLoop de forma assíncrona.

Com isto dito, o timeout só será executado depois que todo o código interpretado passar pelo EventLoop do JavaScript.

Quando não houverem mais mensagens na fila do EventLoop, o callback do setTimeout será executado (no caso do snippet, imediatamente, por conta dos 0ms).

- - - 

É por isso que timeouts e intervalos não são recomendados para usecases que exigem extrema precisão. A depender de quão ocupada a fila de eventos esteja, pode ser que o callback não seja executado no tempo estipulado via parâmetro.

- - -

## Conclusão / Referências

Intervalos e Timeouts podem ser bem confusos e contraintuitivo se não entendermos algumas partes das "entranhas" do JavaScript, rs.

Links úteis:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

https://ankitkamboj18.medium.com/is-javascript-synchronous-or-asynchronous-what-the-hell-is-a-promise-302ee008dfcd

https://medium.com/reactbrasil/como-o-javascript-funciona-o-event-loop-e-o-surgimento-da-programa%C3%A7%C3%A3o-ass%C3%ADncrona-5-maneiras-de-18d0b8d6849a

- - -

## Off Topic

Esse foi o meu primeiro texto aqui. 😅

Se por algum acaso esse texto chegar até você e lhe der vontade de comentar algo, seja gentil 🫶🏼

Nunca fui muito bom em escrever ou ensinar, mas tracei como objetivo melhorar estes aspectos e cá estou eu, começando agora o que havia prometido começar no início de 2022. 
Decidi começar a escrever para melhorar alguns aspectos da minha comunicação e também como forma de estudar/documentar coisas legais de programação. :)

Qualquer crítica construtiva é bem vinda.