teleren/devto huggingface dataset:
TDD CRUD API
Tags: laravel, php, tutorial, programming
Published: 2023-01-11 15:46:14

CRUD refers to four basic functions: Create, Read, Update, Delete. It is the operations performed in the database.

Test Driven Development (TDD) is a software development approach where test cases are developed to specify and validate what the code will do. In simple terms, test cases for each feature are built and tested first and if the test fails, new code is written to pass the test and make the code simple and bug-free.

<u>this tutorial was made with laravel 9
</u>

## Now let's program
**First test - Create User**
*api.php*

```php
Route::post('/users/create', [UserController::class, 'create']);
```
⚠️ **IMPORTANT**: insert in the controller method a return response like this:

```php
return response()->json([
      'status' => true,
      'message' => 'User Created Successfully',
          
], 200);
```
and now test!

```php
public function testCreateUser(){
      $response = $this->postJson('/api/users/create', ['name' => 'Sally', 'surname' => 'Willi', 'email' => 's@gmail.com', 'password' => '12345678']);
      $response->assertStatus(200)->assertJson([
            'message' => 'User Created Successfully',
      ]);
}
```
if I want to run only this test just run this command: 

```bash
./vendor/bin/phpunit --filter testCreateUser tests/Unit/UserControllerTest.php

```
---
**Second test - Show User**

```php
public function testShowUser(){
      $id = User::all()->first()['id'];
      $response = $this->get("/api/users/retrieve/{$id}");        
      $response->assertStatus(200)->assertJson([
            'role' => 'user',
      ]);
}
```
if I want to run only this test just run this command: 

```bash
./vendor/bin/phpunit --filter testShowUser tests/Unit/UserControllerTest.php

```
---
**Third test - Update User**

```php
public function testUpdateUser(){
      $id = User::all()->first()['id'];

      $response = $this->put("/api/users/{$id}", ['name' => 'Homer', 'surname' => 'Simpson', 'email' => 'homerS11@gmail.com', 'password' => '12345678']);
      $response->assertStatus(200)->assertJson([
            'message' => 'User Update Successfully',
      ]);
}
```
if I want to run only this test just run this command: 

```bash
./vendor/bin/phpunit --filter testUpdateUser tests/Unit/UserControllerTest.php

```
---
**Last test - Delete User**

```php
public function testUserDelete(){
      $id = User::all()->first()['id'];
      $response = $this->delete("/api/users/{$id}");
      $response->assertStatus(200)->assertJson([
            'message' => 'User Deleting Successfully',
      ]);
}
```
if I want to run only this test just run this command: 
```bash
./vendor/bin/phpunit --filter testUserDelete tests/Unit/UserControllerTest.php

```
### That's it 
I hope this tutorial helps you in your Laravel experience.
Upgrade Next 12 to 13 - Github build Deploy Next.js app - The root value has an unexpected property, target,
Tags: nextjs, nextjs13
Published: 2023-01-11 15:42:12

Github build failed: - 
name: Deploy Next.js app 
run: npx serverless@2.72.2

aNA error: Error: Command failed with exit code 1: node_modules/.bin/next build warn - Invalid next.config.js options detected:

The root value has an unexpected property, target, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, modularizeImports, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, skipMiddlewareUrlNormalize, skipTrailingSlashRedirect, staticPageGenerationTimeout, swcMinify, trailingSlash, transpilePackages, typescript, useFileSystemPublicRoutes, webpack).

```
/** @type {import('next').NextConfig} */
const headers = async () => {
    return [
        {
            source: '/:path*',
            headers: [
                {
                    key: 'X-Content-Type-Options',
                    value: 'nosniff'
                },
                {
                    key: 'X-Frame-Options',
                    value: 'SAMEORIGIN'
                },

            ]
        }
    ]

}
const nextConfig = {
reactStrictMode: true,
output: 'standalone',
transpilePackages: \['@ionic/react', '@ionic/core', '@stencil/core', 'ionicons'\],
async redirects() {
return \[
 {
    source: '/',
    destination: '/language',
    permanent: true
 }
\]
},
headers,
  images: {
    domains: \['media.graphcms.com', 'res.cloudinary.com', 
   'images.unsplash.com', 'media.graphassets.com'\],
  unoptimized: true,
}
};
module.exports = nextConfig;
```

