teleren/devto huggingface dataset:
Serialize and Deserialize BST
Tags: leetcode, dsa, theabbie
Published: 2022-06-19 04:00:48

Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a **binary search tree**. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.

**The encoded string should be as compact as possible.**

**Example 1:**

**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]

**Example 2:**

**Input:** root = \[\]
**Output:** \[\]

**Constraints:**

*   The number of nodes in the tree is in the range `[0, 104]`.
*   `0 <= Node.val <= 104`
*   The input tree is **guaranteed** to be a binary search tree.

**SOLUTION:**

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Codec:
    
        def serialize(self, root: Optional[TreeNode]) -> str:
            tree = {}
            paths = [(root, 0)]
            while len(paths) > 0:
                curr, i = paths.pop()
                if curr:
                    tree[i] = curr.val
                    paths.append((curr.left, 2 * i + 1))
                    paths.append((curr.right, 2 * i + 2))
            return ";".join(["{}={}".format(k, v) for k, v in tree.items()])
    
        def deserialize(self, data: str) -> Optional[TreeNode]:
            vals = data.split(";")
            tree = {}
            for v in vals:
                if len(v) > 0:
                    key, value = v.split("=")
                    tree[int(key)] = int(value)
            if len(tree) == 0:
                return None
            root = TreeNode()
            paths = [(root, 0)]
            while len(paths) > 0:
                curr, i = paths.pop()
                curr.val = tree[i]
                if (2 * i + 1) in tree:
                    curr.left = TreeNode()
                    paths.append((curr.left, 2 * i + 1))
                if (2 * i + 2) in tree:
                    curr.right = TreeNode()
                    paths.append((curr.right, 2 * i + 2))
            return root
    
    # Your Codec object will be instantiated and called as such:
    # Your Codec object will be instantiated and called as such:
    # ser = Codec()
    # deser = Codec()
    # tree = ser.serialize(root)
    # ans = deser.deserialize(tree)
    # return ans
Webpack & Tailwind CSS Setup
Tags: webdev, programming, webpack, beginners
Published: 2022-06-19 04:00:19

Step by step Webpack and Tailwind CSS configuration setup.  
Create **package.json**

```
npm init -y
```
Create your **src** folder and add an empty **index.js** file.

**Webpack Setup**

Install webpack and loaders

```
npm install webpack webpack-cli webpack-dev-server postcss-loader css-loader
-D
```

Create  **webpack.config.js** in the root and update file.

```
// webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: {
    bundle: path.resolve(__dirname, 'src/index.js'),
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name][contenthash].js',
    clean: true,
    assetModuleFilename: '[name][ext]',
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader', 'postcss-loader'],
      },
    ],
  },
  devServer: {
    static: {
      directory: path.resolve(__dirname, 'dist'),
    },
    port: 3000,
    open: true,
    hot: true,
    compress: true,
    historyApiFallback: true,
  }
};
```

**Setup Tailwind CSS**

Install Tailwind CSS

```
npm install -D tailwindcss postcss autoprefixer

npx tailwindcss init
```
Add Tailwind to your PostCSS configuration:

```
// postcss.config.js

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}
```

Configure your template paths:

```
// tailwind.config.js

module.exports = {
  content: ['./dist/*.html'],
  theme: {
    extend: {},
  },
  plugins: [],
}
```
Add Tailwind directives to your CSS:

```
// styles.css

@tailwind base;
@tailwind components;
@tailwind utilities;
```

Start using Tailwind in your HTML:

```
<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="/dist/main.css" rel="stylesheet">
</head>
<body>
  <h1 class="text-center p-3">
    Webpack with Tailwind CSS
  </h1>
</body>
</html>
```

Add scripts to package.json:

```
"scripts": {
    "dev": "webpack serve",
    "build": "webpack"
  },
```
**Running Your App**

To build once and create your **dist/bundle.js**

```
npm run build
```
To run your webpack server

```
num run dev
```
Now you have Webpack setup with Tailwind CSS!

