teleren/devto huggingface dataset:
Denormaliztion ,its pros and cons
Tags: javascript, python, womenwhocode, 100daysofcode
Published: 2022-03-17 09:29:37

>Denormalization can be defined as an **optimization technique** used to make queries more efficient by **reducing the number of costly joins necessary to retrieve data**.In short we decide to be okey with redundancy unlike in normalization,where no data redundancy is allowed.Instead each table contains its own data and only joins are used to link on data with the other.

## Pros of denormalization

1. Queries are executed much more faster.
This is because we fetch data from one table instead of joining numerous tables to find the data we need.

1. Writing queries becomes much more faster.
Since there is no need to search for joining keys to fetch our data.However , one should always remember to update the tables accordingly once each update is made.

## Cons of denormalization

1. Perfoming updates and insert queries becomes more expensive and even harder to write.
This is due to the increase in data processing as a result of data redundancy and possible data duplication.

1. Increase in table size 
This demands an large storage space for the table.

1. Data may be inconsistent
A failure to update the required tables might lead to inconsistent data which might be expensive to debug.

Thanks for reading this short post ....i hope this gives you some insight.
React, Vue and Svelte: Comparing Conditional Rendering
Tags: javascript, react, vue, svelte
Published: 2022-03-17 09:25:33


## Conditional rendering in ...
### React
[Link](https://stackblitz.com/edit/vitejs-vite-yrosrq?file=src/App.tsx)

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

const App = () => {
  const [isVisible, setIsVisible] = useState<boolean>(true);
  return (
    <div>{isVisible ? <p>I'm right here!</p> : <p>I'm invisible!</p>}</div>
  );
};
```

### Vue
[Link](https://stackblitz.com/edit/vitejs-vite-fdk8p2?file=src/App.vue)

```jsx
<script setup lang="ts">
  import { ref } from 'vue'
  const isVisible:Boolean = ref(true)
</script>

<template>
  <p v-if="isVisible">I'm right here!</p>
  <p v-else>I'm invisible!</p>
</template>
```

### Svelte
[Link](https://stackblitz.com/edit/vitejs-vite-81j3ec?file=src/App.svelte)

```jsx
<script lang="ts">
  let isVisible:boolean = true;
</script>

{#if isVisible}
  <p>I'm right here!</p>
{:else}
  <p>I'm invisible!</p>
{/if}
```
Write 1000x FAST Python using Automatic Memoization (one line of code)⚡
Tags: python, tutorial
Published: 2022-03-17 09:05:39

I came across this decorator in Functools which enables automatic Memoization of a function (Basically, storing what a certain function call returns and not having to run it again)

I'm about to blow your minds. and make the code more than 1000 times faster with just ONE line of code!


So here's a snippet that takes about 52 seconds to run. It's very slow and bad code because it's having to run the same `fib()` function multiple times. So every function call takes twice the amount of time the last function call. oh what a mess
![bad slow code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v9qzxqeotkm163fb6a7j.png)

### Here's the magic ✨

By using the functool library's `cache` decorator, you can memoise the code automatically for much faster results!
Literally just one line of code (and the import, obviously)

```py
from functools import cache

@cache
def fib(n):
    ...
```

Just adding this makes the code run in JUST ` 0.013621500000000009` seconds! What's the cache here?(ha, get it? Catch ? cache?) 
Basically all that the decorator is doing, is "remembering" the function call in memory, so this takes more RAM. But there's a way to make this even better.

It's by using the `recently-used-cache` decorator (lru_cache) 
```py
from functools import lru_cache

@lru_cache(maxsize=5)
```

This only stores the last 5 function calls, which is much better. So here's the complete code:

![LRU cache](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ubbi9drptih6bfureo5c.png)

How mind blowing is that!! 

If you liked this little python trick, make sure to 💖 this post. If you REALLY liked it, Follow me here - https://dev.to/dhravya and if you REALLY REALLY liked it, follow me on twitter! https://twitter.com/dhravyashah
How to create feature modules in Angular 11
Tags: javascript, webdev, angular, opensource
Published: 2022-03-17 08:49:18

**Feature modules are nothing but you dividing your appModule into different modules to make code more clean and for better optimization.**



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


_Here you can notice that the Your ProductListComponent and ProductComponent got separated in a whole different module that is ProductModule .Similarly you can notice for OrdersComponents_

**WHY WE NEED TO DO THAT??**

- In large projects you have multiple components,services and directives. You don't want to confuse your dev by keeping hundreds of components,services at one place.

- To make it look effective we make our feature module and register our component there.

- You will use this majorly in Lazy Loading Optimization.

**How to make your feature Module**

1. First you have to make a component.module.ts file 

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

It will look like this.

2.Remember now that you have made your own module for components,You don't need them in AppMOdule. Remove it from there and also make sure to remove imports of those components at AppModule.(You might not notice but it end up increasing your bundle size if you forgot to remove imports).



**USING ROUTER MODULE AND IMPLEMENT LAZY LOADING IS ESSENTIAL PART WHY WE DIVIDE OUR MODULE AT FIRST PLACE 

I will explain that in next blog.**
Instalando e Configurando PHP CodeSniffer (PHPCS)
Tags: php, vscode, phpstorm, phpcs
Published: 2022-03-14 12:48:40

Repositório Oficial → https://github.com/squizlabs/PHP_CodeSniffer

O PHPCS, abreviação para PHP CodeSniffer é uma ferramenta que tem como objetivo detectar violações de padrões de código. 

Esse tutorial busca auxiliar na instalação e configuração do `phpcs` nas duas principais ferramentas de desenvolvimento da atualidade para PHP (VSCode e PHPStorm) a fim de conseguir alcançar um bom nivelamento da **PSR12** em todos nossos projetos.

## Instalação

O PHPCS precisa de uma versão igual ou superior à 5.4.0.

Existem algumas maneiras de instalar o PHPCS, conforme indicado na documentação do repositório oficial, entretanto, vamos seguir a com a instalação via Composer Global, pois já foi testada e funciona em qualquer ambiente, Linux, MacOS e Windows (incluindo WSL).

```bash
composer global require "squizlabs/php_codesniffer=*"
```

Após instalar, execute o comando abaixo caso precise saber qual o caminho padrão de instalação global do seu composer.

```bash
composer global config bin-dir --absolute
```

Salve esse caminho.

Para verificar se o `phpcs` foi instalado corretamente, basta executar:

```bash
phpcs --version
```

### Visual Studio Code

Instale a extensão `phpcs` publicada pelo Ioannis Kappas.

<img src="https://i.ibb.co/tYdL3wS/image.png">

A extensão é bastante configurável, mas a princípio recomendo apenas a seguinte configuração global, para garantir o mesmo padrão em todos os projetos.

Em `settings.json` do VSCode, adicione o seguinte:

```
"phpcs.enable": true,
"phpcs.standard": "PSR12",
"phpcs.ignorePatterns": ["*/vendor/*"]
```

E é isso, divirtam-se :)

### PHP Storm

Acesse as configurações `Ctrl+Alt+S`.

PHP > Quality Tools > PHP_CodeSniffer > Local

> **Usuários WSL**: Caso não tenha PHP e Composer instalado no Windows e _apenas_ no Linux, o interpretador Local não irá funcionar. Nesse caso, é necessário informar um novo interpretador, que será sua distro linux onde o PHP e Composer estão instalados, clicando no ícone `+` no canto superior esquerdo.

<img src="https://i.ibb.co/Wy4fMFs/image.png">

Em PHP_CodeSniffer path informe o caminho do phpcs instalado no composer global e clique em `Validate`.

<img src="https://i.ibb.co/GHFjg80/image.png">

Se ocorrer tudo bem você receberá um feedback positivo na parte inferior da aba, caso contrário, verifique o caminho informado.

Selecione `Apply` e em seguida `PHP_CodeSniffer inspection`.

Marque a caixinha para ativar a inspeção nesse projeto e ao lado direito, em `Options`, você pode selecionar os arquivos que gostaria que a inspeção ocorra (eu deixei apenas php). Agora o *mais importante*, no select de `coding standard` escolha **PSR12**!

<img src="https://i.ibb.co/fGmFNnk/image.png">

E é isso, um pouco mais complicado do que VSCode, mas tudo certo :)

> **P.S**: Ainda não descobri como deixar padrão para todos os projetos no PHPStorm, ainda é necessário configurar a inspeção para cada projeto individualmente. Caso tenham essa informação comentem e atualizo o tutorial.
The Best Voice assistants in 2022 You Should Know about
Tags: voiceassistant, social, mediamarketin
Published: 2022-03-17 08:31:52

The best voice assistant options in 2022 are what every user could want, right? Ease of use, flexibility, accessibility, value and many other options for usability and reliability. We are the generation that is being dominated by voice assistance. The day-to-day task that a consumer performs is also changing. And as a result, the [Social Media Marketing](https://externlabs.com/social-media-marketing.php) techniques for the targeted consumers are changing, too.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qu4jz7u88vsloksb2a5l.png)
Google fonts och
Tags: googlefont, wordpress, gdpr
Published: 2022-03-17 08:31:05

Omkring 50 miljoner sajter runt om i världen använder sig av [Google Fonts](https://fonts.google.com/), en tjänst med 1 358 kostnadsfria typsnitt för webben och mobilen.

Det är i strid med EU:s GDPR-förordning då de skickar besökarnas ip-adresser vidare till Google, något som kan leda till böter i slutändan.

Nyligen dömde en [domstol i München](https://rewis.io/urteile/urteil/lhm-20-01-2022-3-o-1749320/) ut böter på 100 euro till en sajt som använder sig av Google Fonts, detta då besökarna inte fått möjlighet att välja om deras ip-adresser ska skickas vidare till den amerikanska teknikjätten eller ej.

Vill du [spara Google fonts lokalt i Wordpress](https://webbofsweden.se) men vet inte hur? 
Vi har flera års erfarenhet av att hjälpa företag med [Wordpress hemsida](https://webbofsweden.se/wordpress-hemsida) och Google fonts. 

Har du en hemsida som använder Google fonts? Vi kan hjälpa er att slippa risken med att få [böter Google Fonts] (https://rewis.io/urteile/urteil/lhm-20-01-2022-3-o-1749320/), kontakta oss [webbyrå malmö](https://webbofsweden.se/webbyra-malmo)
Dasturlashda Mutable, Immutable obyektlar
Tags: mutable, immutable, object
Published: 2022-03-17 08:25:21

_Mutable obyektlar yaratilganidan keyin uni o'zgartirish mumkin, immutable obyektlarda esa aksincha o'zgartirib bo'lmaydi._

Javada (Strindan tashqari) hamma obyektlar default holatda mutable hisoblanadi.
```
 public class IntegerPair {
    int x;
    int y;

     IntegerPair(int x, int y) {
        this.x = x;
        this.y = y;
     }
 }

 IntegerPair p = new IntegerPair(5, 10);
 // p.x = 5, p.y = 10

 p.x = 50;
 // p.x = 50, p.y = 10
```
---

Mavjud ob'ektlarni o'zgarmas qilishning hech qanday usuli yo'q. Agar ob'ekt yakuniy deb e'lon qilingan bo'lsa ham, uning field(atribut)larini o'zgartirish mumkin:


```
public class IntegerPair {
    int x;
    int y;

    IntegerPair(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

final IntegerPair p = new IntegerPair(5, 10);
// p.x = 5, p.y = 10

p.x = 50;
// p.x = 50, p.y = 10
```
---

Ya'ni, agar siz o'z classingizmi chaqirib, barcha fieldlarini yakuniy(final) va shaxsiy(private) qilish orqali uning ob'ektlarini o'zgarmas qilishingiz mumkin.

```
public class IntegerPair {
    private final int x;
    private final int y;

    IntegerPair(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

IntegerPair p = new IntegerPair(5, 10);

p.x = 50;
// Compilation error: cannot assign a value to a final variable
// kompiler xatosi final o'zgaruvchinga qiymat berolmaydi 
```
</br>
String tilga qarab oʻzgaruvchan(mutable) yoki oʻzgarmas(immutable) boʻlishi mumkin.

Java-da satrlar o'zgarmasdir.

</br>
Har qanday stringni o'zgartirganingizda (masalan: qo'shimcha belgini qo'shganizda, uni kichik harflarga aylantirganizda, ikkita belgini almashtirganizda), siz aslida yangi va alohida nusxani yaratgan bo'lasi,ishoning :)

```
  String first = "first";

System.out.println(first.hashCode());
// prints something

first = first + "!";

System.out.println(first.hashCode());
// different string, different hash code
```
Ammo ba'zi boshqa tillarda, masalan, C++, stringlar o'zgaruvchan bo'lishi mumkin va biz ularni to'g'ridan-to'g'ri o'zgartirishimiz mumkin:

```
  string testString("mutable?");

testString[7] = '!';
// testString is now "mutable!"
```
</br>
Agar siz mutable ya'ni o'zgartirsa bo'ladigan stringdan foydalanmoqchi bo'lsangiz , sizga StringBuilder/StringBuffer yordamga keladi.StringBuilder dan foydalanganingiz maqul chunki u buffer-ga qaraganda samaraliroq.

```
  StringBuilder mutableString = new StringBuilder("mutable?");

mutableString.setCharAt(7, '!');
// still the same object!
// mutableString is now "mutable!"

// convert to an immutable string
String immutableString = mutableString.toString();
```
Ammo siz stringni o'zgaruvchan char-lar qatoriga aylantirishingiz ham mumkin.

_O'zgaruvchan ob'ektlar(mutable) yaxshi, chunki siz yangi ob'ektni ajratmasdan o'z joyida o'zgartirishlar kiritishingiz mumkin. Ammo ehtiyot bo'ling - ob'ektga o'z joyida o'zgartirish kiritganingizda, ushbu ob'ektga qilingan barcha havolalar endi o'zgarishlarga uchraydi._
Firefox dev edition could not update automatically - issue when manually installed in linux (fedora) (solved)
Tags: fedora, firefox, linux
Published: 2022-03-17 08:00:42

I installed the firefox dev edition by extracting the tar file from [`https://www.mozilla.org/en-US/firefox/developer/`](https://www.mozilla.org/en-US/firefox/developer/) at `/opt/firefox_dev_edition`.

But when an update was available, firefox showed me this error:
>
**Update available**
Firefox couldn't update automatically. Download the new version - you won't lose saved information or customizations.

![screenshot of the above error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qqduuaanauxlvitckfp7.png)

Turns out the `/opt/firefox_dev_edition` directory was owned by `root` user, which resulted in `Permission denied` error when firefox tried to update itself. So, I changed the owner to the main user, which I use the system through:
```sh
chown -R "$USER":"$USER" /opt/firefox_dev_edition
```

This command changes both the user and the group of the directory and all of its files and sub directories recursively(the `-R` option is an alias for `--recursive`)
A Nice Developer Joke For Today
Tags: jokes, dailydeveloperjokes
Published: 2022-03-17 08:00:13

---
title: "A Nice Developer Joke For Today"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
published: true
tags: #jokes, #dailydeveloperjokes
---

Hi there! Here's today's Daily Developer Joke. We hope you enjoy it; it's a good one.

![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e125896e0846.png)

---

For more jokes, and to submit your own joke to get featured, check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/). We're also open sourced, so feel free to view [our GitHub Profile](https://github.com/dailydeveloperjokes).

### Leave this post a ❤️ if you liked today's joke, and stay tuned for tomorrow's joke too!

_This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit._

<!--
Joke text:
___Q:___ Why was the developer unhappy at their job?

___A:___ They wanted arrays.
 -->
Dockerfile: ADD vs COPY
Tags: docker, devops, tutorial, 100daysofcode
Published: 2022-03-17 07:23:39

`COPY` and `ADD` are both `Dockerfile` instructions that serve similar purposes. They let you copy files from a specific location into a Docker image.

## COPY
The COPY instruction copies new files or directories from `<src>` and adds them to the filesystem of the container at the path `<dest>`.

COPY has two forms:
```
COPY [--chown=<user>:<group>] <src>... <dest>
COPY [--chown=<user>:<group>] ["<src>",... "<dest>"] (this form is required for paths containing whitespace)
```

## ADD
ADD has two forms:
```
ADD [--chown=<user>:<group>] <src>... <dest>
ADD [--chown=<user>:<group>] ["<src>",... "<dest>"] (this form is required for paths containing whitespace)
```

## Dockerfile best practice for copying from a URL
Docker suggests that it is often not efficient to copy from a URL using `ADD`, and it is [best practice](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#add-or-copy) to use other strategies to include the required remote files.

`COPY` only supports the basic copying of local files into the container, while ADD has some features (like local-only tar extraction and remote URL support) that are not immediately obvious. Consequently, the best use for `ADD` is local tar file auto-extraction into the image, as in `ADD rootfs.tar.xz /.`

> — [Dockerfile Best Practices](https://docs.docker.com/)
> Because image size matters, using ADD to fetch packages from remote URLs is strongly discouraged; you should use `curl` or `wget` instead. That way you can delete the files you no longer need after they’ve been extracted and you don’t have to add another layer in your image. For example, you should avoid doing things like:

```
ADD http://example.com/big.tar.xz /usr/src/things/
RUN tar -xJf /usr/src/things/big.tar.xz -C /usr/src/things
RUN make -C /usr/src/things all
```
And instead, do something like:
```
RUN mkdir -p /usr/src/things \
    && curl -SL http://example.com/big.tar.xz \
    | tar -xJC /usr/src/things \
    && make -C /usr/src/things all
```

For other items (files, directories) that do not require `ADD`’s tar auto-extraction capability, you should always use `COPY`.

  

## Like to learn?
Follow me on [twitter](https://twitter.com/grigorkh) where I post all about the latest and greatest AI, DevOps, VR/AR, Technology, and Science! Connect with me on [LinkedIn](https://www.linkedin.com/in/grigorkh) too!
Start a server: Node Vs Golang
Tags: go, node, tutorial, javascript
Published: 2022-03-17 07:14:22

###### _Disclaimer: The purpose of this post is not to compare the two programs; rather, it is to demonstrate how to start the server._

Today, we'll look at how to start our server in Node.js with the express framework and Nodemon, as well as in Golang with the fiber framework and air. 

![start](https://media.giphy.com/media/oS8pRFxbD0d44/giphy.gif)

#### Nodejs

###### Initialize your project
`npm init -y`

###### Install Pacakages
`npm i express` and `npm i -D nodemon`

###### Start server
```
node index
```

```javascript
const express = require("express")
const app  = express()

const port = process.env.PORT || 4546

app.get("/", (req,res)=>{
  res.send("Home page")
})
app.listen(port, ()=>{
   console.log(`app is running on port ${port}`)
})
```

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

#### Golang
###### Initialize your project
`go mod init "github.com/drsimplegraffit/fibre-api"`

###### Install Pacakages
`go get "gorm.io/gorm"`
`go get "github.com/gofiber/fiber/v2"`

###### Start server

```go
package main

import (
	"log"

	"github.com/gofiber/fiber/v2"
)

func welcome(c *fiber.Ctx) error {
	return c.SendString("Welcome")
}

func main() {
	app := fiber.New()

	app.Get("/api", welcome)

	log.Fatal(app.Listen(":3002"))
}

```

###### Run go server

######## Method 1
`go run main.go`

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

######## Method 2: with hot reload
Install the <mark>air package</mark>[here](https://github.com/cosmtrek/air)

To install:
`curl -sSfL https://raw.githubusercontent.com/cosmtrek/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin`

Run: `air`

Result: 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3skg2zgcg7kaeb6gyyx7.PNG)
 

#### Discuss

What other frameworks do you use for Golang and Nodejs besides fiber and Express?
React Native - Modern theming!!
Tags: reactnative, react, javascript, theming
Published: 2022-03-17 07:06:42

Good day, everyone! Today we'll talk about theme-csx, a new react native theming library that was created to alleviate the pain that developers may experience when attempting to add dark mode support to mobile apps.

**Github Link:** https://github.com/KJ-GM/theme-csx 

### Without further ado, let's get started: 

Theme-csx focuses on providing an easy and simple way to add dark mode support to our mobile apps. With three simple steps, your app will be set up and ready to go!

You may wonder what makes this library special than other libraries such as styled-components, react native paper...

1) Similar to standard react native styling

2) Light & Fast

3) Expo & React Native

4) Supports React Navigation

**System**: changes to the phone _`appearance`_ preference while the app is running will be applied dynamically. - **IOS:** changes will be shown immediately without the need to reopen the app
 
let's go over the steps very briefly: 

> **StyleSheet**

- Is similar to the usual styling format, but now you have additional props to make style themeable.

> **T() Function** - _Themed_

- Apply **only** your themed styles using the T() function wrapper.

> **TV() Function** - _Themed Value_

- Is an extra helper function that can be used to theme a specific value. (this becomes helpful with react navigation)

> **appearanceHook**

- Use the appearanceHook to switch theme from anywhere in your app.



## Usage ❓

```js
// Styles
import { StyleSheet, T, appearanceHook } from 'theme-csx';

// Components
import { Text, View } from 'react-native';
import { Button } from '@components/atoms';

const DemoComponent = () => {
  // Theme switch
  const switchTheme = () => {
    appearanceHook.switch(
      appearanceHook.activeTheme === 'dark' ? 'light' : 'dark'
    );
  };

  return (
    <View style={T(styles.THEMED_CONTAINER)}>
      <Text style={styles.NORMAL_TEXT}>Hey, I am normal text</Text>

      <Text style={T(styles.THEMED_TEXT)}>Hey, I am themed text</Text>

      <Button text={'Switch theme'} onPress={switchTheme} />
    </View>
  );
};

const styles = StyleSheet.create({
  THEMED_CONTAINER: {
    flex: 1,
    backgroundColor: 'white',
    backgroundDark: 'gray', // backgroundDark prop was added to make it themeable
    alignItems: 'center',
    justifyContent: 'center',
  },
  NORMAL_TEXT: {
    fontWeight: 'bold',
    fontSize: 14,
    color: 'green',
  },
  THEMED_TEXT: {
    fontWeight: 'bold',
    fontSize: 14,
    color: 'black',
    colorDark: 'white', // colorDark prop was added to make it themeable
  },
});
```