teleren/devto huggingface dataset:
LeetCode Meditations: Invert Binary Tree
Tags: computerscience, algorithms, typescript, javascript
Published: 2024-04-16 17:27:58

Let's start with the description for [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree):

> Given the `root` of a binary tree, invert the tree, and return _its root_.


For example:

![Example image](https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg)

---

Although this one has a very simple recursive solution, let's see one approach that I come up with initially:

```ts
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *   val: number
 *   left: TreeNode | null
 *   right: TreeNode | null
 *   constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *     this.val = (val === undefined ? 0 : val)
 *     this.left = (left === undefined ? null : left)
 *     this.right = (right === undefined ? null : right)
 *   }
 * }
 */

function invertTree(root: TreeNode | null): TreeNode | null {
  let queue = [];
  queue.push(root);

  while (queue.length > 0) {
    let currentNode = queue[0];
    if (currentNode !== null) {
      queue.push(currentNode.left);
      queue.push(currentNode.right);
      [currentNode.left, currentNode.right] = [currentNode.right, currentNode.left];
    }

    queue.shift();
  }

  return root;
}
```

This version uses [level-order traversal](https://rivea0.github.io/blog/leetcode-meditations-chapter-7-trees#bfs); we store the children of each node in a queue as we go through each level in the tree, and swap the node's left and right children.

#### Time and space complexity

Since we visit each node once, the time complexity is {% katex inline %} O(n) {% endkatex %}.
The space complexity will be proportionate to the size of the queue we keep, which holds a whole level at a time, which amounts to {% katex inline %} O(n) {% endkatex %} overall.

---

Now, let's look at the recursive solution, which is much simpler:

```ts
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *   val: number
 *   left: TreeNode | null
 *   right: TreeNode | null
 *   constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *     this.val = (val === undefined ? 0 : val)
 *     this.left = (left === undefined ? null : left)
 *     this.right = (right === undefined ? null : right)
 *   }
 * }
 */

function invertTree(root: TreeNode | null): TreeNode | null {
  if (root === null) {
    return null;
  }

  [root.left, root.right] = [root.right, root.left];

  invertTree(root.left);
  invertTree(root.right);

  return root;
}
```

#### Time and space complexity

The time complexity is {% katex inline %} O(n) {% endkatex %} as we visit each node to swap its left and right children. The space complexity is also {% katex inline %} O(h) {% endkatex %}—where {% katex inline %} h {% endkatex %} is the height of the tree—because of the recursive calls to the function on each level.

---

Next up is [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/). Until then, happy coding.
Revolutionize Your Revolutionize Your Business with AI by TechnBrains
Published: 2024-04-16 17:18:21

Empower your business with our advanced AI services, including an AI search engine for developers and exceptional [AI customer service](https://www.technbrains.com/artificial-intelligence-services) expertise. Our dedicated team ensures seamless alignment with your goals, from ideation to execution. Experience the pinnacle of innovation with TechnBrains' AI solutions.
dEv-Commerce: Headless e-commerce platform
Tags: webdev, php, vue, react
Published: 2024-04-16 17:02:54

🚀 Exciting News Alert! 🌟

We're thrilled to announce that dEv-Commerce is now LIVE! Get ready to revolutionize your e-commerce experience like never before! 🤩

🛠️ With our headless platform, you're in control of the frontend. Build stunning, customized storefronts using ANY frontend framework you love. No limitations, just pure creativity! 💡

💳 Plus, enjoy seamless single and subscription payments right out of the box, making transactions a breeze for you and your customers. 💸

👩‍💼 And here's the best part – we've got your back with our intuitive admin system. Say goodbye to admin headaches and hello to smooth sailing! 🌊

Ready to dive in? Join our waiting list TODAY and claim your FIRST MONTH FREE! 🎁 Don't miss out on this exclusive offer! 😎

Sign up now: https://devcommerce.co.uk
Learning AWS Day by Day — Day 38 — Amazon RDS
Tags: aws, cloud, cloudcomputing, beginners
Published: 2024-04-16 17:11:48

Exploring AWS !!

**Day 38:**

**Amazon RDS:**

Check out Day 37 for Overview and advantages of RDS over deploying database on EC2.

https://dev.to/rksalo88/learning-aws-day-by-day-day-37-amazon-rds-redshift-and-aurora-overview-3g0d

**RDS Backups:**
- Backups are automatically enabled.
- Automated backups
- Daily full backup of database (during maintenance windows)
- Transaction logs are backed up by RDS every 5 minutes
- ability to restore at any point in time (from oldest to 5 mins ago)
- 7 days retention (increased to 35 days)
- Database snapshots:
Manually triggered by user
Retention of backup for as long as you want.

**RDS — Storage Autoscaling:**
- Helps increase storage on RDS database instance dynamically
- When RDS detects you are running out of free database storage, it scales automatically.
- Avoid manually scaling database storage
- You have to set the maximum storage threshold (max limit for database storage)
- Automatically modify storage if:
Free storage is less than 10% of allocated storage
Low storage lasts at least 5 mins
6 hours have been passed since last modification
- Useful for apps with unpredictable workloads
- Supports all RDS database engines (MariaDB, MySQL, PostgreSQL, SQL server, Oracle)

**RDS Read Replicas for read scalability:**
- can create upto 5 replicas
- within Az, cross Az or cross region
- Replication is Asynchronous, so reads are eventually consistent
- replication can be promoted to own database
- Application must update connection string to leverage read replicas.

**Use Cases:**
You have a production application that is taking on normal load.
You want to run a reporting application for running some analytics.
So, you create a read replica to run new workload there.
The production application is unaffected.
Read replicas are used for SELECT (=read) only kinds of statements (not INSERT, UPDATE or DELETE)

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

**RDS Read Replicas — Network Cost:**
There’s some network cost when data goes from one Az to another Az.
For RDS Read Replicas within same region, you don’t pay fees.

**RDS Multi-AZ (Disaster Recovery):**
- SYNC Replication
- One DNS name — automatic app failover to standby
- Increase availability
- Failover in case of loss of AZ, loss of network, instance or storage failure
- No manual intervention in applications
- Not used for scaling
Note: Read replicas can be setup as Multi-AZ for Disaster Recovery(DR).

**RDS from Single AZ to Multi-AZ:**
- Zero downtime operation (no need to stop database)
- Just click “modify” for database
- Following happens internally:
A snapshot is taken
A new database is restored from snapshot in a new AZ
Synchronization is established between 2 databases
Check if the Sentence Is Pangram | LeetCode | Java
Tags: java, leetcode, beginners, algorithms
Published: 2024-04-16 16:59:23

_In this article, we will focus on 3 different approaches to solve the problem._

## Approach 1 : Using HashSet
In this, we store the entire sentence in a HashSet. The catch here is that the set will not contain duplicate characters. So, we add the elements to the set and see if the set size is equal to the 26 letters.

``` java
class Solution {
    public boolean checkIfPangram(String sentence) {
        
        Set<Character> set = new HashSet<>();
        
        for(char ch : sentence.toCharArray()){
            set.add(ch);
        }
        
        return set.size()==26;
    }
}
```



## Approach 2 : Using Frequency Array
Here, we are going to store the entire sentence in a frequency array of size 26. We will calculate the occurrence of every element of the alphabet and later run through the frequency array to check if any character is not present.

``` java
class Solution {
    public boolean checkIfPangram(String sentence) {
        
        boolean freq[] = new boolean[26];
        
        for(char ch : sentence.toCharArray()){
            freq[ch-'a'] = true;
        }
        
        for(boolean val : freq){
            if(val==false)
                return false;
        }
        
        return true;
    }
}

```


## Approach 3 : Using Built-in function
`indexOf() method returns the index within the string of the first occurrence of the specified character or -1, if the character does not occur.`

``` java
class Solution {
    public boolean checkIfPangram(String sentence) {
        
        for(int i=0; i<26; i++){
            char ch = (char)(i+'a');
            
            if(sentence.indexOf(ch)==-1)
                return false;
        }
        
        return true;
    }
}
```


_Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀_

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7
📌Data Structure PT I
Published: 2024-04-16 16:51:59

## What is a Data Structure? 🗃️

In computer science, a data structure is a way of organizing and storing data in a computer so that it can be accessed and manipulated efficiently.

Think of data structures as the building blocks of software applications, providing a means to manage and organize data effectively.

## Where do we need Data Structures? 🔍

Data structures are used virtually everywhere in software development, from simple programs to complex systems.

Here are some common areas where data structures are crucial:

**- Algorithm Design:**
 Data structures are fundamental to the design and analysis of algorithms. Different data structures are suited to different types of operations, so understanding them helps in choosing the right data structure to optimize algorithm performance.

**- Database Systems:**
 Databases rely heavily on data structures to store and retrieve information efficiently. speed up database operations such as searching and sorting.

**- Operating Systems:** 
Operating systems use various data structures to manage system resources, such as processes, files, and memory. Examples include queues for scheduling processes and linked lists for managing file systems.

**- Compiler Design:**
 Compilers use data structures like syntax trees and symbol tables to analyze and manipulate source code during the compilation process.

**- Network Protocols:**
 Data structures play a vital role in implementing network protocols for communication between devices. For example, packet headers in network protocols are often structured using data structures like arrays and linked lists.


## Why do we need Data Structures? 🧸


**Efficiency:** Using the right data structure can significantly improve the efficiency of operations such as searching, insertion, deletion, and sorting.

**Organization:** Data structures provide a systematic way to organize and manage data, making it easier to understand and maintain large datasets.

**Abstraction:** Data structures abstract away the details of how data is stored and accessed, allowing programmers to focus on solving higher-level problems without worrying about low-level implementation details.

**Reuse and Modularity:** Well-designed data structures can be reused across different applications, promoting code reusability and modularity.
notas
Published: 2024-04-16 16:50:26




Normal distribution
La probabilidad normal de distribucion
funcion con la media la mediana y la moda en el mismo punto


Cuando la Desviacion estandar es muy amplia no hay muchos datos concentrados




distribucion de probabilidad normal




=NORM.DIST(B5, D$2,D$3, FALSO)




RECURSIVIDAD

tecnica de programacion

Base: donde se define el elemento inicial o fundamental
Induccion: la regla que se le aplica a ese elemento para el siguiente


Recurrente


instancias de la misma funcion
pila del programa




lazos - arista al mismo nodo
multigrafos - aristas paralelas, dos al mismo nodo



paseo - vertices se pueden repetir
camino -  vertices no se repiten

puede haber infinitos paseos pero pocos caminos


grafo conexo - todos los vertices hay minimo 1 camino
grafo inconexo - tiene diferentes componentes, tiene vertices sin caminos

paseo cerrado - cuando empieza y termina en el mismo vertice, (circuito)

ciclo - no se repite ningun vertice 
Sale por un lado y entra por otro, no puede regresar por donde mismo.


Arboles permiten organizar informacion jerargica y es facil acceder a la información.
Implementación dinámica

Principio de induccion estructural}






A tree is a connected graph of minimum cost. It means that it has a minimun acount of edges to keep connectivity. Assume two different vertices

-hay un camino de un nodo a cualquier otro nodo
- aciclico, un solo camino para ir a cada nodo


sin ciclos
Que sea conexo


Se usan dos conjuntos de nodos
Elegir uno y conectar aleatoriamente con el otro conjunto

Conjuntos: arboles binarios - permite manejar conjuntos



Grafos en estructura de datos

- Grafos no dirigidos

Uso de matrices, arreglos bidimencionales
ตรวจจับวัตถุบนรูปด้วย OpenCV โดยใช้ Python
Published: 2024-04-16 16:48:56

ตรวจจับวัตถุบนรูป หรือ Object Detection เป็นกระบวนการที่มีความสำคัญในการพัฒนาและประยุกต์ใช้งานในด้านการประมวลผลภาพ โดยสามารถนำ Object Detection ไปพัฒนาต่อในโปรเจกต์ IoT ที่ต้องการจับวัตถุในสถานการณ์ต่างๆ เช่น การตรวจจับการเคลื่อนไหวในบ้าน 

ในบทความนี้เราจะสำรวจและเรียนรู้เกี่ยวกับการตรวจจับวัตถุด้วย OpenCV-Python ซึ่งเป็นไลบรารีที่มีความสามารถในการทำ Object Detection ได้อย่างมีประสิทธิภาพ

Haar Cascades
คลาสฟังก์ชัน Haar Cascade เป็นวิธีที่มีประสิทธิภาพสำหรับการตรวจจับวัตถุ วิธีนี้ถูกเสนอโดย Paul Viola และ Michael Jones ในบทความ Rapid Object Detection using a Boosted Cascade of Simple Features Haar Cascade เป็นวิธีการที่ใช้การเรียนรู้ของเครื่องโดยใช้ภาพบวกและภาพลบเพื่อฝึกคลาสฟังก์ชันตรวจจับวัตถุ

- ขั้นตอนการทำ

> ขั้นตอนที่ 1 นำเข้า libraries ที่ต้องใช้ทั้งหมด

```
pip install opencv-python
pip install matplotlib
import cv2
from matplotlib import pyplot as plt
```


> ขั้นตอนที่ 2 นำเข้ารูปภาพที่ต้องการตรวจจับ

ข้อมูลรูปภาพ: [Download](https://drive.google.com/file/d/1amieL09Q8G5auRC2_l9hwehuqFkKDHwf/view)

```
# Opening image
img = cv2.imread("image.jpg")

# OpenCV opens images as BRG 
# but we want it as RGB and 
# we also need a grayscale 
# version
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Creates the environment 
# of the picture and shows it
plt.subplot(1, 1, 1)
plt.imshow(img_rgb)
plt.show()
```
ผลที่ได้จาก code
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9yklxnfi3olnrscsv06g.png)

> ขั้นตอนที่ 3 ระบุข้อมูลด้วยการใช้ฟังก์ชัน detectMultiScale() ของ OpenCV ในการวิเคราะห์รูปภาพ

```
# Use minSize because for not 
# bothering with extra-small 
# dots that would look like STOP signs
stop_data = cv2.CascadeClassifier('stop_data.xml')
found = stop_data.detectMultiScale(img_gray, 
								minSize =(20, 20))
# Don't do anything if there's 
# no sign
amount_found = len(found)


if amount_found != 0:
	
	# There may be more than one
	# sign in the image
	for (x, y, width, height) in found:
		
		# We draw a green rectangle around
		# every recognized sign
		cv2.rectangle(img_rgb, (x, y), 
					(x + height, y + width), 
					(0, 255, 0), 5)
```

> ขั้นตอนที่ 4 ตรวจสอบผลที่ได้
```
# Creates the environment of 
# the picture and shows it
plt.subplot(1, 1, 1)
plt.imshow(img_rgb)
plt.show()
```
ผลที่ได้จาก code
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/achrau2s3viokckyk9fz.png)


