teleren/devto huggingface dataset:
129. Sum Root to Leaf Numbers
Tags: php, leetcode, algorithms, programming
Published: 2024-05-01 22:42:00

129\. Sum Root to Leaf Numbers

Medium

You are given the root of a binary tree containing digits from `0` to `9` only.

Each root-to-leaf path in the tree represents a number.

- For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.

Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer.

A **leaf** node is a node with no children.


**Example 1:**

![num1tree](https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg)

- **Input:** <code>**root = [1,2,3]**</code>
- **Output:** <code>**25**</code>
- **Explanation:** 
  - <code>**The root-to-leaf path 1->2 represents the number 12.**</code>
  - <code>**The root-to-leaf path 1->3 represents the number 13.**</code>
  - <code>**Therefore, sum = 12 + 13 = 25.**</code>

**Example 2:**

![num2tree](https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg)

- **Input:** <code>**root = [4,9,0,5,1]**</code>
- **Output:** <code>**1026**</code>
- **Explanation:**
  - <code>**The root-to-leaf path 4->9->5 represents the number 495.**</code>
  - <code>**The root-to-leaf path 4->9->1 represents the number 491.**</code>
  - <code>**The root-to-leaf path 4->0 represents the number 40.**</code>
  - <code>**Therefore, sum = 495 + 491 + 40 = 1026.**</code>

**Constraints:**

- The number of nodes in the tree is in the range `[1, 1000]`.
- `0 <= Node.val <= 9`
- The depth of the tree will not exceed `10`.

**Constraints:**

```
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($val = 0, $left = null, $right = null) {
 *         $this->val = $val;
 *         $this->left = $left;
 *         $this->right = $right;
 *     }
 * }
 */
class Solution {

    /**
     * @param TreeNode $root
     * @return Integer
     */
    function sumNumbers($root) {
        return $this->sumNumbersRecu($root, 0);
    }

    function sumNumbersRecu($root, $num) {
        if ($root === null) {
            return 0;
        }

        if ($root->left === null && $root->right === null) {
            return $num * 10 + $root->val;
        }

        return $this->sumNumbersRecu($root->left, $num * 10 + $root->val) + $this->sumNumbersRecu($root->right, $num * 10 + $root->val);
    }
}
```


**Contact Links**

