teleren/devto huggingface dataset:
SOLID principle #4: Interface Segregation (JavaScript)
Tags: solid, javascript, programming
Published: 2022-03-09 15:22:55

The interface segregation principle states that an entity should never be forced to implement an interface that contains elements which it will never use. For example, a `Penguin` should never be forced to implement a `Bird` interface if that `Bird` interface includes functionality relating to flying, as penguins (spoiler alert) cannot fly.

Now, this functionality is a little more difficult to demonstrate using JavaScript, due to its lack of interfaces. However, we can demonstrate it by using composition.

Composition is a subject all by itself, but I’ll give a very high level introduction: Instead of inheriting an entire class, we can instead add chunks of functionality to a class. Here’s an example that actually addresses the interface segregation principle:

{% embed https://gist.github.com/DuncanMcArdle/337f177cdcf5acab39653b1158558553 %}

What this example does is to add the flying functionality (or interface) only to the class(es) that require it. This means that penguins won’t be given the ability to fly, whereas birds will.

This is one method of adhering to the interface segregation principle, but it is a fairly rough example (as, once again, JavaScript doesn’t play well with interfaces).
SOLID principle #3: Liskov Substitution (JavaScript)
Tags: solid, javascript, programming
Published: 2022-03-09 15:21:47

The Liskov substitution principle states that any class should be substitutable for its parent class without unexpected consequences. In others words, if the classes `Cat` and `Dog` extend the class `Animal`, then we would expect all of the functionality held within the `Animal` class to behave normally for a `Cat` and `Dog` object.

A classic example of a Liskov substitution violation is the “square & rectangle problem”. In this problem, it is posed that a `Square` class can inherit from a `Rectangle` class. On the face of it, this makes sense; both shapes have two sides, and both calculate their area by multiplying their sides by each other.

But the problem arises when we try to utilise some `Rectangle` functionality on a `Square` object. Let’s look at an example:

{% embed https://gist.github.com/DuncanMcArdle/4db68de093075c9b23b5153174674259 %}

In this example we initialise a `Rectangle` and `Square`, and output their dimensions. We then call the `Rectangle.setHeight()` on the Square object, and output its dimensions again. What we find is that the square now has a different height than its length, which of course makes for an invalid square.

This can be solved, using polymorphism, an if statement in the Rectangle class, or a variety of other methods. But the real cause of the issue is that `Square` is not a good child class of `Rectangle`, and that in reality, perhaps both shapes should inherit from a `Shape` class instead.
DFS and BFS of a graph
Tags: python, algorithms, graph
Published: 2022-03-09 15:17:47

###What is DFS(depth first search)?
It's an algorithm to traverse a graph in a depth first manner, i.e. going deep into one branch before backtracking and continuing the process until all vertices are visited.

**Example**
![image](https://www.geeksforgeeks.org/wp-content/uploads/undirectedgraph.png)
Pick vertex **0** traverse **1, 2** and then backtrack to **1** and traverse **2, 3, 4** and then backtrack to traverse **4**. So the final result would be **[0, 1, 2, 3, 4]**
**Note:** **[0, 4, 3, 2, 1]** is also correct.
&nbsp;
To implement the algorithm, we need a **set** to keep track of visited nodes and an **array** to store the result
&nbsp;
**Algorithm**
1) pick any vertex
2) if the vertex is not in the set, go to step 3
3) add the vertex to the set and the result array, and repeat the process for each vertex of the current vertex.
&nbsp;
**Code**
```python
def depth_first_search(graph, currVertex, seen, result):
  if currVertex in seen: return
  seen.add(currVertex)
  result.append(currVertex)
  for vertex in graph[currVertex]:
    depth_first_search(graph, vertex, seen, result)


# main function 
def dfs(v, graph):
  result = []
  seen = set()
  depth_first_search(graph, 0, seen, result)
  return result
```
&nbsp;
###What is BFS(breadth first search)?
It's an algorithm to traverse a graph in breadth first manner, i.e. traversing all the vertices of a vertex and then moving to another vertex and repeat the process until all the vertices are visited.

