teleren/devto huggingface dataset:
How to Stop FilamentPHP Actions On Certain Conditions
Tags: laravel, php
Published: 2023-08-06 00:58:30

In some cases, FilamentPHP processes need to be stopped based on certain conditions. To achieve this, we can use the `cancel() `method of an action. This article demonstrates how to use `cancel()` effectively and includes notifications to provide meaningful feedback to users.

You can also use `halt()` but halt does not close modals.

Example Scenario:
Consider a scenario where we want to prevent force-deleting a user if they have active orders. We will use a ForceDeleteBulkAction and its before callback to perform the necessary checks and notify the user accordingly.


```php
Tables\Actions\ForceDeleteBulkAction::make()
    ->before(
        function ($records, Tables\Actions\ForceDeleteBulkAction $action) {
            // code goes here
        }
    )
```

Checking for Active Orders and Canceling the Process:
To check for active orders, query the relevant data and cancel the process if any orders are found. We can achieve this as follows:

```diff
Tables\Actions\ForceDeleteBulkAction::make()
    ->before(
        function ($records, Tables\Actions\ForceDeleteBulkAction $action) {
+            $ids = $records->pluck('id')->toArray();
+            $exists = Order::whereIn('user_id', $ids)->exists();
+            if ($exists) {
+                $action->cancel();
+            }
        }
    )
```

Cancel does not show notification about why process canceled. Use [Notification](https://filamentphp.com/docs/2.x/notifications/sending-notifications) documentation.

```diff
+use Filament\Notifications\Notification;

Tables\Actions\ForceDeleteBulkAction::make()
    ->before(
        function ($records, Tables\Actions\ForceDeleteBulkAction $action) {
            $ids = $record->orders()->pluck('id')->toArray();
            $exists = Order::whereIn('user_id', $ids)->exists();
            if ($exists) {
+                Notification::make()
+                    ->title('Errors!')
+                    ->body("You can't force delete users because someone has orders.")
+                    ->status('danger')
+                    ->send();
                $action->cancel();
           }
        }
    )

```

By using the cancel() method in FilamentPHP, we can effectively halt an action based on specific conditions. In the example provided, we prevent force-deleting users with active orders and enhance the user experience by sending a notification explaining the reason for the process cancellation. This approach ensures that users are informed about the constraints and can take appropriate actions accordingly.
Learn PostgreSQL! - How to use String matching from multiple columns?
Published: 2023-08-06 00:07:35

## Introduction
In the vast landscape of data management, PostgreSQL stands as a powerful and versatile open-source relational database system. As data enthusiasts, we are often faced with complex challenges in extracting valuable information from our databases efficiently. One such common task is searching for a specific word that may occur as a standalone word or as part of a larger word across multiple columns. In this comprehensive guide, we will explore the most scalable and effective solution to achieve this in PostgreSQL without resorting to separate LIKE statements for each column.

Similarly, I was working on an extensive database with tons of data. I faced a similar problem where I had to look up for occurrence of "yes" in not one but six columns at once. I needed to design a query that will return rows if any of the columns contained the word "yes". 

## Naive Approach
The most basic approach that I thought about first was to use separate `LIKE` statement for all the columns in my `WHERE` clause. 
Although applicable and suitable for small sets of data, this approach can be tiresome and exhausting on larger tables both for the computer and developer. So what can be the smarter approach? 

## A Better Approach
Use concatenations and functional regex matching! I knew about concatenation but the shorter syntax for Regex matching I discovered in PostgreSQL docs was entirely new to me. 

How did this work? Let me show an example with code! 

`SELECT *
FROM my_table
WHERE CONCAT_WS(' ', col1, col2, col3, col4, col5, col6) ~ '\myes\b';
`
In this query:

`CONCAT_WS(' ', col1, col2, col3, col4, col5, col6)` combines all six columns into a single string, using a space as the separator between the values.

The `~` operator is used to apply a regular expression pattern on the concatenated string.

`'\myes\b'` is the regular expression pattern. The `\m` and `\b` are word boundary anchors that ensure that "yes" is matched as a whole word and not as a part of a larger word. So, it will match "yes" as a standalone word and not as part of another word like "yesterday".

This approach is scalable as it allows you to easily search for the word "yes" in any number of columns without having to write separate LIKE statements for each column. It effectively treats all six columns as one combined column for the purpose of the search.

You can look up the more refined and shorthand syntax for Regex matching in PostgreSQL at [PostgreSQL Docs](https://www.postgresql.org/docs/current/functions-matching.html)
:(colons), =(equals) and ;(semicolons) in Javascript (Bite-size article)
Tags: beginners, javascript
Published: 2023-08-05 23:32:34

#Intro

Today I am writing a short article about **:(colons)**, **=(equals)** and **;(semicolons)** in Javascript.

When you use Javascript, you may often use those three operators.

I know how to use them in the codes, but when I'm asked to explain their exact definition, I found I can't explain them clearly.

So I will write about these operators today. For many of you may feel it’s basic, but please take a look if you are interested in :)


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



#: (colons)

**Colons** are mainly used to <u>define the properties of an object</u>. JavaScript objects are composed of key/value pairs, with a colon between each key and value.

```js
// example

const person = {
  name: "Terry",
  age: 30,
  occupation: "Engineer"
};

```


#= (equals)
**Equals** are mainly used to <u>assign a value to a variable</u>. When a value is assigned to a variable, the variable is assigned the value specified on the right side.

```js
// example

let x = 150;
let y = "Hey Guys!";

```

#; (semicolons)
**Semicolons** are used in JavaScript to <u>indicate the end of statement</u>. 

```js
// example

let x = 10;
let y = 20;

```

##Tip: Omit The Semicolon
In JavaScript, a semicolon is generally used to separate statements, but <u>it is also possible to omit the semicolon</u>. But you should use this way carefully because the statement will be automatically ended if you omitting the semicolon.

Normally, using a semicolon to explicitly indicate the end of a statement is recommended to <u>improve code readability</u>. However, in recent JavaScript, semicolons are often omitted in some cases. But anyways, as you write your code, you must be careful to avoid unintended behavior.


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


#Outro
The topic today is a part of basic knowledges in JS, but I enjoyed to write this article and glad that I got a chance to study about it!

Thank you for reading :)
Git Upstream Commands Guide
Tags: git
Published: 2023-08-05 23:14:32