- สรุป
การใช้ Object Detection ใน OpenCV ใช้งานง่ายและมีความสามารถสำหรับการตรวจจับวัตถุ สามารถตรวจจับวัตถุทั่วไปได้หลากหลาย โดยไม่จำเป็นต้องกำหนดให้เฉพาะวัตถุใดๆ ตามลักษณะ เช่น ตรวจป้าย, รถ, คน

- References
https://www.youtube.com/watch?v=iyHlRIwiiS4
https://www.geeksforgeeks.org/detect-an-object-with-opencv-python/?ref=lbp
https://www.geeksforgeeks.org/python-haar-cascades-for-object-detection/?ref=lbp
Using Callback and useMemo Hooks in ReactJS
Tags: react, javascript, webdev, programming
Published: 2024-04-16 16:47:57

In ReactJS, the callback and useMemo hooks are powerful tools that can enhance the performance and functionality of your components. In this article, we will explore how to use these hooks effectively with examples.

**Section 1: Callback Hook**

The useCallback hook allows you to memoize a function and prevent unnecessary re-renders. It is particularly useful when passing callbacks to child components, as it ensures that the callback reference remains stable unless the dependencies change.

**_Example:_**
Let's say we have a parent component that renders a child component and passes a callback function as a prop. Without using useCallback, the callback function would be recreated on every render, potentially causing unnecessary re-renders in the child component.

