teleren/devto huggingface dataset:
Understanding Laravel Collections: `reject` vs. `map`
Tags: php, programming, development, laravel
Published: 2023-12-10 13:31:36

**Laravel Collections ** provide a powerful and expressive way to work with arrays or sets of data. In this post, we'll explore two fundamental functions: `reject` and `map`. While both are essential tools in your Laravel toolkit, they serve distinct purposes in data manipulation.

### The `reject` Function:

The `reject` function is your go-to tool for filtering out items from a collection based on a specified condition. It creates a new collection that excludes items for which the callback returns `true`. Let's look at an example:

```php
$collection = collect([1, 2, 3, 4, 5]);

$filtered = $collection->reject(function ($item) {
    return $item % 2 == 0; // Exclude even numbers
});

dd($filtered->all()); // Output: [1, 3, 5]
```

In this example, we use `reject` to create a new collection that excludes even numbers from the original collection.

### The `map` Function:

On the flip side, the `map` function is your ally when you need to transform each item in a collection using a callback. It creates a new collection with the results of applying the callback to each item. Here's an illustration:

```php
$collection = collect([1, 2, 3, 4, 5]);

$squared = $collection->map(function ($item) {
    return $item * $item; // Square each number
});

dd($squared->all()); // Output: [1, 4, 9, 16, 25]
```

In this example, we use `map` to create a new collection where each item is squared.

### Key Differences:

1. **Purpose:**
   - `reject`: Filters items based on a condition, excluding items that satisfy it.
   - `map`: Transforms items based on a callback, creating a new collection with the transformed values.

2. **Result:**
   - `reject`: Returns a new collection with items that did not meet the specified condition.
   - `map`: Returns a new collection with items transformed according to the provided callback.

3. **Callback Return Value:**
   - `reject`: Includes items for which the callback returns `false`.
   - `map`: Includes the results of applying the callback to each item.

In summary, while `reject` is your tool for excluding items, `map` is your friend for transforming them. Choose the right function based on your data manipulation needs.

Happy coding! 🚀
How difficult do you think it is to set up a youtube-like site?
Tags: tutorial, webdev, programming, ai
Published: 2023-12-10 13:16:04

I want to set up a site similar to Youtube. I don't have any coding knowledge, can I still do it? Can I do it by using multiple artificial intelligence, with the help of such sites and the people on these sites?. Most artificial intelligence I can do with the one I use now (Google bard), I think bard gives me the code for everything I want. Search boy, upload videos, create channels, like and dislike buttons, etc...
QH88
Published: 2023-12-10 13:15:12

QH88 DKM - Nhà cái trực tuyến số 1 Việt Nam, cung cấp đa dạng sảnh chơi chất lượng từ thể thao, casino, lô đề, bắn cá,... tham gia nhận ngay  
Website: https://qh88dkm.com/
Địa Chỉ: 24 Nguyễn Văn Trỗi, Tân Thịnh, Hòa Bình, Việt Nam
Map: https://maps.app.goo.gl/jjw7YT5YYmqeDnTM9 
Email: qh88dkm@gmail.com
Số Điện Thoại: 0865279542
Zipcode: ​36000
#qh88 #qh88casino #qh88dkm #nhacaiqh88
https://qh88dkm.com/huong-dan-qh88/
https://qh88dkm.com/dang-nhap-qh88/
https://qh88dkm.com/nap-tien-qh88/
https://qh88dkm.com/dang-ky-qh88/
https://qh88dkm.com/tai-app-qh88/
https://qh88dkm.com/rut-tien-qh88/
https://qh88dkm.com/khuyen-mai-qh88/
https://qh88dkm.com/casino-qh88/
https://qh88dkm.com/casino-qh88/
https://qh88dkm.com/xo-so-qh88/
https://qh88dkm.com/gioi-thieu-qh88/
https://qh88dkm.com/lien-he-qh88/
https://twitter.com/qh88dkm
https://www.pinterest.com/qh88dkm/
https://www.tumblr.com/qh88dkm
https://www.twitch.tv/qh88dkm/about
https://www.reddit.com/user/qh88dkm
https://www.youtube.com/@qh88dkm
https://500px.com/p/qh88dkm?view=photos
https://www.flickr.com/people/199668413@N05/
Transforming Pixels to Rem with Ease on PlexCalc.com!
Published: 2023-12-10 11:33:04

