teleren/devto huggingface dataset:
Ten tips on Writing cleaner React Code.
Published: 2022-12-15 10:16:00

1. Use functional components instead of class-based components whenever possible. Functional components are simpler and easier to read than class-based components, and they can often achieve the same functionality without needing additional features like state or lifecycle methods.

2. Use descriptive, meaningful names for components, props, and variables. This will make your code more readable and easier to understand.

3. Use destructuring to extract values from props and state. This can make your code more concise and easier to read by avoiding the need to reference props and state using the `this` keyword.

4. Use the `map()` method to render a list of components, rather than using a `for` or `while` loop. This makes your code more concise and readable, making it easier to understand the intent of the code.

5. Avoid using inline styles or CSS-in-JS libraries; instead, use a separate CSS file to define styles for your components. This keeps your component code focused on rendering the UI, making it easier to manage and maintain your styles.

6. Use prop types to define the types of props that a component expects. This will help catch potential errors and ensure that your components are always provided with the correct types of props.

7. Use default prop values to specify the values that props should have if they are not provided. This will help ensure that your components always have the data they need to render, making your code more predictable and easier to work with.

8. Use higher-order components (HOCs) to abstract common functionality into reusable components. This can help you avoid duplicating code and make your components more modular and easier to understand.

9. Use the `useMemo()` hook to memoize expensive calculations and avoid recalculating them unnecessarily. This can help improve the performance of your application by avoiding unnecessary calculations.

10. Use the `useCallback()` hook to memoize callback functions and avoid creating new functions on each render. This can help improve the performance of your application by avoiding unnecessary re-creations of functions.

The key to writing cleaner React code is to focus on readability and maintainability. By following these tips, you can make your code more concise and easier to understand, making it easier to work with and maintain over time.
Build a docker image for backup Mysql database to AWS S3
Tags: devops, docker, osbkca
Published: 2022-12-15 10:13:04

In this tutorial, we will build a docker image for cronjob on Kubernetes to auto backup Mysql database.

**Let’s build a docker image with Dockerfile:**

```docker
FROM mariadb:latest

WORKDIR /app
RUN apt-get update && apt-get install -y curl unzip python3 python3-venv

RUN ln -s /usr/bin/python3 /usr/bin/python
RUN curl "https://s3.amazonaws.com/aws-cli/awscli-bundle.zip" -o "awscli-bundle.zip" && unzip awscli-bundle.zip && ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws
COPY backup_to_s3.sh ./backup_to_s3.sh

ENTRYPOINT [ "./backup_to_s3.sh" ]
```

In this Dockerfile, we use `mariadb:latest` to call `mysqldump` . In addition, we also install aws-cli to be able to interact with AWS using the command line.

File `backup_to_s3.sh`

```bash
#!/bin/bash

# Dump and upload to S3
FILE_NAME=backup-$(date "+%Y-%m-%d-%H%M%S").sql
mysqldump -h $DATABASE_HOST -P 3306 -u $DATABASE_USER --password=$DATABASE_PASSWORD $DATABASE_NAME > $FILE_NAME
aws s3 cp $FILE_NAME s3://$AWS_S3_BUCKET/$FILE_NAME
```

Don’t forget run `chmod a+x backup_to_s3.sh`

```shell
docker build -t backup_mysql:latest .
```