```jsx
import React, { useCallback } from 'react';

const ParentComponent = () => {
  const handleClick = useCallback(() => {
    console.log('Button clicked!');
  }, []);

  return <ChildComponent onClick={handleClick} />;
};

const ChildComponent = ({ onClick }) => {
  return <button onClick={onClick}>Click me</button>;
};
```

In the example above, the useCallback hook ensures that the handleClick function is only recreated when the dependencies change (in this case, there are no dependencies). This optimization can significantly improve the performance of your application.

**Section 2: useMemo Hook**

The useMemo hook allows you to memoize the result of an expensive computation. It is useful when you have a computationally expensive function that is called within your component.

**_Example:_**
Let's consider a scenario where we have a component that needs to compute a factorial value based on a given number. Without using useMemo, the factorial computation would occur on every render, even if the input number remains the same.

```jsx
import React, { useMemo } from 'react';

const FactorialComponent = ({ number }) => {
  const factorial = useMemo(() => {
    const computeFactorial = (n) => {
      if (n === 0 || n === 1) return 1;
      return n * computeFactorial(n - 1);
    };

    return computeFactorial(number);
  }, [number]);

  return <div>Factorial of {number} is {factorial}</div>;
};
```

In the example above, the useMemo hook memoizes the result of the factorial computation based on the `number` prop. It ensures that the computation is only performed when the `number` prop changes, preventing unnecessary calculations and improving performance.