---
title: Git Upstream Commands Guide 
published: true
description: description
tags: Git
cover_image: 
---
Git's upstream refers to a default remote branch for a given branch. Setting an upstream makes it easier to synchronize and compare changes between the branch and its corresponding remote branch.

## Setting Up Upstream

```bash
git remote add upstream <original-repository-url>
```

This command configures the original repository as a new remote called "upstream".

## Configuring an Upstream for a Branch

To set the upstream for a branch:

```bash
git branch --set-upstream-to=<remote>/<branch> <local-branch>
```

For instance, to set the `main` branch of the `origin` remote as the upstream for the local `feature` branch:

```bash
git branch --set-upstream-to=origin/main feature
```

## Checking Upstreams

To view all local branches and their respective upstreams:

```bash
git branch -vv
```

## Pushing to Upstream

To push changes from the current branch to its upstream:

```bash
git push
```

## Pulling from Upstream

To pull changes from the upstream to the current branch:

```bash
git pull
```

By setting up upstreams, you no longer need to specify the remote name and branch name each time you run `git push` or `git pull`. This enhances the efficiency of your workflow.
Unleashing the 🦄 Power of checkValidity() Method: Keeping Web Forms in Check! 😎
Tags: javascript, webdev, beginners
Published: 2023-08-05 23:07:01

## Introduction

Hey there, fellow web wizards! 🧙‍♂️ Let's embark on a magical journey into the whimsical world of form validation! 🌈✨ Buckle up, because we've got the ultimate spell up our sleeves - the checkValidity() method! 🧙‍♀️

**What is the checkValidity() Method?: 🤔**

Behold! The checkValidity() method is like a wizard's wand for your HTML forms! 🪄 With a swish and flick, it works its magic on each input field, ensuring they all follow the right incantations. 🧙‍♂️💫

**A Magical Boolean Result: 🧙‍♀️**
Abracadabra! Once the checkValidity() charm is cast, it conjures up a nifty Boolean result: "true" if everything is spellbindingly valid, and "false" if any input mischievously misbehaves! ⚡✨