Can anyone advice how to resolve this issue next 13? trying to fix/rewrite all day and no luck... cant find Target in anything. In case, local terminal: npm run build is passed.

Thank you in advance.
What is the ideal session timeout?
Tags: security, webdev, discuss
Published: 2023-01-11 15:31:29

To make applications that rely on user sessions secure, it is necessary to define a session timeout.
The timeout defines the validity of a user session and after the set amount of time without activity, the session will expire and the user needs to authenticate himself again.

There is always the clinch between convenience for the user to not need to login too often and strict security from the code side to keep it as short as possible.

I've seen anything throughout my carreer, from 4 hours up to 30 days.

**What is the ideal session timeout for you and why?**
Meu terminal boostado com ZSH
Tags: braziliandevs, productivity, zsh
Published: 2023-01-11 15:27:39

Já faz alguns anos que eu curto usar o [zsh](https://www.zsh.org/) em conjunto com [ohmyzsh](https://github.com/ohmyzsh/ohmyzsh). Basicamente o **ohmyzsh** transformou toda a minha experiência ao usar um terminal.

![Imagem do terminal do ZSH](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7u39ovzgq6t640wz1tc3.png)

Recentemente eu troquei meu PC e precisei configurar tudo novamente, então aproveitei para trazer pra vocês **plugins essenciais** que eu não consigo ficar sem e melhoram muito minha produtividade.

---

## 1. zsh-autosuggestions

![Exemplo do terminal gerando uma sugestão para autocomplete](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o4x3jww78nsap0k52837.png)

Esse plugin completa os comandos para você. Sinceramente, como eu usava o terminal sem isso antes?

🔗 [https://github.com/zsh-users/zsh-autosuggestions](https://github.com/zsh-users/zsh-autosuggestions)

---

## 2. zsh-syntax-highlighting

![Exemplo de highlight](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2z36d7hk32r5sb0jbri5.png)

Com esse plugin você tem o highlight do comando digitado, facilitando a leitura.

Ele também te ajuda a **identificar se você digitou um comando errado** enquanto você está digitando ele.

🔗 [https://github.com/zsh-users/zsh-syntax-highlighting](https://github.com/zsh-users/zsh-syntax-highlighting)

---

## 3. bgnotify

![Notificação ativa pelo plugin](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bxp2wrhbvehopbn9ht1x.png)

Sabe quando você coloca um comando para rodar e ele é muito demorado (tipo um `npm install`), então você só deixa de lado o terminal e vai fazer outras coisas? 

Esse plugin te avisa quando o comando terminar de rodar!

🔗 [https://github.com/t413/zsh-background-notify](https://github.com/t413/zsh-background-notify)

---

## 4. git-prompt

![Exemplo de ícones com informações sobre o estado da branch atual](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/79t4lk42ndt3y8mgn28l.png)

Você é do tipo de pessoa que fica dando `git status` toda hora? Com esse plugin, isso já não é mais necessário.

Você consegue ver como está a situação da sua branch atual com vários ícones indicativos. 

🔗 [https://github.com/olivierverdier/zsh-git-prompt](https://github.com/olivierverdier/zsh-git-prompt)

---

Existem outros vários plugins para o ZSH, que vocês podem conferir nessa [lista de plugins](https://github.com/unixorn/awesome-zsh-plugins).

O que acharam da lista? Se tiverem mais plugins bacanas para sugerir, deixem aqui nos comentários! 💕
We're on dotnet.social
Tags: meta, dotnet, fediverse
Published: 2023-01-11 15:26:38

The best of DotNet content on DEV Community is now available via Toot 🦣

We've syndicated our [@TheDotNetDev Twitter feed](https://www.twitter.com/thedotnetdev) with [@devcommunity@dotnet.social](https://dotnet.social/@devcommunity) using [moa.party](moa.party).

{% embed https://dotnet.social/@devcommunity %}

Follow us there from anywhere in the Fediverse. Happy .NETing!
Setting Telescope Dev Environment
Tags: telescope, senecaosd700, opensource
Published: 2023-01-11 15:26:32

Telescope is Seneca open source project that I need to maintain for next four months with other students in the class. The current version is `3.1.3`. We will update and add more features to release `4.0.0` by the end of April. 

I set up local dev environment as I contributed last year. But it was only front-end due to some issues with backend setup. My change didn't involve backend. So it's good time for me to do the full setup. 

First I need to install pre-requisite tools such as `Node.js`, `pnpm`, `Docker` which I already have on my machine. Then I installed packages again with `pnpm install` because there might be some changes in dependencies. `Telescope` uses many dependencies built from `Docker`. So I ran `Docker` before next step. To avoid the issues from `Docker` using cached data, it's recommended to run `docker system prune -af --volumes`. 

After clearing old `Docker` data, I could simply run `pnpm services:start` to run both frontend and backend on my machine. If I need a different environment setup such as staging or production, I need to copy and paste a config file. But I don't need it now. It uses default config file which is `env.development`. Also I can run `docker-compose --env-file config/env.development up --build -d`. This is equivalent to `pnpm services:start`. 

Unlike the last setup backend setup, it seems everything is working except for one that I can't search anything. I'm getting a `blocked by CORS policy` with 400. I usually got this response when something was wrong. So I asked `Telescope community` in Slack. I found that I still needed to seed database. To do this, I need to copy `./src/db/env.example` to root and run `pnpm db:init`. It migrates new changes to database and populates data. I have search results now!

After I struggled, some students also had similar problems. I saw one student found a root cause and raised a PR. With this help, I set up my environment much more easily. Yes, it is very important to keep the documents up-to-date all the time.
A Beginner - I'm New Here 👋👋
Published: 2023-01-11 15:14:26

Hi guys. My name is **Inioluwa Adesina**. I'm 16 years old. I just joined this wonderful community of developers today and I'm looking forward to learning a lot from and with you all. I am currently learning web development and I just finished learning HTML. I've started learning CSS already.
.dotisto – Blazing Fast Domain Search with 1200+ TLDs from Around the World
Tags: webdev, productivity, news, domains
Published: 2023-01-11 15:12:52

I have launched a **free, independent, and super-fast search engine for domain names** with some interesting features.

It is called **.dotisto**.

How a domain search engine works, everyone knows. You type in a name and see if it's free or busy. Such search engines are provided by every domain registrar. The only thing is that all these search engines are.... lousy.

I've been on the Internet for a while now, and more than once I was looking for a name for a new site/service/shop/blog or project. Finding a good address is not an easy art. A lot of things bothered me in this kind of search engine on hosting sites. Many things were missing. So I made my own tool. For myself and for others.

**What makes .dotisto different from other domain search engines?**
👉 .dotisto is **EXTREMELY FAST**. In less than 200 ms you will get information on whether the domain is registered or free with an efficiency of ~99.975%. And that's still in the process of typing! Another few hundred milliseconds and hints of other extensions and domains are displayed.
👉 The search engine is **INDEPENDENT** of registrars or hosts, so it is not limited by any particular set of domain extensions (TLDs).
👉 Thanks to the above, **there are 1200+ domain extensions** in .dotisto from all over the world - including various very exotic and hard-to-find (but very interesting :))
👉 All domains are divided into **27 THEMATIC CATEGORIES**, so you can easily search for your perfect name among interesting TLDs
👉 With each search, **smart domain suggestions** are also checked. And if they are available for registration, they are displayed and proposed (all the time in <1 sec). Example: when searching for the domain "bestwebcam.com", the tool also checks the domains "bestweb.cam", "best.webcam" and "bestwebc.am" (yes, there are such extensions 😉)
👉 All this while **respecting PRIVACY**. The search engine does not save or forward anywhere what domains are checked/free/registered.

In addition, .dotisto also has several tools that allow you to verify a domain before you buy it to avoid an unpleasant and painful mishap:
⚒️ **DISPLAY the domain name out loud** (through a speech synthesizer), so we can check how the domain sounds if we were to dictate it over the phone or in an advertisement
⚒️ **Easily search GOOGLE** to see if any other company is already operating under a given name
⚒️ **Checking DOMAIN HISTORY**, i.e. what was previously at that address (very important for SEO and reputation!)
⚒️ **Check if the name is not a REGISTERED TRADEMARK** in Patent Offices around the world (the trademark owner could sue us and, among other things, take the domain away from us)
⚒️ Copying the domain to the clipboard, checking information about the registered domain in WHOIS, 1-click check of what kind of website is at a given address, and other small conveniences.

Search engine available free of charge, without ads or interruptions at [https://dotisto.com](https://dotisto.com) or shorter at [dotis.to](https://dotis.to)
How Kubernetes is benefiting edge devices
Tags: webdev, beginners, programming, devops
Published: 2023-01-11 15:09:23

As the network quickly grows, a manual approach to deploying, managing, and maintaining devices will be challenging and time-consuming. This is why I've been trying to introduce Kubernetes to the IoT world. Here are the benefits it brings:

- Scalability: The ability to scale is the key concern for many IoT solutions. The ability to serve more devices and handle terabytes of data in real-time requires an infrastructure that can independently scale horizontally or vertically. 
- High availability: Edge devices need to be available and reliable for IoT solutions that handle critical business tasks. 
- Efficient use of resources: Kubernetes lowers the cost of hosting IoT applications due to its efficient use of resources. Also, it provides an abstraction layer on top of hosted virtual machines. 
- Deployment to the IoT edge: A key IoT challenge is deploying software updates to edge devices without interrupting services. Kubernetes can run microservices that progressively roll out changes to services. Kubernetes deployments roll out pod-version updates with a rolling update strategy. 
Enabling DevOps for IoT: IoT solutions must be updated seamlessly with zero downtime to end-users to meet market demands. Kubernetes helps development teams quickly verify, roll out, and deploy changes to IoT services. Also, Kubernetes is supported on different cloud providers, such as AWS, Google Cloud, and Azure. It is even supported as on-premise software. Hence, it will be easy to migrate to any cloud service in the future.
Because of these features, Kubernetes has become one of the most common orchestration tools to be deployed and managed.

Shifu is a Kubernetes native, production-grade, protocol & vendor agnostic IoT development framework. You can develope your application while managing your devices, spare the need for maintaining an additional O&M infrastructure. Check https://github.com/Edgenesis/shifu for more details!
Rush Custom Boxes
Tags: customboxes, packagingboxes, printedbox, packagingsolutions
Published: 2023-01-11 14:53:56

[Rush custom boxes](https://www.rushcustomboxes.com/) are among the top choices on the market to offer the best quality packaging for your branded products. We delight our customers with creative and innovative packaging ideas that add a striking look to their products. Our skilled designers guide customers in the most effective way to create the most attractive packaging designs that enhance the aesthetics of their items. In this process, we fully consider the ideas offered by our customers. Our product range includes various shapes and sizes of packaging boxes that can be used in multiple industries, such as food, cosmetics, retail, and more. We use high-quality cardboard and corrugated materials to make durable and reliable product boxes. In addition, the latest printing techniques are used to improve their appearance. We offer our customers the most affordable prices for our best quality products.
Code Refactoring
Tags: refactorit, codenewbie, codereview, beginners
Published: 2023-01-11 14:53:24

When have you found it absolutely necessary to implement code refactoring? 

Add to that list in the comment section 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdr7j2itoo9cfilkp1bc.png)
Idempotent Close in Go
Tags: go, programming
Published: 2023-01-11 14:48:48

_Idempotence_ is when a repeated call to an operation on an object does not result in changes or errors. Idempotence is a handy development tool.

Let's see how idempotence helps to free the occupied resources safely.

## Idempotent Close

Suppose we have a gate:

```go
type Gate struct{
    // internal state
    // ...
}
```

The `NewGate()` constructor opens the gate, acquires some system resources, and returns an instance of the `Gate`.

```go
g := NewGate()
```

In the end, we must release the occupied resources:

```go
func (g *Gate) Close() error {
    // free acquired resources
    // ...
    return nil
}

g := NewGate()
defer g.Close()
// do stuff
// ...
```

Problems arise when in some branch of the code, we want to close the gate explicitly:

```go
g := NewGate()
defer g.Close()

err := checkSomething()
if err != nil {
    g.Close()
    // do something else
    // ...
    return
}

// do more stuff
// ...
```

The first `Close()` will work, but the second (via `defer`) will break because the resources have already been released.

The solution is to make `Close()` idempotent so that repeated calls do nothing if the gate is already closed:

```go
type Gate struct{
    closed bool
    // internal state
    // ...
}

func (g *Gate) Close() error {
    if g.closed {
        return nil
    }
    // free acquired resources
    // ...
    g.closed = true
    return nil
}
```

[playground](https://go.dev/play/p/LFEThpm1nTs)

Now we can call `Close()` repeatedly without any problems. Until we try to close the gate from different goroutines — then everything will fall apart.

## Idempotency in a concurrent environment

We have made the gate closing idempotent — safe for repeated calls:

```go
func (g *Gate) Close() error {
    if g.closed {
        return nil
    }
    // free acquired resources
    // ...
    g.closed = true
    return nil
}
```

But if several goroutines use the same `Gate` instance, a simultaneous call to `Close()` will lead to races — a concurrent modification of the `closed` field. We don't want this.

We have to protect the `closed` field access with a mutex:

```go
type Gate struct {
    mu     sync.Mutex
    closed bool
    // internal state
    // ...
}

func (g *Gate) Close() error {
    g.mu.Lock()

    if g.closed {
        g.mu.Unlock()
        return nil
    }
    // free acquired resources
    // ...

    g.closed = true
    g.mu.Unlock()
    return nil
}
```

[playground](https://go.dev/play/p/i3pFy362YEi)

The mutex ensures that only a single goroutine executes the code between `Lock()` and `Unlock()` at any given time.

Now multiple calls to `Close()` work correctly in a concurrent environment.

That's it!
AI Rubber Ducky
Published: 2023-01-11 14:45:54

---
title: AI Rubber Ducky
published: true
description: 
tags: 
cover_image: https://uberduck.ai/dalle-duck-robot.png
# Use a ratio of 100:42 for best results.
# published_at: 2023-01-11 14:35 +0000
---

ChatGPT has taken the world by storm. There are a ton of use cases I have been playing with. The most profound of those being using chatgpt as a 'rubber ducky' feeding it code and an error in an attempt to solve the issue at hand. Unsure of which package has the needed functionality? ChatGPT may not give you an answer correctly the fist time, but given correct prompts and guidance can be a tool to rapidly speed up you development debugging.

When taking a piece of code to chatgpt one must be aware of the most efficient prompt templates that will generate the response we want, and not unrelated facts or formats. You can think of a prompt being the question we ask the AI. 

Using code examples are a great way to give context to chatGPT about your current problem. Taking a `main.go` as the first prompt field, then on a newline, informing chatGPT exactly what we wish to do with that `main.go`.

Our prompt template can be thought of like this.

{Code example ie. main.go} {The request for new functionality specifying to edit the existing code and add a new function} {any specific guidance that may be needed}

To elaborate on the guidance, chatGPT may think something is a part of a package in Golang, when in fact is not. To give an example, I was asking chatGPT to explain how one might use a go function to load an executable into memory (more on AI runes later).

ChatGPT would get confused, and think packages that must be called via sys call.Syscall() could be called via the windows package. By looking at the original response we can add guidance that Windows does not contain the package it's looking for. More often than not, this would fix the response from ChatGPT to work as expected.

This is just a short way to use prompt templates to rubber ducky with chatGPT. I hope this can save you some StackExchange searches :)