teleren/devto huggingface dataset:
TypeScript Factory Design Pattern in practice (UML)
Tags: programming, typescript, webdev, architecture
Published: 2022-03-05 22:56:09

## Hello, Devs!

**Design Patterns help us to build a better softwares** and like this we can architect the solutions for the knew problems. So, there are a _Gang of Four_ that wrote the book _Design Patterns_ and show us design for problems in creational, structural or behavioral object oriented programming context.

Let's see how to use the **Factory Pattern in Typescript**, but what is it?

> **Factory Pattern is one of the Creational Design Pattern**. We must use when we need to create an object without exposing the creation logic to the client and refer to newly created objects using a common interface. So we have a superclass with multiple sub-classes and based on input, we need to return one of the sub-class.

We can see in UML (_Unified Modeling Language_) the representation of this pattern.

![Factory Design Pattern UML](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gkg7xxuysb090qs4rnlc.png)

Let's build our UML example and observe in practice using Typescript.

![Factory Design Pattern UML](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v15ypd9d2qyvq8amroc9.png)

```
export interface IPerson {
    name: string;
    identifier(): void;
}
```

And then implements:

```
export class NaturalPerson implements IPerson {
    name: string

    constructor() { this.name = '' }

    identifier() {
        return "Identifier of NaturalPerson";
    }
}

export class LegalPerson implements IPerson {
    name: string

    constructor() { this.name = '' }

    identifier() {
        return "Identifier of LegalPerson";
    }
}
```

And then our Factory with a static method:

```
export class PersonFactory {
    public static createPerson(type: string) : IPerson {
        if (type === "N") {
            return new NaturalPerson();
        } else if (type === "L") {
            return new LegalPerson();
        }

        return null as unknown as IPerson;
    }
}


```
And now our usage way. Here we suppose the we have a folder person with IPerson and PersonFactory and the class Main is outside.

```
import { IPerson, PersonFactory } from "./person";

export class Main {
    main(){
      const naturalPerson: IPerson = PersonFactory.createPerson("N");
      const legalPerson: IPerson = PersonFactory.createPerson("L");
    }
}

```

That's all! We implement a Factory Design Pattern in Typescript and see about the UML representation.

https://www.buymeacoffee.com/calaca

**Contacts**
Email: luizcalaca@gmail.com
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca
Practical ReScript
Published: 2022-03-05 22:45:16

---
title: Practical ReScript
published: true
description: 
tags: 
//cover_image: https://direct_url_to_image.jpg
---

![Practical ReScript cover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m61l2vi33yhie6qxw6h3.png)

Hello there, Developer!

* Does your codebase feel like you're stitching together parts from different animals?

* Find it takes longer and longer to change things as your codebase grows?

* Have a hard time understanding where responsibilities begin and end?

* Hear things like “abstract types” and “polymorphic variants”, but don’t know how to use them to make your projects easier to work with?