- **[LinkedIn](https://www.linkedin.com/in/arifulhaque/)**
- **[GitHub](https://github.com/mah-shamim)**
79. Word Search
Tags: php, leetcode, algorithms, programming
Published: 2024-05-01 22:38:24

79\. Word Search

Medium

Given an `m x n` grid of characters `board` and a string `word`, return `true` _if_ `word` _exists in the grid_.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

**Example 1:**

![word2](https://assets.leetcode.com/uploads/2020/11/04/word2.jpg)
- **Input:** `board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"`
- **Output:** `true`

**Example 2:**

![word-1](https://assets.leetcode.com/uploads/2020/11/04/word-1.jpg)
- **Input:** `board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"`
- **Output:** `true` 

**Example 3:**

![word3](https://assets.leetcode.com/uploads/2020/10/15/word3.jpg)
- **Input:** `board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"`
- **Output:** `false` 

**Constraints:**

- <code>m == board.length</code>
- <code>n = board[i].length</code>
- <code>1 <= m, n <= 6</code>
- <code>1 <= word.length <= 15</code>
- `board` and `word` consists of only lowercase and uppercase English letters.

**Follow-up:** Could you use search pruning to make your solution faster with a larger `board`?


**Solution:**

```
class Solution {

    /**
     * @param String[][] $board
     * @param String $word
     * @return Boolean
     */
    function exist($board, $word) {
        for ($i = 0; $i < count($board); ++$i)
            for ($j = 0; $j < count($board[0]); ++$j)
                if ($this->dfs($board, $word, $i, $j, 0))
                    return true;
        return false;
    }

    private function dfs($board, $word, $i, $j, $s)
    {
        if ($i < 0 || $i == count($board) || $j < 0 || $j == count($board[0]))
            return false;
        if ($board[$i][$j] != $word[$s] || $board[$i][$j] == '*')
            return false;
        if ($s == strlen($word) - 1)
            return true;

        $cache = $board[$i][$j];
        $board[$i][$j] = '*';
        $isExist = $this->dfs($board, $word, $i + 1, $j, $s + 1) ||
            $this->dfs($board, $word, $i - 1, $j, $s + 1) ||
            $this->dfs($board, $word, $i, $j + 1, $s + 1) ||
            $this->dfs($board, $word, $i, $j - 1, $s + 1);
        $board[$i][$j] = $cache;

        return $isExist;
    }

}
```


**Contact Links**

- **[LinkedIn](https://www.linkedin.com/in/arifulhaque/)**
- **[GitHub](https://github.com/mah-shamim)**
Learn SwiftUI (Day 11/100)
Tags: swift
Published: 2024-05-01 22:31:59

## Swift

* private / fileprivate / public
* static, self and Self

```swift
import Cocoa

// ## private

struct BankAccount {
    private var funds = 0
}

/*
 * Use private for “don’t let anything outside the struct use this.”
 * Use private(set) for “let anyone read this property, but only let my methods write it.”
 * Use fileprivate for “don’t let anything outside the current file use this.”
 * Use public for “let anyone, anywhere use this.”
 */

// ## static variable and function

struct School {
    static var studentCount = 0
    static func add(student: String) {
        print("\(student) joined the school.")
        studentCount += 1
    }
}

// ## self and Self
/*
 To access static code from non-static code,
 always use your type’s name such as School.studentCount.
 You can also use Self to refer to the current type.
 */

// ## singleton

struct Employee {
    let username: String
    let password: String

    static let example = Employee(username: "abc", password: "xyz")
}

// ## Check point

/*
 create a struct to store information about a car,
 including its model, number of seats, and current gear,
 then add a method to change gears up or down.
 Have a think about variables and access control:
 what data should be a variable rather than a constant,
 and what data should be exposed publicly?
 Should the gear-changing method validate its input
 */

struct Car {
    let model: String
    let numberOfSeats: Int
    private var currentGear: Int
    
    init(model: String, numberOfSeats: Int) {
        self.model = model
        self.numberOfSeats = numberOfSeats
        self.currentGear = 0
    }
    
    mutating func gearUp() -> Bool {
        if self.currentGear == 6 {
            return false
        }
        self.currentGear += 1
        return true
    }
    
    mutating func gearDown() -> Bool {
        if self.currentGear == 0 {
            return false
        }
        self.currentGear -= 1
        return true
    }
}
```
2000. Reverse Prefix of Word
Tags: php, leetcode, programming, algorithms
Published: 2024-05-01 22:30:42

2000\. Reverse Prefix of Word

Easy

Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing.

- For example, if `word = "abcdefd"` and `ch = "d"`, then you should `reverse` the segment that starts at `0` and ends at `3` (**inclusive**). The resulting string will be `"dcbaefd"`.

Return t*he resulting string*.

**Example 1:**

- **Input:** word = "<ins>abcd</ins>efd", ch = "d"
- **Output:** "<ins>dcba</ins>efd"
- **Explanation:** The first occurrence of "d" is at index 3.\
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".

**Example 2:**

- **Input:** word = "<ins>xyxz</ins>xe", ch = "z"
- **Output:** "<ins>zxyx</ins>xe" 
- **Explanation:** The first and only occurrence of "z" is at index 3.\
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe".

**Example 3:**

- **Input:** word = "abcd", ch = "z"
- **Output:** "abcd"
- **Explanation:** "z" does not exist in word.\
You should not do any reverse operation, the resulting string is "abcd".


**Constraints:**

- <code>1 <= word.length <= 250</code>
- `word` consists of lowercase English letters.
- `ch` is a lowercase English letter.


**Solution:**

```
class Solution {

    /**
     * @param String $word
     * @param String $ch
     * @return String
     */
    function reversePrefix($word, $ch) {
        $pos = strpos($word, $ch);
        if ($pos !== false) {
            $prefix = substr($word, 0, $pos + 1);
            $reversedPrefix = strrev($prefix);
            $rest = substr($word, $pos + 1);
            return $reversedPrefix . $rest;
        }
        return $word;
    }
}
```


**Contact Links**

- **[LinkedIn](https://www.linkedin.com/in/arifulhaque/)**
- **[GitHub](https://github.com/mah-shamim)**
Save your life with Git Worktree
Tags: git, javascript, programming, tutorial
Published: 2024-05-01 18:19:18

Hello, today I would like to discuss an issue that I encountered in my recent project.

Lately, I have embarked on a project that has been in development for several years and relies on outdated tools. Consequently, my primary task is to modernize the project and occasionally address issues within the old codebase. The most challenging aspect for me is dealing with the `node_modules` directory, as I am required to reinstall all the packages whenever I switch between branches.

`worktree` is the ultimate solution for tackling such issues. By utilizing this command, you can effortlessly link a specific `directory` to a designated `repository`. For instance, if you want to create a branch named `new-version` and this branch requires a dedicated directory, which can be easily achieved by this command. Let's delve into its practical implementation:
```
git worktree add new-version
```  
The provided code snippet will generate a new directory and branch named `new-version`. Additionally, it will duplicate the contents of the `HEAD` branch into the `new-version` directory.

It is also feasible to create a directory for the branches that already exist:
```
git worktree add path_to_new_directory existing_branch_name
```
This command will create a directory in the provided `path` from the chosen branch.

Thank you for taking the time to read this post. For further details regarding this command, please refer to the official document available at the following [link](https://git-scm.com/docs/git-worktree).
Code Smell 250 - Premature Memoization
Tags: webdev, beginners, programming, python
Published: 2024-05-01 22:23:09

*Memoization is awesome. Let's abuse it*

> TL;DR: Don't apply [premature optimization](https://dev.to/mcsee/code-smell-20-premature-optimization-4moe) too early

# Problems

- Readability

- Code Complexity

- Premature Optimization

- Obscured Logic

# Solutions

1. Apply [memoization](https://en.wikipedia.org/wiki/Memoization) in actual real business situations and measure its impact through empirical benchmarks.

# Context

Memoization can help you improve the performance of recursive functions involving redundant computations but compromise code readability and maintainability  

It would help if you only used it with *strong factual evidence* on *real* business case scenarios.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/7cdd5907fa5404a79581a3fac7a2af65)

```python
memo = {}
def factorial_with_memo(n):
    if n in memo:
        return memo[n]
    if n == 0:
        return 1
    result = n * factorial_with_memo(n-1)
    memo[n] = result
    return result
  
  # This function optimizes the computation of factorials
  # by storing previously computed values,
  # reducing redundant calculations 
  # and improving performance for large inputs.
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/3aa806cc9c3d9eb8493706ec031f7343)

```python
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n-1)
```

# Detection

[X] Semi-Automatic 

You can search for all places where you are using this technique and validate if they are worth it.

# Exceptions

- Real performance problems with strong factual evidence

# Tags

- Premature Optimization

# Level
 
[X] Intermediate 

# AI Generation

Unless you explicitly ask the IAs to use this technique, they will suggest cleaner solutions.

# AI Detection

ChatGPT, Gemini, and Claude.ai detect some problems with this technique but do not mention readability as a concern.

# Conclusion

It would be best if you kept a balance between performance optimization and code clarity.

You can consider alternatives such as iterative approaches or algorithmic optimizations since memoization significantly compromises code readability.

# Relations

{% post https://dev.to/mcsee/code-smell-06-too-clever-programmer-37lb %}

{% post https://dev.to/mcsee/code-smell-20-premature-optimization-4moe %}

# More Info

[Wikipedia](https://en.wikipedia.org/wiki/Memoization)

# Disclaimer

Code Smells are my [opinion](https://dev.to/mcsee/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned-1n3a).

# Credits

Photo by [Steffen Lemmerzahl](https://unsplash.com/@steffen_l) on [Unsplash](https://unsplash.com/photos/snow-covered-field-during-daytime-kp1n4gWKTOg)  
  
* * *

> A cache with a bad policy is another name for a memory leak.

_Rico Mariani_ 
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
Angular Data Binding , one Way - two Way - event Binding
Tags: angular
Published: 2024-05-01 22:11:22

are u diving into Angular and feeling overwhelmed by the concept of data binding ? Data binding lies at the heart of Angular and mastering it can unlock powerful capabilities for ur website let's delve into the fundamentals and advanced techniques of Angular data binding together 

## Understanding Data Binding in Angular:

data binding establishes a connection between the application UI and its underlying data.. it ensures that any changes in the model state are immediately reflected in the view .. and vice versa, providing a seamless user experience..

## Types of Data Binding:

1. **One-Way Data Binding:** this involves binding data from the component class to the template view.. changes in the component class reflect in the template but not the other way around

```
**TypeScript**
export class AppComponent {
    title = 'Welcome';
}

**HTML**
<h1>{{ title }}</h1>
```

2. **Two-Way Data Binding:** this allows data synchronization between the component class and the template .. changes in the template reflect in the component class and vice versa

```
**TypeScript**
export class AppComponent {
    name = 'Nour Bouch';
}

**HTML**
<input type="text" [(ngModel)]="name">
<p>Hello, {{ name }}</p>

```

## Advanced Data Binding Techniques:

1.** Event Binding:** In Angular u can bind methods to events triggered by user interactions such as clicks keypresses and mouse movements.

```
**HTML**
<button (click)="onButtonClick()">Click me!</button>

**TypeScript**
export class AppComponent {
    onButtonClick(): void {
        console.log('Button clicked!');
    }
}

```

2. **Property Binding:** This allows u to set an element's property to the value of a template expression. 

```
**HTML**
<img [src]="imageUrl">

**TypeScript**
export class AppComponent {
    imageUrl = 'path/to/image.jpg';
}

```

## Conclusion

learning data binding in angular is essential for building dynamic and responsive web applications. by understanding the different types of data binding and employing advanced techniques, you can create seamless user experiences and unlock the full potential of Angular development.
Learn SwiftUI (Day 10/10)
Tags: swift
Published: 2024-05-01 21:57:47

## Swift

* define struct
* computed property
* getter and setter
* property observer: willSet, didSet
* customize init function

```swift
import Cocoa

// ## Define struct

struct Employee {
    let name: String
    var vacationRemaining: Int

    mutating func takeVacation(days: Int) {
        if vacationRemaining > days {
            vacationRemaining -= days
            print("I'm going on vacation!")
            print("Days remaining: \(vacationRemaining)")
        } else {
            print("Oops! There aren't enough days remaining.")
        }
    }
}
// ## Computed Properties with getter and setter
struct Employee2 {
    let name: String
    var vacationAllocated = 14
    var vacationTaken = 0

    var vacationRemaining: Int {
        // getter
        get {
            vacationAllocated - vacationTaken
        }
        // setter -> even we have a setter here, no `mutating` needs to be added
        set {
            vacationAllocated = vacationTaken + newValue
        }
    }
}

// ## Property observers
// willSet and didSet
struct App {
    var contacts = [String]() {
        // newValue and oldValue are built-in variable in observers
        willSet {
            print("Current value is: \(contacts)")
            print("New value will be: \(newValue)")
        }

        didSet {
            print("There are now \(contacts.count) contacts.")
            print("Old value was \(oldValue)")
        }
    }
}

// ## custom initializers
// explicitly define `init` function - no `func` needed, and you can use `self.`

struct Player {
    let name: String
    let number: Int

    init(name: String) {
        self.name = name
        number = Int.random(in: 1...99)
    }
}
```
Day 956 : Fam
Tags: hiphop, code, coding, lifelongdev
Published: 2024-05-01 21:26:48

_liner notes_:
- Professional : Pretty good day. Had a bunch of meetings. Gave my thoughts on a project. Got to demo the library I've been working on. Created some slides for another demo I want to do tomorrow for the team meeting. Also did some work on a project for my upcoming trip.

- Personal : Fam, spent so much time getting this code to work to only find that the library I used in a project just a couple of months ago, removed the feature I was trying to implement. You know I had no where else to turn when I go to Discord. haha That's where I saw another person had an issue and that's where I got the news. Good thing that I went through tracks for the radio show and some other stuff before coding.

![﻿The photo shows a view of Kirkjufell mountain in Iceland. The mountain is a steep, pyramid-shaped peak that rises from the edge of a fjord. It is surrounded by a wide expanse of water, with a small strip of land in the foreground. The sky is cloudy, with shades of pink and purple. The water is a deep blue, and the land is a lush green.﻿](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tehfc9ktfs4i31lcg58c.jpg)

Going to dive into the code. I did some research last night and I think I have a game plan make it work. I'm still not sure if I can use third party libraries, but I'm going to find out. If I can't, I think I have an alternate plan, but that'll take more time. May go through Bandcamp to check out some tracks to pick this week.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube 1u9JoEYxFnw %}
VPS
Published: 2024-05-01 21:20:29

I'm a bit of a data nerd, especially when it comes to forex trading. I found a tool that lets me rdp vps https://myforexvps.com/myrdp-console/ latency speeds and it's been invaluable. It's like having a personal assistant to help me understand my trades better. I can't recommend it enough to anyone serious about forex trading.
Navigating the AI Evolution: CodeNewbie Podcast S27E5
Tags: codenewbie, career, ai
Published: 2024-05-01 21:11:56

We are back from our little hiatus! In Episode 5 of Season 27 CodeNewbie Podcast, @saronyitbarek talks about starting your own company, the current coding bootcamp landscape, and the influx of AI in software development with [Chelsea Kaufman](https://twitter.com/ChelsKaufman), Founder and CEO of [LEARN Academy](https://learnacademy.org/).

Chelsea, a strategic people leader, has dedicated the past decade to workforce planning & development.  As the founder and CEO of LEARN Academy and co-founder of the Software Residency, she has transformed the careers of countless individuals in the tech industry. Her work has also been instrumental in helping hundreds of companies establish and maintain a robust talent pipeline of software talent.  

---

- [Listen on Apple Podcasts](https://podcasts.apple.com/us/podcast/codenewbie/id919219256?i=1000654150662)

- [Listen on Spotify](https://podcasts.apple.com/us/podcast/codenewbie/id919219256?i=1000654150662)

Or, listen wherever you normally get your podcasts!

![GIF of a duck giving a thumbs-up at a computer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dmkpseuonak17sjnhpvm.gif)

---

### We will see you next week, happy coding y'all!

PS: Make sure to subscribe to the CodeNewbie Podcast if you haven't yet + review us on your chosen platform!
Stop the Busywork, Start Growing: Automate Your Way to Business Success
Published: 2024-05-01 21:11:34

## Stop Wasting Time, Automate Your Way to Success: A Freelancer's Guide to Business Process Automation

Hey DEV Community! As a freelancer, I see countless businesses bogged down by manual, repetitive tasks. But what if I told you there's a way to free up your team, boost efficiency, and skyrocket your growth? Enter the magic of **Business Process Automation (BPA)!**

**BPA isn't some futuristic fantasy – it's a practical solution for businesses of all sizes.** Imagine automatically generating invoices, scheduling social media posts, or routing customer inquiries to the right department – all without human intervention. Sounds pretty amazing, right? Here's how BPA can transform your client's business:

* **Turbocharge Efficiency:**  Automate repetitive tasks like data entry, report generation, and email follow-ups. Free up your client's team to focus on strategic initiatives and high-value activities.
* **Slash Manpower Needs:**  Reduce reliance on manual labor by automating routine processes. This can translate to smaller teams, lower operational costs, and increased scalability. 
* **Ditch the Dream Team (for some tasks):**  Automation can handle mundane tasks, allowing your client to focus on building a lean, high-performing team for truly critical functions.
* **Accuracy on Autopilot:**  Manual processes are prone to human error. Automation minimizes errors and ensures consistent, reliable execution every time.
* **Audit-Ready in a Flash:**  Automated workflows create a clear audit trail, streamlining audits and reducing the burden of manual record-keeping.
* **24/7 Operations:**  Automated processes keep your client's business running smoothly, even outside of business hours or during vacation periods.

**But wait, wouldn't BPA require a team of developers and a hefty budget?** Not necessarily! As a freelancer, I specialize in crafting cost-effective BPA solutions using powerful automation tools and platforms. 

**I can help your clients:**

* **Identify automation opportunities:**  Analyze current workflows and pinpoint areas ripe for automation. 
* **Develop custom workflows:**  Design automated processes tailored to your client's specific needs and industry.
* **Integrate seamlessly:**  Ensure smooth integration of automation tools with existing business systems. 
* **Train your team:**  Empower your client's team to understand and efficiently manage automated workflows.

**Stop letting manual processes hold you back!** I offer flexible freelance packages to fit any budget, and I'm passionate about helping businesses work smarter, not harder. Feel free to connect with me through DEV Community or the contact information in my profile. 

Together, let's automate the mundane and unleash the extraordinary potential of your business!