**Example**
![image](https://www.geeksforgeeks.org/wp-content/uploads/undirectedgraph.png)
Pick vertex **0** traverse its vertices **1, 4** and then take vertex **1** and traverse its vertices **2, 3, 4**. So the final result would be **[0, 1, 4, 2, 3]** 
**Note:** **[0, 4, 1, 3, 2]** is also correct.
&nbsp;
we need a queue, set and an array to implement the algorithm
**Algorithm**
1) pick a vertex
2) add the vertex to the queue
3) while queue is not empty, pop the queue and traverse the vertices of popped vertex and do step 2 for each vertex of the vertices, if the vertex is not in the set

&nbsp;
**Code**
```python
from collections import deque

def bfs(graph, seen, q, vertex, res):
    q.append(vertex)
    seen.add(vertex)
    res.append(vertex)
    while q:
        currVertex = q.popleft()
        for v in graph[currVertex]:
            if v not in seen:
                seen.add(v)
                res.append(v)
                q.append(v)

# main function
def bfsOfGraph(v, adj):
    q = deque()
    res = []
    seen = set()
    bfs(adj, seen, q, 0, res)
    return res
```
&nbsp;
**Uses of BFS and DFS**
1) Using DFS we can find the path between vertex u, v and also check if the graph is strongly connected.
2) BFS can be used to find neighbors of a vertex