I’m here to help! [**Practical ReScript**](https://practicalrescript.com) is a collection of design patterns I found in production libraries and apps to make code cheaper to change, easier to understand, and faster.
This is the book I wish I had when I got started writing ReScript.

In this book you'll learn:
* How to make the type system work for you
* How to build abstractions that help you deliver and refactor
* How to apply design patterns to your project

See the preliminary table of contents below:

### Table of Contents
#### Part I: A Tour of the Language
* The core of ReScript
* Understanding the Type System
* Keeping Things Fast

#### Part II: Thinking with Types
* Data Structures
* Error Handling
* Typed State Machines
* Business Logic
* External Data
* External Logic

#### Part III: Scaling your Project
* Modules and Interfaces
* Debugging
* Vendoring

---

**Who am I?** I’m Leandro Ostera. I started writing this in the open as a series of ReasonML Design Patterns. In my last seven years of writing OCaml, Reason, and now ReScript, I saw a lot of beautiful, pragmatic code, and a lot of code that was pretty awful. It is my hope that this book can help you write your most pragmatic and beautiful ReScript yet.
Feel free to get in touch with me by emailing me to leandro at abstractmachines dot dev, or just ping me on twitter: [@leostera](https://twitter.com/leostera).
Animated Landing Page with JavaScript
Tags: codepen, javascript, webdev, html
Published: 2022-03-05 21:41:41

<p>A great way to make a landing page stand out is by using interactive animation in a playful or instructional way to engage an audience. </p>

<p>An experiment  with using  HTML  and JavaScript to build a landing page experience.</p>

{% codepen https://codepen.io/Dejeffo/pen/yLPRPVZ %}
#ESP32CAM – Flash on / Flash off 🔦🔦🔦
Tags: englishpost, arduino, camera
Published: 2022-03-06 13:42:07

---
title: #ESP32CAM – Flash on / Flash off 🔦🔦🔦
published: true
date: 2022-03-05 21:27:53 UTC
tags: EnglishPost,Arduino,Camera,EnglishPost
canonical_url: 
---

Hi !

Let’s start a series of posts using an ESP32 CAM board. I had this one from Amazon Canada.

[Wobekuy ESP32-CAM-MB WiFi Development Board OV2640 Camera Module -USB Interface CH340G USB to Serial Port](https://www.amazon.ca/gp/product/B09CTG7NQX)

I choosed this one, because it will avoid me the pain of wiring.

So, 1st test, let’s turn the Flash ON and then OFF.

Let’s start creating a new PlatformIO project, and selecting the right board: **AI Thinker ESP-32CAM**

![Platform IO new project or ESP32 CAM](https://brunocapuano.files.wordpress.com/2022/03/platform-io-new-project-or-esp32-cam.jpg?w=1024)

Once the project is created our ini file contains the following information:

```

; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html

[env:esp32cam]
platform = espressif32
board = esp32cam
framework = arduino

```

And now let’s add some code to make the flash work. And, my only note here is that the Pin is 4.

{% gist https://gist.github.com/elbruno/e892aa53a5907e026a0e9aedb9c2621f %} 
Full project working demo

![ESP32Cam Flash demo](https://brunocapuano.files.wordpress.com/2022/03/2022-03-05-esp32cam-flash-small.gif?w=250)

Happy coding!

Greetings

El Bruno

* * *
Starting a Laravel9 APIs with ReactJS project made easy (Including Tailwind3)
Tags: laravel, react, tailwindcss, api
Published: 2022-03-05 21:22:07

# Laravel9 x ReactJs x Tailwind3 x Sanctum

## Creating the Laravel project

```
laravel new lxr
cd lxr
```

*Set the database and `.env` file*

### Installing Sanctum (For simple authentication)

```
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
```

### Installing React

```
npm install
npm install --save-dev react react-dom
```

- Edit `webpack.config`

```js
mix.js("resources/js/app.js", "public/js")
    .react()
    .extract(["react"])
    .postCss("resources/css/app.css", "public/css", []);
```

- Add `<script src="{{ asset('js/manifest.js') }}"></script>` `<script src="{{ asset('js/vendor.js') }}"></script>` `<script src="{{ asset('js/app.js') }}"></script>` in this order to the bottom of `<body></body>`

- Do `npm run dev`

- Create the folder `resources\js\components` which will contain **React components**

### Installing Tailwind

```
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init
```

- Edit `ressources\css\app.css`

```css
@tailwind base;
@tailwind components;
@tailwind utilities;
```

- Edit `tailwind.config.js`

```js
module.exports = {
    content: [
        "./resources/**/*.blade.php",
        "./resources/**/*.js",
        "./resources/**/*.jsx",
        "./storage/framework/views/*.php",
        "./vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php",
    ],
    theme: {
        extend: {},
    },
    plugins: [],
};
```

- Edit `webpack.config` (Again)

```js
mix.js("resources/js/app.js", "public/js")
    .react()
    .extract(["react"])
    .postCss("resources/css/app.css", "public/css", [
        require("postcss-import"),
        require("tailwindcss"),
        require("autoprefixer"),
    ]);
```

```
npm run watch
```

- Add `<link rel="stylesheet" href="{{ asset('css/app.css') }}">` to `<head></head>`

# Wrap-up

An overview of what we did is:

1. Starting a fresh **Laravel** project.
2. Installing **laravel/sanctum**.
3. Installing **ReactJs**.
4. Installing **Tailwind 3** and configuring it.
5. Configuring **Mix** in **Webpack** to process **ReactJS** and **Tailwind**.

A minimal **Blade** file will look like

```php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="{{ asset('css/app.css') }}">
    <title>Laravel React</title>
</head>
<body class="bg-slate-800">

    <div id="root"></div>

    <script src="{{ asset('js/manifest.js') }}"></script>
    <script src="{{ asset('js/vendor.js') }}"></script>
    <script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
```
Build.ai (.docwrit .addvarr)
Tags: codepen, javascript, webdev, beginners
Published: 2022-03-05 21:17:37



var startpen = "startpen"
print(startpen) = <script src =”https://github.com/startpen.wc"></script>
<!--startpen is an html file that only has the characters: <script src="-->
var endpen = "endpen"
print(endpen) = <script src="endpen.wc"></script>
<!--endpen is an html file that only has the characters: "></script>-->
var docwrit = "docwrit"
print(docwrit) = startpen + fileName + endpen


```
This pen represents code in the way I learned it <!--as it was written-->[news][tech][dev][parallax][autoplay][user]...I wrote the code to be a .ai website builder. #codepen #github #stack #dev_new
[](url){% codepen https://codepen.io/WewokaChronicle/pen/WNXdVzP %}
Error while creating or using an existing pyspark context from Jupyter notebook
Published: 2022-03-05 21:02:00

I recently started working on setting up Pyspark on my new M1 Macbook. While trying to create a new SparkContext from jupyter notebook I get into this issue

`WARN SparkContext: Another SparkContext is being constructed (or threw an exception in its constructor). This may indicate an error, since only one SparkContext should be running in this JVM (see SPARK-2243). The other SparkContext was created at:
org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
py4j.Gateway.invoke(Gateway.java:238)
py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)
py4j.ClientServerConnection.run(ClientServerConnection.java:106)
java.base/java.lang.Thread.run(Thread.java:833)`

Can someone help me figure out what could be the issue? I have set the correct path for Spark and it is able to find it on my system although when i try to getOrCreate pyspark context it fails. Thanks in advance..
String formatting in Golang
Tags: go, opensource, tooling
Published: 2022-03-05 21:01:31

I am quite new to golang. I started programming in golang a couple of months ago because I had to develop a solution based on existing golang open source project. 
Golang differs from other popular languages like C#, Java or Python, in many ways it resembles a modern version of C language.
In my opinion, there is one thing missing from golang sdk, namely the composite string formatting, which is surprising, considering that the rest of the aforementioned languages support this feature in some form. For instance, in Java you can use it by calling String.format and in Python it’s available through "".format().
Let’s take a closer look at the issue. Here is an example of the composite formatting in Java:
```java
    String.format("Hello, mr. {0}. You are here: {1}. 
Good luck mr. {0} and have a nice day.", "Smith", "Office");
```
To reproduce the behavior of this function in Golang we would normally do something like that:
```go
   fmt.Sprintf("Hello, mr. %s. You are here: %s. 
Good luck mr. %s. and have a nice day", "Smith", "Office", "Smith").
```
It’s not very convenient because we have to pass the "Smith" argument twice. And that’s just one duplicate value, imagine how confusing it would get if we had to deal with a whole bunch of them.
So, after scratching my head for a little while, I decided to invent my own wheel and make a string formatting like those in C# or Python available in golang. I made a little library currently consisting of two formatting functions which you can [find here](https://github.com/Wissance/stringFormatter).
My functions allow me to format a string using either indexed {0}, {1}:
```go
str = Format("Hello {0}, we are greeting you here: {1}!", "manager", "salesApp")
```
or named placeholders:
```go
str = FormatComplex("Hello {user}, what are you doing here {app} ?", map[string]string{"user":"vpupkin", "app":"mn_console"})
```

Since I built the library, I have been actively using these functions to format:
database connection strings, 
template-based URLs
complex messages to end-user

Here is an example of how to use it in any golang project:
```go
import "github.com/wissance/stringFormatter"
func CreateDbConnectionStr() string {
    connStrTemplate := "host={0} port={1} user={2} dbname={3} password={4} sslmode={5}"
    connStr, err := stringFormatter.format(connStrTemplate, "127.0.0.1", "5432", "developer", "test_db", "q1w2e3r4", "disable")
    return connStr
}
```
Unfortunately, at the moment, my functions can’t completely substitute fmt.Scanf as they only work with strings while fmt.Scans allows arguments of any type. But I am planning to add support for this feature too. Also, I am going to add support for a format item alignment (i.e., for double/float {0: 0.##} if we pass 123.4567 we get 123.45.) and maybe something else.
Access services in k8s that are not exposed publicly
Tags: kubernetes, devops, cloud, tutorial
Published: 2022-03-05 20:57:21

Services running in Kubernetes are not exposed to the public by default so, no one can access them from outside.To access services running in K8s that are not exposed publicly we have few ways which are secure and will not bring to opening security holes in our systems and services. One of them is the Ingress Controller or API Gateway that most of the service meshes are using which basically mapping domains and subdomains to the services.

Another option is Kubernetes CLI (**kubectl**)using which you can bind any services or POD/container port to your localhost and access private service from your localhost.

Let’s assume we have a service called **customer-dashboard** and we want to access it using Kubernetes CLI (kubectl).

## Connecting to Pod
If we want to connect to Pod/Container we should know the exact name of the Pod, for that we can run this command:
```
kubectl get pod | grep customer-dashboard
```
the output would be something similar:
```
customer-dashboard-7945c779f4-27c5k     1/1   Running   0   4d
customer-dashboard-7945c779f4-885h9     1/1   Running   0   4d
```
Now when you know the pod name you can bind pods specific port to your localhost using this command:
```
kubectl port-forward pod/customer-dashboard-7945c779f4-27c5k 8080:80
```
You will see this output:
```
Forwarding from 127.0.0.1:8080 -> 80
Forwarding from [::1]:8080 -> 80
```
So first port is the port to which you want to bind the service in localhost (so you can access it using 127.0.0.1:8080 or localhost:8080), second port is the pod/container port number.

If you need to open few ports you can do the same for another port too, for that you need to open new terminal tab and type **kubectl port-forward customer-dashboard-7945c779f4–27c5k 8081:81** to bind 81 port as well to your 8081 on localhost.

## Connecting to Service
Connecting to Service (or internal K8s load balancer) is almost same as connecting to the pod but in this case you will need the service name instead of Pod name. To get the service name type:
```
kubectl get service | grep customer-dashboard
```
and you will get the service names:
```
customer-dashboard  ClusterIP 10.24.2.124  <none>   80/TCP,81/TCP
```
To bind it to your localhost type:
```
kubectl port-forward service/customer-dashboard 8080:80
```
You will see this output:
```
Forwarding from 127.0.0.1:8080 -> 80
Forwarding from [::1]:8080 -> 80
```

## 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!
Apresentação e... por quê?
Tags: javascript, braziliandevs, beginners
Published: 2022-03-05 20:47:21

Fala pessoal! Aqui quem vos fala é Eduardo, e como primeiro post, eu gostaria de me apresentar. Sou um Desenvolvedor Fullstack Júnior, e ultimamente tenho desenvolvido minhas habilidades em torno do [React](https://pt-br.reactjs.org/), [NestJS](https://nestjs.com/) e [PostgreSQL](https://www.postgresql.org/). E aí você pode estar se perguntando: porque uma pessoa com o conhecimento limitado está se aventurando a escrever um blog sobre desenvolvimento web?

## Conteúdo em português para iniciantes

Você já pode discordar aqui no primeiro ponto: "Ah, mas no Youtube eu acho rapidinho o que eu quero!". Sim, verdade, mas acredito que nem todo mundo goste de aprender por vídeo-aulas (eu sou um desses heheheh), e nas vezes em que vou sanar alguma dúvida, eu quase nunca acho a resposta em português. Para mim, o inglês não é problema, mas muitas vezes eu quero enviar uma solução para algum colega e muitos não conseguem entender o inglês, ou preferem que esteja em português.


![Dev Jr tentando centralizar uma Div](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azme6mqwgiq64nv4cj2m.jpg)
_Dev Jr tentando centralizar uma div_

---

## Fixar meu aprendizado

Aqui já é um dos motivos para meu ganho pessoal: a melhor forma de aprender é ensinando (já me diria meu mestre Gabriel nas aulas de Lógica de programação). Enquanto vou criando artigos aqui, eu consigo fixar a ideia em minha cabeça, além de servir como um repositório pessoal para soluções que eu já fiz antes e posso me esquecer futuramente!

## Aparecer!

No momento em que estou escrevendo este artigo, sou apenas um aluno e estou desempregado. Recrutadores afirmam que, a melhor forma de conseguir um emprego é ser visto, produzir conteúdo, e aparecer para o mundo. Então resolvi fazer uma série de posts, colocar em minhas redes sociais e com isso, talvez conseguir uma maior visibilidade.

---

### Considerações finais

Em breve estarei escrevendo bem mais aqui, e espero com isso aprimorar a minha escrita também. Aceito sugestões para algum tutorial específico (que eu tenha conhecimento, de preferência!), ou qualquer outra coisa que você queira ver por aqui!
What is Data Profiling?
Tags: data, dataengineering, shortread, analyticsengineering
Published: 2022-03-05 20:42:28

Imagine this scenario...

You have started a new job as a Data Engineer. It's an exciting time, new data, new tools, new people! While you are familiarizing yourself, your manager who is also very excited to have you look at their backlog, sends a request across.

"One of our stakeholders has been waiting on this for a long time - could you look into _this_ job that's resulting in a very large table in the data warehouse. The stakeholder would love an aggregated table with the data rolled up to a week."

What is one of the first things you do?

Data Profiling!

It's a systematic analysis of the data in a table to understand the structure and relationships - leading to conclusions on its usability.

The tools to extract this information are measures in descriptive statistics - min, max, mode, frequency, sum, count (You get the picture).
The next set of parameters to understand are data types, nulls, uniqueness which answer questions on missing data, duplicates and so on.

You could run this analysis on individual columns or do a cross-columns analysis.

At the end of this exercise, you should be able to make a few decisions
1) Is this data able to support the analysis/reporting use case?
2) Do the data quality issues originate from the source or from the ETL jobs?
3) Are there inconsistencies in the structure of the table?

So, this was a short introduction to the Data Profiling technique. For further reading, here are some links.

1. http://www.kimballgroup.com/wp-content/uploads/2012/05/DT59SurprisingValue.pdf
2. https://www.researchgate.net/publication/262221918_Data_Profiling_Revisited