teleren/devto huggingface dataset:
Some handy PHP String functions
Tags: php, webdev, beginners, programming
Published: 2024-01-28 12:14:56

## Hey buddy, here are some handy-dandy PHP String functions for you.


heredoc is a way to declare strings using a special syntax, allowing multiline strings without needing to escape quotes.
```
echo <<<"FOOBAR"
Hello World!
FOOBAR;
```

nowdoc is kinda similar to heredoc but treats the enclosed string literally, ignoring variables and special characters.
```
echo <<<'EOD'
Example of string spanning multiple lines
using nowdoc syntax. Backslashes are always treated literally,
e.g. \\ and \'.
EOD;
```


Get the length of a string
```
echo strlen($str1);
```

Convert a string to lowercase
```
echo strtolower($str1);
```

Convert a string to uppercase
```
echo strtoupper($str1);
```

Uppercase the first character of a string
```
echo ucfirst($str1);
```

Uppercase the first character of each word in a string
```
echo ucwords($str1);
```

Get a substring from a string starting at index 6
```
echo substr($str1, 6);
```

Get a substring from a string starting at index 6 with a length of 4
```
echo substr($str1, 6, 4);
```

Find the position of a substring in a string (case-sensitive)
```
echo strpos($str1, "Hello");
```

Find the position of a substring in a string (case-insensitive)
```
echo stripos($str1, "hello");
```

Convert an array into a string using implode
```
$arr1 = [1, "two"];
print_r(implode($arr1));
```

Convert a string into an array using explode
```
print_r(explode("@foo", $str1));
$str2 = "lol#oof#sheez";
print_r(explode("#", $str2));
```

Replace a substring in a string
```
$str2 = "welcome back!"; 
echo str_replace("back", "home", $str2);
```

Remove HTML tags from a string
```
$html_text_content = "<p>lol</p>";
echo strip_tags($html_text_content);
```

Escape special characters in a string
```
$name = "tom's world";
echo addslashes($name);
```

Remove slashes from a string

```
$str_with_slashes = "\yes \sir";
echo stripslashes($str_with_slashes);
```

Trim white spaces from the beginning and end of a string
```
$str_with_spaces = "    no!   ";
echo trim($str_with_spaces);
```

Shuffle characters in a string
```
$shuffle_me = "hello there!";
echo str_shuffle($shuffle_me);
```

Generate and display a 6-character OTP
```
$otp = "1726341237472364782346253";
echo substr(str_shuffle($otp), 0, 6);
```

Use md5 to a string (not recommended for password hashing)
```
$pwd = "password123";
echo md5($pwd);
echo password_hash($pwd, PASSWORD_DEFAULT);
```

Verify a password hash
```
$hash = '$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a';
if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
```

Encode and decode strings to/from base64
```
$str3 = "test";
echo base64_encode($str3);
echo base64_decode("dGVzdA==j");
```

**Do you have something more to add? Feel free to add them in the comment section to help other devs.**
Part 16.1(x2) Copying RMT
Published: 2024-01-28 11:59:53

Hello, fairy dairy diary ~ fairy dairy diary!

![Two Cirnos](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g9k1dmpln746mc1m2891.png)

LLama* while gave better PPL, create better headache during attempts to copy it: since layer gets increased, you need to do something with new additional weights. I tried couple of ideas, and they all were bad. I didn't try to copy in `ABC->AABBCC` pattern as I want to do proper `ABC->ABCABC` growth. So I decided to try copying mainline step 5: RMT.

Chilling out continues. There should be training graph, but I can't be bothered as it was bad anyway.
How to make the camera appear along with other objects?
Published: 2024-01-28 11:56:53

Hello, good day, I'm trying to center the camera, but if I click on main camera, the objects I had disappear, and if I click on "directional" light, the objects appear, but the camera disappears, how can I solve it?

I already tried unlocking blindfolded eyes and it didn't work, thank you

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzz1brzolqjz7iwo0864.png)
High Availability - Consistency 🏋️
Tags: systemdesign, webdev, interview, ssd
Published: 2024-01-28 11:47:29

