teleren/devto huggingface dataset:
Load Balancing with HAProxy
Tags: webdev, tutorial, programming, beginners
Published: 2023-04-04 04:26:01

In this post, we will discuss how to set up load balancing with HAProxy. **Load balancing** is an essential technique for distributing traffic across multiple servers to optimize resource usage, ensure high availability, and reduce downtime. **HAProxy** is a popular and powerful load balancer that provides advanced features and flexibility to handle various types of traffic.

![A graphic on how Load Balancing works](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mkgmlcgb6d76pypk66iu.png)

#### Installation
First, we need to install HAProxy on our server. On Ubuntu, we can use the following command to install HAProxy:
```bash
sudo apt update
sudo apt install haproxy
```

#### Configuration
After installing HAProxy, we need to configure it to handle incoming traffic. The default configuration file is located at **/etc/haproxy/haproxy.cfg**.

Two key sections of our configuration file are _frontend_ and _backend_. The **frontend** section defines how HAProxy will receive traffic. The **backend** section defines how HAProxy will distribute traffic to the servers.
Here is how our configuration would look like:
```bash
frontend http-traffic
    bind *:80
    default_backend servers

backend servers
    balance roundrobin
    server SERVER1 IP_ADDRESS:PORT check
    server SERVER2 IP_ADDRESS:PORT check
```

In this example, our frontend specifies that HAProxy will listen on _port 80_ for incoming HTTP traffic, we also specify our default backend to be **servers** which implies that all http traffic will be directed to **servers**.