**Form Submission Protection: 🛡️**
Envision a daring knight trying to submit a form with missing or incorrect data. Fear not, for the checkValidity() spell swiftly intervenes! ⏰ Before letting the brave knight venture forth, it double-checks the form for any hidden traps. 👀

**Practical Sorcery: 🧙‍♂️**
Casting the checkValidity() enchantment is as easy as a flick of the wand! Simply grab the form's magic scroll using document.getElementById(), and chant checkValidity() on it. Voila! 🎩
```javascript
function validateForm() {
  const form = document.getElementById("myForm");
  if (form.checkValidity()) {
    alert("Form is valid! Proceed with caution... 🚀");
    form.submit(); // Submit the form to the server if valid
  } else {
    alert("You've got some work to do, young wizard! 🔮💼");
  }
}
```
**Enhancing User Enchantment: 🌟**
Picture this: as your users weave their way through the enchanted web, they encounter the checkValidity() sorcery. In an instant, they receive feedback straight from the wizard's mouth! 🗣️🌟 Errors are spotted, corrected, and the path to form completion becomes a delightful journey! 🌈🎉

**Conclusion:**
Hocus Pocus! The checkValidity() method is a formidable ally for web developers, keeping forms in tip-top shape and users utterly enchanted! 🌟 So, dear magician, the next time you encounter a form, wield this spell with glee and let the magic unfold! 🎊 Happy casting! 🪄😄
This function has too many params
Tags: android, functions, codequality, sonarlint
Published: 2023-08-05 22:49:30

---
title: This function has too many params
published: true
cover_image: https://s3-us-west-2.amazonaws.com/my-blogresources/IMAG1121.jpg
description: Use best practices to reduce the number of parameters in a function
tags: android, functions, quality, sonarlint
series: Quality Quest
---

### Why

As we add new functionality to an existing codebase, we tend to add more and more parameters to existing functions. Often, We want to minimize the changes to the current code and wrap the feature/bugfix quickly. While the intention is good, it can lead to many problems in the future. 

Depending on the project, this number can vary. As per sonarlint, this number should be less than 7. Anything more than that indicates that either, 
  1. Function is doing too much
  2. Parameters can be grouped to form a new class

While one can suppress this warning using `@Suppress("LongParameterList"),` it's better to refactor the code to avoid this warning.

### What to do

Depending on the function, there are different ways to refactor the code to avoid this warning.

1. Check the usage of the parameters inside the function and see if you can
   1. Remove parameters that may serve the same purpose
   2. Split the function into multiple functions
2. Group related parameters into a new class and pass the class instance as a parameter

## How to do

```kotlin
 fun showErrorDialog(
  title: String? = null,
  message: String? = null,
  positiveTitle: String? = null,
  negativeTitle: String? = null,
  val positiveButtonTextColor: Int? = null,
  isCancelable: Boolean = true,
  isSingleButtonDialog: Boolean = true,
  val inCompose: Boolean = false
) {
  ...
}
```

One way to fix this is to group the parameters into a new class and create a new overloaded function that takes the new class as a parameter.

```kotlin
data class DialogParams(
  val title: String? = null,
  val message: String? = null,
  val positiveTitle: String? = null,
  val negativeTitle: String? = null,
  val positiveButtonTextColor: Int? = null,
  val isCancelable: Boolean = true,
  val isSingleButtonDialog: Boolean = true,
)

fun showErrorDialog(
  dialogParams: DialogParams, 
  val inCompose: Boolean = false
) {
  ...
}
```

Replace the function call with the new function and pass the parameters as a new class instance.

```kotlin
fun showLoginFailed() {
  showErrorDialog(
    DialogParams(
      title = "Login Failed",
      message = "Please try again",
      positiveTitle = "Retry",
      negativeTitle = "Cancel",
      positiveButtonTextColor = R.color.green,
      isCancelable = false,
      isSingleButtonDialog = true
    )
  )
}
```

You can remove the old function once you replace all the usages with the new function.

**Note**: The code examples are simplified for brevity. Ideally, use string resources instead of hardcoded strings.

---
How to create the content hash for a Dropbox file upload in Elixir
Tags: elixir, dropbox, tutorial
Published: 2023-08-07 12:16:25