I have posted this docker image to my Docker Hub account [osbkca/backup_mysql](https://hub.docker.com/r/osbkca/backup_mysql)

**Deploy a CronJob to Kubernetes**
`mysql-cronjob-backup.yaml`

```yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  labels:
    app: auto-backup-mysql
  name: auto-backup-mysql
spec:
  jobTemplate:
    spec:
      template:
        spec:
          affinity: {}
          containers:
          - env:
            - name: DATABASE_HOST
              value: <change_value>
            - name: DATABASE_USER
              value: <change_value>
            - name: DATABASE_PASSWORD
              value: <change_value>
            - name: DATABASE_NAME
              value: <change_value>
            - name: AWS_S3_BUCKET
              value: <change_value>
						- name: AWS_ACCESS_KEY_ID
              value: <change_value>
            - name: AWS_SECRET_ACCESS_KEY
              value: <change_value>
            image: osbkca/backup_mysql:latest
            imagePullPolicy: Always
            name: backup-container

  schedule: 12 09 * * *
  successfulJobsHistoryLimit: 3
  suspend: false
```
To deploy:

```bash
kubectl apply -f mysql-cronjob-backup.yaml
```
Enjoy it! More Info [here](https://osbkca.me/blog/build-a-docker-image-for-backup-mysql-database-to-aws-s3)
Native App vs. Hybrid App: Which is the Best for Your Business?
Tags: programming, android, ios, hybirdapp
Published: 2022-12-15 10:08:37


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iki0vqb0bdco3eyvq0er.png)Befor Reading this Read My Last Two Post...

The straight answer is that it depends on your business model, objective, and amount of investment.

- If you want to just reach a global audience through any kind of OS with a limited budget then you can opt for Hybrid app development.

- And in case you want to launch your web app on app stores then, hybrid app development is the best choice.

- Another use case of a Hybrid application is “MVP”. That means, whether you want to test customer engagement and support for your project or business idea, you can develop and launch a Minimum Viable Product (MVP) as a Hybrid application. 

- On another hand, if you want to engage your customers or audience then you can consider Native mobile app development.

- If you want to achieve a high-end performance with heavy-load applications, Native app development can help you.

So, depending on your business objectives, you can opt for one which suits you. In case of any confusion feel free to contact a mobile app development company to get the best suggestion.

## Summing Up
Whatever it may be a Hybrid app or a Native app it must be built with proper codes. That is the main and common factor for the success of a mobile app.

That’s why choosing an eminent [**mobile app development company**](https://www.uplogictech.com/mobile-app-development-company) is important. The experts at the firm can also suggest the best choice for your business.
About active filter
Tags: electroniccomponents, ics, computer, filter
Published: 2022-12-15 10:08:07

An [active filter](https://www.jotrin.com/product/category/Active-Filter) is an electronic filter that uses active components such as transistors, operational amplifiers, or other amplifying elements, in addition to passive components such as capacitors and inductors, to filter a signal. Active filters are able to provide steeper roll-off characteristics and greater flexibility than passive filters, but they require a power source to operate. They are often used in electronic circuits to remove unwanted frequencies or to improve the signal-to-noise ratio.
Naming convention
Published: 2022-12-15 09:56:35

For naming convention I will stick with maximum of 16 digits.

Example:

DVSC-PDS-GEN01

Starting with project name (2 digits), hostname (2), environment (1; D - development, T - testing, P - production).
Next will be OS type (2; WS - Windows Server, WW - Windows Workstation, LS - Linux Server and so on). Last part will cover VM role (2-3) and a number.

Just wondering what kind of naming convention do you use in your homelab? Please share your thoughts in a comment section below.
An idea to tackle GPS Spoofing in autonomous vehicles
Tags: autopilot, gpsspoofing, hackin, ai
Published: 2022-12-15 09:53:31

Today I came to know that there is a threat to autonomous vehicles, GPS Spoofing while attending an event. Suddenly An idea popped up in my mind to tackle this threat. I don't know if this idea is valid or if it is in action already, I didn't go for much research. Just dumping my thoughts. So happy reading.

The idea is why can't we introduce a special communication between the vehicles in the same area. Suppose every vehicle is interconnected with something like Bluetooth just to verify that they are in the same GPS location. I will explain. If there are 10 vehicles in some car's so-called Bluetooth range, at periodic intervals that particular car verifies that, am I in the same location as theirs. If not, there is someone spoofing someone's GPS. We will use AI to improve it to the most sensible level.

This was just a broad explanation of my idea.
virtual in C++
Tags: virtual, cpp
Published: 2022-12-15 09:50:14

# implement virtual in C++

C++에서 클래스를 컴파일하면 그 클래스의 모든 메서드를 담은 바이너리 객체가 생성됨.

컴파일러는 `virtual`로 선언되지 않는 메서드를 호출하는 부분을 정적 바인딩(static binding)함.

`virtual`로 선언하면 vtable이라는 특수한 메모리 영역을 활용하여 메서드를 호출함. vtable을 보고 적합한 버전의 메서드를 실행함. (동적 바인딩, dynamic binding)

virtual 메서드가 하나 이상 정의도니 클래스마다 vtable이 하나씩 있고, vtable에 대한 포인터를 가짐.




## 정적바인딩(static binding)

 이른 바인딩(early binding)이라고도 함. 컴파일 시간에 바인딩이 결정되는 것
Créez votre premier serveur avec node.js
Published: 2022-12-15 09:37:12

Pour créer un serveur avec node, faites seulement ceci : 
const http = require('http');

```
const server = http.createServer((req, res) => {
    res.end('Voilà la réponse du serveur !');
});

server.listen(process.env.PORT || 5000);

```

Ah bon ? Seulement ça ? 😇 

Oui, là nous avons crée notre premier serveur avec node, mais avant de vous expliquez très bien le code, comprenons d'abord c'est quoi un serveur et c'est quoi Node ! 

Quand vous naviguez sur internet, vous faites la plupart de fois une demande à un autre ordinateur connecté sur internet, qui vous fournit alors la page web en réponse. L’ordinateur avec lequel vous parlez au travers internet c'est un serveur web. Un serveur web reçoit des requêtes HTTP d’un client, comme par exemple votre navigateur, et fournit ensuite une réponse HTTP, comme une page HTML ou du JSON d’une API.

Et en quoi est-ce que node intervient dans tout ça...🤔 

Node.js est un runtime qui nous facilite l'écriture de nos taches coté serveur
Transform image to base64 with promise based function
Tags: javascript, webdev
Published: 2022-12-15 09:20:30

```javascript
function imageToBase64(file) {
	    return new Promise(resolve => {
        const reader = new FileReader();
        reader.onloadend =  () => {
            const base64str = reader.result.toString();
            resolve(base64str);
        };
        reader.readAsDataURL(file);
    });
}
```
useReducer hook in React (No redux here)
Tags: webdev, javascript, react, beginners
Published: 2022-12-15 09:15:23

**The useReducer is a hook that provides a way to manage state in a React component.** 

**Is it dependant on redux?**

No, it's  provided by React and can be used independently of Redux. 

_**useReducer is a way to manage state within a single React component, whereas Redux is a state management library that is used to manage state in larger applications.**_


While useReducer and Redux share some similarities, they are not required to be used together. You can use useReducer on its own in a React component, or you can use Redux to manage state in an application that includes multiple components.


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


 **More on useReducers**

**It is similar to the useState hook, but it allows you to manage more complex state logic and handle multiple state updates with a reducer function.**

To use useReducer, you **first need to define a reducer function** that takes in the current state and an action, and **returns a new state.**

 Then, in your component, you can call useReducer and pass in the reducer and an initial state. This returns an array with the current state and a dispatch method, which you can use to **trigger state updates by calling the dispatch method and passing in an action.**

Here is an example of using useReducer in a React component:

```javascript
import {useReducer}from 'react'

const initialState = {
  count: 0,
};

/////takes in the current state and an action, and **returns a new state.**/updates state

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      return state;
  }
};

function MyComponent() {
//call useReducer and pass in the reducer and an initial state

  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: "increment" })}>
        Increment
      </button>
      <button onClick={() => dispatch({ type: "decrement" })}>
        Decrement
      </button>
    </div>
  );
}
```
In this example, the useReducer hook is called with the reducer function and the initialState object. 

This **returns the state object and a dispatch method,** which is used to trigger state updates by calling dispatch and passing in an action object. The state object contains a count property that is incremented or decremented when the corresponding buttons are clicked.
Unexpected end of form when sending form data with Postman- Multer
Tags: javascript, express, multer, typescript
Published: 2022-12-15 09:10:54

I keep getting "Unexpected end of form" errors when sending a post request with form data using Postman. The error is not useful and I couldn't figure out what the problem is. I'm using multer as a memory storage middleware before uploading the file to google storage.

I went through many threads but I couldn't find a cure for my exact problem. This was the closest to my problem but non of the answers seemed to solve this issue for me: [Unexpected end of form error when using Multer](https://stackoverflow.com/questions/72544409/unexpected-end-of-form-error-when-using-multer)

Here is my express server:

```
require("../../bootstrap");

const project = process.argv[2];

const JSUtils = require("../api/utils/JSUtils");
const config = require(`../conf/${project}.json`);
const bodyParser = require("body-parser");

const express = require("express")();
const app = require("./App").default;
const toolkit = require("../toolkit/Toolkit").default;
const admin = require("firebase-admin");

admin.initializeApp({
    credential: admin.credential.cert(config),
    databaseURL: `https://${project}.firebaseio.com`,
});

express.use(bodyParser.json());
express.use("/*/us-central1/v1", app);
express.use("/*/us-central1/toolkit", toolkit);

express.listen(5000, () => {});
```

Multer middleware:

```
export const upload = Multer({
    storage: Multer.memoryStorage(),
    limits: {
        fileSize: 10 * 1024 * 1024, // No larger than 10mb
        fieldSize: 10 * 1024 * 1024, // No larger than 10mb
    },
});
```

Here is the express router I use for the file upload:

```
router.post(
    "/upload",
    UserMiddleware.checkUser(),
    upload.single("imgfile"),
    controller.handleFileUpload,
);
```

controller:

```
export const handleFileUpload = async (req, res) => {
    const bucketName = `$google-storage-bucket`;


    console.log("request file", req.file);
    if (req.file) {
      //Upload file to google storage
     }
}
```

And to so send the request in Postman I'm doing this:

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

**I'm not adding the multipart/form-data content type manually as I know it is being set by postman automatically.**

```
e API v1 - Caused by Error: Unexpected end of form
>      at Multipart._final (/Users/User/app-firebase/functions/node_modules/busboy/lib/types/multipart.js:588:17)
>      at callFinal (internal/streams/writable.js:610:10)
>      at processTicksAndRejections (internal/process/task_queues.js:82:21)
```

I also tried eliminating the middlewares before the multer one but that didn't make a difference. I've also tried testing client-side and sending a fetch request with the created FormData similarly the response is the same.
Automating basic website creation with Node.js
Tags: automation, node, javascript, webdev
Published: 2022-12-15 09:08:02

Node.js is a powerful tool for web development, and one of its key benefits is the ability to automate the creation of websites. In this tutorial, we'll show you how to use Node.js to quickly and easily create a basic website using JavaScript, HTML, and CSS. 

Whether you're a seasoned web developer or just getting started, this tutorial will provide you with the skills you need to create dynamic, interactive websites using Node.js.

Here is the basic shape of a Node.js script that can be used to automate the building of a simple JavaScript, HTML, and CSS website:

```javascript
// Import the required modules and libraries
const fs = require('fs');
const path = require('path');

// Define the paths to the JavaScript, HTML, and CSS files
const jsPath = path.join(__dirname, 'scripts', 'main.js');
const htmlPath = path.join(__dirname, 'index.html');
const cssPath = path.join(__dirname, 'styles', 'main.css');

// Define the contents of the JavaScript, HTML, and CSS files
const jsContent = `console.log('Hello, world!');`;
const htmlContent = `<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="styles/main.css">
  <title>My Website</title>
</head>
<body>
  <h1>My Website</h1>
  <p>Welcome to my website!</p>
  <script src="scripts/main.js"></script>
</body>
</html>`;
const cssContent = `body {
  font-family: sans-serif;
  color: #333;
}

h1 {
  color: #1b8cff;
}`;

// Create the "scripts" and "styles" directories, if they don't already exist
if (!fs.existsSync(path.join(__dirname, 'scripts'))) {
  fs.mkdirSync(path.join(__dirname, 'scripts'));
}
if (!fs.existsSync(path.join(__dirname, 'styles'))) {
  fs.mkdirSync(path.join(__dirname, 'styles'));
}

// Write the JavaScript, HTML, and CSS files
fs.writeFileSync(jsPath, jsContent);
fs.writeFileSync(htmlPath, htmlContent);
fs.writeFileSync(cssPath, cssContent);

```
This script begins by importing the `fs` and `path` modules, which are used to work with the file system. It then defines the paths to the JavaScript, HTML, and CSS files, and the contents of those files.

Next, the script creates the "scripts" and "styles" directories, if they don't already exist, and writes the JavaScript, HTML, and CSS files to those directories.

Of course, this is just a basic example, and you can modify and expand on it to suit your specific needs. For example, you could add additional files, such as images or additional stylesheets, and include them in the HTML file. You could also add more complex logic to the script, such as reading in templates and filling in placeholders with specific data.
Understanding Kubernetes: part 47 – Kubernetes 1.26 Changelog
Tags: kubernetes, devops, docker, beginners
Published: 2022-12-15 09:00:59

---
title: Understanding Kubernetes: part 47 – Kubernetes 1.26 Changelog
published: true
description: Serie of sketchnotes about Kubernetes. Explaining in a visual way Kubernetes principles.
tags: Kubernetes, DevOps, Docker, beginners
series: Understanding Kubernetes in sketchnotes
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ye9umtlfvbn5n5tskzjo.jpg
---

Understanding Kubernetes can be difficult or time-consuming. In order to spread knowledges about Cloud technologies I started to create sketchnotes about Kubernetes. I think it could be a good way, more visual, to explain Kubernetes (and others technologies).

We continue the serie of Sketchnotes about Kubernetes, with a focus on what's new in the new version of Kubernetes: v1.26.

![Kubernetes 1.26](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ye9umtlfvbn5n5tskzjo.jpg)
![Kubernetes 1.26](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wxngk744ijady5taag7f.jpg)
![Kubernetes 1.26](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pxovhm2ca5s3ooo9gfl2.jpg)
![Kubernetes 1.26](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7bx4a7kf4x0obxp7xnzb.jpg)

[Kubernetes 1.26 Complete changelog](https://kubernetes.io/blog/2022/12/09/kubernetes-v1-26-release/)

If you are interested, I published an entire illustrated book about Kubernetes, available in paperback on [Amazon](https://www.amazon.fr/dp/B0BB619188/ref=cm_cr_arp_d_product_top?ie=UTF8) and in digital version on GumRoad: ["Understanding Kubernetes in a visual way"](https://gumroad.com/aurelievache#uCxcr).

As usual, if you like theses sketchnotes, you can follow me, and tell me what do you think. I will publish others sketchs shortly :-).
The Role of HTML5 in Modern Web Development
Tags: webdev, beginners, programming, html
Published: 2022-12-15 08:57:05

HTML5 is the latest and greatest version of the HTML standard. It's a great tool for modern web development and has a bunch of new features that make life easier for developers and users alike.

###The Advantages of HTML5
HTML5 has many advantages that make it a compelling choice for modern web development. These include better support for multimedia and animation, improved semantics, and new features like the canvas element and local storage.
HTML5 also supports offline storage, meaning users can access content even if they're not connected to the internet. And because HTML5 is designed to be more compatible with mobile devices, sites that use it tend to load faster and be less resource intensive than those that don't.

###New Attributes in HTML5
HTML5 also includes new attributes and behaviors. For example, the new autofocus attribute allows web developers to specify that a form element should automatically receive focus when the page loads. The new placeholder attribute allows developers to specify text that should be displayed in an input field until the user begins typing. And the new required attribute specifies that a form field must be filled out before the form can be submitted.

###New APIS in HTML5
HTML5 also includes a number of new APIs that provide more powerful ways to interact with web pages. For example, the Geolocation API allows web applications to access the user's geographic location. The Web Storage API provides a way for web applications to store data locally on the user's device. And the Web Workers API allows web applications to run background tasks without impacting the performance of the page.

With all of these new features, HTML5 provides a more powerful and flexible platform for web development.

Overall, HTML5 is a major step forward for the web. It provides a more robust and efficient platform for developers to build on, and offers users a better experience overall.

Check out the [BLST website](https://bit.ly/2FQYG5Q)
Join the discussion in our [Discord channel](https://bit.ly/3HQtlYo)
Test your API for free now at [BLST](https://www.blstsecurity.com/?promo=blst&domain=https://dev.to/The_Role_of_HTML5_in_Modern_Web_Development)!
1143. Leetcode Solution in cpp
Tags: cpp
Published: 2022-12-15 08:25:15

```cpp
class Solution {
 public:
  int longestCommonSubsequence(string text1, string text2) {
    const int m = text1.length();
    const int n = text2.length();
    // dp[i][j] := LCS's length of text1[0..i) and text2[0..j)
    vector<vector<int>> dp(m + 1, vector<int>(n + 1));

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        dp[i + 1][j + 1] = text1[i] == text2[j]
                               ? 1 + dp[i][j]
                               : max(dp[i][j + 1], dp[i + 1][j]);

    return dp[m][n];
  }
};
```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/longest-common-subsequence/