For the backend section, we specify that HAProxy will balance traffic between two servers using the [round-robin algorithm](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts#load-balancing-algorithms). We also specify the IP addresses and ports of the servers and the `check` option to ensure that HAProxy only sends traffic to servers that are healthy.

Once we have configured HAProxy, we can start the service:
```bash
sudo service haproxy start
```

#### Testing
To test our load balancing setup, we can use `curl` to send HTTP requests to the HAProxy server:
```bash
$ curl -sI 10.0.0.3 # 10.0.0.3 is our load balancing server
HTTP/1.1 200 OK
server: nginx/1.18.0 (Ubuntu)
date: Tue, 04 Apr 2023 03:31:36 GMT
content-type: text/html
content-length: 13
last-modified: Tue, 04 Apr 2023 01:11:07 GMT
etag: "643b-d"
x-served-by: server1
accept-ranges: bytes

$ curl -sI 10.0.0.3 # 10.0.0.3 is our load balancing server
HTTP/1.1 200 OK
server: nginx/1.18.0 (Ubuntu)
date: Tue, 04 Apr 2023 03:31:39 GMT
content-type: text/html
content-length: 13
last-modified: Tue, 04 Apr 2023 01:07:19 GMT
etag: "644b-d"
x-served-by: server2
accept-ranges: bytes
```
Upon running the `curl` command twice, we can see that traffic is being distributed to server1 and server2, indicating that the load balancing mechanism (roundrobin) is functioning correctly.

We also do not have to install Nginx on our load balancer since HAProxy has built-in support for managing HTTP and TCP traffic.
API Security Alert: Attacker Activity Surges By 400% In Half A Year
Tags: apimanagement, api, apisecurity, apidevelopment
Published: 2023-04-06 02:26:43

---
title: API Security Alert: Attacker Activity Surges By 400% In Half A Year
published: true
date: 2023-04-04 04:21:54 UTC
tags: apimanagement,api,apisecurity,apidevelopment
canonical_url: https://pinjarirehan.medium.com/api-security-alert-attacker-activity-surges-by-400-in-half-a-year-72c9ac1f446c
---

![API Security Alert](https://cdn-images-1.medium.com/max/800/1*c9fqR1j8A22a1gB8anHmxw.gif)

According to [Salt Security](https://salt.security/)’s newest State of API Security Report, there has been a 400% jump in unique attackers in the last six months.

Furthermore, approximately 80% of attacks happened via authenticated APIs.

Not surprisingly, nearly half of those surveyed (48%) now say API security is a C-level topic in their company.

According to the report, 94 of the people who responded faced security issues in production APIs in the past year, with 17 percent claiming a data leak as a result of API security problems.

The quick growth in attacks, together with the data supplied by the people surveyed, shows a growing insight in the C-suite about the need for purpose-built API security to reduce business risk,” says Roey Eliyahu, co-founder, and CEO of Salt Security.

“Pushed by APIs, ongoing digital transformation generates new business opportunities and competitive advantages.

So far, the cost of API hacks, such as those recently suffered by T-Mobile, Toyota, and Optus, puts the new services, brand reputation, and company operations at risk.

With threat guys finding new and unexpected ways to attack APIs, companies must take API security very seriously.”

Because of API security problems, more than fifty percent of those polled (59%) said they have had to slow the launch of new apps.

However, only 23% of participants felt their existing safeguards are extremely successful at stopping API attacks.

When asked about the most serious API security problems, 54% of participants said outdated or ‘zombie’ APIs are a big issue, up from 42% in the past period.

(In Salt’s past 5 studies, zombie, or out-of-date, APIs have been the top issue.) Account hijack (ATO) is a main agenda for 43 of the people polled, but only 20 percent mention shadow APIs as a critical interest, even though most environments are likely running unknown APIs.

Similarly, just 18% of participants are very confident that their API profiles give sufficient data about their APIs and the PII or sensitive data stored inside.

The complete research can be found on the [Salt Security blog](https://salt.security/blog/latest-state-of-api-security-report-400-increase-in-attackers-and-more).

I hope you find this info useful. Please don’t hesitate to ask if you have any questions or just want further clarification.

I’m always happy to give you extra details or help.
hello, My name is Peyton Ambs.
Tags: frontend, beginners, webdev, programming
Published: 2023-04-04 03:47:50

I am looking for any help, resources, and advice that people can give me. I am brand new except for a basic hazy understanding of html. Im mostly making this post as a time capsule for me to look back on but one day I hope to become a front-engineer or something similar so we'll see where my journey takes me. If you just wanna talk also then I love space and science.
Why is logic the basis of programming?
Tags: beginners, tutorial, productivity, programming
Published: 2023-04-04 02:57:37

_When you start in this world_, you tried to solve all in one week learning many programing languages, learn all the frameworks and all the technologies, but when you start whit that mindset you start bad, in that post i explain my point of view about the one of the most important points when you start to learn in this area.

![Programer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8c74t2ris117tcfng9qo.png)

**¿Why the logic is one of the most skiped points when you start?**, The answer is easy we skiped all the time, and same you started and take your computer search in google one or two programing languages and start to coding. But when you stop and try to understand the logic about why you put the variable whit that name or why you use the if or else. 


![Research](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5hubbwhzk2idquzeekc3.png)

Try to research why you do that things and what is the purpose. Other tip is start whit pseudocoding that is one good base to start and improve your logic, if you need start right now that is **_my principal tip start whit pseudocoding_** and after choose your first programing languages, and you will saw the difference when you start when you first programing language.

This is all for today thanks and see you in other post 😉.
Implementando o Debounce no React: Melhorando a Experiência do Usuário em Eventos de Entrada
Tags: react, frontend, javascript, programming
Published: 2023-04-04 02:23:29

O Debounce é uma técnica muito útil no desenvolvimento de aplicações React para lidar com eventos de entrada do usuário que ocorrem com muita frequência em curtos períodos de tempo, como a digitação em um campo de pesquisa. Quando um usuário digita em um campo de pesquisa, um evento é acionado a cada letra digitada, o que pode causar uma sobrecarga de solicitações ao servidor e um atraso na resposta para o usuário. É aí que entra o Debounce.

O Debounce é um padrão de design que permite limitar a frequência com que uma função é chamada, aguardando um determinado período de tempo após o último evento antes de executar a função. Dessa forma, ele evita que a função seja chamada muitas vezes em rápida sucessão e reduz a carga no servidor.

No React, existem várias maneiras de implementar o Debounce. Uma das maneiras mais comuns é usando o hook useEffect. Mas também é possível implementar usando outras técnicas, como o useCallback e a biblioteca Lodash.

Para implementar o Debounce com o hook useEffect, basta usar o setTimeout para adiar a chamada da função até que o período de tempo especificado tenha passado. Aqui está um exemplo simples:

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

Nesse exemplo, a função passada para o setTimeout será executada após um atraso de 1000ms (1 segundo) após o último evento de digitação. Além disso, o retorno da useEffect é uma função que limpa o temporizador, garantindo que a função não seja executada caso o usuário continue digitando.

Em resumo, o Debounce é uma técnica valiosa para reduzir a carga no servidor e melhorar a experiência do usuário em aplicações React. Com as diversas opções de implementação disponíveis, vale a pena experimentar e escolher a abordagem que melhor se adapta às necessidades da sua aplicação.
View and Joined Table Design
Tags: opengauss
Published: 2023-04-04 02:20:57

View Design
[Proposal] Do not nest views unless they have strong dependency on each other.
[Proposal] Try to avoid collation operations in a view definition.
Joined Table Design
[Proposal] Minimize joined columns across tables.
[Proposal] Use the same data type for joined columns.
[Proposal] The names of joined columns should indicate their relationship. For example, they can use the same name.
Field Design
Tags: opengauss
Published: 2023-04-04 02:19:31

Selecting a Data Type
To improve query efficiency, comply with the following rules when designing columns:

[Proposal] Use the most efficient data types allowed.

If all of the following number types provide the required service precision, they are recommended in descending order of priority: integer, floating point, and numeric.

[Proposal] In tables that are logically related, columns having the same meaning should use the same data type.

[Proposal] For string data, you are advised to use variable-length strings and specify the maximum length. To avoid truncation, ensure that the specified maximum length is greater than the maximum number of characters to be stored. You are not advised to use CHAR(n), BPCHAR(n), NCHAR(n), or CHARACTER(n), unless you know that the string length is fixed.

For details about string types, see [Common String Types](https://docs.opengauss.org/en/docs/latest/docs/Developerguide/field-design.html#section290310115932).

 Common String Types.

Common String Types
Every column requires a data type suitable for its data characteristics. The following table lists common string types in openGauss.

Table 1 Common string types


Name

Description

Max. Storage Capacity

CHAR(n)

Fixed-length string, where n indicates the stored bytes. If the length of an input string is smaller than n, the string is automatically padded to n bytes using NULL characters.

10 MB

CHARACTER(n)

Fixed-length string, where n indicates the stored bytes. If the length of an input string is smaller than n, the string is automatically padded to n bytes using NULL characters.

10 MB

NCHAR(n)

Fixed-length string, where n indicates the stored bytes. If the length of an input string is smaller than n, the string is automatically padded to n bytes using NULL characters.

10 MB

BPCHAR(n)

Fixed-length string, where n indicates the stored bytes. If the length of an input string is smaller than n, the string is automatically padded to n bytes using NULL characters.

10 MB

VARCHAR(n)

Variable-length string, where n indicates the maximum number of bytes that can be stored.

10 MB

CHARACTER VARYING(n)

Variable-length string, where n indicates the maximum number of bytes that can be stored. This data type and VARCHAR(n) are different representations of the same data type.

10 MB

VARCHAR2(n)

Variable-length string, where n indicates the maximum number of bytes that can be stored. This data type is added to be compatible with the Oracle database, and its behavior is the same as that of VARCHAR(n).

10 MB

NVARCHAR2(n)

Variable-length string, where n indicates the maximum number of bytes that can be stored.

10 MB

TEXT

Variable-length string. Its maximum length is 1 GB minus 8203 bytes.

1 GB minus 8203 bytes
Table Design
Tags: opengauss
Published: 2023-04-04 02:18:51

Comply with the following principles to properly design a table:

[Notice] Reduce the amount of data to be scanned. You can use the pruning mechanism of a partitioned table.
[Notice] Minimize random I/Os. By clustering or local clustering, you can sequentially store hot data, converting random I/O to sequential I/O to reduce the cost of I/O scanning.
Selecting a Storage Mode
[Proposal] Selecting a storage model is the first step in defining a table. The storage model mainly depends on the customer's service type. For details, see Table 1.

Table 1 Table storage modes and scenarios


Storage Type

Application Scenario

Row store

Point queries (simple index-based queries that only return a few records).
Scenarios requiring frequent addition, deletion, and modification.
Column store

Statistical analysis queries (requiring a large number of association and grouping operations).
Ad hoc queries (using uncertain query conditions and unable to utilize indexes to scan row-store tables).
Selecting a Partitioning Mode
If a table contains a large amount of data, partition the table based on the following rules:

[Proposal] Create partitions on columns that indicate certain ranges, such as dates and regions.
[Proposal] A partition name should show the data characteristics of a partition. For example, its format can be Keyword+Range characteristics.
[Proposal] Set the upper limit of a partition to MAXVALUE to prevent data overflow.
The example of a partitioned table definition is as follows:


```
CREATE TABLE staffS_p1
(
  staff_ID       NUMBER(6) not null,
  FIRST_NAME     VARCHAR2(20),
  LAST_NAME      VARCHAR2(25),
  EMAIL          VARCHAR2(25),
  PHONE_NUMBER   VARCHAR2(20),
  HIRE_DATE      DATE,
  employment_ID  VARCHAR2(10),
  SALARY         NUMBER(8,2),
  COMMISSION_PCT NUMBER(4,2),
  MANAGER_ID     NUMBER(6),
  section_ID     NUMBER(4)
)
PARTITION BY RANGE (HIRE_DATE)
( 
   PARTITION HIRE_19950501 VALUES LESS THAN ('1995-05-01 00:00:00'),
   PARTITION HIRE_19950502 VALUES LESS THAN ('1995-05-02 00:00:00'),
   PARTITION HIRE_maxvalue VALUES LESS THAN (MAXVALUE)
);

```
Database and Schema Design
Tags: opengauss
Published: 2023-04-04 02:17:25

In openGauss, services can be isolated by databases and schemas. Databases share little resources and cannot directly access each other. Connections to and permissions on them are also isolated. Schemas share more resources than databases do. User permissions on schemas and subordinate objects can be controlled using the GRANT and REVOKE syntax.

You are advised to use schemas to isolate services for convenience and resource sharing.
It is recommended that system administrators create schemas and databases and then assign required permissions to users.
Database Design
[Rule] Create databases as required by your service. Do not use the default postgres database of a database instance.
[Proposal] Create a maximum of three user-defined databases in a database instance.
[Proposal] To make your database compatible with most characters, you are advised to use the UTF-8 encoding when creating a database.
[Notice] When you create a database, exercise caution when you set ENCODING and DBCOMPATIBILITY configuration items. openGauss supports the A, B, C, and PG compatibility modes, which are compatible with the Oracle syntax, MySQL syntax, Teradata syntax, and Postgres syntax, respectively. The syntax behavior varies according to the compatibility mode. By default, the A compatibility mode is used.
[Notice] By default, a database owner has all permissions for all objects in the database, including the deletion permission. Exercise caution when deleting a permission.
Schema Design
[Notice] To let a user access an object in a schema, assign the usage permission and the permissions for the object to the user, unless the user has the sysadmin permission or is the schema owner.
[Notice] To let a user create an object in the schema, grant the create permission for the schema to the user.
[Notice] By default, a schema owner has all permissions for all objects in the schema, including the deletion permission. Exercise caution when deleting a permission.
Database Object Naming Conventions
Tags: opengauss
Published: 2023-04-04 02:16:15

The name of a database object must meet the following requirements: The name of a non-time series table ranges from 1 to 63 bytes and that of a time series table ranges from 1 to 53 characters. The name must start with a letter or underscore (_), and can contain letters, digits, underscores (_), dollar signs ($), and number signs (#).

[Proposal] Do not use reserved or non-reserved keywords to name database objects.

 NOTE: You can use the select * from pg_get_keywords() query openGauss keyword or view the keyword in Keywords.

[Proposal] Do not use a string enclosed in double quotation marks ("") to define the database object name, unless you need to specify its capitalization. Case sensitivity of database object names makes problem location difficult.

[Proposal] Use the same naming format for database objects.

In a system undergoing incremental development or service migration, you are advised to comply with its historical naming conventions.
You are advised to use multiple words separated with underscores (_).
You are advised to use intelligible names and common acronyms or abbreviations for database objects. Acronyms or abbreviations that are generally understood are recommended. For example, you can use English words or Chinese pinyin indicating actual business terms. The naming format should be consistent within a database instance.
A variable name must be descriptive and meaningful. It must have a prefix indicating its type.
[Proposal] The name of a table object should indicate its main characteristics, for example, whether it is an ordinary, temporary, or unlogged table.

An ordinary table name should indicate the business relevant to a dataset.
Temporary tables are named in the format of tmp_Suffix.
Unlogged tables are named in the format of ul_Suffix.
Foreign tables are named in the format of f_Suffix.
Do not create database objects whose names start with redis_.
Do not create database objects whose names start with mlog_ or matviewmap_.
[Proposal] The name of a non-time series table object shall not exceed 63 bytes. If the length exceeds this value, the kernel truncates the table name. As a result, the table name is inconsistent with the configured name. In different character sets, characters may be truncated and unexpected characters may appear.

Previous
How to add hours to datetime using javascript
Tags: javascript, beginners, programming, tutorial
Published: 2023-04-04 01:43:13

`let date_string = "2023-03-19 07:55:03";
let date_obj = new Date(date_string);

date_obj.setHours(date_obj.getHours() + 7);

let result = date_obj.toISOString().slice(0, 19).replace('T', ' ');

console.log(result); // output: "2023-03-19 14:55:03"
`

Dengan cara tersebut mengubah tanggal data string menjadi objek Date, kemudian menambahkan 7 jam ke objek tersebut dengan menggunakan cara setHours(). Setelah itu, objek tanggal diubah kembali menjadi string dengan format yang sama seperti awalnya menggunakan metode toISOString() dan dihapus karakter "T" pada string hasilnya. Akhirnya, tanggal dan waktu yang dihasilkan ditampilkan pada konsol.
How do I get my first job in tech?
Published: 2023-04-04 00:40:21

To get your first job in tech, start by gaining practical experience through internships or volunteer work. Build a strong online presence through social media and professional networking sites like LinkedIn. Attend tech conferences and events to meet other professionals in the field. It's also important to continually learn and improve your skills through online courses or [course in web development](https://www.geekster.in/full-stack-web-development-program).
What programming languages should I learn to become a software engineer?
Tags: javascript, programming
Published: 2023-04-04 00:28:46

There is no one "best" programming language to learn to become a software engineer, as different languages are better suited for different tasks. However, some commonly used languages in software engineering include Java, Python, JavaScript, and C++. 

It's important to have a strong foundation in programming fundamentals, as well as knowledge of databases, algorithms, and data structures which you can learn at [full stack development course](https://www.geekster.in/full-stack-web-development-program
)
Updating timestamps automatically in Supabase
Tags: supabase, postgres, sql, webdev
Published: 2023-04-05 21:36:37

---
title: Updating timestamps automatically in Supabase
published: true
date: 2023-04-04 00:00:00 UTC
tags: Supabase, Postgres, SQL, Webdev
canonical_url: https://laros.io/updating-timestamps-automatically-in-supabase
---

Supabase makes it easy to update timestamps automatically whenever a row is created or updated in your database, using the `MODDATETIME` extension. This can especially be useful in applications where data is frequently changed.

## SQL snippet 

Replace `YOUR_TABLE_NAME` with the name of your table.

```sql
-- Add new columns to table named `created_at` and `updated_at`
ALTER TABLE YOUR_TABLE_NAME
ADD COLUMN created_at timestamptz default now(),
ADD COLUMN updated_at timestamptz;

-- Enable MODDATETIME extension
create extension if not exists moddatetime schema extensions;

-- This will set the `updated_at` column on every update
create trigger handle_updated_at before update on YOUR_TABLE_NAME
  for each row execute procedure moddatetime (updated_at);
```

The property `created_at` will be set when a new row is added to the table, and `updated_at` will be updated on each update.

## Manually enable extension 

1. Navigate to `Database` -> `Extensions` in your Supabase dashboard
2. Enable the `MODDATETIME` extension
3. Add a new column to your table named `created_at`, with type `timestamptz`, and default value `now()`
4. Add a new column to your table named `updated_at`, with type `timestamptz`
5. Go to the SQL editor and run the following query (replace `YOUR_TABLE_NAME` with the name of your table):

```sql
create trigger handle_updated_at before update on YOUR_TABLE_NAME
  for each row execute procedure moddatetime (updated_at);
```

## Resources 

- [Supabase](https://supabase.com/)