teleren/devto huggingface dataset:
How to build Python packages reproducibly with Poetry
Tags: softwaredevelopment, devops, python, poetry
Published: 2024-02-20 19:39:50

---
title: How to build Python packages reproducibly with Poetry
published: true
date: 2024-02-19 22:37:42 UTC
tags: SoftwareDevelopment,DevOps,Python,Poetry
canonical_url: https://thesnapdragon.github.io/how-to-build-python-packages-reproducibly-with-poetry/
---

For handling dependencies and creating Python packages [Poetry](https://python-poetry.org/) is a great choice. Poetry’s build command can generate _source_ and _wheel_ distributions. [Wheel](https://packaging.python.org/en/latest/glossary/#term-Wheel) is a pre-built distribution format containing files and metadata, which only need to be moved to the target system, to be installed. On the other hand source (or _sdist_) distribution still requires a build step before it can be used.

![Header](https://thesnapdragon.github.io/images/header2.png)

## Poetry’s design issue

There is however a problem with Poetry’s package building functionality: it does not consider the lock file while running the build command. This design flaw leads to multiple issues with the built wheel:

- **No exact dependency versions** are specified in the distribution for explicit dependencies if no [exact requirements](https://thesnapdragon.github.io/efficient-dependency-version-management/#version-constraints) are used
- **Implicit dependencies are fully missing** from the distribution’s dependency specification

![Unsafe dependencies](https://thesnapdragon.github.io/images/02_unsafe_dependencies.png)

Ultimately these issues make the built wheel distribution unreliable and practically unusable in production as explicit and implicit dependencies will be installed non-deterministically.

## Locked versions in distributions

The Poetry team is [aware of the issue](https://github.com/python-poetry/poetry/issues/2778), but making this feature available in a maintainable way is not easy. Until this long-awaited feature is ready I created a plugin to solve the problem. The plugin extends the building process with reading up the lockfile and putting the locked versions into the distribution’s metadata:

![Correct dependencies](https://thesnapdragon.github.io/images/02_correct_dependencies.png)

### Installation & usage

1. The easiest way to install the lockedbuild plugin is via Poetry: 

```
poetry self add poetry-plugin-lockedbuild
```

2. Now the plugin provides a new command to build a wheel file with locked packages: 

```
poetry lockedbuild
```

For further details check out the project:

{%embed https://github.com/thesnapdragon/poetry-plugin-lockedbuild %}
nextjs for beginners
Tags: nextjs, learning, beginners, react
Published: 2024-02-19 22:00:50

Hi guys I want to learn nextjs but I am kind of beginner into programming, I know little bit of react, typescript, css, mysql. now I want to get it to together and learn really good one framework and I chose nextjs. My question is what is the best approach? I am thinking something in this order:

1. learn just front end and work with APIs (fetching, mapping, creating web elements with them)
2. learn how to connect mysql with the app
3. learn how to build API (this is still hard concept to even understand for me but I am not there yet)
4. Deployment the app and set up CI/CD

I would like to hear some insights or advice if I should change something, implement something that is not on my list or if it's good approach overall in your opinion
Compilando o "Hello world" em Pascal
Tags: pascal, compiler, go, antlr
Published: 2024-02-19 21:55:43

Como citei anteriormente, eu iria iniciar o projeto de um novo compilador, _open source_, em Go. Basicamente, o POJ (_Pascal on the JVM_) possibilita que seja executado um _subset_ de [Pascal](https://en.wikipedia.org/wiki/Pascal_(programming_language)) na [JVM](https://en.wikipedia.org/wiki/Java_virtual_machine). Mais detalhes sobre o projeto nesta postagem [aqui](https://dev.to/alexgarzao/pascal-rodando-na-jvm-1m3b).

A primeira meta do projeto era conseguir compilar e executar o "Hello world" em Pascal na JVM. Apesar de parecer simples, envolvia uma série de tarefas como:

- Definir qual gerador de _parsers_ será utilizado: realizei alguns testes com o [ANTLR](https://www.antlr.org/) e, apesar de alguns "perrengues" no início, optei por ele;
- Encontrar uma gramática de Pascal pronta no formato do ANTLR: isso foi bem tranquilo, já que no repositório do ANTLR existe a [gramática pronta para várias linguagens](https://github.com/antlr/grammars-v4/tree/master);
- Ajustar a gramática para reconhecer o _subset_ de Pascal esperado: no momento, apenas removi algumas sintaxes que realmente não serão utilizadas;
- No _parser_ identificar a definição de procedimentos no Pascal para determinar o bloco principal: isso gerou um pouco de trabalho por falta de conhecimento minha sobre a V4 do ANTLR (usei muito a V2 e V3 anteriormente);
- Encontrar um montador Java _Assembly_: o mais conhecido é o [Jasmin](https://github.com/davidar/jasmin), mas não consegui rodar os exemplos simples (talvez por imperícia minha, enfim), então acabei optando pelo [JASM](https://github.com/roscopeco/jasm) porque rapidamente consegui executar os exemplos;
- POJ gerar um código _assembly_ Java válido para o JASM: aqui a dificuldade foi entender como a V4 do ANTLR funciona para obter os tokens no código em Go;
- Criar o README inicial: tentei criar o mínimo necessário, mas já tem as instruções sobre como criar o binário, executar o POJ, executar o "Hello world" na JVM, entre outros.

No momento, dos exemplos citados na [postagem anterior](https://dev.to/alexgarzao/pascal-rodando-na-jvm-1m3b), apenas o exemplo do "Hello world" funciona no POJ. Claro que variações deste exemplo, como várias chamadas a writeln funcionam também:

```
program Hello;
begin
  writeln ('Hello world1!');
  writeln ('Hello world2!');
  writeln ('Hello world3!');
end.
```

Para possibilitar a execução de outros programas em Pascal, nas próximas semanas vou focar em recursos como:

- Declaração e uso de variáveis;
- Entrada e saída de dados (terminal);
- Instrução If/Else, For, Repeat e While;
- Operações aritméticas;
- Declaração e uso de procedures e funções;
- Uso de funções recursivas.

Para quem se interessou, o repositório do projeto é este [aqui](https://github.com/alexgarzao/poj).
How to upload files to Imagekit using Next.js server actions
Tags: nextjs, react, imagekit
Published: 2024-02-19 21:37:00

---
title: How to upload files to Imagekit using Next.js server actions
published: true
description: In a few lines of code, easily implement file upload using Next.js server action
tags: next, react, imagekit
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
published_at: 2024-02-19 21:37 +0000
---

As we're using Imagekit in this tutorial, setup an account there and grab the following keys:

```bash
IMAGEKIT_PUBLIC_KEY=
IMAGEKIT_PRIVATE_KEY=
IMAGEKIT_URL_ENDPOINT=
```

Add them to your `.env.local` file in your Next.js project, then install the `imagekit` package, finally let's create our `FileUpload.tsx` component

```ts
import ImageKit from "imagekit"

const imageKit = new ImageKit({
  publicKey: process.env.IMAGEKIT_PUBLIC_KEY!,
  privateKey: process.env.IMAGEKIT_PRIVATE_KEY!,
  urlEndpoint: process.env.IMAGEKIT_URL_ENDPOINT!,
})


const FileUpload = () => {
  // Server action
  const handleCreateListing = async (formData: FormData) => {
    "use server"

    const image = formData.get("image") as unknown as File
    
    // You could throw an error if image is null here

    const arrayBuffer = await image.arrayBuffer()
    const buffer = Buffer.from(arrayBuffer)

    const response = await imageKit.upload({
      file: buffer,
      fileName: image.name,
    })

    // Do something with response
  }

  return (
    <form action={handleCreateListing}>
     <input name="image" type="file" />
     <button type="submit">Submit</button>
    </form>
  )
}

```

That's all. You could use `useFormState` to handle the pending state and show a loading state and disable the button. You could also add more validation server side in the server action etc...
How does Ecto.Schema's `has_one/3` works?
Tags: elixir, liveview, phoenix, todayilearned
Published: 2024-02-19 21:26:08

### The problem

I have two schemas, `coffees` and `orders` wherein I want to get the `recent completed order from each coffees`

### First solution

```elixir
defmodule Schemas.Coffee do
    # ... more code
    has_many :completed_orders, Schemas.Order

    def coffee_query(coffee_id) do
        from c in __MODULE__,
            where: c.id == coffee_id,
            preload: [completed_orders: Orders.completed_order],
            limit: 1
    end
end

defmodule Schemas.Order do
    # ... more code
    
    @completed_status :completed

    def completed_order_query() do
        from o in __MODULE__,
            where: o.status in ^@completed_status,
            order_by: [desc: o.updated_at] 
    end
end

defmodule Contexts.Coffees do
    # more code

    def get_recent_completed_coffee_order(coffee_id) do
     coffee = coffee_id
              |> Schemas.Coffee.coffee_query()
              |> Repo.one

        List.first(coffee.completed_orders)
    end
end
```

* Based from the setup, I can actually get the `completed_orders` of coffees but the only downside for me is that the preload will return a `list`
    

* Since it will return a `list` , that will result into another process for me just to get the recent completed order.
    

### Then, `has_one/3` came into my life

```elixir
defmodule Schemas.Coffee do
    # ... more code
    has_one :completed_order, Schemas.Order,
        where: [status: :completed],
        preload_order: [desc: :updated_at]

    def coffee_query(coffee_id) do
        from c in __MODULE__,
            where: c.id == ^coffee_id
            preload: [:completed_order],
            limit: 1
    end
end

defmodule Contexts.Coffees do
    # more code

    def get_recent_completed_coffee_order(coffee_id) do
        coffee_id
        |> Schemas.Coffee.coffee_query()
        |> Repo.one
        |> Map.get(:completed_order, nil)
    end
end
```

> What's the magic behind this scheme?

### How does `has_one/3` works?

> Indicates a one-to-one association with another schema

From the current situation, `coffee belongs_to order`. As a result, `coffee has_many orders`, but I only need `one` result to return coming from the orders schema to identify if the coffee order is completed already.

Using \`has\_one/3\` I was able to achieve what I want.

* `has_one/3` - indicates a one-to-one association with another schema.
    
* `where` - indicates a `Filtering associations` to get my specific items.
    
* `preload_order` - Sets the default `order_by` of the association, and since I am using `has_one/3` Ecto set a query `LIMIT` set to `one` .
    

\[see has\_one/3 on docs\]([https://hexdocs.pm/ecto/Ecto.Schema.html#has\_one/3](https://hexdocs.pm/ecto/Ecto.Schema.html#has_one/3))

> Happy Coding
Is there any free text online in Philippines?
Tags: webdev, beginners, sms, tutorial
Published: 2024-02-19 21:11:12

Several web sites provide free text message Philippines. Some of these services may limit the amount of messages you can send each day or the length of each message. In addition, they may display adverts or demand you to create an account. Here are a few options to consider:

**TextPort**: Lets you send free text messages to the Philippines. You can send messages without registering, but there is a daily limit.

**SendSMSNow**: Provides free text messaging in the Philippines. To utilize the service, you must first create an account; nevertheless, registration is free. There may be limits to the number of messages you can send.

**Free Text Messaging** you can send free text Philippines and other countries. You can send messages without registering, however there may be a daily restriction.

**AFreeSMS**: Offers a free SMS Ph and other countries. You can send messages without registering, however there may be a daily restriction.

You should remember that free text Philippine may have limitations compared to paid options. When utilizing these platforms, make sure to follow all terms of service and privacy rules.

NB: If you are in search of free Virtual Numbers for SMS Verification. Take a look at [Legitsms.com](url)
Tasky: minimal planner in C++
Published: 2024-02-19 21:04:27

Check my new project, a minimal planner in C++, 
 [Github: ](https://github.com/pol-cova/Tasky)
if you had any question comment please!


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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/poeni1xgauvtxxgvvyxd.png)
makefile para projetos em Go
Tags: go, devops, beginners, learning
Published: 2024-02-19 20:51:04

`make` é uma ferramenta de sistemas Unix utilizada para *buildar* programas desde 1976.

Embora seja muito utilizada em, e frequentemente associada a, desenvolvimento de programas em C ou C++, o `make` também foi a ferramenta adotada pela comunidade Go para automatizar tarefas relacionadas a projetos.

Para utilizar o `make` precisamos de um arquivo, que por convenção é chamado de Makefile, que contem as instruções de como *buildar* um determinado projeto.

Abaixo segue exemplo de um Makefile qualquer para um programa em Go:

```makefile

# variaveis
GOCMD = go
GOLINT = golint

# declaracao da instrucao default
.DEFAULT_GOAL := build

# rules
fmt:
	$(GOCMD) fmt ./...
.PHONY: fmt

lint: fmt
	$(GOLINT) ./...
.PHONY: lint

vet: fmt
	$(GOCMD) vet ./...
.PHONY: vet

build: vet
	$(GOCMD) build
.PHONY:build
```

Passando por cada aspecto rapidamente:
Nas primeiras linhas do arquivo vemos a declaração de algumas variáveis que serão uteis para nos ajudar a chamar o comando nas regras definidas (rules). A variável GOCMD é especialmente interessante pois podemos deixar nosso Makefile agnóstico de versões do Go, uma vez que, com o suporte built-in da linguagem, deverias ter algo como go1.15.2 quando quisermos utilizar uma versão específica.

Na linha seguinte temos a declaração do .DEFAULT_GOAL que atribui qual vai ser a regra a ser rodada quando não passarmos nenhum argumento pro executável do `make`, ou seja, invocando somente `make` no diretório do projeto vai executar a regra “build”.

Nas próximas linhas temos as declarações de regras (rules), essas regras são os nomes que damos a sequencias de instruções shell que deverão ser executadas, alem disso, temos a declaração do .PHONY, uma instrução que dita que aquela regra em específico não produz um arquivo como output.

A estrutura de uma regra é a seguinte:

```makefile
nome_da_regra: dep1 dep2
	intructions
	instruction2

dep1: ...
```

Um importante aspecto que precisamos nos atentar é que o `make` é bem “chato” quando se trata de espaçamento antes das instruções shell, precisamos sempre usar *tab* ante de cada instrução, não podemos usar espaços (como usamos por padrão em alguns editores de texto, é bom verificar).

## OBS sobre o Makefile de exemplo

Em projetos de produção você vai querer utilizar o [golangci-lint](https://github.com/golangci/golangci-lint), linter que faz o uso de diversos linter por debaixo dos panos, de maneira otimizada.

Utilizamos linters e formatters de maneira separada em cada rule para poder exemplificar como ficaria um Makefile um pouco mais complexo.

## tl;dr

Em resumo, o uso do Makefile para projetos em Go representa uma abordagem eficaz e padronizada para automatizar tarefas relacionadas ao desenvolvimento, proporcionando uma estrutura organizada para execução de comandos essenciais. A flexibilidade oferecida pelo Makefile permite que desenvolvedores configurem regras específicas, como formatação, linting e compilação, de forma concisa e fácil de manter.
React Native Paypal integration
Published: 2024-02-19 20:18:58

I recently undertook the task of integrating PayPal into a React Native project. My initial approach followed the guides of [codecentric](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwjtnaKoiriEAxUAbfEDHf5tB7kQFnoECBoQAQ&url=https%3A%2F%2Fwww.codecentric.de%2Fwissens-hub%2Fblog%2Fpaypal-integration-with-react-native&usg=AOvVaw2AmS-MZcCHe5VhAH8GCgVO&opi=89978449) and [Logrocket](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwjtnaKoiriEAxUAbfEDHf5tB7kQFnoECBIQAQ&url=https%3A%2F%2Fblog.logrocket.com%2Fhow-to-integrate-paypal-payments-with-react-native%2F&usg=AOvVaw2rpUlHztJDKcMSPeH5Qv5n&opi=89978449), which relied on utilizing PayPal's Smart Payment Buttons within a React (web) application. However, I found this method to be somewhat suboptimal for two reasons.
 
Firstly, it needs an additional dependency - the React (web) application hosting PayPal's Smart Payment Buttons. This, coupled with the bridging setup required to facilitate communication between React Native Webview and the React Web deployment, adds unnecessary complexity.

Secondly, you start the payment Process with PayPal's Smart Payment Buttons, which directly communicate with the paypal api and in the end return you an order id, which you then need to report to your own API again. But what about cases, where users should not be able to start a new payment process, because they have already paid the product or because they already have a PayPal subscription (and need to upgrade). You have to handle these things in the frontend and ask your API before you show PayPal's Smart Payment Buttons to your users. Another unnecessary step that adds to application complexity.

Alternatively, we can streamline the process by leveraging PayPal's HATEOAS links. When [creating a PayPal order](https://developer.paypal.com/docs/api/orders/v2/#orders_create) via the PayPal REST API, PayPal returns a payer_action link. 

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

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

Similarly, when [creating a PayPal subscription](https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_create), an approve link is provided. 

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

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

By utilizing these links generated via our API and transmitting them to the React Native app, we can stick them into e.g. React Native Webview and the user can start the payment approval process.
Terraform Backends
Tags: terraform, backends, s3, local
Published: 2024-02-19 19:52:32

**Backend Configuration**
A backend defines where Terraform stores its state data files.

**Terraform Backend** is a configuration option in Terraform that allows you to store and manage the state of your infrastructure in a remote or local location. The backend is responsible for storing the state file and providing an interface for reading and writing state data.

**Available Backends**
1.local: The local backend stores state on the local filesystem

```
terraform {
  backend "local" {
    path = "relative/path/to/terraform.tfstate"
  }
}

```
create a file - backend.tf and add the below to save the state file locally

```
terraform {
  backend "local" {
    path = "C:/srinivas/terraform.tfstate"
  }
}

```
**2.S3** : 

- Stores the terraform state as a given key in a given bucket on Amazon S3. 
- This backend also supports state locking and consistency checking via Dynamo DB, which can be enabled by setting the dynamodb_table field to an existing DynamoDB table name. 
- A single DynamoDB table can be used to lock multiple remote state files. 
- create a file backend.tf and keep the below mentioned code

```
terraform {
  backend "s3" {
    bucket = "bucket_name"
    key    = "myproject/terraform.tfstate"
    region = "eu-west-1"
  }
}
```
Note : You need to replace  bucket_name to desired bucket and 
"myproject" to the desired folder and terraform.tfstate to be replaced with the desired state file name 

**3.azurerm** : Stores the state as a Blob with the given Key within the Blob Container within the [Blob Storage Account.
](https://learn.microsoft.com/en-us/azure/storage/common/storage-introduction)

When authenticating using the Azure CLI or a Service Principal (either with a Client Certificate or a Client Secret):

```
terraform {
  backend "azurerm" {
    resource_group_name  = "terraform-training"
    storage_account_name = "training2024"
    container_name       = "tfstate"
    key                  = "prod.terraform.tfstate"
  }
}

```
Note :  Replace resource group name ,storage account name , container name and key based on your requirement.
 
Some more backend types in terraform 

- remote
- consul
- cos
- gcs
- http
- kubernetes
- oss
- pg

Conclusion : Discussed about terraform backends and will further add more about other backends. Any needs one github samples let me know in the comments will share the github repo link

💬 If you enjoyed reading this blog post and found it informative, please take a moment to share your thoughts by leaving a review and liking it 😀 and follow me in [linkedin](https://www.linkedin.com/in/srinivasuluparanduru/)
Refactoring MSM GUI 2
Published: 2024-02-19 19:35:41

##**Creating a standard instance method**

- Standard practice for getting a specific piece of information from each database
```
class Character < ApplicationRecord

  def movie
    key = self.movie_id

    matching_set = Movie.where({ :id => key })

    the_one = matching_set.at(0)

    return the_one
  end

end
```
##**meta methods**

##**`belongs_to`**
```
belongs_to( :name_that_we_want, :class_name => "", :foreign_key => "" )
``` 
so for example, if you wanted to change the code above, you would turn the prompt given above into this 
```
belongs_to( :movie, :class_name => "Movie", :foreign_key => "movie_id"  )
```
since you are typically name all of these the same convention, you can even go further and take out the classname. 
```
belongs_to(:movie, :foreign_key => "movie_id" )

```
they decided to write this method if you omit the class name, they're going to guess that the class name matches the method name that you select, which is the case 99% of the time.

```
belongs_to(:movie)
```
##**`has_many`**
```
has_many( :name_that_we_want, :class_name => "", :foreign_key => "" )
``` 
producing a lot from this specific method so we want to use it for when we would we would be getting information back that comes in many, say characters, or comments, or movies. stuff like that. 
```
belongs_to( :name_that_we_want )
``` 
can also deduce it the same way like before if the class name matches the method name, then rails will assume that that is the name that you are going to use unless stated otherwise.  
##**example on how to use in rails console**

type these into rials console to understand where we can add on methods to meta methods. 

- `Character.joins(:movie).where("movies.year > 1994")`