teleren/devto huggingface dataset:
Depth of composition
Tags: typescript, patterns, react
Published: 2023-08-20 21:58:37

When developing applications, it is common to split a large amount of code into smaller units. However, one of the difficulties is how to compose these parts together. In this post, we will emphasize the "depth" of a composition. This refers to how nested composition differs from flat composition in different contexts.


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

## Class

```typescript
// -- nested --
class Low {}

class Middle {
    private low = new Low();
}

class High {
    private middle = new Middle();
}

// usage
const high = new High();

// -- flat --
class Low {}

class Middle {
    constructor(
        private low: Low,
    ) { }
}

class High {
    constructor(
        private middle: Middle,
    ) { }
}

// usage
const high = new High(new Middle(new Low()));
```

## React component
```tsx
// -- nested --
const Low = () => <low />;

const Middle = () => <middle><Low /></middle>;

const High = () => <high><Middle /></high>;

// usage
<High />

// -- flat --
const Low = () => <low />;

const Middle = ({ children }) => <middle>{children}</middle>;

const High = ({ children }) => <high>{children}</high>;

// usage
<High>
  <Middle>
    <Low />
  </Middle>
</High>
```

## Function

```typescript
// -- nested --
function low() {}

function middle() {
  low();
}

function high() {
  middle();
}

// usage
high();

// -- flat --
function low() {}

function middle(low: () => void): () => void {
  return () => {
    low();
  }
}

function high(middle: () => void): () => void {
  return () => {
    middle();
  }
}

// usage
high(middle(low))();
```

## Interface
```typescript
// -- nested --
interface Low { }

interface Middle extends Low { }

interface High extends Middle { }

// -- flat --
interface Low { }

interface Middle { }

interface High extends Middle, Low { }
```

Why flat?
- Easier to navigate between layers
- More control over each layer of the code
- Easier to manage and modify
- It facilitates mocking
- It encourages reliance on interfaces

Why nested?
- More intuitive structure
- Easier to implement and use
- It hides inner details from the API
- It provides a simpler interface for users

By considering these factors, developers can choose the most suitable approach for their specific needs and context.
The fastest method for string replacement in PHP
Tags: php, code, coding, programming
Published: 2023-08-20 21:46:16

`[No BS, only code]`

Exploring different ways of replacing strings to determine the fastest method for string replacement:

**Used Language**
- PHP

## Problem

A defanged IP address replaces every period "." with "[.]".

## Solution

### 1. str_replace 
Replace all occurrences of the search string with the replacement string

```
function defangIPaddr($address) {
    return str_replace('.', '[.]', $address);
}
```

**Complexity**
* 62 / 62 test cases passed.
* Status: Accepted
* Runtime: 6 ms
* Memory Usage: 18.9 MB


### 2. str_ireplace
A case-insensitive version of str_replace

```
function defangIPaddr($address) {
    return str_ireplace('.', '[.]', $address);
}
```

**Complexity**
* 62 / 62 test cases passed.
* Status: Accepted
* Runtime: 0 ms
* Memory Usage: 19.1 MB


### 3. preg_replace
Perform a regular expression search and replace

```
function defangIPaddr1($address) {
    return preg_replace('/\./', '[.]', $address);
}
```

**Complexity**
* 62 / 62 test cases passed.
* Status: Accepted
* Runtime: 5 ms
* Memory Usage: 19.4 MB


### 4. implode - explode
Join array elements with a string

```
function defangIPaddr2($address) {
    return implode('[.]', explode('.', $address));
}
```

**Complexity**
* 62 / 62 test cases passed.
* Status: Accepted
* Runtime: 5 ms
* Memory Usage: 19 MB

## Conclusion

* 😱 Implode-Explode takes less runtime than 'str_replace'.
* 'str_replace' show lower memory usage compared to other string methods.

Feel free to share your thoughts! :)
How Constraints Works In Swift 5 UIKit | 2023
Tags: tutorial, programming, swift, beginners
Published: 2023-08-20 21:13:34

