teleren/devto huggingface dataset:
React Deep Dive: Element vs. Component
Tags: javascript, react, webdev
Published: 2021-02-07 16:53:03

This year, I'm reading through the React docs and [taking notes as I go](https://dev.to/laurenmbeatty/react-deep-dive-153e). 
## React Element
A React Element is an object representation of a [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction) node. It is a plain old object, and not an actual DOM element. In essence, it is a description of what you want to appear on the screen (oh, and [it's declarative!](https://dev.to/laurenmbeatty/react-deep-dive-it-s-declarative-ee2)). 

```javascript
{
  type: 'h2',
  props: {
    className: 'heading heading-medium',
    children: 'React Deep Dive'
  }
}

const header = (
  <h2 className="heading heading-medium">
    React Deep Dive
  </h2>
)
```
An Element has a `type`, props, and any children nested inside of it. The type can be either a DOM Element (like 'h2', in the above example), or a Component Element (like the `Heading` described below).

## React Component
A React Component is *composed* of React Elements. It is either a class with a render function, or a stateless functional component. It takes props as an input and returns an element tree as its output. Component names start with a capital letter (`Heading` vs `h2`).
```javascript
const Heading = (props) => {
  return (
   <h2 
    className={`heading heading-${props.size}`}
   >
    {props.children}
   </h2>
  )
}
``` 
I found [this blog post](https://reactjs.org/blog/2015/12/18/react-components-elements-and-instances.html) (from 2015!) very helpful in understanding the differences.
The Architecture Cake
Tags: ios, architecture, softwaredesign
Published: 2021-02-07 16:48:21

Many people tend to talk about architecture as layers. It makes sense to some extent. You develop one layer, and the layer immediately above knows and can communicate with the layer below.

If we develop iOS apps following this principle, we could probably develop the models, repositories, viewModels and controllers, as separate layers, each layer communicating with the layers below, and we could create a folder/group for each of these layers, and put every component of that layer in that folder. Following this principle, we'll end with a group full of models, another group full of repositories, and so on.

![ArchitectureCake-01](https://dev-to-uploads.s3.amazonaws.com/i/eyztzop90hhg88s2zfez.png) 

Well, from my viewpoint, this is not the ideal, and I'll explain you why.

What are our goals when designing an architecture? I can say that in my opinion, the goal is reducing the developer cognitive load while isolating modules as much as possible. I tend to think apps as modules. A module is a cohesive unit that contains all the layers that belong to a single concern. **In the architecture cake, a module is a piece of the cake.**

Architecture is not an onion, it's a cake. Unlike an onion, you serve a cake in pieces, each piece of the architecture cake is a module you can eat without involving the rest of the cake.

If you have a Twitter client, you might have a Tweet creation screen, where every class related to the Tweet creation will belong to the same folder/group. When you are working on the Tweet creation, you know that everything related will be in the same place.

![ArchitectureCake-02](https://dev-to-uploads.s3.amazonaws.com/i/co29zlg8ak7mn29hkvl2.png)
 
Another benefit that comes with this approach is that it will be easier to split your app in different modules and then integrate all of them using a package manager like SPM or Cocoapods.
Let's Create A Simple Smiley Face With CSS
Tags: css, codenewbie, webdev, codepen
Published: 2021-02-07 16:23:08

In this article I'm gonna show you how to create a very simple smiley face with css.

Let us begin <br>

<h2> Step 1 : Creating the face </h2>

First create a div and give it a class.
Since this div will be the face I named it "face".


```html
<div class="face"></div>
```
The styling part is easy. 
We create a square first and then with the help of <code> border-radius </code> we'll make it round.
```css
.face {
 background-color: #fcba03;
 width: 400px;
 height: 400px;
 border-radius: 100%;
}
```

<img src="https://dev-to-uploads.s3.amazonaws.com/i/ey9vqj6ll3pryhzcg25g.png"> 
_____________

<h2> Step 2 : Creating the mouth </h2> 

We want the mouth to be on the face so we need to create a new div <i>inside </i> our previous div.

```html
<div class="face">
  <div class="mouth"></div>
</div>
```

```css
mouth {
  position: absolute;
  background-color: black;
  width: 215px;
  height: 90px;
  border-radius: 7px 7px 100px 100px;
  top: 250px;
  left: 90px;
} 
```

<img src="https://dev-to-uploads.s3.amazonaws.com/i/4kw6hrlsi0ds7b7j06q2.png">

______________________

<h2> Step 3 : Creating the eyes </h2>

Moving on to the eyes :
I've created a div for the eyes , so that both eyes would be in the same section. itds also be easier to move them around.

<b> A: Eye section : </b>

```html
<div class="face">
  <div class="mouth"></div>
  <div class="eye-section"></di>
</div>
```
```css
.eye-section {
/*   added border just to see the where the eye section is. We'll remove it later. */

  border: solid red 2px;
  width: 275px;
  height: 100px;
  position: absolute;
  left: 60px;
  top: 70px;
}
``` 
<img src="https://dev-to-uploads.s3.amazonaws.com/i/84ixm0yc63jq6xb90zj5.png">


<b> B: Creating the eyes </b>

```html
<div class="face">
  <div class="mouth"></div>
  <div class="eye-section">
    <div class="left-eye"></div>
    <div class="right-eye"></div>
  </di>
</div>
```


```css
.left-eye, .right-eye {
  background-color: #4f2103;
  width: 52px;
  height: 65px;
  border-radius: 50px;
  position: absolute;
  top: 25px;
}
```
```css
.right-eye {
  right: 20px;
}
```

<img src="https://dev-to-uploads.s3.amazonaws.com/i/or64zqqpe5j0on3wf6bk.png">
________________________

<h2> Step 4 : Creating pupil </h2>


And at last we create the pupils with pseudo elements. <br>

```css
.left-eye::before, .right-eye::before {
  content: "";
  display: block;
  background-color: white;
  width: 23px;
  height: 23px;
  border-radius: 100px;
  position: absolute;
  top: 20px;
  left: 10px
}
```

<img src="https://dev-to-uploads.s3.amazonaws.com/i/bpdkfzpe8rwl6bweqdwg.png">

<br> And now you're done.

____________________

Here's the codepen

{% codepen https://codepen.io/nazaneyn/pen/poNyRjg %}


__________________

I hope you guys liked this simple and easy css art
Margin Indentation In Strings | Problem
Tags: kotlin, appdev, android
Published: 2021-02-07 16:48:18

Hello guys, 
I was practising some of Kotlin on the coding ground.
It's about margin indentation. I practised using the pipe with the function .trimMargin(). And I applied it correctly.
Now, I'm trying the triangle prefix. But it doesn't work.
Here's the link if you want to check.
http://tpcg.io/ieHQZzJs
The IPv4 address validation algorithm
Tags: algorithms, javascript
Published: 2021-02-07 16:33:28

# Introduction
We are implementing an IPv4 validation algorithm to check whether a string input is a valid IPv4 address.

# What is an IPv4 Address
IPv4 addresses are usually represented in dot-decimal notation, consisting of four decimal numbers, each ranging from 0 to 255, separated by dots(.). Each part represents a group of 8 bits (an octet) of the address.
Example: 172.16.254.1

# Implementation
IPv4 has 4 parts that are separated by a dot(.). Each part is a numerical value ranging from 0 to 255. 
We don't care about the IP address classes, we only care about a valid IPv4 address
##Here is our solution implemented in JavaScript:

```
function validateIpAddress(ipaddress) {
    if (!ipaddress) return false;

    const ipArray = ipaddress.split('.');
    if (!Array.isArray(ipArray) || ipArray.length !== 4) return false;

    const invalidIPArray = ipArray.filter((octet) => {
        const number = parseInt(octet);
        return isNaN(number) || number < 0 || number > 255;
    });

    if (invalidIPArray.length) return `Wrong octet: ${invalidIPArray}`;

    return true;
}
```

# Breakdown
**Step 1**: In algorithms, it's always the best approach to check for falsy values to eliminate unwanted errors. 

**Step 2**: Let's split the string argument by dot(.) using `split function` which returns an array.

**Step 3**: We check the array length as it must be composed of 4 parts. If the array length different from 4, you guessed it!! It's invalid.

**Step 4**: Filter the array `filter function` performing these 2 important tasks: 
1. Parse array value to an integer value
2. Check and return the value that is not ranging between 0-255, or if the value failed while converting to an integer that returns NaN.

**Step 5**: Check the returned filtered array length, if the length is not 0, you guessed it!! it's an invalid IP. We return the invalid parts of the given IP address.

>**filter()** method creates an array filled with all array elements that pass a test/condition specified
>**split()** method is used to split a string into an array of substrings and returns the new array.

# Conclusion
Feel free to contribute and improve this approach.
Thank you for reading the blog post. Subscribe for more articles
Contributor: [Deogratias](https://dev.to/adeogratias)
[Repo](https://github.com/ADeogratias/programming_is_fun/blob/master/check_ip_address.js)
Animated Shadow using ShineJs
Tags: html, beginners, css, tutorial
Published: 2021-02-07 16:28:34

Hello, guys in this tutorial we will create animated text shadow animation on the mouse using shinejs, we will learn into this tutorial how to create awesome text shadow
###Shine.js (A library for pretty shadows)###

**Features**
1. Dynamic light positions
2. Customizable shadows
3. No library dependencies, AMD compatible
4. Uses text or box shadows based on content
5. Works in browsers that support textShadow or boxShadow and auto-prefixes if necessary

***Include the script***
`<script src="path/to/shine.min.js"></script>`
***Instantiate shine.js***
```js
var shine = new Shine(document.getElementById('my-shine-object'));
Change the light position:

window.addEventListener('mousemove', function(event) {
  shine.light.position.x = event.clientX;
  shine.light.position.y = event.clientY;
  shine.draw();
}, false);
```

First, we need to create two files ***index.html*** and ***style.css*** then we need to do code for it.

###Animated Shadow Step:1###
**Add below code inside index.html**
```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>shadow animation</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@500&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/shine.js/0.2.7/shine.min.js" integrity="sha512-qqcCgMiPGAtvUSAAErvR6w8Y0/MdKWW1aO2sjg/TVvpO56Z6o1TTsHf+i+nCMxeCxmRbVlzjPnU8FvDNt+8cOA==" crossorigin="anonymous"></script>
  </head>
  <body>
    <h1 id="shiny-text">Stackfindover</h1>

    <script>
      var shine = new Shine(document.getElementById('shiny-text'));
      window.addEventListener('mousemove', function(event) {
        shine.light.position.x = event.clientX;
        shine.light.position.y = event.clientY;
        shine.draw();
      }, false);
    </script>
  </body>
</html>
```
###Animated Shadow Step:2###
Then we need to add code for ***style.css*** which code I provide in the below screen.
```css
* {
  padding: 0;
  margin: 0;
  outline: 0;
  font-family: 'IBM Plex Sans', sans-serif;
}
body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background-color: #ffffff;
}
h1 {
  color: #f7f7f7;
  font-size: 150px;
  display: table;
  text-align: center;
}
```

###Animated Shadow Video Output:###
{% youtube RgXSKg49gyQ %}

###Animated Shadow CodePen Output:###
{% codepen https://codepen.io/stack-findover/pen/GRNNbRm default-tab=js,result %}
How to cleanUp firestore data fetch on useEffect?
Tags: help, javascript, react
Published: 2021-02-07 16:22:31

Hello guys... I need your help... When (quickly) navigating on my react website... I get this error on the console. I heard I need to use the cleanUp function in order to correct this error. But I am using firebase firestore to fetch the data so I dont know how to solve this error...
Here is the error on the console
![image](https://dev-to-uploads.s3.amazonaws.com/i/8kyr5kn74p4913o9m4j1.png)
 

Here is the code of the useEffect hook I am using...

``` js
useEffect(() => {
    const fetchDb = db.collection('posts');

    fetchDb.get()
      .then(response => {
        const fetchedPosts = [];
        response.docs.forEach(post => {
          const fetchedPost = {
            id: post.id,
            ...post.data()
          };
          fetchedPosts.push(fetchedPost);
        });
        setPosts(fetchedPosts);
        setIsLoading(false);
      })
      .catch(error => {
        error = 'Houve um erro'
        setError(error);
      });
  }, []);
```
MultiVariate Anomaly Detection
Tags: machinelearning, webdev, javascript, datascience
Published: 2021-02-07 16:21:37

Discovering anomalies in complex multivariate and multidimensional data can be quite a challenge. Visualizing these anomalies can be even trickier, especially if you want to keep it simple without having to go over thousands of charts to filter out issues from false positives and noise. Using statistical methods we can aggregate complex data to be displayed on a single heatmap. By hovering over specific cells, we can quickly display the individual data on charts.

Heatmap: https://healzer.github.io/Industrial-Data-Analysis/hmap1.html?testdays=3&testlike=1

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/czvpw2dyy5dxk8itnt3r.png)

This system was first implemented for a high-tech enterprise's CI/CD pipeline. It is being used by R&D, Q&A and management to keep track of all processes and variables throughout the development lifecycle. Any anomalies can easily be identified and pinpointed as soon as they appear on the heatmap. Anomalous decreases (green) indicate performance improvements (time, memory and parameter reductions), while degradations (red) imply performance issues.

Very subtle improvements or degradations are tricky to identify and detect, but overall the system has a very high accuracy. The best use of this system is for data that should remain static over time, it may not work very well if you have alternating/seasonal data. Separate charts can be built for mapping GitHub commits to each individual data point, allowing the team to instantly pinpoint which code change caused which performance change.

The demo URL can contains three parameters:

- `testdays`: how many days from the data should be used as test data (versus baseline data)
- `testlike`: filter data whose test value should contain a certain string (these are the Y-axis values)
- `annotate`: (0 or 1) primarily for debugging reasons, indicating whether to show Z-values on each cell (may slow down your browser!)

This code may not be directly usable for your purposes, but the general idea of using statistical functions like MADe and Z-values to detect anomalies in datasets may be very useful in CI/CD pipelines but also many industrial processes.

GitHub: https://github.com/healzer/Industrial-Data-Analysis
How to make a collage using Javascript: Part 3 (Downloading the collage)
Published: 2021-02-07 16:21:07

Read first two parts here:
* [part 1: starting files](https://dev.to/coulke/how-to-make-a-collage-using-javascript-part-1-starter-files-4a13) 
* [part 2:Previewing](https://dev.to/coulke/how-to-make-a-collage-using-javascript-part-2-javascript-section-6k0)
<br/>

First let's define a function for downloading the image:
````javascript
/**
 * Generate image from the canvas then downloads it.
 */
1 function downloadImage() {
2    const dataSrc = cvns.toDataURL("image/png");
3    let hiddenLink = document.querySelector("#hidden-link");
4    hiddenLink.setAttribute("href", dataSrc);
5    hiddenLink.setAttribute(
6      "download",
7      `collage${new Date().getMilliseconds()}`
8    );
9    hiddenLink.click();
10  }
```
`HTMLCanvasElement.toDataURL()` as explained by MDN, <br/>
> returns returns a data URI containing a representation of the image in the format specified by the type parameter.

On __line 2__ we add the type as `image/png` even though that's the default, you can add even as `jpg.`
On __line 4__ we add the `href` to the hidden link and put the `dataSrc` as the url. We also add the attribute of `download` and a name which starts with collage.
The hidden link is in the `index.html` file.
Still that won't work as we need to paint the main canvas but first we need to prevent the default of download button so it won't redirect.
Add to `upload.js`
```javascript
downloadButton.addEventListener("click", function (e) {
    e.preventDefault();
    paintThenDownload(downloadImage);
  });
```
We then define the `paintThenDownload` button.
Add to `upload.js`:
````javascript
 /**
 * Paints the canvas then call the function to download image.
 * @param callback Function
 */
function paintThenDownload(callback) {
    let img1 = document.querySelector("#img-1");
    let img2 = document.querySelector("#img-2");
    let query = window.location.search;
    let pickedTemplate = query.split("=")[1];
  
    if (img1 !== null && img2 !== null) {
      if (pickedTemplate === "1") {
        template_1(img1, img2, "main");
      } else if (pickedTemplate === "2") {
        template_2(img1, img2, "main");
      } else if (pickedTemplate === "3") {
        template_3(img1, img2, "main");
      } else {
        template_1(img1, img2, "main");
      }
    }
    callback();
  }
```
It's the same as the `previewCollage` function on the last section but this one receives a callback function and the templates third parameter is `main` and not preview.
The function is called and passed to the `downloadImage` function when the `downloadButton` is clicked.
That's it, I hope you found that worth your time.
Generate a unique random code to store in DB
Tags: php, randomcode, unique
Published: 2021-02-07 16:01:24

In this post I will show one of the methods I usually choose to generate unique random code.

First, the function that will return the string code.
```php
function generateCode(int $size = 10){
  $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVZYabcdefghijklmnopqrstuvwxyz';
  $code = substr(str_shuffle($chars), 0, $size);
  return $code;
}
```
EXPLAN: A very simple function that accept an integer as attribute which will be the length of our code, in this case if the legth is not given, a 10 is passed by default.
Then we set a string of characters we want to be used to build our code.
Then the code itself is built by shuffling the string and get a substring from the first character as long as indicated by the int we pass in the function.


For this to be unique, we can search the table we want to interact with
```php
      // Generate + update code
      do {
        // Generate code
        $code = generateCode();
        // Loop to search for an identical code, if found generate another one
        $stmt = $conn->prepare("SELECT count(id) from tablename where code = ?");
        $stmt->bind_param("s", $code);
        $stmt->execute();
        $result = $stmt->get_result();
        $row_code = $result->fetch_row();
      } while ($row_code[0]!=0);
      // Update record
      $stmt = $conn->prepare("UPDATE tablename SET code = ? WHERE id = ?");
      $stmt->bind_param("si", $code, $id);
      $stmt->execute();
```
EXPLAN: with a do-while we can call the function and get a first-try code. Then we search for it in the table with a select. In the while we check if the result is different from zero (the code already exists). If it exists, the loop will keep running and create codes until a really brand new one is created. Then the code will exit the loop and we can do something with this unique code, maybe update an existing record.

Of course, the shorter are the codes and the fewer are the characters used to build them, the higher will be the risk to have a very long and resources sucking code. 

If you have any suggestion or correction about this, I'll be glad to hear about it.
Change the prompt in powershell
Tags: powershell, shell, productivity
Published: 2021-02-07 15:55:33

Hello everyone, 

short post this week. Was working on another post but not really satisfied with it. So you get this short intermission. 

What i learned not to long ago ist, that you are able to change you prompt in powershell. You have to put a function named prompt into your Powershell Profile. 

```powershell 

function prompt {"PS: $(get-date) / $PWD \n >"}

```

And after the next start you will get the changed prompt:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rfgobaxcsfom6d5nve04.PNG)

By the way  a line break in powershell is written like this: 

```powershell
"`n"
``` 
The double quotes are important, if you use single quotes it will not work.
Optimize tests with Setup & Teardown methods
Tags: python, testing, webdev, tutorial
Published: 2021-02-07 15:52:21

In this post, we will learn how we can use SeleniumBase Setup & Teardown methods to optimize our tests even further. If you are not familiar with setup & teardown concepts, essentially, it allows you to run certain steps before and after your actual test.

So, when you run the Setup method, it will trigger the steps BEFORE your test will run and the TearDown will run the steps AFTER your test has finished.

### **Setup Method**
The setup method will run the steps before each of your tests. Let’s take a look at the sample code below –

![setup code](https://dev-to-uploads.s3.amazonaws.com/i/pij3uh1euhu465n4qrua.png)

Typically, you would use your setup method for any repetitive code between your tests such as opening the page, test data creation, or log in.

---

### **TearDown method**
The tearDown method will run the steps after each of your tests has finished running. Let’s take a look at the sample code below –

![teardown code](https://dev-to-uploads.s3.amazonaws.com/i/k8j7mtrrjua0hfycyod1.png)

Typically, you would use the tearDown method for actions such as taking screenshots after the test has finished running, logging some data, or for Logout.

---

### **Check out the video below to learn more about the Setup & TearDown methods using Selenium Python –**
{% youtube uZ-sgPTM0eM%}

---

📧 Subscribe to my [mailing list](https://automationbro.com/mailing-list) to get access to more content like this 

👍 Follow [automationbro](https://twitter.com/automationbro) on Twitter for the latest updates

...

This post was written with the help of a high amount of caffeine. And, if this post helped you out and you would like to support my work, you can do that by clicking on the button below and continue supporting my caffeine love :)

<a href="https://www.buymeacoffee.com/automationbro">![Buy me a coffee](https://dev-to-uploads.s3.amazonaws.com/i/4aw2ub3f4qkyjk0ivwt4.png)</a>

You can also support me by liking and sharing this content.

Thanks for reading!
If you were the new CEO of Amazon Web Services what would be your first executive order?
Tags: aws
Published: 2021-02-07 15:35:10

Andy Jassy who is the current CEO of Amazon Web Services (AWS) is going to be the new CEO of Amazon. It's uncertain who will be next to the CEO of AWS. 

If you could have full control of AWS what would you decree?

I would add a Dark Theme to the AWS Console.