teleren/devto huggingface dataset:
[ptbr] Consumir Funções do PostGIS direto do Python
Published: 2024-05-17 20:30:00

Todo o tutorial está sendo feito dentro de uma WSL2 com Ubuntu do Windows 11.

Primeiro precisamos de um PostgreSQL com PostGIS instalado. Nesse exemplo vamos iniciar utilizando Docker Container com o comando abaixo:

```bash
docker run --name postgis -p 5432:5432 -e POSTGRES_PASSWORD=admin -d postgis/postgis
```

Explicando os parâmetros;

- `--name postgis` : nome dado ao container
- `-p 5432:5432`: mapeando a nossa porta 5432 com a porta 5432 do container
- `-e POSTGRES_PASSWORD=admin`: definindo a senha do default do usuário **postgres** para **admin**
- `-d`: roda o container em background, printando o ID do container, sem travar o terminal

Precisamos de um ambiente com Python instalado. Vou partir do princípio que o leitor sabe como criar esse ambiente, mesmo que seja em ambiente virtual. Nesse exemplo estou usando pipenv.

Criando um diretório, entrando no mesmo, criando o ambiente com Python3.12 e iniciando o ambiente:

```bash
mkdir sqlalchemy_postgis && cd sqlalchemy_postgis/ && pipenv --python 3.12 && pipenv shell
```

Vamos instalar umas dependências para esse tutorial:

```bash
pip install psycopg2 sqlalchemy
```

Criando um arquivo .py:

```bash
touch main.py
```

Dentro do arquivo:

```python
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine, text
from sqlalchemy.sql.expression import literal_column

# no exemplo usaremos as seguintes variáveis setadas hardcoded para ser mais sucinto
user: str = "postgres"  # usuário padrão do container postgis
password: str = "admin"  # senha que definimos no comando docker run
host: str = "127.0.0.1"  # vulgo localhost
database_name: str = "postgres"

engine = create_engine(f"postgresql://{user}:{password}@{host}/{database_name}")

Session = sessionmaker(bind=engine)
session = Session()

encoded_polyline = "sdxIy~vrkL"

def get_line_from_encoded_polyline(engine, encoded_polyline) -> str:
    with engine.connect() as conn:
        # Consulta SQL para chamar a função ST_LineFromEncodedPolyline
        query = text(
            f"SELECT ST_AsText(ST_LineFromEncodedPolyline('{encoded_polyline}')) AS geom"
        )
        result = conn.execute(query)
        return result.scalar()

result = get_line_from_encoded_polyline(engine, encoded_polyline)

print(result)
```

Esse foi um exemplo simples de como utilizar funções do PostGIS diretamente do Python.
Database indexing and selectivity
Tags: database, webdev, backend, sql
Published: 2024-05-17 20:15:31

As you may already know, indexing is a great way to improve the performance of your queries. But is that really it?
>There are no silver bullets, only trade-offs. What's the catch? There's always a catch!

When you create an index, the RDBMS creates a copy of your table containing one or more columns depending on how many columns you have indexed.

This copy will always be sorted, and it has to be maintained while inserting, updating, and deleting rows. That's why indexes slow down writes and lock tables during index creation.

Enough about the RDBMS job, let's talk about yours. Which columns should you index?
It depends!. Your queries should drive your indexes, but you can use column selectivity to decide if a column will make a good index or not.

Selectivity describes the `uniqueness` of values in a column.

>A highly selective index is good because it filters out more rows in a search. 

Let's imagine a table with columns for email, country, and gender.
- The **gender** column is the **_least selective_**, since it can only - hold two values.
- The **country** column is **_more selective_** since it can hold more values.
The **email** column is the **_most selective_** because it's unique.

Selectivity affects search performance because it divides the table into slices and uses these slices for searching. Selective columns form smaller slices, which makes searching them faster.

How to find the selectivity of a column?
simply run this query:
```sql
select count(distinct column)/count(*) from table;
```
>In postgres, you'll need to cast values to numeric for this to work
Get the ChatGPT equivalent in less than 5 minutes with Ollama and Open WebUI
Tags: ollama, openwebui, docker, chatgpt
Published: 2024-05-17 19:43:46