---
title: How to create the content hash for a Dropbox file upload in Elixir
published: true
date: 2023-08-05 22:43:01 UTC
tags: elixir, dropbox, tutorial
canonical_url: https://donaldfeury.xyz/how-to-create-the-content-hash-for-a-dropbox-file-upload-in-elixir/
---

Dropbox has a specific way they want you to calculate the content hash for a file you are uploading. You can find the instructions [here](https://www.dropbox.com/developers/reference/content-hash) but to summarize:

- Split the file into blocks of 4 MB (4,194,304 or 4 \* 1024 \* 1024 bytes). The last block (if any) may be smaller than 4 MB.
- Compute the hash of each block using SHA-256.
- Concatenate the hash of all blocks in the binary format to form a single binary string.
- Compute the hash of the concatenated string using SHA-256. Output the resulting hash in hexadecimal format.

We can convert each of these steps into parts of a pipeline!

First we need to start reading in a file, split into chunks of the specified size. [File.stream!](https://hexdocs.pm/elixir/File.html#stream!/3) is a good way of achieving this.

```
chunk_size = 4 * 1024 * 1024

File.stream!("my_file.txt", [], chunk_size)
```

Next, we need to create a new hash from each chunk. Iterating over the stream chunks with [Enum.map](https://hexdocs.pm/elixir/Enum.html#map/2) and passing those chunks into the Erlang module [:crypto.hash](https://hexdocs.pm/elixir/Enum.html#map/2) will get us our chunk hashes.

```
chunk_size = 4 * 1024 * 1024

File.stream!("my_file.txt", [], chunk_size)
|> Enum.map(&:crypto.hash(:sha256, &1))
```

After that, we'll combine all individual hashes into one big chunky string of hashes. [Enum.join](https://hexdocs.pm/elixir/Enum.html#join/2) will let us that list of strings and slap them together

```
chunk_size = 4 * 1024 * 1024

File.stream!("my_file.txt", [], chunk_size)
|> Enum.map(&:crypto.hash(:sha256, &1))
|> Enum.join()
```

Getting warmer, time to take that big boy and get one final hash using [:crypto.hash](https://hexdocs.pm/elixir/Enum.html#map/2) again. We'll have to wrap it inside an anonymous function since we need to pass the string in as the second argument.

```
chunk_size = 4 * 1024 * 1024

File.stream!("my_file.txt", [], chunk_size)
|> Enum.map(&:crypto.hash(:sha256, &1))
|> Enum.join()
|> (&:crypto.hash(:sha256, &1)).()
```

Home stretch! Lastily, base 16 encode the final hash using [Base.encode16](https://hexdocs.pm/elixir/Base.html#encode16/2). Don't forget to lowercase it by passing in `case: :lower`.

```
chunk_size = 4 * 1024 * 1024

File.stream!("my_file.txt", [], chunk_size)
|> Enum.map(&:crypto.hash(:sha256, &1))
|> Enum.join()
|> (&:crypto.hash(:sha256, &1)).()
|> Base.encode16(case: :lower)
```

There ya go! You should now be able to create the content hash for a file that you intend to upload to Dropbox.
How to get rid of the hidden wasted space in Docker Desktop
Published: 2023-08-05 22:39:31

Everyone of us that using Docker Desktop for his containers application or for fast testing by createing a lot of containers and then remove it and same for images, and we think when delete them that we saved spaces, but the bad news that we didn't .

Docker Desktop for Windows uses WSL to manage the images and containers files and keeps them in a thin private virtual hard drive called ext4.vhdx.
we can find this file in path :

           C:\Users\Eslam\AppData\Local\Docker\wsl\data
      *** Replace my user Eslam with your user profile name ***

This file will grow and will became big more and more , regardless if we delete all of our images and containers or not, so let's follow the below commands to shrink it.


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

![E2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1vt1mkhz2mznpxqs30pt.png)

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

![E4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uafd92fd45k6ct2gix9r.png)
For who is not using Windows Pro Edition and optimize-vhd command  not work with him , you can try running these commands instead:

![E5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/thbgnmp56k5b6f82tasv.png)
******** You can Copy All of the used commands from GitHub ******* 
-->>[https://github.com/Eslam-Basyouni/DevOps-Tips-Tricks-Scripts]<<--
5 Authentic Websites to Generate Stunning Favicons for Your Next.js or React Project
Tags: webdev, productivity, tutorial
Published: 2023-08-05 22:20:31

Have you ever come across a website with an impressive logo and a seamless user interface, yet found its browser tab lacking that distinctive touch? That's where favicons come into play! Favicons are those tiny, yet impactful, icons that grace your browser tabs, bookmarks, and browser history, leaving a lasting impression on your users.

If you're developing a Next.js or React app, don't overlook the power of a well-crafted favicon. Not only does it add a touch of professionalism, but it also reinforces your brand and provides users with a visual cue that keeps them engaged. 

In this post, I'll share five authentic websites that will help you generate perfect favicons for your Next.js or React project. Let's dive in! 🚀

1️⃣ Favicon.io 🎨 https://favicon.io/
Favicon.io offers a user-friendly interface, making favicon creation a breeze. Simply upload your logo or icon, and Favicon.io generates a comprehensive set of favicon files compatible with all major browsers and devices. It also provides additional options like Apple Touch Icons and Windows 8/10 tiles for complete branding coverage.



2️⃣ Favicon Generator 🛠️ https://www.favicon-generator.org/
Favicon Generator is a powerful tool that caters to both novices and advanced users. It allows you to upload your image and provides customization options for different platforms. Additionally, it offers an extensive library of pre-designed favicons if you're looking for some creative inspiration.



3️⃣ RealFaviconGenerator 🔄 https://realfavicongenerator.net/
RealFaviconGenerator takes favicon generation to the next level. It automatically generates favicons for not only browsers but also for various platforms like Android, iOS, and even Windows. The website also checks for favicon compatibility issues and helps you fix any potential problems.

4️⃣ Favic-O-Matic 📦 https://favicomatic.com/
Favic-O-Matic is an easy-to-use tool that caters to those who prefer simplicity. Upload your image, and it instantly generates a package of favicon files for you. You'll find all the standard favicon formats, ensuring your website looks great across all devices.


5️⃣ Genfavicon 🎯 https://www.genfavicon.com/
Genfavicon is a nifty favicon generator that allows you to create favicons in a matter of seconds. It supports a wide range of image formats and provides handy options like favicon size adjustments, background color selection, and more.

💡 Pro Tip: When choosing or designing your favicon, keep it simple, memorable, and aligned with your brand's identity. Also, ensure that the favicon is appropriately sized (usually 16x16 or 32x32 pixels) for optimal display.

With a well-designed favicon, you're not just enhancing your website's identity, but also providing users with a memorable and cohesive browsing experience. ✌🏾 Happy development and coding!

Follow me for more insights. I am Mr. Paul Ishaili, a dedicated Software Developer based in Abuja.

#webdesign #favicons #branding #Nextjs #React #webdevtips
The 52nd Day of the 100 Days of Code Challenge
Published: 2023-08-05 21:51:31

Hey everyone!

Indeed, I have missed some days. I have a math summer assignment that takes up a lot of time and sometimes, I don't have as much time as I'd like to for coding.

However, today, I stayed up late and I fixed some bugs in the real-time transcription app so that it'd be ready for merging! Made sure that the stream ends correctly, made sure to transcribe all the remaining audio data at once to make sure the client sees the final result as fast as possible, and touched some things up (like improving the logging messages) :)

That's it for today! Made the README file more concise and nice to read. The demo as well!

Some more projects are on my plate, hoping that math won't bother me too much! Important to never let go of my other responsibilities :)
Snowflake July 2023 Releases
Tags: newreleases, technology, data, snowflake
Published: 2023-08-31 17:46:26

---
title: Snowflake July 2023 Releases
published: true
date: 2023-08-05 20:11:24 UTC
tags: newreleases,technology,data,snowflake
canonical_url: 
---

[![](https://cdn-images-1.medium.com/max/1508/1*TE4U01eD17Yhj-_HyOBBDA.png)](https://blog.infostrux.com/snowflake-july-2023-releases-17e044135971?source=rss-fab031e08990------2)

A Detailed Account of All Snowflake New Features and Releases, including a technical demo: Snowflake Organizations

[Continue reading on Infostrux Engineering Blog »](https://blog.infostrux.com/snowflake-july-2023-releases-17e044135971?source=rss-fab031e08990------2)