&nbsp;
**Problems on BFS and DFS**
1) Implement DFS: [geeks-for-geeks-link](https://practice.geeksforgeeks.org/problems/depth-first-traversal-for-a-graph/1/)
2) Implement BFS: [geeks-for-geeks-link](https://practice.geeksforgeeks.org/problems/bfs-traversal-of-graph/1/)
Data as a Service: Domain-Driven Design
Published: 2022-02-21 10:39:53

In an organisation, while working with data, we tend to consider every new request as a new data pointer and expose it to the visualisation layer in an isolated manner. There isn’t a problem in most cases, however, what will happen when the organisation grows to a bigger scale? Problems will start surfacing out and causing issues. There will no longer be enough resources to sustain pulling larger data chunks, and there will be issues with data alignment across different data pulls or dashboards. The inevitable performance impact and increased computational cost of a query are better to be avoided, so let’s try to find out how.

This kind of problem requires retrospection as to how to gain leverage and have a data model or domain-driven design well coupled with a data model. To better understand how this is done, let’s see what domain-driven design actually is first. The “Domain” part in Domain-Driven Design officially refers to a “sphere of knowledge and activity around which the application logic revolves”. In other words, the “Domain” is what is commonly referred to as “business logic” in the software world. In Domain-Driven Design, business logic is considered to be the heart of the software.

In the Investment Banking world, for example, trade settlement is a domain where settlement ratio, settlement exposure, etc. are key metrics that are sliced based on Asset type or Account Type, etc. Regarding settlement as a domain is the first key towards adoption and anticipating the needs based on demand or past queries done. 
Once you get to the depth of the domain, we can tie functional needs to an efficient scalable data model so that we can serve all data requests in a consistent manner, and in the best abstract way. This helps users to think about functional needs, and technologists work towards a scalable model as a repository to build.

Once the domain and modelling are in shape, then, irrespective of need, we should invoke one query with a different filter or dimensionality needed to serve it, along with the real-time or batch requests. At this stage, all abstract data models need to be exposed as a service/API (REST/SOAP), so that consumption can be done not only specific to visualisation or DB but for widespread use. This process of exposing makes your data go places while at the core of it is an efficient domain-driven design and a data model.

Some insight on how to build API/Service is to start with databases, queries as a collection in No SQL catalogue as configuration to map service, DAO to map service to API, ElastiCache to serve faster, Flask, Angular and Python for API and UI.

In conclusion, always look from a business lens to consolidate requests as a domain, build it into a model and serve as a batch or API in the service method.
SOLID principle #2: Open-Closed (JavaScript)
Tags: solid, javascript, programming
Published: 2022-03-09 15:12:28

The open-closed principle says that code should be open for extension, but closed for modification. What this means is that if we want to add additional functionality, we should be able to do so simply by extending the original functionality, without the need to modify it.

To explain this, let’s look at an example. Below we have a Vehicle class. When a Vehicle instance is created, we pass in the fuel capacity and fuel efficiency. To get our range, we simply multiply our capacity by our efficiency.

{% embed https://gist.github.com/DuncanMcArdle/5c070b361405c2c49835514d5446594a %}

But let’s say we add a new type of vehicle; a hybrid vehicle. This vehicle doesn’t just have standard fuel-based range, it also has an electric range which it can use as well. To find out the range now, we need to modify our `getRange()` method to check if the vehicle is hybrid, and add its electric range if so:

{% embed https://gist.github.com/DuncanMcArdle/bebf594eebeeec71a503a631e2b66d4d %}

This violates the open-closed principle, because whilst adding our new HybridVehicle class we have had to go back and modify the code of our Vehicle class in order to make it work. Going forward, every time we add a new type of vehicle that might have different parameters for its range, we’ll have to continually modify that existing `getRange` function.

Instead what we could do, is to override the `getRange` method in the HybridVehicle class, giving the correct output for both Vehicle types, without every modifying the original code:

{% embed https://gist.github.com/DuncanMcArdle/c258044a8fd108dabdd86d12de0f8350 %}
SOLID principle #1: Single responsibility (JavaScript)
Tags: solid, javascript, programming
Published: 2022-03-09 15:10:49

The single responsibility principle says that a class or module should have only a single purpose. For example, if you have a wallet class, that class should only implement wallet functionality. It’s fine to call other functionality, but it shouldn’t be written there.

Let’s look at a bad example. In the code below, the Car class has a single method; start. When this method is called the car may or may not start, depending on some logic which isn’t included here as it’s not important. The class will then log some information depending on the outcome. But notice how the logging functionality is implemented as a method of this class:

{% embed https://gist.github.com/DuncanMcArdle/73ee5b85ae429d4e52f47b5ec140849b %}

This violates the single responsibility principle, because the logic for logging the information should not be a responsibility of the Car class.

There are a number of readability and code management issues that are caused by this, but the easiest issue to describe is actually refactoring.

Let’s say your logger logs to a file, and this works great for several months. Suddenly, an update occurs on the underlying system that the car class is running on, and you need to change the way you write to files. Suddenly you now need to update every file writing instance of every class you’ve ever implemented a logger inside of. The task would be huge! But what if you’d followed the single responsibility principle?

{% embed https://gist.github.com/DuncanMcArdle/0394f6a5dee1ee29af00917b34e0a5ac %}

As you can see here, we wouldn’t have this problem. The logger is stored in a separate class, which means its functionality is separate to the Car class. The Car class can be changed, moved around or even deleted without affecting the logger class. Likewise, if a change is required to the logger class, it only needs to be carried out in a single place.
Major Difference between Web2 and Web3
Tags: web3, programming
Published: 2022-03-09 15:04:48

**_The Latest Fancy word in town is Web3.0…. So what is Web 3.0 all about??_**


If you use a mobile device or any form of Computer, you should be familiar with the web:  a subset of the Internet consisting of the pages that can be accessed by a Web browser. 

The web has it’s known has undergone a lot of transformation,  from static desktop web pages designed for information consumption and served from expensive servers(_Let's call that web 1_),  to interactive experiences and user-generated content that brought us Facebook, Instagram and other products_(Web 2)_.

_The rise of Web 2.0 was largely driven by three core layers of innovation: **Mobile, Social and Cloud.**

## **Web 2**

Web 2 significantly changed the way we communicate and interact with each other, Web 2 is based on a server-client structure, meaning centralised private corporations control and own the data. The result is that these corporations have enormous monopoly power and create barriers to entry for potential competitors. All Web2 applications are controlled by centralised corporations, including the entire banking and financial system.
![Web 3 image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9sk1ahrmg4f7ffvgq348.jpeg)

**

## Web 3
**
Web3 is an even more fundamental disruption. It is a leap forward to_ open, trust less and permission less _networks.

**Open:** in that they are built from open source software built by an open and accessible community of developers and executed in full view of the world.

**Trustless:** in that the network itself allows participants to interact publicly or privately without a trusted third party.

**Permissionless** in that anyone, both users and suppliers,can participate without authorisation from a governing body.

Where Web 2.0 was driven by the advent of mobile, social and cloud, Web 3.0 is built largely on three new layers of technological innovation: edge computing, decentralised data networks and artificial intelligence.

## **WEB3 LIMITATIONS**
Web 3 has some limitations right now:

**Scalability –** transactions are slower on web 3 because they're decentralised. Changes to state, like a payment, need to be processed by a miner and propagated throughout the network.

**UX –** interacting with web 3 applications can require extra steps, software, and education. This can be a hurdle to adoption.

**Accessibility-**  lack of integration in modern web browsers makes web 3 less accessible to most users.

**Cost –** most successful dapps put very small portions of their code on the block-chain as it's expensive.
 




## **Conclusion:**
As Web 3 , talents are needed to help provide the necessary infrastructure, The [Zuri](https://zuri.team/) team in conjunction with [Nestcoin](https://blockgames.gg/) is providing opportunities for interested persons to skill  up and become employable in the web 3 space. In few years watch out for graduates of the program do wonderful things.

##
[OPINIÃO] Construindo uma Carreira como Data Engineer
Tags: bigdata, dataengineering, tips
Published: 2022-03-09 15:01:48

Hoje trago mais um dos artigos do livro [_97 Things Every Data Engineer Should Know_](https://www.oreilly.com/library/view/97-things-every/9781492062400/) publicado pela O'Reilly, a editora queridinha da área de Dados. O livro foi organizado por Tobias Macey, host do popular [_Data Engineering Podcast_](https://www.dataengineeringpodcast.com/).

![97 Things Every Data Engineer Should Know](https://m.media-amazon.com/images/I/51QO1kgDpeS.jpg)

Em uma das publicações deste livro, o autor Vijay Kiran nos traz diversas dicas de como construir uma carreira de sucesso em Engenharia de Dados.

Um fato inegável é que a Engenharia de Dados abrange muitas disciplinas sobrepostas, portanto é difícil traçar um único caminho para se tornar um engenheiro de dados. Uma das primeiras dicas que Kiran traz aqui é 

> Tenha experiência básica em escrever pequenos scripts e desenvolva projetos de limpeza de dados, dessa maneira você deve estar pronto para dar seus primeiros passos no mundo de Engenharia de Dados.

Além disso, o autor cita em seu artigo 3 habilidades essenciais para que um aspirante a Data Engineer tenha sucesso em sua carreira. São elas:

## 1. Ter conhecimento sólido em ciclo de vida do Software

Lembre-se sempre de que ter conhecimento do ciclo de vida do desenvolvimento de software é inestimável ​​no mundo da Engenharia de Dados!

## 2. Ter conhecimento em linguagem de programação estática e  dinâmica

O uso correto do SQL aliado a uma boa compreensão de pelo menos uma outra linguagem de programação estática e uma dinâmica (um exemplo disso são linguagens como Python e Rust) te dará a importante visão de como um software de qualidade é construído e em como ele pode ser aplicado ao mundo dos dados.

## 3.  Decidir antecipadamente em qual área deseja se concentrar e desenvolver suas habilidades para complementar essa função

A terceira habilidade fundamental depende da subfunção da Engenharia de Dados você deseja se especializar. Para aqueles que desejam se especializar em processamento de dados, desenvolver sua compreensão das tecnologias de armazenamento de dados, bem como continuar a aprimorar suas habilidades com SQL, é fundamental. Para quem quer descer uma rota de Engenharia de Software mais tradicional, aprimorando suas habilidades analíticas será crucial, pois seu foco principal será em projetos de Big Data.

## Conselho Final: Entrar de cabeça no universo Open-Source!

O conselho final se aplica a todos os níveis, desde aspirantes a engenheiros de dados até engenheiros de software estabelecidos que desejam dar o próximo passo: entrar em código aberto! Se você está aprendendo a construir e se divertindo com Engenharia de Dados de código aberto, você está adicionando ao seu repertório essas habilidades.
__________________________________________________________________
E aí? O que você achou dos conselhos do Vijay Kiran? Você concorda com todos eles? Acrescentaria outras dicas pra quem tá começando na área?

Comenta aí embaixo o que você achou e não esqueça de curtir, salvar e compartilhar esse post. (:
Cheplag - Best Plagiarism Checker for Educators and Students
Tags: saas, writing, education, plagiarism
Published: 2022-03-09 14:59:22

👉 Cheplag allows more authentic assessments to educational institutions by avoiding duplicate content or plagiarism of educational assessments. In turn, it helps students to do their best original work.

It is:
**● Easy And Effective:** Cheplag supports and promotes academic integrity by assisting in the identification of any types of duplications in works.
**● Fast and Safe:** Our solution simplifies the assessment process by automating plagiarism detection and giving full results.
**● The best software for you:** Because of our user-friendly design and integrations, you will be able to utilize the product quickly and efficiently.
Configure Git to Always Push to the Current Branch
Tags: git, todayilearned
Published: 2022-03-09 14:45:55

---
canonical_url: https://waylonwalker.com/til/git-push-default-current/
published: true
tags:
- git
- til
series: til
title: Configure Git to Always Push to the Current Branch
---

## **fatal** has no upstream branch

If you have not yet configured git to always push to the current branch, you will get a `has no upstream branch` error if you don't explicitly set it.

Let's show an example

``` bash
git checkout -b feat/ingest-inventory-data git add conf/base/catalog.yml git commit -m "feat: ingest inventory data from abc-db" git push
```

You will be presented with the following error.

``` bash
fatal: The current branch feat/ingest-inventory-data has no upstream branch. To push the current branch and set the remote as upstream, use

    git push --set-upstream origin feat/ingest-inventory-data
```
## Option 1: follow the instructions

To resolve this fatal error your first option is simply to follow the instructions given.  Just copy and paste it in.

``` bash
git push --set-upstream origin feat/ingest-inventory-data
```

## Option 2: push to current bransh wihtout setting upstream

Honestly I am pretty aware of the branch I am on, and Very few times have I ever accidently pushed to the wrong branch.  The one that you might have a bigger chance with a more detrimental effect is `main`, which I will argue you should have blocked to require a passing `ci`, and potentially reviewers to merge in.  Therefore you can't even push to `main` anyways.

To just push to the branch you are currently on each and every time and never see this error again, you can run this to configure git to always push to your current branch.

``` bash
git config --global push.default current
```
Entendendo o Flexbox
Tags: flexbox, css
Published: 2022-03-09 14:44:53

Neste post não irei entrar em detalhes sobre cada atributo que usamos dentro do flexbox. Darei mais um conceito geral, para melhor entendermos o funcionamento.

**O que é?**

O Flexbox (CSS Flexible Box Layout), é um conceito do CSS3 que visa organizar elementos de uma página tornando-os "flexíveis". Ou seja independente da dimensão da tela (mobile, desketop e etc.) os elementos se reorganizarão conforme sua necessidade.

**Conceito iniciais**

O flexbox se resume em um conjunto de propriedades que organiza itens (elementos filhos) dentro de um container (elemento pai).

![Explicação conceitual de como é composto os elementos do flexbox](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3xh4davvw6nl5uhkkb13.jpeg)

**Os eixos**

O flexbox lida com o layout em uma dimensão de cada vez.
Sendo assim ele lida com o eixo horizontal (row) e o eixo vertical (Column).

![Imagem descritiva de como funcionam os eixos principais do do flexbox (row e column)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kiw83g5v7jj4bvysgket.jpeg)
 
Através destes eixos poderemos escolher se nosso itens se moverão em direção horizontal (row) ou vertical (column).

**Linhas de início e fim**

Elas basicamente determinam se você quer alocar seus itens no início ou no fim do seu container. 

![Descrição do conceito de inicio e fim de um container](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ix4pfmap96js0qucshgb.jpeg)

**Quebra de linha**

Com flexbox também é possível fazer uma quebra de linha dentro dos nosso containers. Pois como sabemos existem diversas proporções de tela, e muitas vezes o layout inicial não se adaptará em uma tela pequena.
Para não prejudicarmos o layout e desalinhar nossos itens podemos quebrar sua linha, fazendo com que tudo se adapte.

![Explicação do conceito de quebra de linha do flexbox](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f8ijhyco005ydaa2cfjc.jpeg)

**Alinhamento, justificação e distribuição de espaço livre   entre os elementos**

O atributo chave do flexbox é a capacidade de alinhar e justificar os elementos nos eixos principal e transversal e distribuir o espaço entre eles, através de seus atributos.

Como podemos ver ao decorrer do texto o flexbox é um grande aliado para que possamos fazer layouts mais responsivos independente da plataforma (web / mobile).

Pretendo fazer um post mais futuramente para explicar detalhadamente cada atributo que compõem o flexbox.

Espero que tenham aproveitado a leitura e até a próxima.
Paracetamol.js💊| #74: Explica este código JavaScript
Tags: javascript, beginners, spanish, webdev
Published: 2022-03-09 14:24:11

## **Explica este código JavaScript**

```js
console.log(typeof("22" - 0))
```

A. `number`
B. `string`
C. `object`
D. `TypeError`

Respuesta en el primer comentario.

---