This post is a continuation to my previous post [HighAvailability](https://dev.to/avinashd10/high-availability-536k) 
You might have got an idea of high-availability and why is it important, we will see what else we can do to achieve high availability.

**2. Consistency**
The moment I heard this word, my thoughts are filled with 
 motivation videos saying "consistency is root of success."
So, is it same in System Design as well?
Let's see....

![system design high availability](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6yot6rpnckzlq9xfiwsh.gif)

**Story:**
Let's say you are running a famous restaurant, and it is very successful, and you open 2 more in the same city.
You plan to run coupons to increase sales and started with only 1 of your popular restaurants. The word spread via online and people nearby other 2 restaurants started to complain that there is no coupon offer. This not only affects your customers & sales but also the reputation of your business.

There is no consistency (**Weak Consistency**) here. If the coupons were introduced in all the restaurants, It would have improved the sales, satisfied customers & increase in popularity (**Strong Consistency**)

**Twist:**
Maybe you don't know if the coupons can increase the sales right away and you prefer not to take risk. So initially the coupons were introduced in 1 restaurant and based on the results you started the strategy in the other 2 (**Eventual Consistency**)

**Story to Solution in System Design:**
Same story applies in case of High Availability. 
In Distributed Systems, it is pretty common to have more than 1 database (more on dbs later). 
With each API call, you will make some transactions in database. With increased traffic you might need more than 1 db to handle the load.

> More dbs more problems 🫤

1st api call is updating user A's address in database db1
2nd api call is getting user A's details from database db2
In this case 2nd api may receive old address bcoz data in d2 is old...

**Solution:**
You either choose 

**Strong Consistency**: Change in db1 should also be made in db2 at that instant. Downside of this would be decrease in performance as the api call may take more time to update all the db replicas

**Weak Consistency**: Allowing the inconsistency at that instant, upside is that api calls are fast which increases the performance.

**Eventual Consistency**: Allows the inconsistency for a while and updates the replicas eventually. Balance in both consistency & performance. 

PS: This post is a part of **SillySystemDesign** in which each post gives very silly way to understand a complicated concept. 
 
Meet u again with another complex topic with a silly example🫡
Isar Database - Record Deletion in Flutter
Tags: isar, flutter
Published: 2024-01-28 11:37:25

# Introduction
I have been doing a small project in Python for a while now. It's been called [Sitemarker](https://github.com/aerocyber/sitemarker). It is live in the [Flathub ](https://flathub.org/apps/io.github.aerocyber.sitemarker) app store. It's been fun and all but recently, I've been busy getting it rewritten in Flutter.

## Why Flutter?
I've been trying to get the entire program run on different platforms. First I tried web technologies to get it done. Sadly enough, my experience on the Web was not enough for the task. And, I was interested in learning Flutter.

## The core things

I could get the entire code written in a few weeks. The UI was fine, and routings were doing good, until

## Deletion of records

Any insertion must have a deletion. It's a thing. However, in my case, every insertion _did_ have a deletion until the application closed.

## The issue

Isar must have compaction to update the database to remove stale records. As with any great library, isar had _one_ issue on the topic. _Documentation_.

I'm not going to lie. Isar has good if not great, documentation. The issue I found though, is that there is literally _no guide_ for compacting an isar database. And I am new to local databases. MySQL did a good job making me comfortable with it. And I was practically close to completing the entire code.

## The Workaround.

The workaround is a trick of sorts. When the deletion is called, it first deletes from the application runtime records. Then, said records that did _not_ have the record to be deleted were copied to a new variable. The database now is closed, with deletion enabled on database closure.

## The code

```dart
  void deleteRecord(DBRecord record) async {
    final isar = await db;
    await isar!.writeTxn(() async {
      isar.dBRecords.delete(record.id);
      _records.remove(record);

    });
    deleteWorkaround();
  }

void deleteWorkaround() async {
    final recs = _records; // Get records.

    final isar = await db;
    await isar!.close(deleteFromDisk: true); // Close the db. Delete the db.

    final isarTemp = await openDB();
    List<DBRecord> localRecords = [];
    isarTemp!.txn(() async {
      final dbrecordCollection = isarTemp.dBRecords;
      localRecords = await dbrecordCollection.where().findAll();
    });

    for (int i = 0; i < recs.length; i++) {
      await isarTemp.writeTxn(() async {
        await isarTemp.dBRecords.put(recs[i]);
        localRecords.add(recs[i]);
      });
    }
    await isarTemp.close();
    _records = [];
    db = openDB();
    init();
    notifyListeners();
  }
```

The `notifyListeners();` function is part of the `provider` package for state management.
Maximizing Container Density on Amazon ECS
Tags: aws, eni, ecs
Published: 2024-01-28 11:30:33

## Introduction

If you're leveraging Amazon Elastic Container Service (ECS) with EC2 instances for your containerized workloads, optimizing your resource utilization is crucial. In this article, we'll explore the importance of profiling your application and selecting the right EC2 instance type based on your app's resource requirements. Specifically, we'll delve into a game-changing feature called ENI (Elastic Network Interface) trunking, designed to enhance container density on your EC2 instances.

## Understanding ENI Attachment Limits

Each EC2 instance type supports a limited number of ENI attachments. This is a critical factor to consider when provisioning your ECS cluster. Larger instance types naturally support more ENIs, allowing for a greater number of concurrently running tasks. But larger instances also costs more.

## ECS Simplifies Container Orchestration

ECS abstracts away the complexities of setting up containerized environments, providing a streamlined solution for running tasks. In ECS, each task consumes one IP address, equivalent to one ENI attachment. For example, if you're running an ECS cluster on an m5.xlarge instance, supporting three ENI attachments, you may find yourself underutilizing the instance, limiting you to running only three tasks.

## ENI Trunking Unleashes Container Density

ENI trunking, a feature enabled by the awsvpc network mode. ENI trunking resolves the limitation on the total number of ENIs that can be attached to an EC2 instance, allowing for a more efficient use of resources.

## How ENI Trunking Works

With ENI trunking, an EC2 instance undergoes two ENI attachments: the primary ENI and the Trunk ENI. The addition of the Trunk ENI empowers the EC2 instance to host a greater number of containers, effectively maximizing container density.

## Managing IP Address Exhaustion

It's important to note that even with ENI trunking, IP addresses are still allocated from the subnet. Small subnets could lead to IP exhaustion issues. To mitigate this, Amazon VPC Container Network Interface (CNI) can be configured to utilize a different IP space than the host network, preventing potential challenges related to IP address limitations.

## Conclusion

ENI trunking is a powerful feature that enables ECS users to break free from the constraints of ENI attachment limits, unlocking the potential for higher container density on EC2 instances. By understanding and leveraging this feature, you can optimize your ECS cluster, ensuring efficient resource utilization and maximizing the benefits of containerization on AWS.

## References

https://docs.aws.amazon.com/AmazonECS/latest/bestpracticesguide/networking-networkmode-awsvpc.html

https://docs.aws.amazon.com/AmazonECS/latest/developerguide/container-instance-eni.html?icmpid=docs_ecs_hp_account_settings
Lets talk about linked list
Tags: dsa, beginners, tutorial, python
Published: 2024-01-28 11:17:21

_It's gonna be small blog on what is linked list, how they work and what they do._

## So what are linked list?
Linked list is basically a type of data structuer where the main objects of the structure are its nodes and pointers of those nodes. 
Nodes are basically objects that consist of a value(it's not limited my any data structure) and a pointer than points to the next node.

```
Class Node:
    def __init__(self, value):
        self.value = value
        self.next = //Next value
```
There is a starting of a linked list called "Head" and an end of it called "Tail". Head points to the first value and tail points to the last value. Elements of the list can be accessed by traversing through a loop. Just like list it has features like deleting, instering, changing values etc with its own time and space complexity

![Visual representation of linked list](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ug7xt05kzy33ymdqq8o.png)
## Difference between linked list and list:
The main difference between linked list and list is how they are arrange in the memory. List are arranged in a linear manner with indexing.

![visual representation List in memory](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x6tc5kgu10flov6g7sbp.png)
And as for linked list they're scattered over the memory pointing with pointers to next element 

![visual representation Linked list in memory](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ltbulpa65g4y2dih7f38.png)

## The key use of Linked list:
The main use case of linked list is for insertion and deletion. Generally in list to delete or insert an item it's needed to left shift or right shift the other elements of the list as it's in a continious memory location

![Left shifing a list](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/897gt7oa4phunh6oqxu4.png)
But it's different for linked list as the locations of the elements of linked list are scattered and connected through a pointers only the few pointers needed to be changed. It has a big impact on time complexity if the dataset is large enough.

![Changing pointers of a linked list](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1491x8tagl9h64voxrpr.png)

## Overview and Core Differences between linked list and list:

- **Memory location**: In list elements are stored in a 
  contiguous space in memory
  where as in linked list it's scattered throughout the memory 
- **Access time:** List can be accessed throuhg indexes, as 
  for linked list it's needed to be traversed to access 
  elements of it.
- **Insersion and deletion**: The items in a list needed to 
  be left shifted or right shifted for deletion or insertion of 
  an element and for linked list only pointers needed to be 
  changed
Đá Gà Trực Tiếp Thomo Hôm Nay - Trực Tiếp Đá Gà Campuchia
Published: 2024-01-28 10:41:09

https://daga86.com/ Đá gà trực tiếp Thomo✔️ Trường gà đá Camphuchia có bình luận viên trực tuyến✔️ Trực tiếp đá gà cựa dao, gà Mỹ✔️ gà Thái, gà tre ngay tại casino✔️✔️✔️
43 P. Phan Văn Trị, Hàng Bột, Đống Đa, Hà Nội, Vietnam
#daga #daga86 #dagathomo #dagatructiep #dagacampuchia #dagacuadao
https://podcasters.spotify.com/pod/show/daga86com
https://daga86com.webflow.io/
https://daga86com.hashnode.dev/
https://hackmd.io/@daga86com
Dubverse
Published: 2024-01-28 10:27:18

"[Dubverse](https://dubverse.ai) is an AI-powered online video dubbing platform that enables content creators to easily make their videos multilingual. It uses deep learning, text-to-speech, machine translation, and generative AI to create ready-to-publish videos quickly and cost-effectively. Dubverse solves the problem of language barriers by allowing creators to dub their video content from one language to another in almost real-time, and at a reduced cost, using advanced AI technologies. The platform offers a self-servable script editor and a range of human-like AI voices in various languages, making it ideal for a wide range of creators, including those in e-learning, product explainer videos, news outlets, and more.

Why use Dubverse?

- Reach a wider audience: Break down language barriers and expand your reach exponentially.
- Save time and money: Forget expensive studios and voice actors. Dubverse is fast and affordable.
- Go global: Share your message with the world. Education, marketing, entertainment - the possibilities are endless."
DSA v/s Web Dev
Tags: webdev, datascience, beginners, discuss
Published: 2024-01-28 10:18:44

Hello everyone! 👋 I am an aspiring Data Scientist from India 🇮🇳 currently developing my data science skills. Recently, I've been having some problems in understanding the importance of skills.

I am confused whether to learn DSA (Data Structures & Algorithms) or Web Development. I believe that with data science these skills are also necessary to include in your codebase. But which one holds more importance, that is the main question that troubles me the most.

So, I came across this platform to look for professionals who have years of valuable experience. Please, if anyone can help me & guide me in the proper direction or clear my thoughts.

Thank you! 🙏💻
Validating Function Parameters (Pogo Pt:12)
Tags: python, go, compiler, transpiler
Published: 2024-01-28 10:08:24

## Intro
In this series I am creating a transpiler from Python to Golang called [Pogo](https://github.com/Chig-Beef/Pogo). In the last post we made the errors so much better, adding line numbers and the function line. In this post we will be fixing functions so that the compiler understands that parameter variables count as declarations.

## Current Errors
Here is some sample code.
```golang
from GoType import *

def test(x: int):
    print(x)
```
Compiling this gives us this compiler error.
```
[Analyzer (analyze-call)] An uninitialized variable was used in a function call
```
Firstly, lets fix this error a bit.
```
analyze.go -> analyze:ST_CALL -> line: 4
An uninitialized variable was used in a function call
```
There we go, that's better. So now that we have an uninitialized variable in a function call, we should initialize it.
This is actually pretty easy, as we have looked at initializing variables in declarations, so a lot of the code can be copy pasted.
```golang
else if s.code == structureCode["ST_FUNCTION"] {
    i := 3
    for s.children[i].code == structureCode["IDENTIFIER"] {
        n := s.children[i]   // IDENTIFIER - name
        t := s.children[i+2] // IDENTIFIER - type
        v := Variable{n.text, t.text}
        vars = append(vars, v)

        i += 4 // Next variable, otherwise this will end up on an anti-colon
    }
}
```
We use `i` to keep track of the index of the identifier. If `i` points to an identifier then we can add it to the slice of variables. By incrementing by 4 we end up on the next identifier to repeat the process. If we're one the last parameter then we will end up overshooting, and we land on the anti-colon. This fixes the errors!

## Next
I know that we didn't do _too_ much here, I've been a bit busy, but in the next post we will work on variables when calling a function, because at the moment when we try to put anything in a function call it gives us an error.
A First Look at Apples New Switch Control
Tags: css, webdev, tutorial, showdev
Published: 2024-01-28 10:06:26

Apple have just released _Safari Technology Preview 17.4_, which introduces a new addition to checkboxes: The `switch`-attribute:

```html
<input type="checkbox" switch>
<input type="checkbox" switch checked>
```

In all it's glory, this is what you get with the above markup:

![Checkbox Switch](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tvmzi6micvx03lo2k2n0.png)



It's still early days, because when you zoom in, you get this funky result:

![Checkbox Switch Zoomed In](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kvbh45fp1rz8hg0rq253.png)

Interestingly enough, it's **not** using [system colors](https://developer.mozilla.org/en-US/docs/Web/CSS/system-color) for the un-checked state, but for the checked state, it's using `AccentColor`. 

In dark mode, weirdly enough, it doesn't use  `AccentColor`. 

It would be much more consistent, if the system colors `ButtonFace` and `AccentColor` were used for the two states, no matter what the `color-scheme` is.

> **NOTE:** At the moment, Safari is actually the **only** browser that supports the system color `AccentColor`.

---

## Under the Hood

Inspecting the control reveals an `aspect-ratio` of `1.8/1` and a relative height of approx. `1.1em`, so a super-simple fallback could be:

```html
<input type="checkbox" role="switch">
```

```css
[role=switch] {
  appearance: none;
  aspect-ratio: 1.8/1;
  background: #ddd;
  border-radius: 1em;
  display: grid;
  height: 1.1em;
  margin: 0;
  padding: 0.0625em;
  &::after {
    background: #fff;
    border-radius: 50%;
    content: '';
    width: 1em;
  }
  &:checked {
    background: #16f;
    justify-content: end;
  }
}
```

Using grid here, you can control the border with `padding` and scale it to any size, by updating `font-size`:

![Switch fallback](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oijr0pv7qk308bfvuwuj.png)

If you want to fine-control the various parts better, add some CSS custom properties:

```css
[role=switch] {
  --_bg: #DEDEDE;
  --_bga: #FFF;
  appearance: none;
  aspect-ratio: 1.8/1;
  background: var(--_bg);
  border-radius: 1em;
  display: grid;
  height: 1.1em;
  margin: 0;
  &::after {
    background: var(--_bga);
    border-radius: 50%;
    border: 0.046875em solid color-mix(in srgb, var(--_bg) 95%, #000);
    content: '';
    display: block;
    height: 1.00625em;
    width: 1.00625em;
  }
  &:checked {
    --_bg: #0f83ff;
    justify-content: end;
  }
}
```

![Finer Control](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pq608u86iko023t9ax2i.png)

And if you **really** want to simulate Apple's switch, dive into `box-shadow`, as they're using very subtle box-shadows for both parts of the switch!

---

It will be interesting to see, if `switch` will make it into the standard, and if other browsers will adopt it.

Otherwise, stick with `role="switch"` for now.
How To Disable Bluetooth on Android TV
Tags: android
Published: 2024-01-28 10:04:53

Modern (and not-so-modern) Android TVs often come with built-in Bluetooth for connecting other smart devices, such as voice-enabled remotes. This is nice.

However, for reasons beyond my understanding, Google and most TV manufacturers decided to leave Bluetooth discoverability always enabled on the device with **no option to turn it off**, resulting in annoying neighbors spamming consent pairing dialogs on the TV whenever they want. This is not nice.

The sensible solution would be for manufacturers to add an option to disable Bluetooth in the TV settings, but unfortunately that's not how modern software development works.

Since this is not an isolated problem, other people have come up with alternative solutions that involve installing an app:
- https://www.reddit.com/r/AndroidTV/comments/6dwczn/
- https://www.reddit.com/r/AndroidTV/comments/tdfh0e/
- https://forum.lowyat.net/topic/5196128

Of course, my Android TV does not support that app (thanks, market fragmentation!), so here's my solution to disable Bluetooth:

1. Enable USB Debugging on your TV [just like any other Android device](https://developer.android.com/studio/debug/dev-options)
2. Connect to the TV through the network: `adb connect <tv-ip-address>`
3. Run `adb shell svc bluetooth disable`