[plexcalc.com](https://plexcalc.com) is a valuable online resource that simplifies the process of converting pixel (px) values to rem units in CSS. This conversion is essential for creating responsive and scalable designs. 

By navigating to [plexcalc.com/px-to-rem-converter](http://localhost:4444/px-to-rem-converter), users can conveniently input their pixel measurements and swiftly obtain the equivalent values in rem units. 

This platform streamlines the often intricate calculations, providing designers and developers with an efficient way to ensure their websites or applications adapt seamlessly to various screen sizes. 

With [plexcalc.com](https://plexcalc.com), the conversion process becomes user-friendly, enabling individuals to effortlessly implement responsive design principles and enhance the overall user experience across different devices.
Starter template for Laravel + Nuxt.js development
Tags: opensource, nuxt, laravel, webdev
Published: 2023-12-10 12:37:06

The goal of the project is to create a template for development on Laravel and Nuxt with maximum API performance, ready-made authorization methods, image uploading with optimization and ready-made user roles.

## Features

 - [**Laravel 10**](https://laravel.com/docs/10.x) and [**Nuxt 3**](https://nuxt.com/)
 - [**Laravel Octane**](https://laravel.com/docs/10.x/octane) supercharges your application's performance by serving your application using high-powered application servers.
 - [**Laravel Telescope**](https://laravel.com/docs/10.x/telescope) provides insight into the requests coming into your application, exceptions, log entries, database queries, queued jobs, mail, notifications, cache operations, scheduled tasks, variable dumps, and more.
 - [**Laravel Sanctum**](https://laravel.com/docs/10.x/sanctum) Token-based authorization is compatible with **SSR** and **CSR**
 - [**Laravel Socialite**](https://laravel.com/docs/10.x/socialite) OAuth providers
 - [**Spatie Laravel Permissions**](https://spatie.be/docs/laravel-permission/v6/introduction) This package allows you to manage user permissions and roles in a database.
 - UI library [**Nuxt UI**](https://ui.nuxt.com/) based on [**TailwindCSS**](https://tailwindui.com/) and [**HeadlessUI**](https://headlessui.com/).
 - [**Pinia**](https://pinia.vuejs.org/ssr/nuxt.html) The intuitive store for Vue.js
 - Integrated pages: login, registration, password recovery, email confirmation, account information update, password change.
 - Temporary uploads with cropping and optimization of images.
 - [**ofetch**](https://github.com/unjs/ofetch) preset for working with Laravel API, which makes it possible
use $**fetch** without having to resort to custom $**fetch** wrappers.

{% embed https://github.com/k2so-dev/laravel-nuxt %}

## Requirements

 - PHP 8.2 / Node 20+
 - **Redis** is required for the [**Throttling with Redis**](https://laravel.com/docs/10.x/routing#throttling-with-redis) feature
 - [**Laravel Octane**](https://laravel.com/docs/10.x/octane) supports 2 operating modes: Swoole (php extension) or Roadrunner

## Installation
1. clone repository
2. `composer install`
3. `cp .env.example .env && php artisan key:generate && php artisan storage:link`
4. `php artisan migrate`
5. `php artisan db:seed`
6. `php artisan octane:install`
7. `php artisan octane:start --watch --port=8000 --host=127.0.0.1`
8. `yarn install`
9. `yarn dev`

> Nuxt port is set in package.json scripts via **cross-env**
Generic Survey Tool
Tags: api, learning, springboot, workflow
Published: 2023-12-10 12:36:26

I have an idea for a project for a generic survey tool. 
The app is said to be as intuitive as kobotoolbox but powerful like CSPRO.
That is to say, to be able to create projects, in these projects there are surveys that are made up of one or more forms (a set of questions).
I created a web application in Angular for the creation of forms and an application in ionic for data collection but I noticed a serious problem my api does not allow to take into account the data collected, facilitates the creation of conditional questions, the analysis of the data collected.
I'm looking for information and guidance on how I could create my api in springboot.
Connection io socket is not showing in console
Tags: node, webdev, express, socket
Published: 2023-12-10 12:36:00

import express from "express";
import { Server } from "socket.io";
import createServer from "node:http";
import cors from "cors";
import path from "path";

const app = express();
const port = process.env.PORT || 9000;
app.use(cors());
app.use(express.static(path.resolve("./public")));

const server = createServer.createServer(app);

const io = new Server(server);

io.on("connection", (socket) => {
  console.log("a user connected");
  socket.on("disconnect", () => {
    console.log("user disconnected");
  });
});

app.get("/", (req, res) => {
  res.sendFile("/server/public/index");
});

const startServer = () => {
  server.listen(port, () =>
    console.log(Server running on port http://localhost:${port})
  );
};

startServer();





Below is my code for html file






<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Chat App</title>
  </head>
  <body>
    <h1>Chatting...</h1>

    <script src="/socket.io/socket.io.js">
      const socket = io();
    </script>
  </body>
</html>





there is no error in console or anything like that and connection io socket is not showing in console
Grafana and Prometheus Setup on Ubuntu 22.04
Published: 2023-12-10 12:31:48


This tutorail will show you how you can create a Grafana Server and how to download Grafana agents and Prometheus to your servers.

### Start Prometheus Main server

1. `wget https://github.com/prometheus/prometheus/releases/download/v2.48.0/prometheus-2.48.0.linux-amd64.tar.gz`

2. `tar xvfz prometheus-*.tar.gz` 

3. `cd prometheus-*-amd64/`

4. `screen -S prometheus` => creates a new screen in you server
* Update prometheus yaml file:
`nano /prometheus-2.48.0.linux-amd64/prometheus.yml`

Example:
```
# my global config
global:
  scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
    - static_configs:
        - targets:
          # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: "prometheus"

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ["localhost:9090"]

  # configs for scraping node exporter metrics
  - job_name: node
    static_configs:
      - targets: ['localhost:9100']
```

Run `./prometheus --config.file=prometheus.yml`

- `http://public ip:9090/metrics` You should be able to see Prometheus metrics.

(Use Ctrl a+d = go to main screen)

## Download Node exporter:

6. `screen -S node-exporter`
7. `wget https://github.com/prometheus/node_exporter/releases/download/v1.5.0/node_exporter-1.5.0.linux-amd64.tar.gz `
8. `tar xvfz node_exporter-*.*-amd64.tar.gz `
9. `cd node_exporter-*.*-amd64 `
10. `./node_exporter`

- `http://<public ip>:9100/metrics` Prometheus metrics

(Ctrl a+d = Go to main screen)

11. Install Grafana
`sudo yum install -y https://dl.grafana.com/enterprise/release/grafana-enterprise-9.5.2-1.x86_64.rpm sudo systemctl start grafana-server.service`

This is your Grafana server: `http://public ip:3000/`

Setup your admin name and pass
- Username: admin
- Password: mypass

Note: `service grafana-server restart` = If you make any changes to the main server's configuration, be sure to run this command afterwards.

Resources:
* [prometheus.io/download/](https://prometheus.io/download/)
* [grafana.com/grafana/download](https://grafana.com/grafana/download
)

The upcoming tutorials will cover the topics of creating dashboards, alerting systems, and integrating with Slack.
Docker vs Podman
Tags: docker, podman, comparison, devops
Published: 2023-12-10 11:57:51

## Introduction
Containerization has become a popular way to test, build, and deploy applications in a streamlined manner. Docker has been the most popular container management engine on the market for a long time. However, as containerization became the norm in the DevOps world, competitors like Podman emerged. This article will compare two container management engines - Docker and Podman. It will also help you choose the right engine for your needs.

## Definitions
### Docker
Docker is a popular platform for creating, deploying, and managing containers. Docker containers allow developers to apply a system-agnostic approach to software deployment. Since Docker runs the same docker containers on any OS, containerized applications are cross-platform.

### Podman
Podman is a daemonless, rootless container engine developed by RedHat, designed as an alternative to Docker. The modular design allows Podman to use individual system components only when needed. Its rootless approach to container management allows containers to be run by non-root users.

## Comparison
### Daemon
Docker uses the Docker daemon, while Podman uses a daemonless architecture.

### Root
Docker runs containers as root only, while Podman runs containers as root and as non-root.

### Images
Docker can build container images, while Podman uses Buildah to build container images.

### Monolithic platform
Docker is a monolithic platform, while Podman is not.

### Docker-swarm
Docker-swarm is supported by Docker, but not by Podman.

### Docker-compose
Docker-compose is supported by both Docker and Podman.

### Architecture
Docker utilizes client-server architecture, while Podman manages containers using the fork-exec model.

### Operating System
Docker runs natively on Linux, macOS, and Windows, while Podman runs on Linux, macOS, and Windows (with WSL).

## Conclusion
In conclusion, both Docker and Podman have their own strengths and weaknesses. Docker is a more user-friendly platform with a larger ecosystem, while Podman is more lightweight and secure. If you are looking for a container management engine that is easy to use and has a large community, Docker is the way to go. However, if you are looking for a more secure and lightweight container management engine, Podman is the better choice.
PHP 8.3: a new major in town
Tags: php, programming
Published: 2023-12-10 11:25:36

PHP 8.3 is available with cool features you might not know yet.

## You have now a built-in JSON validator

```PHP
var_dump(json_validate('{ "test bad": { ')); // false
```

## You can now type constants

Pretty cool new feature:

```PHP
class MyClass
{
    public const string MY_TABLE = 'my_table'; 
}
```

Also note that the visibility of constants defined in interfaces is now checked (which wasn't the case before).

The following code will throw an error in PHP 8.3:

```PHP
interface MyInterface {
    public const HOLY_CONST = 'constantly constant';
}

class MyClass implements MyInterface {
    private const HOLY_CONST = 'constantly constant';
}
```

## PHP can now detect stack overflows

Thanks to new built-in directives `max_allowed_stack_size` and `reserved_stack_size` (INI setting), PHP can detect when the program is about to overflow the stack.

The idea is to throw an exception before the stack overflows instead of letting the program exhaust the memory. This is automatic but you can still set custom values if you know what you're doing.

While these new mechanisms look efficient, it cannot prevent all kinds of stack overflows. However, this RFC aims to improve the developer experience in most cases.

[Source: GitHub - php-src](https://github.com/php/php-src/pull/9104)

## You can catch more specific Date/Time exceptions

Catching Date/Time exceptions can be problematic is some cases, as they are not specific enough.

New exceptions such as `DateMalformedIntervalStringException` or `DateRangeError` will certainly improve the developer experience.

[Source: rfc - datetime-exceptions](https://wiki.php.net/rfc/datetime-exceptions)

## Improve readability with the `#[\Override]` attribute

> By adding the #[\Override] attribute to a method, PHP will ensure that a method with the same name exists in a parent class or in an implemented interface. Adding the attribute makes it clear that overriding a parent method is intentional and simplifies refactoring, because the removal of an overridden parent method will be detected.

[Source: PHP 8.3 release announcement](https://www.php.net/releases/8.3/en.php#override_attribute)

Nice!

## Wrap this up

This post is obviously not exhaustive, so please [check this page](https://www.php.net/releases/8.3/en.php) to get more details.
Read .CSV to get value
Tags: go, csv, basic, currency
Published: 2023-12-10 11:11:09

Read .CSV file by golang.

```
package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strings"
)

func main() {
	f, err := os.Open("teksfile.csv")

	if err != nil {
		log.Fatal(err)
	}
	
	line_list := []string{}
	
	defer f.Close()
	scanner := bufio.NewScanner(f)
	i := 1
	for scanner.Scan() {
		if i == 1 {
			i = 0
			continue
		}
		line := scanner.Text()
		line_list = append(line_list, line)
	}
	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}
	for _, ln := range line_list {
		row := strings.Split(ln, ":")
		debit 	:= row[0]
		credit 	:= row[1]
		db_acct := row[2]
		cr_acct := row[3]
		date 	:= row[4]

		fmt.Println(debit)
		fmt.Println(credit)
		fmt.Println(db_acct)
		fmt.Println(cr_acct)
		fmt.Println(date)
	}
}
```
Output:
```
10
-10
12345678
12345679
20231210
```
Zod - TypeScript-first schema declaration and validation library #6
Published: 2023-12-10 11:00:00

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/86gl8zo8s7kq4wax36kj.jpg)

✨ **Make Schemas Optional** ✨

We have a function called validateFormInput:

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

The values type is _unknown_, which is safe in this case because we only have a vague idea of the form's shape. In this case, we are collecting a _name_ and _phoneNumber_ as seen in the _Form_ object schema:

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

We have a failing test when a phone number is not included.

We need to update our _Form_ to pass the validation test whether or not a _phoneNumber_ string has been included.

By adding _.optional()_ onto the end of our _phoneNumber_ schema, our test will pass:

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

What we are saying here is that _name_ is a _string_, and _phoneNumber_ is either a _string_ or _undefined_.

We do not have to parse anything, making this an excellent way to set a property as optional.

---

I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:
- **Medium:** https://medium.com/@nhannguyendevjs/
- **Dev**: https://dev.to/nhannguyendevjs/
- **Hashnode**: [https://nhannguyen.hashnode.dev](https://nhannguyen.hashnode.dev/)/
- **Linkedin:** https://www.linkedin.com/in/nhannguyendevjs/
- **X (formerly Twitter)**: https://twitter.com/nhannguyendevjs/
57. Assignments now and dreams later (Day 55)
Published: 2023-12-10 10:59:45

Happy Sunday!

As the sun shone brightly in Sydney beckoning one and all to the beach, I found myself immersed in a world of assignments and deadlines at home.

Firstly, the relief of finally submitting an assignment was exhilarating! It was a victory worth celebrating, yet my mind couldn’t completely let go. Despite submitting well before the deadline, that familiar pang of anxiety lingered. The temptation to review and perfect my work nagged at me, but I knew I had to redirect my focus to the next task at hand.

Enter the third assignment, a venture into building a simple Python application of my choice. Exciting, yet demanding. It’s not merely about coding; there’s a comprehensive set of requirements— a Readme file, a PowerPoint presentation, a video walk-through, and the use of a project management platform to track progress. The clock is ticking; everything needs to come together neatly within the next two weeks.

Dreams of exploration and travel loomed in my thoughts. Completing this coding course (mid-2024!) will be a milestone, a step closer to a future where I can afford the luxury of time for wanderlust. Maybe then, once I’ve conquered these assignments and wrapped up this course, I’ll reward myself with local or international travel. A celebration, a culmination of hard work and dedication, and cherishing the rewards of persistence and determination.

So, adventure travel will have to wait a bit longer, but when the time comes, it will be an adventure worth the wait.

_Time: 9:35 PM. Early to bed today and get ready for a busy work week ahead_.
Settings for PowerShell to show the name of virtual environment (pipenv)
Tags: python, windows, pipenv
Published: 2023-12-10 10:54:43

+ Open PowerShell.

Open PowerShell with administrator permission.

+ Check PowerShell profile availability:

Check that you have PowerShell profile, run the command:
```powershell
Test-Path $profile
```

If you get False, than create profile by running the command:
```powershell
New-Item -Type File -Force $profile
```

+ Open the profile in editor:
```powershell
notepad $profile
```
    
+ Add the code to the profile file:

```powershell
function prompt {
        # Check,  if virtual environment is activated by using  pipenv shell
        if ($env:PIPENV_ACTIVE) {
            Write-Host "(pipenv) " -NoNewline -ForegroundColor Cyan
        }
        # Check,  if virtual environment is activated by using  venv
        elseif ($env:VENV_PROMPT -eq "activated") {
            Write-Host "(venv) " -NoNewline -ForegroundColor Cyan
        }

        "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "
    }
```
+ To change the current value of the PowerShell script launch policy, the Set-ExecutionPolicy cmdlet is used.
For example, let's allow local scripts to run:
```powershell
Set-ExecutionPolicy RemoteSigned
```
+ For further use, restart the terminal
+ Result:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bx0jx8s8t3xuc3lsgpv6.png)
How to Modernize Java Development Environment using VS Code and WSL2 to Improve Productivity
Tags: java, vscode, wsl, productivity
Published: 2023-12-10 10:30:51

Since 2007, I’ve been writing Java code in Eclipse. Eclipse is a pretty solid IDE for Java based development and I enjoy writing backend code in eclipse a lot. But now in modern development world we need to use several plugins to write code efficiently and it’s not limited to backend side code. We need to write code in frontend technologies too. I started feeling urge to switch from eclipse as two things really annoyed me. Slowness and frontend(Angular, React, Vue and many more) development support. Whenever I start eclipse it takes around 30 seconds to load workspace, another 30 seconds to load plugins, doing indexing and it blocks me from writing code. But frontend development support and speed isn’t everything. I've written full article about this on medium, use below link to read full article: [https://medium.com/@pravinpreneur/how-to-modernize-java-development-environment-using-vs-code-and-wsl2-to-improve-productivity-1c9681390170]