**Conclusion:**
By utilizing the useCallback and useMemo hooks in ReactJS, you can optimize your components, reduce unnecessary re-renders, and improve the overall performance of your application. These hooks are valuable tools to enhance the efficiency and responsiveness of your ReactJS projects.

**Follow me in [X/Twitter](https://twitter.com/ashsajal1)**
Bloom CBD Gummies Review, SCAM WEBSITE COST & Worth Buying
Published: 2024-04-16 16:21:35

Product Name :- Bloom CBD Gummies

Main Benefits:- Pain Relief, Official Store And Price

Composition:- Natural Organic Compound

Side-Effects:- NA

Rating:- ⭐⭐⭐⭐⭐

Availability:- Online

Where to Buy:- Official Website – {Buy Now Here — Click Here}

Bloom CBD Gummies:- 

Today, with the analysis and studies made on the extensive topic on how to cope with issues related to your bodily functions, medical experts have put their findings into work through the Bloom CBD Gummies.

Official Website@:- https://allsupplementstore.com/bloom-cbd-gummies/ 

Click Here@:- https://allsupplementstore.com/bloom-cbd-gummies-buy/ 
Facebook@:- https://www.facebook.com/BloomCBDGummiesOfficial/ 
Jimdo@:- https://bloom-cbd-gummies-usa.jimdosite.com/ 

PDF SITES@:- https://cms1.publuu.com/flipbook-maker/1051539 
https://flipbooklets.com/pdfflipbooklets/bloom-cbd-gummies-buy#page1 
https://online.fliphtml5.com/otapx/uory/#p=1 
https://issuu.com/georgegummi/docs/bloom_cbd_gummies_usa 
https://anyflip.com/kuzgf/iafc 

Official Blog@:- https://thebloomcbdgummies.blogspot.com/2024/04/bloom-cbd-gummies.html 
https://sites.google.com/view/bloom-cbd-gummies-official/ 
https://medium.com/@georgegummi/bloom-cbd-gummies-surveys-scam-uncovered-2024-read-fixings-and-aftereffects-92246d1365b1 
https://www.irvac.org/group/mysite-200-group/discussion/f2184d3f-753c-4f48-915e-605b756150e3 
https://www.linkedin.com/events/bloomcbdgummies-benefits-offer-7185544506933424128/ 
https://the-bloom-cbd-gummies.company.site/ 
https://in.pinterest.com/pin/1000995454668062351  
https://teeshopper.in/products/How-to-devour-Bloom-CBD-Gummies 
https://www.eventbrite.com/e/bloom-cbd-gummies-reviews-reduces-pain-stress-anxiety-best-for-pain-relief-tickets-883189472487?aff=oddtdtcreator 
https://fms.microsoftcrmportals.com/forums/general-discussion/b7b99da1-06fb-ee11-a73c-6045bd20e9c7 
https://bloomcbdgummiesbuy.mystrikingly.com/ 
https://bloom-cbd-gummies.hashnode.dev/bloom-cbd-gummies-update-2024-price-ingredients-benefits-reviews 
https://solo.to/bloomcbdgummiesus  
https://sketchfab.com/3d-models/bloom-cbd-gummies-list-of-ingredients-d9261830b49c446290520227d5beda65
Azure Kubernetes Services 101
Published: 2024-04-16 16:03:53

**I would like to cover some of Azure Kubernetes Services **

1. Introduction to Azure Kubernetes Service (AKS): An Overview
2. Getting Started with AKS: Step-by-Step Guide
3. Deploying Your First Application on AKS
4. Managing AKS Clusters: Best Practices
5. Autoscaling Applications on AKS
6. Monitoring and Logging in AKS
7. Securing AKS Workloads: Policies and Best Practices
8. Disaster Recovery Strategies for AKS Clusters
9. Upgrading and Patching AKS Clusters
10. Networking in AKS: Configuration and Best Practices
11. Using Helm Charts to Simplify AKS Deployments
12. Implementing Stateful Applications on AKS
13. Cost Optimization Techniques for AKS Environments
2024-04-15: Machine learning
Tags: devjournal
Published: 2024-04-16 16:02:12

Last week was a fairly slow week. Two of the main psychologists were out doing personal things so I was basically on my own.

One of the things that needed to get done was improvement on one of the prompts for generating the second part of the app, but obviously the psychology is not my responsibility or domain so I naturally had to wait for an opportune time to meet with them once they came back.

In the meanwhile, I spent a lot of my time learning more about LLMs and ML. For LLM research, I was following DeepLearning.ai's new course on parsing unstructured data. For ML, I was following freeCodeCamp's course. Both have been teaching me a lot thus far.

I also had two interviews but nothing super interesting to report in that regard.

Friday I was met with a bug from our marketer who said that past message history was carrying over to a new chat, and though I wasn't able to reproduce her issue with the raw code, I recognized that it was probably due to some kind of latency on the actual website that may present itself due to the online nature of things vs. my running it on my local machine which has near-instantaneous connections. My hunch was confirmed when I introduced some artificial latency and I started chatting before the chat history would actually get cleared in the memory.

I got to work implementing some thread locks so that the chat can't be accessed if the chat history is still being cleared. It was a mild pain because the syntax for it is a bit strange in Python, but I eventually got it working flawlessly and even started with adding some logging for important data flow points in the code, which will be useful for the future.

Anyway, that's kinda it for last week. Hopefully I have some more interesting stuff to write for next week. Cheers.