## Introduction

In this tutorial, I will show you how to install a graphical interface equivalent to ChatGPT on your PC, using Ollama, without requiring an internet connection after installation, while maintaining complete control over your data. This guide is compatible with all operating systems (Windows, macOS, Linux). I'm going to assume you are familiar with using a terminal and docker.

Open WebUI ?
- Open WebUI is an extensible, feature-rich, and user-friendly self-hosted WebUI designed to operate entirely offline. It supports various LLM runners, including Ollama and OpenAI-compatible APIs.

Ollama ?
- Ollama is an open-source project that serves as a powerful and user-friendly platform for running LLMs on your local machine.

---

## Let's start

<u>Step 1: Docker</u>
- Download Docker and install it. Then, launch the application.
- [docker](https://www.docker.com/)

<u>Step 2: Ollama</u>
- Same process as Docker, this time with Ollama.
- [Ollama](https://ollama.com/)

_At this stage, you can already use Ollama in your terminal._

_*For Windows Users:_
<u>2.1 : WSL</u>
- Install Windows Subsystem for Linux
- [WSL](https://learn.microsoft.com/fr-fr/windows/wsl/install)

<u>2.2 CUDA</u>
- To use the GPU, install CUDA
- [Cuda GPU WSL](https://developer.nvidia.com/cuda/wsl)
- _if you need more information about cuda in wsl, you can check [this link](https://learn.microsoft.com/en-us/windows/ai/directml/gpu-cuda-in-wsl)_

<u>Step 3: Install a Graphical Interface with WebUI</u>

To have a user interface, run the following Docker command:

```bash
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always https://github.com/open-webui/open-webui/pkgs/container/open-webui
```

- It will run as a docker image, open webui.
- If you want to learn more about Open WebUI, especially if you want your model to use your GPU, change port, etc., you can check [this link](https://github.com/open-webui/open-webui) on the GPU section support.

_Additional Notes:_
- Change the port if **3000** is already in use on your machine.

---

## What's next?
- run in you web browser : [http://localhost:3300](http://localhost:3300) (or your replacement port)
- Now, you can go to Settings > Models > Pull a model from Ollama.com. Set it as default, configure it, provide instructions before starting the conversation, etc.

![Open WebUI parameters](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h8lshss4zon4rl8d9nl4.png)

- Example, you can put **llama3** as _model tag_, then download it, to use it.

---

**Conclusion**

You now have everything you need to start using your own instance of ChatGPT like with Llama3, Mistral, and others. You can continue to download and configure other models as needed, such as multimodal models capable of reading PDFs, performing image recognition, etc.
Method References
Published: 2024-05-17 19:42:27

Java'da **method references** (metod referansları), Java 8 ile gelen ve lambda ifadelerinin daha okunabilir ve kısa hale getirilmesini sağlayan bir özelliktir. Metod referansları, belirli bir metodun doğrudan adını kullanarak, o metodu bir lambda ifadesi yerine geçirebilir. Bu, özellikle tekrar tekrar kullanılan metodlar için kod tekrarını azaltır ve kodun okunabilirliğini artırır.

Metod referansları dört ana türde olabilir:
1. **Statik Metod Referansları**:
   - Sınıfın statik metodlarına direkt sınıf adı üzerinden erişim sağlar.
   - Örnek: `ClassName::staticMethodName`

2. **Belirli Bir Nesnenin İnstance Metod Referansları**:
   - Belirli bir nesnenin instance metodlarına o nesnenin referansı üzerinden erişim sağlar.
   - Örnek: `instance::instanceMethodName`

3. **Belirli Bir Tipin Herhangi Bir Nesnesinin İnstance Metod Referansları**:
   - Belirli bir tipin herhangi bir nesnesinin instance metodlarına direkt tip adı üzerinden erişim sağlar.
   - Örnek: `ClassName::instanceMethodName`

4. **Yapıcı Metod Referansları** (Constructor References):
   - Bir sınıfın yapıcı metoduna (constructor) direkt sınıf adı üzerinden erişim sağlar.
   - Örnek: `ClassName::new`

Metod referansları, `::` operatörü kullanılarak ifade edilir. Örneğin, bir listenin her elemanını büyük harfe çeviren bir metodunuz varsa ve bu işlemi bir stream üzerinde yapmak istiyorsanız, şu şekilde bir lambda ifadesi yazabilirsiniz:
```java
list.forEach(s -> System.out.println(s.toUpperCase()));
```
Aynı işlemi metod referansı kullanarak daha kısa ve okunabilir bir şekilde yapabilirsiniz:
```java
list.forEach(System.out::println);
```
Bu örnekte, `System.out` nesnesinin `println` metoduna bir referans verilmiş ve lambda ifadesi yerine geçmiştir.

Metod referansları, fonksiyonel arayüzlerle (functional interfaces) birlikte kullanıldığında, kodun daha temiz ve anlaşılır olmasını sağlar. Ayrıca, Java'nın işlevsel programlama özelliklerini daha etkin kullanmanıza olanak tanır¹²³.

Kaynaklar:
- [Java 8 - Method Reference – KodEdu](^1^)
- [Method References in Java | Baeldung](^2^)
- [Java 8 Method Reference - javatpoint](^3^)

Kaynak: Bing ile konuşma, 17.05.2024
(1) Java 8 - Method Reference – KodEdu. https://kodedu.com/2014/09/java-8-method-reference/.
(2) Method References in Java | Baeldung. https://www.baeldung.com/java-method-references.
(3) Java 8 Method Reference - javatpoint. https://www.javatpoint.com/java-8-method-reference.
(4) Java 8 - Method Reference – KodEdu. https://kodedu.com/2014/09/java-8-method-reference/.
(5) Method References in Java | Baeldung. https://www.baeldung.com/java-method-references.
(6) Java 8 Method Reference - javatpoint. https://www.javatpoint.com/java-8-method-reference.
(7) Method References | Java Tutorial for Beginners. https://java-tutorial.dev/docs/Functional-Programming-In-Java/Method-References.
Underfitting and Overfitting Concepts in Machine Learning
Tags: machinelearning, ai, deeplearning, datascience
Published: 2024-05-17 19:39:43

Underfitting and overfitting are issues that can occur in supervised machine learning problems. These problems involve training a model to learn a mapping from input data to output labels based on a given dataset.

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

# Overfitting

The model shows high accuracy during the training phase but fails to show similar accuracy during the testing phase.

The model is too complex and learns not only the underlying patterns but also noise and outliers specific to the training set. While it performs exceptionally well on the training set, it struggles to generalize to new, unseen data in the testing phase.

# Underfitting
The model fails to show satisfactory accuracy during the training phase.


The model is too simple and fails to capture the complexities in the data, resulting in poor performance in both the training and testing phases.

## Actual Good fitting:
Training and testing overall performance is good.

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

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

Thanks for reading 💙✨

### References:

https://www.superannotate.com/blog/overfitting-and-underfitting-in-machine-learning
https://www.geeksforgeeks.org/underfitting-and-overfitting-in-machine-learning/
Build Beautiful Chart from Any JSON Object
Tags: webdev, javascript, showdev, json
Published: 2024-05-17 19:06:02

Visualize your data further with our interactive json to chart online. By selecting any key from your JSON object 

Visit: https://www.jsonviewer.tools/jsonchart


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rhuy4fvyp2qbxtyn26b4.gif)
Safety First: Tips for Handling Gas Line Emergencies
Published: 2024-05-17 19:03:03


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


If you're reading this, chances are you're facing a gas line emergency or want to be prepared for one. Gas line emergencies are serious situations that require immediate attention to ensure the safety of everyone involved. Whether you're in Dayton or anywhere else, knowing how to handle such emergencies can make all the difference. In this post, we'll discuss some essential tips for dealing with gas line emergencies, emphasizing safety above all else.

**Recognize the Signs:** Gas line emergencies often come with warning signs. If you detect the smell of gas (often described as rotten eggs), hear hissing sounds near a gas appliance, or notice dead vegetation near your gas lines, there may be a leak. React promptly.

**Evacuate Safely:** If you suspect a gas leak, evacuate the area immediately. Warn others nearby and move to a safe location away from the property. Avoid using electronic devices or anything that could create a spark, as this could ignite the gas.

**Call for Help:** Once you're in a safe location, call your gas company's emergency hotline or 911. Inform them of the situation and your location. Gas line emergencies require professional intervention, so avoid trying to fix the issue yourself.

**Shut Off Gas Supply: **If it's safe to do so, turn off the gas supply to your property. The gas shut-off valve is typically located near the gas meter. Use a wrench to turn the valve perpendicular to the pipe to stop the flow of gas.

**Avoid Flames and Sparks: **Until professionals arrive and confirm that it's safe, avoid using anything that could cause a spark or flame. This includes lighting matches, using lighters, operating electrical switches, or starting vehicles.

**Ventilate the Area:** If you can safely do so, open windows and doors to ventilate the area. This can help dissipate the gas and reduce the risk of ignition.

**Seek Medical Attention: **If anyone experiences symptoms of gas exposure, such as dizziness, nausea, headaches, or difficulty breathing, seek medical attention immediately. Gas leaks can cause serious health issues and should not be taken lightly.

**Wait for Professionals:** Once you've taken the necessary safety precautions, wait for trained professionals to arrive. They have the expertise and equipment to assess the situation, repair the gas line, and ensure that it's safe to return to your property.

**Gas line emergencies are not to be underestimated.** Prioritize safety above all else and act swiftly to minimize risks. Remember, when it comes to [gas line repair near Dayton](https://www.integrityplumbinganddrains.com/water-line-gas-and-drain-repair/) or anywhere else, always rely on qualified professionals to handle the situation. Your safety and the safety of those around you depend on it.
Scaling Font Sizes with REM Units: A Versatile Approach
Published: 2024-05-17 18:59:38

REM (Root EM) units are a versatile and scalable way to define font sizes and other measurements in CSS. Unlike pixels (px), which are fixed units, REM units are relative to the root element's font size, typically the <html> element. This relative nature allows for more responsive and accessible designs, as adjusting the root font size can scale the entire layout proportionally.

## Advantages of Using REM Units:

Scalability: REM units make it easier to scale entire layouts by changing the root font size. This is especially useful for creating responsive designs that adapt to different screen sizes and devices.

**Accessibility:** By using REM units, designers can ensure that their websites are more accessible. Users who need larger text can adjust their browser settings, and the website will scale accordingly.

**Consistency:** REM units promote consistency in design by providing a uniform scale. This helps in maintaining a consistent look and feel across different parts of the website.

**Ease of Maintenance:** Adjusting the layout becomes simpler as changing the root font size will proportionally change all elements sized with REM units. This can save significant time in the long run.

**Better Performance:** REM units reduce the need for media queries for different screen sizes, which can enhance website performance.

To efficiently [convert pixels to REM units](https://visualfrontend.com/tools/px-to-rem-converter/), use tools like the PX to REM Converter. This handy tool works efficiently and bidirectionally converts px to rem and rem to px, ensuring consistent and responsive design practices in web development.
Create Professional Forms in Minutes with ZIGAFORM
Published: 2024-05-17 18:55:42

Are you tired of struggling with clunky, outdated contact forms and estimation tools for your website? Look no further! ZIGAFORM offers a comprehensive suite of solutions to meet all your form-building needs, whether you're running a WordPress site, or Magento store, or any other platform.

WordPress Form Builder: Tailored for Your Needs

With ZIGAFORM's WordPress form builder, creating sleek, responsive forms has never been easier. Say goodbye to static, one-size-fits-all forms – our intuitive builder allows you to customize every aspect of your forms, from layout to functionality. Need conditional logic? We've got you covered. Want to add eye-catching animation effects? It's just a click away.

Estimation Forms Made Simple

Estimating costs, payments, or project timelines? ZIGAFORM's estimation form builder streamlines the process, allowing you to create dynamic, interactive forms that adapt to user input. Whether you're calculating loan payments or project quotes, our plugin empowers you to create accurate, user-friendly estimators that enhance the user experience and drive conversions.

Seamless Integration Across Platforms

Don't let platform limitations hold you back. ZIGAFORM's PHP form builder enables you to embed forms seamlessly on any website, regardless of the platform. From Joomla to custom-built sites, our versatile builder ensures that your forms look and function flawlessly, wherever they're deployed.

Easy Implementation with Widget Codes

Gone are the days of complex integrations and coding headaches. With ZIGAFORM, adding forms to your site is as simple as copy and paste. Our widget codes allow you to effortlessly embed forms and estimation tools on any page, giving you full control over placement and design.

Comprehensive Documentation and Support

We understand that mastering new tools can be daunting. That's why ZIGAFORM provides comprehensive documentation and support every step of the way. Whether you're a seasoned developer or a novice user, our detailed guides and responsive support team ensure that you can harness the full power of our platform with confidence.

Join the ZIGAFORM Community Today

Ready to take your website to the next level? Join the thousands of satisfied users who have revolutionized their online presence with ZIGAFORM. Whether you're building contact forms, estimation tools, or anything in between, ZIGAFORM has the solution you need to succeed. Try it today and see the difference for yourself!

Have questions or need assistance? Don't hesitate to reach out – our dedicated support team is here to help. Leave a comment below, and let's build something amazing together!

More info at https://zigaform.com

{% youtube.com https://youtu.be/Z3ZneAg1AD8?si=V9klWhfR7PxObA9v %}
how to create wizard form with ZIGAFORM Cost Estimation Form Builder
Published: 2024-05-17 18:51:26

In the realm of form creation, simplicity and functionality reign supreme. Today, we embark on a journey to craft a wizard form paired with a single form estimator, a dynamic duo that promises streamlined user experiences and efficient data collection. Let's dive into the process of creating this intuitive form from scratch.

Setting the Stage

Our adventure begins by navigating to the new form section. While there are pre-existing wizard form templates available, we opt to forge our path from the ground up. First, we activate the wizard forms feature, unlocking a plethora of possibilities for step-by-step navigation.

Designing the Form

With our canvas ready, we begin to populate it with elements essential to our wizard form's functionality. Text boxes, text areas, select lists—each meticulously placed to guide users through the form seamlessly. We ensure each step is equipped with the necessary navigation tools, allowing users to progress effortlessly.

Validation and Customization

No form is complete without validation mechanisms. We implement checks to ensure data integrity, withholding progression until required fields are filled. Additionally, we harness the power of custom HTML elements to display dynamic content, such as total prices, enriching the user experience.

Themes and Styles

As architects of user experience, we understand the significance of aesthetics. We explore various themes and styles, experimenting with different visual elements to enhance the form's appeal. From circular motifs to sleek, minimalist designs, each alteration adds a unique flair to our creation.

Advanced Features

Our journey doesn't end with basic form functionalities. We delve into advanced features, such as mail settings and custom calculations, elevating our wizard form to new heights. With mail settings configured to display all form fields, users can expect comprehensive summaries delivered straight to their inboxes.

Continuous Improvement

As we near the completion of our wizard form, we remain vigilant in our pursuit of perfection. We continuously refine and expand our creation, adding new elements like file uploads and dynamic buttons to further enhance its capabilities.

Final Touches

With the finishing touches in place, our wizard form stands as a testament to thoughtful design and meticulous craftsmanship. Its seamless navigation, coupled with robust validation and customization options, ensures a delightful user experience from start to finish.

Conclusion

In the ever-evolving landscape of form creation, innovation is key. By harnessing the power of wizard forms and single form estimators, we've crafted a solution that seamlessly combines functionality with elegance. As we bid farewell to our creation, we invite you to embark on your journey of form creation, armed with the knowledge and inspiration gained from our adventure.

More info at https://zigaform.com

{% youtube https://youtu.be/3bwn1HA_UtU?si=IfkMYznWpDT8kXgr %}