To see this (and more) in action check: 
[GITHUB](https://github.com/j45t7/webpack-tailwind)

Sources:
[Tailwind CSS](https://tailwindcss.com/docs/installation/using-postcss)
[Webpack](https://webpack.js.org/)
Don't hard code a function's name anymore
Tags: javascript, typescript, node, logs
Published: 2022-06-19 03:46:21

I've been coding in Javascript/typescript and Nodejs for quite a while now and I've seen that is a common practice to hard code the name of the currently executing function's name in a string, usually to log it to help during debugging.

Sometimes this may cause some issues. If we change the function name, then we need to remember and read the code to find and replace all the old function names hard coded in a string. We may forget to replace the function name instances and the logs would then be logging the wrong function name.

Take a look at the following block of code. We can see that we are hard coding the class and function names, which I think doesn't look really good.

```js
import log4js from "log4js";

log4js.configure("./log-config.json");

class FunctionNameExample {

  logger: log4js.Logger;
  id: number;

  constructor() {
    this.logger = log4js.getLogger("FunctionNameExample");
  }

  getId() {
      this.logger.trace("[getId]");
      return this.id;
  }

  processTransaction(tx: any) {
      this.logger.trace("[processTransaction]");
      if(!tx) {
          this.logger.warn(`[processTransaction] no tx was provided`);
      }
  }

}

```

So, I better solution is to use the class and function `name` included in the class and function themselves.

Take a look at the following block of code, which uses the class and functions `name` property instead of hard coding the names:

```js
import log4js from "log4js";

log4js.configure("./log-config.json");

class FunctionNameExample {

  logger: log4js.Logger;
  id: number;

  constructor() {
    this.logger = log4js.getLogger(FunctionNameExample.name); // now using the .name property that the class has.
  }

  getId() {
    this.logger.trace(this.getId.name); // now using the .name property that the function has.
    return this.id;
  }

  processTransaction(tx: string) {
    const functionName = this.processTransaction.name;
    this.logger.trace(this.processTransaction.name);
    if (!tx) {
      this.logger.warn(`[${functionName}] no tx was provided`);
    }
  }

}

```

I think this is a better solution. If we change the function name, then the compiler will complain that there are uses of functions that are not defined, which helps us find them and right away replace them.

For example, after changing the function name from `processTransaction` to `processTheTransaction` the compiler complains and tells me exactly where I need to look for the issue:

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

There are other programming languages that have a different way to easily get the currently executing function's name, like PHP with it's global _____FUNCTION_____ value:

```js
function test() {
    echo __FUNCTION__;
}
```
With Javascript we need to use the approach I described above to be able to get the currently executing function's name in a 'compilable' way, since the compiler would complain if it doesn't find the function.

Comment below if you have any thought about this approach.
Valid Palindrome
Tags: leetcode, dsa, theabbie
Published: 2022-06-19 03:30:36

A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_.

**Example 1:**

**Input:** s = "A man, a plan, a canal: Panama"
**Output:** true
**Explanation:** "amanaplanacanalpanama" is a palindrome.

**Example 2:**

**Input:** s = "race a car"
**Output:** false
**Explanation:** "raceacar" is not a palindrome.

**Example 3:**

**Input:** s = " "
**Output:** true
**Explanation:** s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.

**Constraints:**

*   `1 <= s.length <= 2 * 105`
*   `s` consists only of printable ASCII characters.

**SOLUTION:**

    class Solution:
        def isPalindrome(self, s: str) -> bool:
            s = "".join([c.lower() for c in s if c.isalnum()])
            return s == s[::-1]
Average Salary Excluding the Minimum and Maximum Salary
Tags: leetcode, dsa, theabbie
Published: 2022-06-19 03:00:41

You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.

Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.

**Example 1:**

**Input:** salary = \[4000,3000,1000,2000\]
**Output:** 2500.00000
**Explanation:** Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500

**Example 2:**

**Input:** salary = \[1000,2000,3000\]
**Output:** 2000.00000
**Explanation:** Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000

**Constraints:**

*   `3 <= salary.length <= 100`
*   `1000 <= salary[i] <= 106`
*   All the integers of `salary` are **unique**.

**SOLUTION:**

    class Solution:
        def average(self, salary: List[int]) -> float:
            n = len(salary)
            total = 0
            currmin = float('inf')
            currmax = float('-inf')
            for i in range(n):
                currmin = min(currmin, salary[i])
                currmax = max(currmax, salary[i])
                total += salary[i]
            return (total - currmin - currmax) / (n - 2)
Cyber Security resources
Tags: oscp, ctf, bugbounty, cybersecurity
Published: 2022-06-19 02:54:09

Collection of useful resources I found on the Internet related to Cyber Security career.

## General

- [The Career](https://www.quora.com/Is-penetration-testing-a-rewarding-career)
- [Media Resources](https://github.com/nahamsec/Resources-for-Beginner-Bug-Bounty-Hunters/blob/master/assets/media.md)
- [Web Vulnerabilities](https://sucuri.net/guides/owasp-top-10-security-vulnerabilities-2020/)
- [Learn & Practice](https://portswigger.net/web-security/all-materials)

## Bug Bounty

- [What is it really?](https://geekflare.com/bug-bounty-platforms/)
- [Hunting Methodology](https://forum.bugcrowd.com/t/how-do-you-approach-a-target/293)
- [Popular Tools](https://github.com/nahamsec/bbht)
- [Practice Hacking Skills](https://github.com/EdOverflow/bugbounty-cheatsheet/blob/master/cheatsheets/practice-platforms.md)
- [Write ups](https://pentester.land/list-of-bug-bounty-writeups.html)
- [Reporting Bugs](https://researcherdocs.bugcrowd.com/docs/reporting-a-bug)

## Capture The Flags

- [The Beginner Guide](https://medium.com/bugbountywriteup/beginners-guide-to-ctfs-c934a0d7f5f9)
- [Calender of All Events](https://ctftime.org/)
- [Popular Tools List](https://github.com/zardus/ctf-tools)

## Penetration Testing

- [Guide To Method](https://www.cloudflare.com/en-in/learning/security/glossary/what-is-penetration-testing/)
- [OSCP Certification](https://github.com/superhero1/OSCP-Prep)
- [Practice Penetration](https://www.hackthebox.eu/)
- [LinkedIn Jobs](https://www.linkedin.com/jobs/search/?keywords=oscp)
Twitch and YouTube
Tags: beginners, tutorial, programming, gamedev
Published: 2022-06-19 02:47:49

Hello :wave: I just wanted to reach out to the community and let anyone that may be interested every WED at 9pm CST (10EST/2a UTC) I run a live Twitch of just tinkering with various frameworks. I focus on .NET but who knows , maybe if I get a good following we can dive into whatever together. Notice I said We? the point of the stream is to learn together and build some stuff. What do I get? I get to learn too. If apps and such are not your jam then I also do Game development with Unity on Sat 9a CST (10 EST/ 2p UTC). We have been building Galaxy Wars 2 . You can play the first [here](https://slugga.itch.io) . Come join me and lets have some fun while we learn! The more I grow the more I will invest in the show and tailor the experience for learning paths for all. That is my end goal. As for [YouTube](https://www.youtube.com/channel/UCJmONoDK8mDZswc1t5WiW0Q), currently it will have a reduced version of the Twitch live stream but I am planning out structured learning experiences to upload. I want to avoid the usually tutorial habit of showing something I know works. We will break stuff sometimes, I do not script this at all besides the idea of the night. Just know you will learn something at least, or laugh at me and I def like making people laugh :laugh:
[JOIN ME!](https://twitch.tv/abm_dev)
[YouTube](https://www.youtube.com/channel/UCJmONoDK8mDZswc1t5WiW0Q)
WED - 9pm CST (10EST/2a UTC) - .NET APPs (Currently TMNT MAUI App)
SAT - 9a CST (10 EST/ 2p UTC) - UNITY3D Galaxy Wars 2 development 
[Galaxy Wars](https://slugga.itch.io/galaxy-wars)

PS .
I am also looking for people to play Lost Ark with . Zosma and I forget the other one :sweat: but least Zosma ! comment below your handle if you want to play!
Backspace String Compare
Tags: leetcode, dsa, theabbie
Published: 2022-06-19 02:30:40

Given two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character.

Note that after backspacing an empty text, the text will continue empty.

**Example 1:**

**Input:** s = "ab#c", t = "ad#c"
**Output:** true
**Explanation:** Both s and t become "ac".

**Example 2:**

**Input:** s = "ab##", t = "c#d#"
**Output:** true
**Explanation:** Both s and t become "".

**Example 3:**

**Input:** s = "a#c", t = "b"
**Output:** false
**Explanation:** s becomes "c" while t becomes "b".

**Constraints:**

*   `1 <= s.length, t.length <= 200`
*   `s` and `t` only contain lowercase letters and `'#'` characters.

**Follow up:** Can you solve it in `O(n)` time and `O(1)` space?

**SOLUTION:**

    class Solution:
        def backspaceCompare(self, s: str, t: str) -> bool:
            ss = ""
            tt = ""
            for c in s:
                if c == "#":
                    ss = ss[:-1]
                else:
                    ss += c
            for c in t:
                if c == "#":
                    tt = tt[:-1]
                else:
                    tt += c
            return ss == tt
Crawler Log Folder
Tags: leetcode, dsa, theabbie
Published: 2022-06-19 00:30:36

The Leetcode file system keeps a log each time some user performs a _change folder_ operation.

The operations are described below:

*   `"../"` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain in the same folder**).
*   `"./"` : Remain in the same folder.
*   `"x/"` : Move to the child folder named `x` (This folder is **guaranteed to always exist**).

You are given a list of strings `logs` where `logs[i]` is the operation performed by the user at the `ith` step.

The file system starts in the main folder, then the operations in `logs` are performed.

Return _the minimum number of operations needed to go back to the main folder after the change folder operations._

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/09/09/sample_11_1957.png)

**Input:** logs = \["d1/","d2/","../","d21/","./"\]
**Output:** 2
**Explanation:** Use this change folder operation "../" 2 times and go back to the main folder.

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/09/09/sample_22_1957.png)

**Input:** logs = \["d1/","d2/","./","d3/","../","d31/"\]
**Output:** 3

**Example 3:**

**Input:** logs = \["d1/","../","../","../"\]
**Output:** 0

**Constraints:**

*   `1 <= logs.length <= 103`
*   `2 <= logs[i].length <= 10`
*   `logs[i]` contains lowercase English letters, digits, `'.'`, and `'/'`.
*   `logs[i]` follows the format described in the statement.
*   Folder names consist of lowercase English letters and digits.

**SOLUTION:**

    class Solution:
        def minOperations(self, logs: List[str]) -> int:
            ctr = 0
            for log in logs:
                if log == "../":
                    ctr =  max(ctr - 1, 0)
                elif log != "./":
                    ctr += 1
            return ctr
SaasRock v0.2.7 - Roles, Permissions, Groups, and Row-level visibility
Tags: saas, roles, permissions, javascript
Published: 2022-06-19 02:25:07

---
title: SaasRock v0.2.7 - Roles, Permissions, Groups, and Row-level visibility
published: true
description: Added admin and application Roles & Permissions for page views and actions. Added application Groups and Row-level visibility - only you, public, or share with account members, groups, or specific users.
tags: saas,roles,permissions,javascript
cover_image: https://yahooder.sirv.com/saasrock/blog/june-2022-update/cover2.png
---

v0.2.7 has been released with security features - [saasrock.com](https://saasrock.com).

Added admin and application Roles & Permissions for page views and actions. Added application Groups and Row-level visibility - only you, public, or share with account members, groups, or specific users.

## Closed issues

- ✅ Add Page: Roles and User roles [#14](https://github.com/AlexandroMtzG/remix-saas-kit/issues/14)
- ✅ Add Page: Object-level permissions (Create, Read, Update, Delete) [#15](https://github.com/AlexandroMtzG/remix-saas-kit/issues/15)
- ✅ Rename the "tenant" nomenclature to "account" [#52](https://github.com/AlexandroMtzG/remix-saas-kit/issues/52)

## Roles & Permissions 🪨

[Click here to view the demo.](https://www.loom.com/share/131cb3b5d558474da260f02247ec48ed)

### Roles

![Roles](https://user-images.githubusercontent.com/8606530/174460485-0c17e2bb-1eb7-490b-8e6e-1546770401d7.png)

### Permissions

![Permissions](https://user-images.githubusercontent.com/8606530/174460558-589ac602-2061-4fe6-a9a0-e734f75269b4.png)

### Set Admin Roles

![Set Admin Roles](https://user-images.githubusercontent.com/8606530/174461740-65b264ce-38f4-4e82-a6a9-77bd123a0deb.png)

### Set App/Account Roles

![Set App/Account Roles](https://user-images.githubusercontent.com/8606530/174460587-ef90a695-1fcd-4ddb-af9b-641c27a73481.png)

## Row-level visibility & permissions 🪨

[Click here to view the demo.](https://www.loom.com/share/da273ba374e543508358443663b2dd79)

### Groups

![Groups](https://user-images.githubusercontent.com/8606530/174460615-a20dbedc-bdbf-4248-91dc-f86002aac812.png)

### Private (default)

![Private (default)](https://user-images.githubusercontent.com/8606530/174460688-7069d654-ce39-4b55-8777-69e17a69c315.png)

### Share to Account Members

![Share to Account Members](https://user-images.githubusercontent.com/8606530/174460695-4de0bf14-7e95-46e0-9852-9cacb92f55fa.png)

### Share to Specific Groups

![Share to Specific Groups](https://user-images.githubusercontent.com/8606530/174460699-9a149df9-7406-4fe6-923d-9cb04560395d.png)

### Share to Specific Users

![Share to Specific Users](https://user-images.githubusercontent.com/8606530/174460705-ec683416-2ac1-4efb-91da-4de152e88459.png)

### Set Public

![Set Public](https://user-images.githubusercontent.com/8606530/174460711-ac9beeca-6af9-4a6e-959d-5b03a744b9ee.png)

### Public row view

![Public row view](https://user-images.githubusercontent.com/8606530/174460727-d2a10e3e-70a1-46c1-b5f2-e558ee6e840a.png)

---

If you liked this post, [subscribe to the newsletter](https://saasrock.com/newsletter) for more 😃.
How did Blogging changed my life?
Published: 2022-06-19 02:21:29

Blogging changed my life. I will keep it short, crisp and to the point discussion.

It all started with,

→ The problem I solved.
→ Putting the solution in a document.
→ Sharing it in public.


Here are few lessons from my BLOGGING journey and a few Bonus tips.🔥

1. START TODAY.

Do not get stuck thinking when is the right time. Any time you have a topic in hand and the willingness to start is the right time.

For me, it started with journaling and helping my friends with article writing. Anything can be a trigger.

2. Find your NICHE

The thing you are best in is always around you. Find this thing and work on it and share it with the world.

3. READ MORE

A great writer is also a great reader. 
Yes, It's hard to create value with writing without reading. Build a reading habit to write better. 

4. Your Writing Is Your Reflection.

You are unique, your style is unique, your expressions are unique, your writing will be unique too. Your writing style is a reflection of who you are.

Be AUTHENTIC. Inspiration is ok but No need to borrow the style. 
·
Oct 9, 2021
5. Be CONSISTENT

To become great at it or build a career around it, you need to translate the Hobby into a Habit. 

You do it by putting yourself on a roadmap like 1 article a week for a month! I would suggest reading ATOMIC HABITS, it focuses on building small habits but they have a big cumulative effect in the long term and takes you to the success.
How to Solve Unwanted CSS Transitions on Page Load
Tags: html, css, csstransitions, frontend
Published: 2023-01-12 14:24:47

---
title: How to Solve Unwanted CSS Transitions on Page Load
published: true
date: 2022-06-19 02:07:33 UTC
tags: 
- HTML
- CSS
- CSSTransitions
- Frontend
canonical_url: https://fajarwz.com/blog/how-to-solve-unwanted-css-transitions-on-page-load/
---
![Writing CSS illustration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2t9jidguvxtj0o7pnc3z.png)

There is a case where you need to add transitions to your page. Maybe you put it on some pages or even all pages. Then you noticed there is an unwanted transitions on page load.

## Transitions Enabled Only After Page Load
We can fix that. The idea is to disable transitions in our page first then enable it after the page loaded.

First we can create a CSS class that disable transitions: 

```css
.no-transition * {
    -webkit-transition: none !important;
    -moz-transition: none !important;
    -ms-transition: none !important;
    -o-transition: none !important;
    transition: none !important;
}
```

Then put it on body element:

```html
<body id="body" class="no-transition">
```

When the page loads, remove it:

```js
function transitionAfterPageLoad() {
    document.getElementById("body").classList.remove("no-transition");
}

// call the function inside an Immediately Invoked Function Expression (IIFE) to invoke it immediately after page load
(function() {
    transitionAfterPageLoad();
})()

// jQuery 
$(function() {
    $("#body").removeClass("no-transition");
});
```

That's it, easier than we think.

## Conclusions
To fix unwanted CSS Transitions on page load we can disable transitions to our page first then re-enable it after the page loaded.

Have another tip or even a better one about this issue? Please let us know in the comments section below 👇. Share this if you think this is helpful. Thank you.