teleren/devto huggingface dataset:
How to Deploy a Static Webapp on Azure Static app.
Published: 2023-05-09 20:32:31




In today's post, I am going to be showing how to deploy a static web app on Azure Static App. Before we proceed, Let me quickly explain what Azure Static App does.

Azure Static Web Apps is a service that automatically builds and deploys full stack web apps to Azure from a code repository.

To continue with this tutorial , you will need

1. An Azure subscription. In case you do not have a subscription, get it here. 
2. A github account and a static HTML File. The resource used for this tutorial can be found
 [here](https://github.com/graceamole/ChristmasGift)

#### Step 1 : Create Azure Static Web App
After a successful login to your account, click on create resource.


![create azure app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vmd9zd9wh2nx2vi8zgl3.png)


in the search bar, type in static app, then click on static web app, then click on create.


#### Step 2: Configuring the Azure Static App


![create a static app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dwzgv90r53o6v56toxu8.jpeg)

Under resource group, create a new resource group

Under static web app details, enter the name of your static Web App

Under Deployment details, select Github as your source. you will required to authorize Azure to access your Github.


![Github authentication](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i6qfg0naqtqho0q3b4wk.jpeg)

After authorization, enter the repository and the branch that contains the code you want to deploy.

![selecting file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lfy86esbng20va4gsqwb.jpeg)

Under build details, select custom and provide the path to where your html file is located as the app location. Then click on preview + create

![preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hjv45gsko0qtg8cvg2wq.jpeg)

If successful, your azure static app should be similar to the picture above. Wait for the static app to be deployed

Once deployment is complete, you will be redirect to the page shown below. click on go to 


![click Resource](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i8trhcji70rbzzuqn812.jpeg)
  
click on url on the right had side to redirect you to the static web app you just uploaded.

![uploaded file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x6tsgeakwwughw4i50oq.jpeg)

You will be redirected to your static app.



![Static App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8r0lk7ccutkdp9beq0le.jpeg)


congratulations, you just Deployed a static web app on Azure.


![Delete resource](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/46i8yiwzi7mdq1zk0wks.jpeg)


Do not forget to delete your resource when not in use!!. You do not want to get billed.
How to use regex in javascript:
Tags: webdev, javascript, beginners, programming
Published: 2023-05-09 20:28:43

Hey, for today’s blog we going to create a function which takes away spaces and special characters from an input and inserts an underscore using regular expressions or regex.
The reason you would need this piece of code is, special characters can cause alot of problems in your database and system if not handled properly so you would need a way to get rid of them if a user had to insert them.

So what is a regular expression.
A regular expression, commonly referred to as regex or regexp, is a sequence of characters that define a search pattern. It is mainly used for text-based searching and string manipulation.

So for our program we going to create a simple input with a button which will display the word inside the input when clicked, but if the word inside the input has spaces or special characters it will replace it with an underscore.

```
<input type="text">
<button onclick="displayWord()">Display</button>
<h1 id="word"></h1>
```

```
function displayWord() {
         let word = document.querySelector('input').value // Grab the value inside the input
         .trim() // remove all the white space on the left and right
         .replace(/[\s\W]+/ig, "_"); // replace all spaces in between words and all characters with underscore

           document.getElementById("word").innerHTML = word;
        }
```

Inside our replace function I added in regex, the “\s” is looking for all the spaces and the \W is looking for all the non-word characters or special characters which are for e.g: !, @, #, $, %.... The “+” just means that the regex should look for one or more occurrences of the whatever we looking for. The “i” means that the regex should be case-insensitive meaning it should treat “HELLO” the same as “hello”. The “g” means the regular expression should perform a global match meaning if a sentence contains multiple instances of the same word it should find all of them and not just stop on the first match.
Power of useLayoutEffect for solving Hydration error in Next js.
Tags: javascript, react, nextjs, frontend
Published: 2023-05-09 20:04:21

If you've worked with Next.js before, you may have encountered the dreaded "Text content did not match" error, also known as a hydration error. This error occurs when the HTML generated on the server does not match the HTML generated on the client during the first render. One common cause of this error is the use of useEffect to update the state, which causes a flicker or jarring effect on the page.

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

Fortunately, there is a solution to this problem: useLayoutEffect. This hook has the same signature as useEffect, but it runs synchronously after all DOM mutations. This means that it is guaranteed to run before the browser can paint anything on the screen, making it perfect for handling hydration errors.

Let's take a look at an example. Suppose you have a component that sets the active category in local storage when the user clicks on a button:

``` javascript
import { useState } from 'react';

const MyComponent = () => {
  const [activeCategory, setActiveCategory] = useState('A');

  const handleClick = (category) => {
    setActiveCategory(category);
    localStorage.setItem('activeCategory', category);
  };

  return (
    <div>
      <button onClick={() => handleClick('A')}>Category A</button>
      <button onClick={() => handleClick('B')}>Category B</button>
      <button onClick={() => handleClick('C')}>Category C</button>
    </div>
  );
};

```

This code works fine during the initial render, but if you navigate away from the page and then come back, the active category will be reset to 'A' because the state is being reset to its initial value. To fix this problem, you can use useLayoutEffect to set the active category in local storage:

``` javascript
import { useState, useLayoutEffect } from 'react';

const MyComponent = () => {
  const [activeCategory, setActiveCategory] = useState('A');

  useLayoutEffect(() => {
    localStorage.setItem('activeCategory', activeCategory);
  }, [activeCategory]);

  const handleClick = (category) => {
    setActiveCategory(category);
  };

  return (
    <div>
      <button onClick={() => handleClick('A')}>Category A</button>
      <button onClick={() => handleClick('B')}>Category B</button>
      <button onClick={() => handleClick('C')}>Category C</button>
    </div>
  );
};
```

Now, when the user clicks on a button, the active category is updated in the state, and then useLayoutEffect runs and sets the active category in local storage. This ensures that the active category is preserved even if the user navigates away from the page and then comes back.

In conclusion, useLayoutEffect is a powerful tool for handling hydration errors in Next.js. Using it instead of useEffect ensures that your state updates are reflected correctly on the client during the first render, and avoids the dreaded "Text content did not match" error.
Midpoint Reminder! — GitHub + DEV 2023 Hackathon
Tags: githubhack23, github
Published: 2023-05-09 20:01:49

---
title: Midpoint Reminder! — GitHub + DEV 2023 Hackathon 
published: true
description: We're halfway through the GitHub + DEV 2023 Hackathon!
tags: githubhack23, github
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2axbd2rjtbxga8ccqvfw.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-05-09 18:15 +0000
---
**We're already halfway through the [GitHub + DEV 2023 Hackathon](https://dev.to/devteam/announcing-the-github-dev-2023-hackathon-4ocn)!** Congratulations to those who have already posted their projects.

For those who haven't finished yet, don't worry! There's still plenty of time to make progress and submit your project. Remember, the most important thing is to try your best and learn something new throughout the hackathon. 

We want to take a moment to ask: how are your projects going? Have you hit any roadblocks? Do you need any help? Don't hesitate to reach out to the community for support in our **[official help thread](https://dev.to/devteam/github-dev-hackathon-2023-help-thread-1pf)**.

We can't wait to see what amazing creations you come up with in the second half of the hackathon. Keep up the great work!
🌌 Digital identities journey w. Neo4J
Tags: datascience, neo4j, productivity, beginners
Published: 2023-05-09 20:01:07

## ❔ About

More and more, as digtialization spreads in our organizations, the importance of digital identities becomes every day more crucial for many reasons.

If you add the fact that we rely on hybrid platforms (SaaS & onPrem) and services, at a point in time, you will need to know what a digital identity looks like for :

- 🛡️ **Security** (access management, Active Directory,...) governance
- 💸 **Licences** management
- 🧑‍💼 **HR knowledge** (management, roles, peoples skills balance, prevent mental health issues,...)
- ☁️ Third party **cloud platforms** (eLearning, GitHub, Kaggle, Onlineformapro,...)

👉 This post is about **showing how we implemented this as a data-driven solution with Neo4J and code to answer complex question on our digitalization journey.**

## 🗺️ Digital identity... the data way

To discover what digital entities (current state of the art), we query our Neo4J instance's data with introspection like follows with [`apoc.meta.subGraph`](https://neo4j.com/labs/apoc/4.4/overview/apoc.meta/apoc.meta.subGraph/):

```cypher
CALL apoc.meta.subGraph({
  includeLabels: ["Person",
                  "GhMember",
                  "KaggleMember",
                  "OnlineFormaProUser",
                  "DevToAccount",
                  "SumoAgent",
                  "UO",
                  "CigrefJob"],
  includeRels: []
});
```

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

Now, enought talk, let's see how it looks.

## 📘 The digital identity metagraph

{% youtube 2aMK7LLAv2E %}

## 🧑‍🤝‍🧑 Browse identities & people

{% youtube KWaId5i88Ks %}

## 🔖 Related resources

I hope you enjoyed this content and found inspiration.

For more about our data journey, just watch the dedicated speak at `#NODES22` : 


{% embed https://dev.to/optnc/our-speech-about-it-holism-at-nodes22-1bpl %}
Типы данных С++
Published: 2023-05-09 19:55:57

Ассаламу алейкум, сегодня мы с вами обсудим `типы данных.`

```
#include <iostream>

using namespace std;
​
int main()
{
  int myNum = 5;               // Весь (whole number)
  float myFloatNum = 5.99;     // Десятичный разряд
  double myDoubleNum = 9.98;   // Decimal отличается от Float своим пределом.
  char myLetter = 'D';         // Char
  bool myBoolean = true;       // Boolean (Правда или ложь)
  string myText = "Hello";     // текст

  return 0;
}
```

**Основные типы данных**

`Тип данных `определяет размер и тип данных, которые хранит переменная:


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

`Типы чисел - integer = int - для целых чисел.`

```
#include <iostream>

using namespace std;
​
int main() 
{

  int butun = 13; // Весь  (whole number)

  return 0;
}
```

`Типы чисел - float - для десятичных чисел.`

```
#include <iostream>

using namespace std;
​
int main() 
{

  int mn = 13.15; // Десятичный разряд (whole number)

return 0;
}

```

`double - для дробных чисел.`

```
#include <iostream>

using namespace std;

int main()
{

double myNum = 19.99;
cout << myNum;

return 0;
}
```

**float va double**

`float` — может хранить только `8` чисел после точки.
`double` - может хранить только `16` чисел после точки.
`String` - строковые типы;
`string` - символ типа (текст или текст), используемый для хранения последовательности. Не забывайте использовать кавычки именно так, как они появляются в строке.

**Например:**

```
#include <iostream>

using namespace std;

int main()
{

cout << "Мы начали изучать С++";

return 0;
}
```

`char - типы символов.`

`char` — единственный символ, который тип данных использует для хранения. Символы должны быть заключены в одинарные кавычки, например `A` или `c`:

**Например:**

```
#include <iostream>

using namespace std;

int main()
{

char belgi = 'A';
char belgi1 = 'c';
char belgi2 = '#';

cout << belgi << endl;
cout << belgi1 << endl;
cout << belgi2;

return 0;
}
```

`В качестве альтернативы вы можете использовать значения ASCII для представления определенных символов:`

```
#include <iostream>

using namespace std;
​
int main()
 {
  char a = 65, b = 66, c = 67;
  cout << a;
  cout << b;
  cout << c;

return 0;
}
```
**Natija: ABS**

**Boolean типы**

`Boolean тип данных` объявляется с ключевым словом bool и может принимать только значения `true или false`. `True = 1 и false = 0,` когда значение возвращается.

`Например:`

```
#include <iostream>

using namespace std;
​
int main() 
{
    bool togri = true;
    bool yolgon = false;
    cout << togri;  // Chiqadi 1 (true)
    cout << yolgon;  // Chiqadi 0 (false)

return 0;
}

```
A business user’s guide to APIs
Tags: api, webdev, beginners
Published: 2023-05-09 19:40:16


Join Discover application architect Geoff Godwin as he dives into the world of Application Programming Interfaces, aka APIs. We’ve all heard about them, but what exactly are they and how do they work? 

__Hint: The Library of Congress can help answer those questions__. 

Take A Moment of Your Time to learn about the differences between Experience, Process, and System/Data APIs, what you should expect from them, and why their quality and usefulness are king.

Check out the video below:

{% embed https://youtu.be/24TedrSB58c %}
Константа С++
Tags: webdev, beginners, programming, tutorial
Published: 2023-05-09 19:36:50

Ассаламу алейкум уважаемый программист, сегодня мы поговорим с вами о константах `Const`.

Константа есть константа.Для объявления констант в языке программирования C++ мы используем вспомогательное слово `const `(Мы объявляем эту переменную как константу).
Константа может только читать (получать) значение.

```
#include <iostream>

using namespace std;
​
int main() {

    const int n = 13; // Значение n всегда равно 13

    return 0;
}
```

```
#include <iostream>

using namespace std;
​
int main()
{
  const int n = 13; // Значение n всегда равно 13
  п = 15; // ошибка: n здесь только для чтения
    cout << n;

  return 0;
}

```

```
Результат::
В функции 'int main()':
6.9: ошибка: присвоение переменной только для чтения 'n'
```

1. **строка:** попытка изменить здесь константу будет отклонена компилятором C++ и выдаст вам показанный выше экран ошибки. Будьте внимательны при объявлении константы, потому что этот идентификатор нельзя изменить во время выполнения программы, а если вы попытаетесь его изменить, возникнет ошибка.

`Переменная необязательного типа может быть объявлена ​​как константа при объявлении константы.`

**Например:**

```
#include <iostream>

using namespace std;
​
int main() 
{
    const int age = 24; // возраст константа
    const string name = "ИТ-школа Ilmhub"; // имя является константой
    const bool is_developer = true; // константа is_developer
    const char is_char = 'M'; // константа is_char    
    const float PI = 3.14;
}
```
Talking about React Reconciliation
Tags: react, reactnative, webdev, javascript
Published: 2023-05-09 19:33:00

In the Render phase, React will execute all your app components and resolve the JSX tree. If it is the first time rendering, React will return all the JSX tree but if the render is an update like the most of the times, React will compare with the old one and compute a diff. This process is called “Reconciliation”. 

![JSX tree with different elements](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llwp39fe05quy4dq3fwv.png)

The first virtual DOM is when react render the entire JSX tree. The second one is the modified Virtual DOM and as you can see, react compare the new with the old one. It's like we have two snapshots at the same repository than we compare and compute the diffs.

After computing diffs, React goes to the Commit phase. 

Commit phase is the process that React does to update the DOM. Is all about applying the visual updates to your website.

![JSX tree updating the real DOM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z5kbvfr29952fo6h2yry.png)

Hope you enjoy it!
Идентификатор С++
Tags: webdev, cpp, programming, beginners
Published: 2023-05-09 19:26:09

Ассаляму алейкум, в языке программирования C++ переменные именуются отдельными ключевыми словами.

**Например:** уникальные имена, такие как `name, num,` `age, cpp,` считаются идентификаторами.Идентификаторы могут быть короткими именами `(такими как x и y)` или более описательными именами `(age, cpp, age name, day, month)`.

`Необязательное имя, данное программистом переменной, константе или функции, называется идентификатором.`

Примечание. Я объясню использование описательного имени при создании идентификатора на языке программирования C++.
**Например:**

```
int age = 24;
string name = "Ilmhub IT school";
```

Приведу пример идентификатора на языке программирования C++.

```
#include <iostream>

using namespace std;

int main()
{

int age = 24;
string name = "I am learning C# at the moment";
string country = "Uzbekistan";

cout << name << endl;
cout << country;

return 0;
}
```

`При выборе идентификатора следует уделить внимание следующему:`

- Идентификатор должен начинаться с латинских букв;

- Числа можно использовать, начиная со второго символа;

- C++ чувствителен к регистру. То есть каждое из следующего является отдельным идентификатором: KATTA, katta, KaTTa, kAttA, KattA..;

- Probel используется для разделения слов в C++. Следовательно, в идентификаторе нельзя использовать зонд.

- Слова нельзя использовать в качестве идентификаторов в типах данных `(таких как int, float, for, while)`;

`Примечание. Не рекомендуется использовать ` _ ` в качестве первого символа при выборе идентификатора.`
Function Scopes and IIFE Pattern
Tags: javascript, webdev, functional, programming
Published: 2023-05-09 19:20:19

### WHY
Consider you've written code like the below at some point. We've declared a var and hope that it still has the same value. Well, right now it looks good.
```js
var ninja = 'Naruto';

// ...

console.log(ninja); // Naruto
```
But say after a few months a jr. dev comes along and unknowing try to make a change like this.
```js
var ninja = 'Naruto';

// ...

var ninja = 'Sasuke';
console.log(ninja); // Sasuke

console.log(ninja); // Sasuke -- oops!
```
So, you can easily see the issue here.
We have a naming collision problem.

You may think, we should just use const there. But the problem is not if the variable can be reassigned (because the developer if not aware could just modify your const to var anyways) but we have a naming collision problem.

So, the problem is: We have a problem where 2 different people wanna use the same semantic name for their purposes.

### PSEUDO FIX

Since the problem could be thought of as mainly arising due to the declaration of the variable in the same scope. So, the natural fix coming to mind would be, to make use of different scopes, and one simple way to do so could be by wrapping a function around it.
```js
var ninja = 'Naruto';

function anotherNinja() {
    var ninja = 'Sasuke';
    console.log(ninja); // Sasuke
}
anotherNinja();
console.log(ninja); // Naruto
```

So, now those vars don't seem to collide anymore and the code seems to work well. But now the problem is, we have a named function in the same scope.

So it seems, we didn't solve the name collision problem, we just shifted it to a different variable name.

### REAL FIX - IIFE
```js
var ninja = 'Naruto';
(function anotherNinja() {
    var ninja = 'Sasuke';
    console.log(ninja); // Sasuke
})();
console.log(ninja); // Naruto
```
So, this code pattern you see is called an IIFE pattern i.e. Immediately Invoking Function Expression, which does exactly what it sounds like.

Using IIFE, we're creating a new scope and immediately invoking it.

Another use case: when you want to turn statements into expressions

Consider below example:
```js
var ninja;
try {
    ninja = fetchNinja();
}
catch (err) {
    console.log(err);
}
```

If you wanna do something like this, since `try-catch` is a statement it doesn't work in an expression position.
You can do something like this:
```js
var ninja = (try {
    ninja = fetchNinja();
}

catch (err) {
    console.log(err);
})();
```

### Summary

Try to follow "**The principle of least privilege**" whenever possible.
> The principle of least privilege is the idea that any user, program, or process should have only the bare minimum privileges necessary to perform its function.

Leverage the power of function scopes and IIFE patterns to enjoy the benefits of the principle like:
1. Avoid naming collisions
2. Restrict code access
3. Ability to freely refactor code
Переменные С++.
Tags: webdev, beginners, programming, cpp
Published: 2023-05-09 19:14:21

Здравствуйте, сегодня мы поговорим о переменных в языке программирования C++.
Переменные можно понимать как контейнер или стакан, в котором хранятся значения данных. Язык программирования C++ имеет множество переменных, каждая из которых имеет свое ключевое слово.

`Переменные — это именованные части памяти, в которых хранятся значения определенной категории. Переменная будет иметь имя и значения. Имя переменной относится к части памяти, где хранится значение. Значение переменной может быть изменено во время выполнения программы. Прежде чем использовать любую переменную, ее необходимо объявить.`

1. `int` - хранит целые числа (целые числа), такие как 123 или -123.

2. `float` - 19,99 или -19,99 для десятичных чисел.

3. `double` — сохраняет десятичные числа, например 19,99 или -19,99.

4.`char` — хранит отдельные символы, такие как `a` или `B`. Значения `Char` заключаются в одинарные кавычки.

5. `string` — Содержит текст, например `Hello World`. Строковые значения заключаются в двойные кавычки.

6. `bool` — хранит значения с двумя состояниями: true или false, `True` или `False` (1 или 0).

Переменная может иметь короткое имя `(например, x и y)` или более описательное имя `(возраст, имя, cpp,)`. Правила для переменных C++:

- Имена переменных не начинаются с цифры!

- Переменная может быть смешана с числами, начинающимися с букв a - Z, числом или числом1.

- Имена переменных чувствительны к регистру, например, брат и Брат — это два разных имени переменных!

- Например: у нас есть переменная `cpp` с целочисленным значением `13`, отобразите эту переменную.

```
#include <iostream>

using namespace std;

int main()
{

 int cpp;
 cpp = 13;
 cout << cpp;

  return 0;
}
```