teleren/devto huggingface dataset:
Chamadas HTTP com Java
Tags: aigenerated, java, beginners, programming
Published: 2022-12-22 01:18:44

Para fazer uma requisição HTTP em Java, você pode usar a classe **HttpURLConnection** do pacote **java.net**. Aqui está um exemplo de como enviar uma requisição GET simples e ler a resposta:

```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
  public static void main(String[] args) throws Exception {
    // Cria a URL da requisição
    URL url = new URL("http://www.example.com");

    // Cria a conexão HTTP
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // Define o método da requisição como GET
    connection.setRequestMethod("GET");

    // Envia a requisição e armazena a resposta
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
    }
    in.close();

    // Exibe a resposta
    System.out.println(response.toString());
  }
}
```

Você também pode adicionar cabeçalhos à sua requisição usando o método setRequestProperty. Por exemplo, para adicionar um cabeçalho "User-Agent" à sua requisição, você pode fazer o seguinte:

`connection.setRequestProperty("User-Agent", "My Java App");`

Para enviar dados com a sua requisição, como um corpo de solicitação em uma requisição POST, você pode usar os métodos **setDoOutput** e **getOutputStream**. Aqui está um exemplo de como enviar um corpo de solicitação em uma requisição POST:

```
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
  public static void main(String[] args) throws Exception {
    // Cria a URL da requisição
    URL url = new URL("http://www.example.com");

    // Cria a conexão HTTP
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // Define o método da requisição como POST
    connection.setRequestMethod("POST");

    // Adiciona o cabeçalho "Content-Type" com o tipo de conteúdo do corpo de solicitação
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // Ativa a opção de envio de dados com a requisição
    connection.setDoOutput(true);
```

_ Este post foi gerado pelo chatgpd e revisado por mim._
[Basico] Utilizando threads em Java
Tags: aigenerate, java, beginners, chatgpt
Published: 2022-12-22 01:08:23


O Java permite que você crie threads para que seus programas possam fazer mais de uma coisa ao mesmo tempo. Isso é especialmente útil quando você precisa realizar tarefas que levam muito tempo, como acessar a Internet ou ler arquivos grandes.

Para criar uma thread em Java, você deve criar uma classe que implemente a interface Runnable. Essa interface possui apenas um método: run(). Você deve implementar esse método para conter o código que a thread deve executar. Por exemplo:

`public class MinhaThread implements Runnable {
  public void run() {
    // código da thread aqui
  }
}
`
Para iniciar uma thread, você deve criar uma instância da classe Thread e passar sua instância de Runnable como argumento para o construtor da classe Thread. Em seguida, chame o método start() da classe Thread para iniciar a execução da thread. Por exemplo:

`MinhaThread minhaThread = new MinhaThread();
Thread thread = new Thread(minhaThread);
thread.start();
`
Você também pode criar uma thread anônima diretamente ao passar um novo Runnable como argumento para o construtor da classe Thread. Por exemplo:

`Thread thread = new Thread(new Runnable() {
  public void run() {
    // código da thread aqui
  }
});
thread.start();
`

Você também pode usar a classe Thread para criar uma thread extendendo-a e sobrescrevendo o método run(). Por exemplo:


`public class MinhaThread extends Thread {
  public void run() {
    // código da thread aqui
  }
}

MinhaThread minhaThread = new MinhaThread();
minhaThread.start();
`

Existem várias outras coisas que você pode fazer com threads, como alterar a prioridade da thread, aguardar a conclusão de uma thread ou interromper uma thread. 

Consulte a documentação da classe Thread para obter mais informações.

_Este post foi gerado automaticamente pelo chatGPT._
Configurando Open API no Spring Boot 3
Tags: java, spring, openapi, braziliandevs
Published: 2022-12-22 01:03:32