In this informative video, we dive deep into the world of constraints in Swift 5 and UIKit, demystifying the process of creating pixel-perfect layouts for your iOS apps. Constraints are the backbone of responsive design, and understanding how to wield them effectively is crucial for any iOS developer.

{% embed https://www.youtube.com/watch?v=mE2vcu-IRRc %}

🔗 Watch as we cover key topics, including:
- Introduction to Auto Layout and Constraints
- The Anatomy of Constraints: Exploring Attributes, Relations, and Constants
- Creating Constraints Programmatically vs. Interface Builder
- Mastering Common Constraint Types: Leading, Trailing, Top, Bottom, Centering
- Advanced Techniques: Aspect Ratio, Priority, Content Hugging, and Compression Resistance
- Debugging and Troubleshooting: Identifying and Resolving Constraint Conflicts
React Custom Hook: useLongPress
Tags: webdev, javascript, programming, react
Published: 2023-08-20 21:00:00

In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the "useLongPress" hook, one of the many carefully crafted hooks available in the collection of React custom hooks.

Github: https://github.com/sergeyleschev/react-custom-hooks
```javascript
import useEventListener from "../useEventListener/useEventListener"
import useTimeout from "../useTimeout/useTimeout"
import useEffectOnce from "../useEffectOnce/useEffectOnce"

export default function useLongPress(ref, cb, { delay = 250 } = {}) {
    const { reset, clear } = useTimeout(cb, delay)
    useEffectOnce(clear)
    useEventListener("mousedown", reset, ref.current)
    useEventListener("touchstart", reset, ref.current)
    useEventListener("mouseup", clear, ref.current)
    useEventListener("mouseleave", clear, ref.current)
    useEventListener("touchend", clear, ref.current)
}
```
One of the key advantages of **useLongPress** is its simplicity. By utilizing this hook, developers can easily define a long-press action on any element in their React application. With just a few lines of code, the hook takes care of handling the intricacies of tracking the long-press duration and triggering the associated callback function.

The useLongPress hook offers flexibility through customizable options. Developers can specify the desired delay for a long press, allowing them to fine-tune the duration required for an action to be triggered. Additionally, the hook intelligently integrates with other custom hooks like useTimeout, useEventListener, and useEffectOnce, enhancing code reusability and maintainability.
```javascript
import { useRef } from "react"
import useLongPress from "./useLongPress"

export default function LongPressComponent() {
    const elementRef = useRef()
    useLongPress(elementRef, () => alert("Long Press"))
    return (
        <div
            ref={elementRef}
            style={{
                backgroundColor: "red",
                width: "100px",
                height: "100px",
                position: "absolute",
                top: "calc(50% - 50px)",
                left: "calc(50% - 50px)",
            }}
        />
    )
}
```
The applications for _useLongPress_ are wide-ranging. Whether you're developing a touch-sensitive UI, implementing context menus, or creating custom gestures, this hook proves to be a valuable tool. From mobile applications to complex web interfaces, useLongPress provides an elegant solution for incorporating long-press interactions that elevate user engagement and improve overall usability.

Full Version | React Custom Hooks:
https://dev.to/sergeyleschev/supercharge-your-react-projects-with-custom-hooks-pl4
Astro Beginners Guide, Part 1: Overview
Tags: astro, beginners, resources
Published: 2023-08-20 20:40:08

Astro focuses on complete server-side rendering to speed up page loads. Other popular frameworks (NextJS, Remix, Svelte) rely on client side rendering. The trade off is that while server side can be quicker depending on your internet speeds, other errors don't occur as often such as hydration errors. 

The reason for the speed is that Astro used Multi-page application (MPA) architecture as opposed to the other popular SPA (Single Page Application). The main difference is that MPA and Astro loads HTML pages from the server whereas SPA loads, you guessed it, a single page with JavaScript locally and sorts through the pages as the user navigates.

Astro also focuses on content rich websites as opposed to feature rich sites that you can build with the aforementioned frameworks. However, that does not mean that you cannot build in Astro without those as Astro provides support for many of those frameworks out of the box. 

The Astro framework builds it's web-pages out of islands. You can think of islands like sections on a page or maybe even components for those of you coming from other web dev utilities. These islands can be a mix of interactive and non-interactive and let you easily build out a page. These islands can be built using your favorite UI framework; React, Svelte, Vue, etc. Islands strip out any unused client-side Javascript from the frontend framework to keep your site speedy and responsive.

Another great benefit of Astro's island feature is that you can prioritize each island or component individually with _client _directive. This makes it so that certain islands load based on the priority. Meaning that if you have an island that needs to load first for whatever reason or is heavy on JS, this can structure it so that the higher priority islands load first or that your JS-heavy island can hydrate only when the user sees this part of the webpage.

That's all for now. The next article we'll discuss basics of Astro projects.

This is part 1 in a multi-part series. Anything to add or corrections? Please let me know.
Unveiling Our Art-Guide Telegram Bot: Where AI and Artistry Converge
Tags: machinelearning, ai, programming, bot
Published: 2023-08-20 20:15:30

Delighted to unveil the outcome of our collaborative efforts during Module 14, "Practicing DS Skills in ML Competitions," in my academic journey at Harbour.Space University!

I'm excited to introduce our recent accomplishment: a Telegram bot that leverages AI technology to craft intricate audio descriptions for diverse artworks. By feeding the bot an image, it ingeniously composes a comprehensive narrative that not only encapsulates the artist's vision but also delves into the artwork's components, creation date, estimated value, and more.

Given the constrained timeframe of just one week, we strategically chose to adopt streamlined initial approaches to ensure a successful outcome. Engaging with this project has been exceptionally enlightening and rewarding. I'm eagerly looking forward to immersing myself in more such enriching learning experiences in the times ahead.

For those who are intrigued by our endeavor, I invite you to explore the project's GitHub repository: [Art-Guide GitHub Repository](https://github.com/aguschin/art-guide). Dive into the intricacies of the codebase, the methodologies that underpin our work, and the innovative machine learning models that power the bot's insightful audio descriptions.

Stay tuned for more updates on this exciting journey. I'm all ears for discussions, questions, and potential collaborations related to this project. Let's keep the conversation thriving on Dev.to!

A heartfelt thank you for your unwavering support and interest in our unique exploration of the synergy between art and artificial intelligence.

Warm regards.
Unveiling the Distinction: Frameworks vs. Libraries and Navigating React's Abundant Ecosystem
Published: 2023-08-20 20:15:14


I noticed misconceptions about **frameworks** and **libraries**, so I'll try to explain the differences. 🔍

Note: REACT IS A LIBRARY AND **NOT** A FRAMEWORK!!! 🚫📦

####What are Frameworks?

In the world of JavaScript, a framework (_an all-in-one kit_) is a complete structure that includes everything you need in order to build a large-scale application. It encompasses everything (like HTTP requests, Styling, Routing, Form Management, etc.) all out of the box. 

However, the downside is that you're bound by the framework's tools and conventions (_which is not always bad_). Examples of Frameworks include **Svelte**, **Vue**, **Angular**, etc. 

####What are Libraries?

Basically, libraries are pieces of code that developers share with other developers to use. _A good example is React_, which we call a view library because all it does is draw components onto the user interface (UI).

However, if you want to build a large-scale single-page application, you'll need to include a lot of external libraries for things like **HTTP requests, Styling, Routing, Form Management**, etc. 

Using a library gives you freedom; you can choose multiple 3rd-party libraries to build a complete application. The downside is that you need to research, download, learn, and stay up to date with multiple external libraries. 📚🕵️‍♂️

###REACT'S 3RD PARTY LIBRARY ECOSYSTEM 

Due to React's immense popularity, it has led to a vast ecosystem of libraries that we can include in our projects for various needs, such as:

#####Routing (for single-page applications SPA):

- React Router 
- React Location etc.

#####Making HTTP Requests:
- Fetch() 
- Axios etc.

#####Managing Remote Server State:
- React Query 
- Apollo Client etc.
- SWR (Stale-While-Revalidate) etc.

#####Global State Management:
- Context API 
- Redux 
- Zustand etc.

#####Styling:
- CSS Modules 
- Styled Components 
- Tailwind CSS etc.

#####Form Management:
- React Hook Form 
- Formik etc.

#####Animations/Transitions:
- Motion 
- React Spring 

#####Entire UI Components:
- Material UI 
- Chakra UI 
- Mantine 

Due to the numerous library options for React application needs, developers saw a need to create frameworks on top of React, which include:
- Next.js 
- Remix 
- Gatsby 

These are opinionated React frameworks. They offer many features such as server-side rendering (SSR), static state generation (SSG), and a better developer experience, among others. 🛠️🚀

If you found this helpful please leave a like, or feedback on your thoughts.
The 62nd Day of the 100 Days of Code Challenge
Published: 2023-08-20 20:14:12

Hey everyone!

Today was a day of exploring the topic of latency within the personal assistant project I'm working on and exploring the approaches to reduce it, as well as their implementations within the tools I'm using.

Revised the strategy for the following week and hoping for a productive one!

That's it for today,
happy coding everyone!
From Learning to Leading: Join my journey @ Chat JPT
Tags: data, azure, python, ai
Published: 2023-08-20 18:58:28

Welcome to my inaugural post of Chat JPT on dev.to, where I'm embarking on an exciting, albeit kinda scary, self-development journey in the realm of technology, and I hope to take you along for the ride! As a lifelong learner deeply passionate about data engineering, automation, solution architecture, most recently AI, and just overall making things for others that make their lives easier, I've decided it's time to put myself out there and dive headfirst into the tech world. As my career has mostly been in higher education, most of my demos and tutorials will focus on solutions to higher ed challenges.

Subscribe to my new YouTube channel where I am currently walking through using Microsoft Fabric DataFactory, to ingest faculty research publications from Google Scholar.  We will eventually tie in PowerPlatform, Notebooks, AzureOpenAI, Entra, and Azure for a complete solution.

Http://www.YouTube.com/@chat-jpt
Using Git 1
Tags: git, tutorial, webdev
Published: 2023-08-12 16:02:46

## Git

Git is a source control program. It can be used to,

- Version control (maintain all version of a project)
- Revert to older version if something breaks
- Collaborate with people (allowing multiple people work on a single project)
- Track all the changes done by multiple people

In this article, we just explore all the features we can use locally. 

## Using Git

### Create a git repo

The way to create a git repo is to run the git init command in the project folder

```bash
git init
```

Git will create a folder called .git in the current working directory. 

### Start tracking

From now on, all the changes done in the folder will be tracked. Try adding a file and just check it out.

```bash
git status
```

This will show unstaged files i.e files not yet committed in red, committed files in green.

### Commiting the changes

If we commit the changes, it will create a snapshot of the version. But before that the changes need to be added to staging.

```bash
git add .
```

To add the files to staging using the above command. Now git status will return the files in green. Now the changes can be committed.

```bash
git commit -m "Changes done"
```

This will now create a snapshot with the commit.

### Tracking changes

To checkout the history of the changes, we can use git log.

```bash
git log
```

### Reverting a commit

To revert to an older version, we choose the version needed from git log and use git reset to go back to previous commit. This will revert the changes and unstage the changes done as well.

```bash
git reset $prev_commit_hash
```

A git status should show us the changes done after the reverted hash in red.

If we use the flay --hard, it removes the files as well from the working directory, so use with caution if required.

```bash
git reset --hard $prev_commit_hash
```

### Stash changes

Suppose we need to temporarily move the changes and get it to previous committed version, we can use git stash.

```bash
git stash
```

To bring back from stash, we can bring it back using git pop

```bash
git stash pop
```

We can stash and remove the changes as well.

```bash
git stash clear 
```

To remove just the top of stash changes we can use git stash drop

```bash
git stash drop
```

### Getting the changes back after a git reset --hard

There is another set of logs in git called reference logs. The command to access reference logs is reflog

```bash
git reflog
```

We can use this to checkout a branch from here to an older before a hard reset was done to get the changes.

In part 2, we will explore the feature we can use to collaborate.
C# data types
Tags: webdev, beginners, programming, news
Published: 2023-08-20 18:43:51

Like many programming languages, C# has its own data type system that is used to create variables. The data type defines the internal representation of the data, the set of values ​​that an object can take, and the allowed actions that can be performed on the object.

The C# language has the following basic data types:

- _bool_: stores true or false (boolean literals). Represented by the system type System.Boolean

- _byte_: stores an integer from 0 to 255 and occupies 1 byte. Represented by the system type System.Byte

- _sbyte_: stores an integer from -128 to 127 and occupies 1 byte. Represented by the system type System.SByte

- _short_: stores an integer from -32768 to 32767 and occupies 2 bytes. Represented by the system type System.Int16

- _ushort_: stores an integer from 0 to 65535 and occupies 2 bytes. Represented by the system type System.UInt16

- _int_: stores an integer from -2147483648 to 2147483647 and occupies 4 bytes. Represented by the System.Int32 system type. All integer literals represent values ​​of type int by default:

- _uint_: stores an integer from 0 to 4294967295 and occupies 4 bytes. Represented by the system type System.UInt32

- _long_: stores an integer from -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807 and occupies 8 bytes. Represented by the system type System.Int64

- _ulong_: stores an integer from 0 to 18446744073709551615 and occupies 8 bytes. Represented by the system type System.UInt64

- _float_: stores a floating point number from -3.4*1038 to 3.4*1038 and takes 4 bytes. Represented by the system type System.Single

- _double_: Stores a floating Point number from ±5.0*10-324 to ±1.7*10308 and occupies 8 bytes. Represented by the system type System.Double

- _decimal_: stores a decimal fractional number. If used without a decimal point, it has a value of ±1.0*10-28 to ±7.9228*1028, can store 28 decimal places, and occupies 16 bytes. Represented by the system type System.Decimal

- _char_: Stores a single Unicode character and occupies 2 bytes. Represented by the System.Char system type. Character literals correspond to this type:

- _string_: stores a set of Unicode characters. Represented by the System.String system type. This type corresponds to string literals.

- _object_: can store a value of any data type and takes up 4 bytes on a 32-bit platform and 8 bytes on a 64-bit platform. Represented by the System.Object system type, which is the base type for all other .NET types and classes.

References:
1.[Microsoft](https://learn.microsoft.com/ru-ru/dotnet/csharp/fundamentals/types/)
Simple UUID wrapper for MySQL in Go that covers UUID to BIN conversion
Tags: go, mysql, beginners, tips
Published: 2023-08-20 21:54:36

---
title: Simple UUID wrapper for MySQL in Go that covers UUID to BIN conversion
published: true
date: 2023-08-20 18:08:51 UTC
tags: golang, mysql, beginner, tips
canonical_url: https://alexandrubucur.com/tech/2023/simple-uuid-wrapper-for-mysql-in-go-that-covers-uuid-to-bin-conversion/
---

Here's a quick snippet you can use to create a custom type that maps an UUID to a Binary(16) representation in MySQL.

I assume this is not present in `gofrs/uuid` since it's database specific, but having NullUUID available is an easy 'inspiration' opportunity ;).

```golang
import (
	"database/sql/driver"

	"github.com/gofrs/uuid/v5"
)

type NullBinaryUUID struct {
	UUID  uuid.UUID
	Valid bool // Valid is true if UUID is not NULL
}

// Value implements the driver.Valuer interface.
func (u NullBinaryUUID) Value() (driver.Value, error) {
	if !u.Valid {
		return nil, nil
	}

	// Delegate to UUID Value function
	return u.UUID.Bytes(), nil
}

// Scan implements the sql.Scanner interface.
func (u *NullBinaryUUID) Scan(src interface{}) error {
	if src == nil {
		u.UUID, u.Valid = uuid.UUID{}, false
		return nil
	}

	// Delegate to UUID Scan function
	u.Valid = true
	return u.UUID.Scan(src)
}
```