teleren/devto huggingface dataset:
Testing in Python: Pytest fixtures scope
Tags: python, testing, pytest
Published: 2022-07-04 19:43:42

I was recently working on a Django project. We decided to use `pytest` to write the tests because we planned to have a lot of unit tests, and pytest is very and ridiculously fast. 

The project uses a lot of fixtures, and we quickly ran into a problem: something I will call **fixtures hell**. Let me explain. 
## The problem
We have a fixture that uses another fixture. 
```python
import pytest

pytest.fixture
def user():
    return User.objects.create(name="foo")

pytest.fixture
def business(user):
    return Business.objects.create(name="foo", owner=user)
``` 
Now, if we want to use the business feature in a test, it won't work and return an error. 
```python
import pytest


pytest.mark.django_db
def test_activate_business(business):
    business.activate()
```
This is because the `business` fixture depends on the `user` fixture, thus, we need to add the `business` fixture and the `user` fixture. And the `business` fixture was also shared between multiple tests. 

## Solution
We decided to add the fixture in the `conftest.py` file. Doing this, the fixture was available on multiple tests and set the `autouse` to `True` so you don't even need to require it in your tests. 

```python
import pytest

pytest.fixture
def user():
    return User.objects.create(name="foo")

pytest.fixture(autouse=True)
def business(user):
    return Business.objects.create(name="foo", owner=user)
```
Also, learning about [pytest `scopes`](https://betterprogramming.pub/understand-5-scopes-of-pytest-fixtures-1b607b5c19ed) can be helpful to better the organization of fixtures in your tests.
A More Modern Youtube Interface
Tags: codepen, youtube, design, ux
Published: 2022-07-04 19:42:02

**The YouTube interface always seemed a bit clunky to me. **So I set out to try and redesign the video widget in a more dynamic way. Also just for fun tried to keep JS to a minimum. 

{% codepen https://codepen.io/eitanwaxman/pen/mdxJNKE %}

Things I was experimenting with in this pen:
1. Scaling using em.
2. Flexbox inside a button.
3. Video with rounded corners.

Overall I think as a user I would enjoy the immediate response of the UI and the dynamic scaling - the only possible downside I still haven't solved is the other widgets in the row moving aside.

**What do you think? 
**
P.S. anyone have a creative solution for one directional transition delays in CSS?
Zielgruppenanalyse: Die Grundlage für erfolgreiche Vertriebs- und Marketingaktivitäten
Tags: onlinemarketing, persona
Published: 2022-07-05 13:51:30

---
title: Zielgruppenanalyse: Die Grundlage für erfolgreiche Vertriebs- und Marketingaktivitäten
published: true
date: 2022-07-04 19:16:35 UTC
tags: OnlineMarketing,persona
canonical_url: https://bloggerpilot.com/zielgruppenanalyse/
---

![Zielgruppenanalyse: Die Grundlage für erfolgreiche Vertriebs- und Marketingaktivitäten](https://bloggerpilot.com/wp-content/uploads/2022/06/zielgruppenanalyse.png)

Deine Marketingstrategie ist wie ein Navigationssystem, das dich auf direktem...

Der Original-Artikel erschien auf [Zielgruppenanalyse: Die Grundlage für erfolgreiche Vertriebs- und Marketingaktivitäten](https://bloggerpilot.com/zielgruppenanalyse/).
Ng-News: Episode 22/26
Tags: javascript, angular, webdev, programming
Published: 2022-07-04 19:05:11

{% embed https://youtu.be/y7VilEcAIuk %}

## NgRx 14

It has been two weeks since the last episode. In the meantime, NgRx was released in version 14. It comes with `createActionGroup`, which reduces the amount of code required for creating actions.

For some time, NgRx linting rules were inofficially available. They have now been packed into a library called @ngrx/eslint-plugin.

Most changes in NgRx 14 though, went into the component-store, which is a library for kind of component/local and not global state management.

What's not made it into 14 release, are NgRx Standalone APIs. This means that we still have to initiate NgRx via the `StoreModule`/`EffectsModule` and not via functions similar to the `bootstrapApplication` function we know from Angular 14.

## MicroFrontends survey

You can help when it comes to Angular's support for Microfrontends. The Angular team is still researching how MicroFrontends are used and what challenges we face. There is a now survey with a few question that you can fill in.

{% embed https://twitter.com/angular/status/1536377858205143042/ %}

## Minor release upgrades

Other than that, nx got a minor version upgrade to 14.4.

The same is true for two E2E frameworks. 

Cypress got upgraded to 10.3 and Playwright to 1.23.

[nx 14.4](https://github.com/nrwl/nx/releases/tag/14.4.0): 

[Cypress 13](https://www.cypress.io/blog/2022/06/28/cypress-10-3-0-speed-up-testing-workflows-with-improved-visibility-into-your-test-results/)

[Playwright 1.13](https://github.com/microsoft/playwright/releases/tag/v1.23.0)
Generic typing a hash-map with dynamic key and T array
Tags: typescript, json, hashmap
Published: 2022-07-04 18:51:27

---
title: Generic typing a hash-map with dynamic key and T array
published: true
description: 
tags: typescript, JSON, hashmap
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

I have a JSON like this. I need an add a type of this JSON. As you can see this is a hash-map structure let's see how we declare the hash-map interface in typescript.  


![hash-map json example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/28lu4zqmqulolva7i9jr.png)
 
I declared this hash-map in my useState like that.

```js
  const [faqCategories, setFaqCategories] = useState<FAQ[]>([]);
```

We are declaring hash-map like that in typescript.

```ts 
export interface FAQ {
  [key: string]: Category[];
} 
```

The whole type system like this for this JSON.

```ts
export interface Question {
  question: string;
  answer: string;
}
export interface Category {
  categoryName: string;
  iconName: string;
  questions: Question[];
}

export interface FAQ {
  [key: string]: Category[];
}
```

Source: https://stackoverflow.com/a/52913569/10694425
Find The Parity Outlier
Tags: programming, python, beginners
Published: 2022-07-04 17:54:42

You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N.

Examples-

```
[2, 4, 0, 100, 4, 11, 2602, 36]
Should return: 11 (the only odd number)

[160, 3, 1719, 19, 11, 13, -21]
Should return: 160 (the only even number)
```

Sample Tests

```
test.assert_equals(find_outlier([2, 4, 6, 8, 10, 3]), 3)
test.assert_equals(find_outlier([2, 4, 0, 100, 4, 11, 2602, 36]), 11)
test.assert_equals(find_outlier([160, 3, 1719, 19, 11, 13, -21]), 160)
```
Solution-  ###Python

```
def find_outlier(integers):
    even=[]
    odd=[]
    for i in integers:
        if i % 2 == 0:
            even.append(i)
        else:
            odd.append(i)
    if len(even)==1:
        return even[0]
    else:
        return odd[0]
```
LGPD - Parte VI - Sanções Administrativas
Tags: lgpd, security
Published: 2022-07-04 17:50:49

Em caso de descumprimento de algumas das definições da Lei Geral de Proteção de Dados Pessoais, o agente de tratamento de dados pode sofrer algumas sanções administrativas aplicáveis pela autoridade nacional.
O nível de sanção aplicada dependerá do grau de descumprimento da LGPD e a gravidade da infração.

O processo de apuração por parte da ANPD deve possibilitar a oportunidade de ampla defesa, de acordo com as peculiaridades dos casos e devem considerar alguns parâmetros como a gravidade e a natureza das infrações, a boa-fé do infrator, a vantagem obtida pelas infrações, a reincidência, grau de dano, cooperação do infrator, a adoção de política de boas práticas e governança, a pronta adoção de medidas corretivas, etc.

Portanto, cada caso de infração à LGPD será analisado pela autoridade nacional de forma individual, e uma sanção aplicada a um agente de tratamento pode não ser igual à outro.

Estas são as sanções administrativas previstas na lei:

### I - Advertência

Uma advertência formal feita pela ANPD, que também indicará o prazo para a adoção de medidas corretivas;

### II - Multa simples

Uma multa única, de até 2% sobre o faturamento da empresa, limitada a R$50 milhões de reais **por infração**;

### III - Multa diária

Quando o infrator não conseguir demonstrar reais esforços para a resolução dos problemas encontrados, é possível que
uma multa diária seja aplicada, limitando-se ao valor estabelecido no item II.

### IV - Publicização da infração

Após as infrações serem devidamente apuradas e confirmadas, elas devem ser publicadas e informadas ao público.

### V - Bloqueio dos dados pessoais

O agente de tratamento pode ter os dados pessoais a que se refere a infração bloqueados, até a regularização da
situação.

### VI - Eliminação dos dados

Obrigação de eliminar os dados pessoais a que se referiram as infrações.

### VII - Suspensão parcial do funcionamento do banco de dados

Suspensão do funcionamento do banco de dados a que se refere a infração.
O período máximo da suspensão é de 6 meses, prorrogável por mais 6 meses, até a regularização da situação.

### VIII - Suspensão do exercício da atividade de tratamento dos dados pessoais

O controlador pode sofrer uma suspensão temporária das atividades de tratamento de dados por no máximo 6 meses, prorrogável por mais 6 meses.

### IX - Proibição parcial ou total do exercício de atividades relacionadas a tratamento de dados

Essa é uma sanção mais severa, que pode proibir total ou parcialmente que o controlador faça o tratamento de dados.
💩 happens: public speaking edition
Published: 2022-07-04 17:41:00

I have recently been doing quite a bit of public speaking.

Almost every one of these events went wrong.

An incomplete list of things that have gone wrong so far:
💩 Zoom link to the event never appeared on the event meetup page.
💩 Zoom link appeared but nobody could open it.
💩 We started recording a video stream, but then had to turn off video because bandwidth was too slow, recording stopped as well, we noticed it after recording for about 10 minutes and had to re-record (and lost some golden content in the meantime).
💩 A kitten started biting my legs and jumping on my keyboard while I was talking about Object Oriented Programming.
💩 The organizer of the event didn’t have access to the internet for external reasons and I couldn’t prep properly.

I’m scared to think what will happen next.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zvt8h3lvcwri29x3vbex.jpg)
LGPD - Parte V - Direitos do Titular
Tags: security, lgpd
Published: 2022-07-04 17:35:49

Depois de verificarmos os requisitos e princípios para o tratamento de dados, também devemos nos atentar aos direitos do titular dos dados pessoais. Sempre que uma empresa faz algum tipo de tratamento ela deve se certificar de que esses direitos sejam garantidos.

### I - Confirmação da existência de tratamento

Todo titular tem o direito de solicitar a confirmação por parte do controlador da existência de tratamentos ou não, e essa resposta deve ser imediata.
Também é possível que essa confirmação seja solicitada de forma completa, que indique a origem dos dados, os critérios utilizados, finalidades do tratamento, etc. Para a confirmação completa, o controlador pode ter um prazo de até 15 dias para retornar.

### II - Acesso aos dados

Assim como o direito sobre a confirmação dos tratamentos, o titular tem o direito de obter uma cópia de todos os dados pessoais mantidos pelo controlador.

### III - Correção dos dados

A lei garante ao titular o direito de solicitar a correção de dados incompletos, inexatos ou desatualizados. Caso esses dados tenham sidos compartilhados pelo controlador, a correção também deve ser informada aos outros agentes de tratamento.

### IV - Anonimização, bloqueio ou eliminação de dados desnecessários

O titular tem o direito de solicitar que seus dados sejam anonimizados, bloqueados ou eliminados caso os dados se mostrem desnecessários para as finalidades apresentadas, sejam excessivos para alcançar as finalidades, as finalidades não estejam em conformidade ou não sejam justificáveis.

### V - Portabilidade dos dados

O titular tem o direito de solicitar a portabilidade dos dados a outro fornecedor de serviço ou produto, desde que os dados não estejam anonimizados.

### VI - Eliminação de dados consentidos

Em casos de tratamento de dados consentidos, é garantido ao titular o direito de, a qualquer momento, revogar o consentimento e solicitar que os dados sejam eliminados.

### VII - Informação sobre compartilhamento dos dados

O titular tem o direito de ser informado caso os seus dados sejam compartilhados com outras empresas ou órgão públicos pelo controlador.

### VIII - Informação sobre consequências do não consentimento

Para os tratamentos de dados que são feitos com base no consentimento do titular, deve ser informada a possibilidade da negação do consentimento, assim como as consequências dessa negativa.

### IX - Revogação do consentimento

É direito do titular poder solicitar a revogação do consentimento do tratamento de dados junto ao controlador.
CSSBattle | #22 Cloud
Tags: css, challenge, cssbattle, cloud
Published: 2022-07-04 17:26:22

Welcome to CSSBattle Challenges!

In this short article, I go through my solution for [CSSBattle - #22 Cloud](https://cssbattle.dev/play/22) challenge. Please refer to the code snippet below to get a better insight into my thought processes and the implementation detail.

---

> #### Challenge:

![Cloud Challenge](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/izuwu9olh4ppgmp5n990.png)

---

> #### Solution:

```html
<div class="container">
	<div class="left-circle circle bg-orange"></div>
  	<div class="bottom-rect bg-orange"></div>
  	<div class="right-circle circle bg-orange"></div>
</div>

<style>
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  .bg-orange {
    background: #D86F45;
  }
  .circle {
    width: 100px;
    height: 100px;
    border-radius: 50%;
  }
  .container {
    background: #F5D6B4;
    width: 100vw;
    height: 100vh;
    position: relative;
  }
  .left-circle, .bottom-rect, .right-circle {
    position: absolute;
    left: 50%;
    top: 50%;
  }
  .left-circle {
    transform: translate(-100px, -35px);
  }
  .bottom-rect {
    transform: translate(-75px, 15px);
    width: 175px;
    height: 50px;
    border-top-left-radius: 50px;
    border-top-right-radius: 50px;
    border-bottom-left-radius: 50px;
    border-bottom-right-radius: 50px;
  }
  .right-circle {
    transform: translate(-20px, -65px);
  }
</style>
```

---

> #### Key Takeaway(s):
- breaking down a complicated shape into smaller, easily reproducible chunks 
- feel free to use position `absolute` to place elements relative to each other 

As always, I welcome any feedback or questions regarding the implementation detail of the challenge. Otherwise, I hope this was useful!
Add Basic Auth to Elixir Phoenix + Daily password
Tags: elixir, auth, phoenix
Published: 2022-07-04 17:08:00

In this article we’ll learn how to add a basic auth to Elixir Phoenix Framework and how to use a password that changes every day.

This method isn’t the most secure, but it’s a good trick.


## Daily password

First of all we’ll create the function to generate the daily password.

It’s something like this.

```elixir

defmodule MyApp.Helpers.DailyPassword do  
  @doc """
  Generate a daily password.
  """
  def today_password do
    {year, month, day} =
      today()

    Timex.format!({year, month, day}, "{0D}{0M}{YY}")
    |> String.to_integer()
    |> Kernel.+(day * 17 - 5)
    |> Kernel.+(month * 13)
    |> Kernel.+(year * 17)
  end
  
  defp today, do: :calendar.local_time |> elem(0)
end
```

## Basic Auth Plug

```elixir

defmodule MyAppWeb.BasicAuth do
  import Plug.Conn
  @realm "Basic realm=\"Staging\""
  
  def init(opts),
    do: opts ++ [password: MyApp.Helpers.DailyPassword.today_password() |> to_string()]
    
  def call(conn, correct_auth) do
    case get_req_header(conn, "authorization") do
      ["Basic " <> attempted_auth] -> verify(conn, attempted_auth, correct_auth)
      _ -> unauthorized(conn)
    end
  end
  
  defp verify(conn, attempted_auth, username: username, password: password) do
    with ^attempted_auth <- encode(username, password) do
      conn
    else
      _ -> unauthorized(conn)
    end
  end
  
  defp encode(username, password), do: Base.encode64(username <> ":" <> password)
  
  defp unauthorized(conn) do
    conn
    |> put_resp_header("www-authenticate", @realm)
    |> send_resp(401, "unauthorized")
    |> halt()
  end
end
```

## Router

Now we need to configure the basic auth in router.ex.

```elixir
pipeline :auth do
  plug MyAppWeb.BasicAuth, [username: "admin"]
end
```

And use auth wherever we want.

```elixir
scope "/", MyAppWeb do
  pipe_through :auth
  
  ...
end
```

## Conclusion

Phoenix provides a basic auth that you can use, [here the docs](https://hexdocs.pm/plug/Plug.BasicAuth.html), but it's cool to see how we can configure our own.
Ngày 1: Vector
Tags: machinelearning
Published: 2022-07-04 17:06:53

Vector là một đại lượng gồm có: hướng và độ lớn
VD:
- 5km/s không phải là vector (chỉ có độ lớn)
- 5km/s về hướng Nam (vector) -> vận tốc là một vector

Vector được biểu diễn trong hệ trục tọa độ:

Khi nhắc đến vector, chúng ta chỉ quan tâm đến độ lớn và chiều, không cần biết bắt đầu từ đâu:



Q: Làm sao để biểu diễn 2 vector trên bằng kí hiệu toán học? Bản chất chúng đều là một mà?  
A: Dùng kí hiệu vector: $$ \vec{v} = (5, 0) $$
hoặc biểu diễn bằng ma trận
{% katex %}
\begin{bmatrix}
   a & b \\\
   c & d
\end{bmatrix}
{% endkatex %}
Announcement: Detailed PHP development practices series
Tags: php, programming, tutorial, productivity
Published: 2022-07-04 17:04:00

This post is an announcement of upcoming series of posts. Target audience of the series are primarily PHP and OOP developers in general (although some languages might have different flavors of OOP).

It will be written from a perspective of primarily PHP backend developer with 12+ years of experience working in Magento/Zend framework and Symfony (although I do prefer raw PHP and writing code which is independent from any framework). I have worked on enough both brand new and completely ruined legacy projects that I've started to see multiple patterns of behavior leading to code degradation. It's time to put that experience on paper, summarize and spread the knowledge.

The series will cover a lot of stuff:

- Object Oriented Programming in PHP and in general, with a hint of Functional Programming and other paradigms
- SOLID principles
- Design patterns
- Warning signs and bad practices
- Good development practices

But, this will not be just another series of generic tutorials with dry information available everywhere else. This will be a focused effort of analyzing software development practices and potential problems in them by running through well known and established principles - and criticizing them to oblivion when and if needed. The reason is simple: many software development practices are dangerous and create more problems than they solve, but they are still being repeated in numerous online tutorials/courses and taught in schools just because they are "well known and established". I'm sorry, but I'm more utilitarian and pragmatic than dogmatic about everything in life, including work and programming. If something deserves bashing and discarding, it will be bashed to hell and forgotten like Google Glass.

Everything in the series will be well documented, covered with arguments, theoretical and practical examples. It will be all available in a GitHub repository along with samples integrated into a Symfony 6 application.

So, feel free to follow me and expect the articles soon.

Cheers!
Programming interface Security Assessment
Published: 2022-07-04 16:45:48

I'm extremely eager to show you this device I have been chipping away at. This device is based on top of Apisec.ai, an API security stage.

This help is for people with versatile/web applications with backend REST APIs. It performs free and moment entrance testing/security evaluation for the REST APIs.

Simply point towards your live OpenAPI determination record and get a PDF infiltration test report soon.

Kindly attempt and let me in on what is your take?

Here is the immediate connection
https://www.apisec.ai/free-programming interface pen-test
context api in react
Tags: react, contextapi, usecontext, hook
Published: 2022-07-04 16:28:10

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.

Full React Blog: [](https://itznur07.medium.com/react-context-api-usecontext-hooks-explained-c01ee7306a48)
Learning Python #1 - The beginning...
Tags: python, programming, webdev, devjournal
Published: 2022-07-04 16:16:17

**Learn and grow with Python**

Ever wondered what happens when you have extensive amount of experience in [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) and you trying to learn [Python](https://www.python.org/) as a hobby programming language.

- You do the mistakes and learn from them
- You learn the data types and basic constructs
- You get your hands dirty with the new programming language
- Write a hello world app


![python1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/851o3qsptbv1pmnwnf63.png)

Never think that Python will bite you. Grace it and embrace it.

> I am starting a new series on Python so that I can learn few interesting topics like AI/ML, Data Science as a noob. It will be a long journey but a challenging one.


![challenge_accepted](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/52yvuxzy1r0lqvrm03wi.png)

Coming up next will be blog post on Python basics like
- Operators
- Data types
- Variable creation
- Python Syntax - Why is it necessary?

Let's learn and grow ourselves.
Thanks everyone in advance for reading this article !!
Best approach to advertising yourself as a freelance developer?
Tags: freelance, discuss, career
Published: 2022-07-04 16:02:19

I’ve recently discovered that Fiverr takes 20% of your earnings as a seller which is a lot in my opinion, and it’s got me thinking about the best way to advertise as a freelance developer and build a client base.

Interested to find out how other devs are approaching freelance work…

Are you using a platform? If so, which one(s)? If not, what methods are you using to reach clients?