O Spring Boot 3 chegou e com diversas [novidades](https://www.baeldung.com/spring-boot-3-spring-6-new).

Se você já realizou a migração ou mesmo criou uma aplicação com a nova versão e precisa ou deseja inserir o OpenAPI para documentar suas APIs então vai uma dica importante.

Basta utilizar o [springdoc-openapi](https://springdoc.org/v2/), biblioteca que fornece suporte para OpenAPI nos projetos Spring.

Segue abaixo dependência necessária em projetos Maven ou Gradle:

**Maven**

```
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
      <version>2.0.2</version>
   </dependency>
```

**Gradle**

```
implementation group: 'org.springdoc', name: 'springdoc-openapi-starter-webmvc-ui', version: '2.0.2'
```

Observações importantes:

- _Versões inferiores a 2.0.0 da biblioteca não funcionam para Spring Boot 3_
- _A dependência acima está relacionada com uma aplicação usando Spring Web, e não Spring WebFlux_

Após adicionar a dependência, realize um teste rodando a aplicação e acessando o endereço do Swagger:

`http://localhost:8080/swagger-ui/index.html`

Exemplo: [Github](https://github.com/willyancaetano/spring-boot-with-open-api)

Refs:

- https://springdoc.org/v2/
- https://www.baeldung.com/spring-boot-3-spring-6-new
- https://spring.io/blog/2022/05/24/preparing-for-spring-boot-3-0
PowerShell install Ubuntu 20.04
Tags: powershell, linux, automation
Published: 2022-12-22 00:49:34

# Update the list of packages
sudo apt-get update
# Install pre-requisite packages.
sudo apt-get install -y wget apt-transport-https software-properties-common
# Download the Microsoft repository GPG keys
wget -q "https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/packages-microsoft-prod.deb"
# Register the Microsoft repository GPG keys
sudo dpkg -i packages-microsoft-prod.deb
# Update the list of packages after we added packages.microsoft.com
sudo apt-get update
# Install PowerShell
sudo apt-get install -y powershell
# Start PowerShell
pwsh
Ghost cms javascript
Published: 2022-12-22 00:43:23

install local 

masuk menu developer 

![Image ghost developer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nokcm51eso7vef8rqm7s.png)

![Image node 16 support](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/klukd3ggu4x37lek78lz.png)

![Image sudah versi 18](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hjkx1iceelpylabhamch.png)

kita harus berpindah dari 18 mundur ke 16 node version, cara nvm download installernya instal ok.

![Image petani kode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2xrqlg10hk3beg7kkdzz.png)

![Image nvm github](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oq77t2rfu3w4d022v262.png)

![Image nvm use v16](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zb8h09yy40yeqplbekjn.png)

```
mkdir ghost
npm install ghost-cli@latest -g
ghost install local
```

![Image websitenya jadi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xzw3kbb0gesxzgze7li1.png)

jalankan server dengan perintah 

```
ghost start
`http://localhost:2368/ghost`

ghost stop
ghost help
```
Setear rutas relativas en NextJS
Tags: nextjs, programming, typescript, frontend
Published: 2022-12-22 00:39:08

Hey! Todos en algún momento de nuestros proyectos de NextJS nos hemos encontrado con la situación de tener que importar algún componente que se debe usar.

Generalmente, importamos las rutas de ésta manera 👇🏾

![old method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r3gd517qq69cly1klban.png)

Y eso no está mal, sólo que los proyectos crecen y a medida que pasa ésto puede ser muy tedioso porque debemos movernos entre carpetas y tenemos que empezar a buscar para encontrar el que necesitamos. Esto se puede solucionar de manera muy fácil y acá te voy a mostrar cómo:

Dentro de la raíz del proyecto, vas al archivo `tsconfig.json` en caso de que estés usando Typescript, de lo contrario debes tener `jsconfig.json`

Una vez en éste archivo, tienes un objeto llamado `compilerOptions` en el que como primero, vas a agregar la opción `baseUrl` así👇🏾

![base](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kotjexueb4qs6tgaud63.png)

Luego, se agrega el atributo `paths` y en éste objeto las paths 👇🏾

![path](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/shto6nugr3arzmqmwhyl.png)

Se puede agregar cuantas rutas consideres necesarias, al final podrás tener algo como ésto👇🏾


![paths](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ll39qo3eeo6rspxqegy.png)

Al final, la estructura de tu proyecto en NextJS va a lucir mucho más limpia y deberías poder ver tu proyecto así


![next project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kesd21rd26wj64316fbb.png)



[www.viistorrr.com](https://www.viistorrr.com/)
[@viistorrr](https://twitter.com/viistorrr)
How to step by step learn cURL implementation in C language?
Published: 2022-12-22 00:32:29

I want to learn the implementation of `cURL` libraray in `C` language but I am unable to find the tutorial over the internet which will guide me from the beginner level moving to the advance. Hoping, you guys are somewhere near to the expert level or expert in this `cURL` programming using `C`, I want to know the best resource you got in your learning process. Saying this, I am not enforcing you to tell me that **you must do this coz it is only the way** as this may be beyond the rules. I am only asking for the platform that may be a book, website, pdf, etc. from where I can learn this library easily with `C` implementation. The resources I found focus on programs rather than the basics, flow of program, why and how the things being done. They does not tell that this should be done and this and this. 

So, as I mentioned earlier assuming you have already learned this library(or may be using and learning for a good healthy period of time) then it is obvious that you can suggest the beginners how to go and how to learn.
Es mala práctica renderizar JSX en React Hook?
Tags: react, bestpractice, hooks, javascript
Published: 2022-12-22 00:24:08

Seguramente mas de uno hemos caído en anti-patrones utilizando React Hooks, y es que React Hooks viene a resolver un problema de reutilización, donde su principal tarea es extraer la lógica de estado de un componente de tal forma que este puede ser probado y re-utilizado independientemente.

Sin embargo muchos desarrolladores lo utilizan para renderizar JSX, lo cual lo convierte en un anti-patrón. Veamos un ejemplo:


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

Hay varias razones por las cuales no tenemos que hacer lo del ejemplo:

Una función que devuelve JSX puede convertirse simplemente en un componente funcional con Hooks. Si lo escribimos como un componente nos ayudara de varias maneras:

- Brindar flexibilidad para transmitir propiedades y controlar el comportamiento fácilmente.

- También es más fácil memorizar componentes funcionales y evitar renderizaciones adicionales si nada ha cambiado. _(También puede hacerlo con Hooks personalizados, pero luego tendrá que hacer uso de useMemo)._

- Facilita la definición de una jerarquía clara de elementos.

---


> Ahora ya saben, renderizar JSX dentro de un Hook puede funcionar pero estarás haciendo uso de un anti-patrón 😉

[☕ Invitarme un café](https://www.buymeacoffee.com/manuelmorales)
Microservices to a Monolith, Making a case with Elixir Phoenix
Tags: elixir, phoenix, architecture, productivity
Published: 2022-12-22 00:20:52

Increasing productivity, affordability, scalability, and even less coding (gasp!) are the goals for any web application. Add on top unpredictable server traffic, then a solution you might consider is going serverless and throwing in one of those nifty NoSQL database solutions. Easy enough, but at what cost? You can unintentionally suffer vendor lock-in, deal with cold starts, architect your application improperly, and miscalculate cost structure at scale. But there is an even better solution you might want to consider, Elixir. Elixir and Phoenix can help developers solve all these technical challenges, allowing you to focus on the end-user experience.

Check out out my tech at Elixir Conf 2022 talking about how I made the switch.
{% embed https://www.youtube.com/watch?v=Tf3U3HPC1X8 %}
Safe casts in Unreal Engine
Tags: gamedev, unrealengine
Published: 2023-04-23 13:58:42

---
title: Safe casts in Unreal Engine
published: true
date: 2022-12-22 00:00:00 UTC
tags: gamedev, unrealengine
canonical_url: https://tinygame.dev/posts/Safe-casts-in-Unreal-Engine/
---

## Actor to Character

Say you have a pointer to an Actor and you'd like to cast this to a Character so you can call your function. Unreal has the Cast function template to do this safely:

```cpp
ACharacter* Character = Cast<ACharacter>(GetOwner());
if (!Character)
{
	return;
}
```

In the above case GetOwner() returns an AActor* which the Cast turns into a nullptr if it's not an ACharacter (or a child) object.

That is all.
A Developer Roadmap for High School Students: How to Get Started in Tech
Tags: beginners, career, codenewbie, computerscience
Published: 2022-12-21 23:38:06

## Overview

As a high school student myself, I understand the challenges and excitement of pursuing a career in tech. The tech industry is vast and constantly evolving, and it can be overwhelming to figure out where to focus your efforts.

## Roadmap

To help you get started, here is a roadmap of steps you can take to begin your journey as a developer:

### Learn the fundamentals

Before diving into specific technologies, it's important to build a strong foundation in computer science concepts. This includes topics such as algorithms, data structures, and programming languages. There are many online resources and courses available to help you learn these concepts, such as Codecademy or Khan Academy.

### Choose a programming language

Once you have a solid understanding of the fundamentals, it's time to start learning a specific programming language. There are many languages to choose from, each with its own strengths and use cases. Some popular options for beginners include Python, Java, or C++.

### Build projects

The best way to learn and improve as a developer is by building projects. This can be as simple as creating a simple program or app, or participating in online coding challenges and hackathons. Not only will building projects help you develop your skills, but it will also give you something to showcase on your resume and portfolio.

### Join a community

The tech community is full of supportive and knowledgeable people who are happy to help others learn and grow. Join online communities such as dev.to or Reddit's /r/learnprogramming to connect with other developers and get feedback on your projects.

### Consider internships or part-time work

As a high school student, you may not be able to commit to a full-time job in tech. However, internships and part-time positions can be a great way to gain valuable experience and make connections in the industry. Keep an eye out for opportunities in your area or consider reaching out to local tech companies to inquire about potential openings.

## Conclusion

Pursuing a career in tech as a high school student can be exciting and rewarding, but it also requires dedication and hard work. By following this roadmap and staying committed to your goals, you can set yourself up for success in the tech industry. Good luck!
Awesome JavaScript hacks
Tags: javascript, beginners, programming, tutorial
Published: 2022-12-21 23:30:27

In this post I will share **useful hacks for JavaScript**. These hacks reduce the code and will help you to run optimized code. So let’s start hacking!!!

![hacker](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y23namu1uyqwbflqtxpx.gif)

#**Use shortcuts for conditionals**
Javascript allows you to use certain shortcuts to make your code easier on the eyes. In some simple cases, you can use logical operators && an || instead of _if and else_.
**&& Operator Example:**
```js
//instead of
if(loggedIn) {
  console.log("Successfully logged in")
}

//use
loggedIn && console.log("Successfully logged in")
```

The || functions as an "or" clause. Now, using this operator is a bit trickier since it can prevent the application from executing. However, we can a condition to get around it.
**|| Operator Example:**

```js
//instead of 
if(users.name) {
  return users.name;
} else {
  return "Getting the users";
}

// use
return (users.name || "Getting the users");

```

#**Check if an object has values**
When you are working with multiple objects it gets difficult to keep track of which ones contain actual values and which you can delete.
Here is a quick hack on how to check if an object is empty or has value with Object.keys() function.

```js
Object.keys(objectName).length
// if it returns 0 it means the object is empty, otherwise it
 // displays the number of values.
```

#**Console Table**
This awesome hack will help you to convert your CSV format or dictionary format data into tabular form using the console.table() method.

```js
//console.table
const data = [
  {"city": "New York"},
  {"city": "Chicago"},
  {"city": "Los Angeles"},
]

console.table(data); // the result is a table below
```
![table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qwoq58ewqzwf11kcd74i.png)


#**Operator Typeof**
This simple hack will show you how you can use typeof() operator to check the type of any data in JS. You just need to pass the data or the variable as an argument of typeof().

```js
let v1 = "JavaScript";
let v2 = true;
let v3 = 123;
let v4 = null;

console.log(typeof v1) //---> string
console.log(typeof v2) //---> boolean
console.log(typeof v3) //---> number
console.log(typeof v4) //---> object
```

#**Shuffling array elements**
To shuffle the array's elements without using any external libraries like Lodash, just run this magic trick:

```js
const list = [1, 2, 3];
console.log(list.sort(function() {
   return Math.random() -0.5;
})); //---> [2, 1, 3]
```

That's it!!! **#HappyCoding**

Let me know in the comments section any other awesome JS hacks to add to the list :)


![cheers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1btrout83gpuc6apeu42.png)
Bursting the TDD Bubble
Tags: management, podcast, devops, programming
Published: 2022-12-21 22:37:12

Test-driven development has gone from buzzword to development dogma. Listen as Katerina Trajchevska CEO at Adeva explains when and where the use of TDD makes sense, tips for ignoring trolls on Twitter and how to craft the perfect MVP. 

This episode of Dev Interrupted is a YouTube Exclusive. This is the first YouTube Exclusive in our content catalog - but expect to see many more! 

We’re excited to launch YouTube Exclusives as a way to better connect with our growing audience. Behind the scenes we’ve been working hard to create even more high-quality content and interviews with the smartest engineers, leaders and entrepreneurs in tech. 

If you enjoyed this episode, please let us know in the comments.

{% youtube iOAYsyItE3o %}

## Episode Highlights Include:
* (0:46) Katerina's start in engineering
* (4:35) Minimum viable product - don't let perfect be the enemy of good
* (14:39) Common mistakes crafting MVP's
* (18:59) Budget restrictions and feature building
* (29:35) TDDs and Twitter

### Want to cut code-review time by up to 40%? Add estimated review time to pull requests automatically!
*gitStream is the free dev tool from LinearB that eliminates the No. 1 bottleneck in your team’s workflow: pull requests and code reviews. After reviewing the work of 2,000 dev teams, LinearB’s engineers and data scientists found that pickup times and code review were lasting 4 to 5 days longer than they should be.* 

*The good news is that they found these delays could be eliminated largely by adding estimated review time to pull requests!*

### Learn more about how gitStream is making coding better [HERE](https://linearb.io/blog/why-estimated-review-time-improves-pull-requests-and-reduces-cycle-time/?utm_source=Substack%2FMedium%2FDev.to&utm_medium=referral&utm_campaign=gitStream%20-%20Referral%20-%20Distribution%20Footers).

![Start using gitstream today!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xg1l6hxt134px501bf7d.png)
Welcome
Tags: go, programming, ddd, eventdriven
Published: 2022-12-21 22:24:04

Welcome to my blog!

Let me introduce myself. I'm a Senior Software Engineer. I'm a father of two wonderful kids and married to the most amazing woman on earth. I love outdoor activities like hiking and camping. I live in Argentina.

If you are interested in my software engineer background, you can look at my [linkedin](https://www.linkedin.com/in/federico-moya/). In short, I worked for some years for a sports betting company as a Senior Backend Engineer. Then I moved to a crypto exchange where I led a small team of Golang engineers. At the moment of writing this, I'm working as a Senior Golang Engineer for a company that offers a payments API to banks.

Blogging is something that has been on my TODO list for some years now, so I'm very excited that I'm finally doing it. I have several notes waiting to become in what I believe will be great articles.

So, what will this blog be about? Software Engineering Stuff. 
I will share thoughts, ideas, and concepts about topics like Event-Driven Architecture, Domain Driven Design, and  Hexagonal Architecture (or Ports&Adapters). You may also find some articles about automated end-to-end testing, cloud-native technologies, and who knows what. The sky is the limit, right? I'm a Golang fan so most of the code (examples and stuff like that) will be written in Go.

Enjoy it!
Integrating Astro, Netlify and Mantine
Tags: astro, mantineui, netlify, react
Published: 2022-12-21 22:22:23

Warning, don't bother using this stack as of Dec 21, 2022. 

In the spirit of cultivating more empathy in my life, I'm recreating my sister's virtual kitchen website using Astro for blazingly fast response times, Mantine UI for out-of-the-box components and Netlify for ease of distribution.

The steps from nothing to all components viewable in production should've been simple:

1. Create a new Astro project using Netlify's template wizard
2. Pull that repo down from Github and `npm install`
3. Follow instructions to install React on Astro's website and Mantine from their documentation

What started as a terrible first experience using Astro with a component library like Mantine, turned into a wild goose chase if they're compatible.

After stumbling upon [this Stackoverflow issue](https://stackoverflow.com/questions/73941829/how-to-integrate-mui-in-react-integrated-astro-site) and [this Github Issue](https://github.com/withastro/astro/issues/4432), it's concluded that Astro does not support CSS-in-Javascript for their component styling. BOO!