teleren/devto huggingface dataset:
970. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-13 05:58:44

```
class Solution {
public:
    vector<int> powerfulIntegers(int x, int y, int bound) {
        set<int> res;
        for (int a = 1; a < bound; a *= x) {
            for (int b = 1; a + b <= bound; b *= y) {
                res.insert(a + b);
                if (y == 1) break;
            }
            if (x == 1) break;
        }
        return vector<int>(res.begin(), res.end());
    }
};
```

#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/powerful-integers/
How to change column to nullable with modify in Ecto migration?
Tags: elixir, beginners, programming, productivity
Published: 2022-07-13 05:57:12

Sooner or later you'll have to change the null constraint in one of your DB relations. How to do it easily in Ecto?

Although I came across many different examples where a raw SQL has been used to perform this type of operation in Ecto, it's actually super easy to do it with [modify/3](https://hexdocs.pm/ecto_sql/Ecto.Migration.html#modify/3) function.

Let's assume that your migration looks like this:

```elixir
create table(:blog_posts) do
  add :title, :string, null: false
  add :intro, :text, null: false
  add :body, :text, null: false
  add :category_id, references(:blog_categories, on_delete: :delete_all)
end
```

[Read more...](https://curiosum.com/til/change-column-to-nullable-ecto-migration)
933. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-13 05:57:08

```
class RecentCounter {
public:
    RecentCounter() {}
    
    int ping(int t) {
        while (!q.empty()) {
        	if (q.front() + 3000 >= t) break;
        	q.pop();
        }
        q.push(t);
        return q.size();
    }

private:
	queue<int> q;
};
```

#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/number-of-recent-calls/
969. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-13 05:55:21

```
class Solution {
 public:
  vector<int> pancakeSort(vector<int>& A) {
    vector<int> ans;

    for (int target = A.size(); target >= 1; --target) {
      int index = find(A, target);
      reverse(begin(A), begin(A) + index + 1);
      reverse(begin(A), begin(A) + target);
      ans.push_back(index + 1);
      ans.push_back(target);
    }

    return ans;
  }

 private:
  int find(vector<int>& A, int target) {
    for (int i = 0; i < A.size(); ++i)
      if (A[i] == target)
        return i;
    throw;
  }
};

```

#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/pancake-sorting/
971. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-13 05:54:14

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
// Time: O(NlogN)
// Space: O(logN)
class Solution {
private:
    vector<int> ans;
    int find(vector<int>& v, int begin, int end, int target) {
        int i = begin;
        while (i < end && v[i] != target) ++i;
        return i;
    }
    bool preorder(TreeNode *root, vector<int>& voyage, int begin, int end) {
        if (!root) return end == begin;
        if (end == begin || voyage[begin] != root->val) return false;
        if (!root->left && !root->right) return begin + 1 == end;
        int leftIndex = end, rightIndex = end;
        if (root->right) {
            rightIndex = find(voyage, begin + 1, end, root->right->val);
            if (rightIndex == end) return false;
        }
        if (root->left) {
            leftIndex = find(voyage, begin + 1, end, root->left->val);
            if (leftIndex == end) return false;
        }
        if (preorder(root->left, voyage, begin + 1, rightIndex)
                && preorder(root->right, voyage, rightIndex, end)) return true;
        if (preorder(root->left, voyage, leftIndex, end)
                && preorder(root->right, voyage, begin + 1, leftIndex)) {
            ans.push_back(root->val);
            return true;
        }
        return false;
    }
public:
    vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) {
        if (preorder(root, voyage, 0, voyage.size())) return ans;
        return { -1 };
    }
};
```

#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/
979. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-13 05:52:07

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
 public:
  int distributeCoins(TreeNode* root) {
    int ans = 0;

    dfs(root, ans);

    return ans;
  }

  // return how many coins I can give (positive) / take (negative)
 private:
  int dfs(TreeNode* root, int& ans) {
    if (!root)
      return 0;

    const int l = dfs(root->left, ans);
    const int r = dfs(root->right, ans);
    ans += abs(l) + abs(r);

    return (root->val - 1) + l + r;
  }
};

```

#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/distribute-coins-in-binary-tree/
974. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-13 05:50:51

```

class Solution {
 public:
  int subarraysDivByK(vector<int>& A, int K) {
    int ans = 0;
    int prefix = 0;
    vector<int> count(K);
    count[0] = 1;

    for (int a : A) {
      prefix = (prefix + a % K + K) % K;
      ans += count[prefix];
      ++count[prefix];
    }

    return ans;
  }
};

```


#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/subarray-sums-divisible-by-k/
1952. Leetcode Solution in Java
Tags: java
Published: 2022-07-13 05:48:50

```
class Solution {
    public boolean isThree(int n) {
        int sqrt = (int) Math.sqrt(n);
        if (sqrt * sqrt != n)
            return false;
        int divisors = 1;
        for (int i = 1; i < sqrt; i++) {
            if (n % i == 0)
                divisors += 2;
        }
        return divisors == 3;
    }
}
```

#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/three-divisors/
What is unsubscribe in Sveletekit?
Tags: svelte, sveltekit, webdev
Published: 2022-07-13 05:48:49

When I tried to create persited store in SvelteKit, I had to understand unscribe function like below.

```
<script>
	import { onDestroy } from 'svelte'
	import { writable } from 'svelte/store';
	
	const count = writable(0, () => {
		console.log('Start subscribing')
                // Below function is called when execute unsubscribe function.
		return () => console.log('Stop subscribing');
	})
	
	const increment = () => count.update(value => {
		return value + 1
	})

	const unsubscribe = count.subscribe(value => {
		console.log(value)
	})

        onDestroy(unsubscribe)
</script>

<button on:click={increment}>
	Increment
</button>
<button on:click={unsubscribe}>
	Stop subscribe
</button>
```

## What is unsubscribe function?
If we use subscribe, we should stop the subscribing. Because when component is died, we cannot stop it and use lots of memory. So we should call unsubscribe function with `onDestory` function. But it is too trouble to develop... ... so we can use `$` prefix as instead.
1974. Leetcode Solution in Java
Tags: java
Published: 2022-07-13 05:46:29

```
class Solution {
    public int minTimeToType(String word) {
        int time = 0;
        char prev = 'a';
        int length = word.length();
        for (int i = 0; i < length; i++) {
            char curr = word.charAt(i);
            int difference = Math.abs(curr - prev);
            difference = Math.min(difference, 26 - difference);
            time += difference + 1;
            prev = curr;
        }
        return time;
    }
}
```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter/
110. Leetcode Solution in Java
Tags: java
Published: 2022-07-13 05:42:12

```
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        if(Math.abs(leftHeight - rightHeight) > 1)
            return false;
        return isBalanced(root.left) && isBalanced(root.right);
    }
    private static int getHeight(TreeNode node){
        if(node == null) return 1;
        return Math.max(getHeight(node.left), getHeight(node.right)) + 1;
    }
}
```


#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/balanced-binary-tree/submissions/
110. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-13 05:41:35

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
 public:
  bool isBalanced(TreeNode* root) {
    if (!root)
      return true;
    return abs(maxDepth(root->left) - maxDepth(root->right)) <= 1 &&
           isBalanced(root->left) &&
           isBalanced(root->right);
  }

 private:
  int maxDepth(TreeNode* root) {
    if (!root)
      return 0;
    return 1 + max(maxDepth(root->left), maxDepth(root->right));
  }
};

```

#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/balanced-binary-tree/submissions/
226. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-13 05:40:13

```
class Solution {
 public:
  TreeNode* invertTree(TreeNode* root) {
    if (!root)
      return nullptr;

    TreeNode* const left = root->left;
    TreeNode* const right = root->right;
    root->left = invertTree(right);
    root->right = invertTree(left);
    return root;
  }
};

```

#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/invert-binary-tree/
621. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-13 05:38:40

```
class Solution {
 public:
  int leastInterval(vector<char>& tasks, int n) {
    if (n == 0)
      return tasks.size();

    vector<int> count(26);

    for (const char task : tasks)
      ++count[task - 'A'];

    const int maxFreq = *max_element(begin(count), end(count));
    // put the most frequent task in the slot first
    const int maxFreqTaskOccupy = (maxFreq - 1) * (n + 1);
    // get # of tasks with same frequency as maxFreq,
    // we'll append them after maxFreqTaskOccupy
    const int nMaxFreq = std::count(begin(count), end(count), maxFreq);
    // max(
    //   the most frequent task is frequent enough to force some idle slots,
    //   the most frequent task is not frequent enough to force idle slots
    // )
    return max(maxFreqTaskOccupy + nMaxFreq, static_cast<int>(tasks.size()));
  }
};

```


#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/task-scheduler/
2131. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-13 05:37:06

```
class Solution {
 public:
  int longestPalindrome(vector<string>& words) {
    int ans = 0;
    vector<vector<int>> count(26, vector<int>(26));

    for (const auto& word : words) {
      const int i = word[0] - 'a';
      const int j = word[1] - 'a';
      if (count[j][i]) {
        ans += 4;
        --count[j][i];
      } else {
        ++count[i][j];
      }
    }

    for (int i = 0; i < 26; ++i)
      if (count[i][i])
        return ans + 2;

    return ans;
  }
};
```



#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/
102. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-13 05:35:13

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
 public:
  vector<vector<int>> levelOrder(TreeNode* root) {
    if (!root)
      return {};

    vector<vector<int>> ans;
    queue<TreeNode*> q{{root}};

    while (!q.empty()) {
      vector<int> currLevel;
      for (int sz = q.size(); sz > 0; --sz) {
        TreeNode* node = q.front();
        q.pop();
        currLevel.push_back(node->val);
        if (node->left)
          q.push(node->left);
        if (node->right)
          q.push(node->right);
      }
      ans.push_back(currLevel);
    }

    return ans;
  }
};

```



#Leetcode
#challende
Here is the link for the problem:
 https://leetcode.com/problems/binary-tree-level-order-traversal/
[ReactNative] How to solve "Unable to resolve module xxx"
Published: 2022-07-13 05:23:02


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

1: rm -rf ios/build
2: rm -rf node_modules
3: npm cache clean --force
4: npm install
5: npm start -- --reset-cache
6: npx react-native run-ios
Obika GPS Pt 1: My First Project using Traccar.
Tags: traccar, beginners, gps, tracking
Published: 2022-07-13 05:21:58

Hi there! ✌

  Once upon a time me and a friend were trying to build a customized GPS System but it was complicated because of money and knowlwdge. After a while I still looking for information to build a customized GPS tracker. I live in Mexico and the technical information in these topics are limited sometimes(I mean, Spanish information).


## **What I'm trying with this?:**

  Basically a simple and portable GPS Tracker with alarm button to send it as a WhatsApp/Telegram/E-Mail notification in addition to a good battery life. 

  Yes, I know that there are many options in the market but many of them have issues to customize or use them in different ways. I'm focused in drivers for example as a personal project by the moment considering that is not a hard project for experienced people, I'd like to start with this... 😊

## **How it will works?:**

  I have in mind three principal complements for this project:

-📕 Traccar as mastermind of tracking.
-📗 WhatsApp/Telegram as notifers.
-📘 Customizable GPS tracker with alarm button.

  In this way the GPS send the location and the alarm notification to Traccar. If the button alarm is pusshed it'll send a notification to WhatsApp/Telegram trought Traccar, it depends if you want the notification only for the driver or other people.

## Closing Step one

  In next steps I'll explain the three components to connect them together and make them functional 😊


Thanks for reading 🙌
102. Leetcode Solution in JavaScript
Tags: javascript
Published: 2022-07-13 05:14:01

```
var levelOrder = function(root) {
    let q = [root], ans = []
    while (q[0]) {
        let qlen = q.length, row = []
        for (let i = 0; i < qlen; i++) {
            let curr = q.shift()
            row.push(curr.val)
            if (curr.left) q.push(curr.left)
            if (curr.right) q.push(curr.right)
        }
        ans.push(row)            
    }
    return ans
};
```


#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/binary-tree-level-order-traversal/
#4. Creating models for mongoDb collections ☀
Tags: mongodb, react, javascript, webdev
Published: 2022-07-13 05:13:22

## Today we'll see How to create model for mongoDB in js.

- Create a folder name models in vscode directory.

- Create a file 'Users.js' as we prefer capital latter for models.

Below is the ss of directory


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

```
const mongoose = require('mongoose');

const UserSchema = mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true,
    },
    avatar: {
        type: String,
    },
    date: {
        type: Date,
        default: Date.now
    }
})

module.exports = User = mongoose.model('user', UserSchema);
```
We have used mongoose as a lib for mongoDb.

[YT link for reference](https://youtu.be/JLJirfb2JWU)
Introducing Authsignal
Published: 2022-07-13 05:06:22

{% embed https://youtu.be/5RUq4cuDCGU %}

👋 My name is Justin, On my first day of my last job, I walked into my office hoping to be greeted with high fives and fist pumps after my company's first big fund raise.

I got the opposite, I walked into a burning fire 🔥 where my company (FinTech) didn't realize that they had been credential stuffed for 3 months straight! Just as I was walking through the door, they were facing the onslaught of account take overs. I spent the next 3 years learning about the world of scales ups and how it creates a big target for fraud.

🚫 Problem
1. It was very hard to observe fraud within your platform, there was no Google analytics for fraud, there were disparate reporting tools, a team of people who can write SQL, and two weeks later you have some insight on your risk. A little too late.

2. If you were able to observe your risk, great! Your next move is to defend against the adversarial nature of fraud actors. You do this through implementing risk controls and risk management. Risk and ops quickly turned into "if" statements littered through the code base and our teams were tasked with constant requirements to tweak and modify parameters and rules, it was a resource drain and didn't empower business users. We found many platforms with the same problem.

3. The last thing on the list to think about, and typically the most overlooked is the User Experience, after spending so much time on problem 1 and 2, most companies leave this to last and give a sub par experience for good customers, blocks, customer support wait times, frustrating conversations with support reps to verify who you are over email. Meanwhile cyber criminals exploit this knowing the more chaos they wreck into your system the more good customers get impacted.


✅ Solution
[Authsignal.com](https://www.authsignal.com/?utm_source=dev_to&utm_medium=post) is a suite of tools for platforms to observe fraud risk in their systems in near real time, make operational adjustments to how they manage risk via a no code rules engine, and passwordless authenticator flows that can be used to step up customers or to sign transactions, all through a single API call, augmentable into your current stack, with no additional vendors/sales people to talk to.

Authsignal solves a fragmented ecosystem of solutions through great Developer Experience (DX) via a lightning fast integration and out of the box Fraud Ops best practices so you don't have to do the heavy lifting.

🚀 Vision
A Fraud Ops operating system, delivering delightful trust and safety for customers.
Find & Document a Go Project's Flags as Markdown
Published: 2022-07-13 04:50:12

Goal: Given a Go project, I want to find all of the flags available and document the flag name, flag type, description, and default value as a Markdown table.

The `_process_line` can probably be cleaned up a bit, but this worked enough for my use case. Optimizations welcome as comments!

Note:
- Only works if flag is on 1 line (likely missing description if line is too long)

```python
import subprocess

def _find_flag_initializations():
    """Grep for a lines that initalize a flag"""
    cmd = "grep -nr '= flag.' . --include=*.go"
    return subprocess.check_output(cmd, shell=True).splitlines()


def _write_flags_to_md(lines):
    """Write the flag name, type, desc, & default value to stdout as md"""
    print(f"Name | Type | Description | Default")
    print("|-|-|-|-|")
    for line in lines:
        flag_name, flag_type, flag_desc, flag_default  = _process_line(line)
        print(f"`{flag_name}` | {flag_type} | {flag_desc} | {flag_default}")

def _process_line(line):
    """Given a line of Go code that initalizes a flag, derive the
    flag's name, type, desc, & default value"""
    prepped = str(line.decode().split("= flag.")[1])
    flag_name = prepped.split(',')[0].split('(')[1].replace('"','')
    flag_type = prepped.split('(')[0]
    flag_desc = prepped.split(',',2)[2].replace('`','').replace(')','').replace('"','').strip()
    flag_default = prepped.split(',')[1].strip()
    return flag_name, flag_type, flag_desc, flag_default

lines = _find_flag_initializations()
_write_flags_to_md(lines)

# Tests
happy_path = b'./logic/recommender.go:28:\tpodMinMemoryMb       = flag.Float64("pod-recommendation-min-memory-mb", 250, `Minimum memory recommendation for a pod`)'
f_name, f_type, f_desc, f_default = _process_line(happy_path)
assert f_name == 'pod-recommendation-min-memory-mb'
assert f_type == 'Float64'
assert f_desc == 'Minimum memory recommendation for a pod'
assert f_default == '250'

description_with_comma = b'./routines/recommender.go:52:\tmemorySaver             = flag.Bool("memory-saver", false, `If true, only track pods which have an associated VPA`)'
f_name, f_type, f_desc, f_default = _process_line(description_with_comma)
assert f_name == 'memory-saver'
assert f_type == 'Bool'
assert f_desc == 'If true, only track pods which have an associated VPA'
assert f_default == 'false'

default_with_string = b'./main.go:56:\tpodNameLabel        = flag.String("pod-name-label", "kubernetes_pod_name", `Label name to look for pod names`)'
f_name, f_type, f_desc, f_default = _process_line(default_with_string)
assert f_name == 'pod-name-label'
assert f_type == 'String'
assert f_desc == 'Label name to look for pod names'
assert f_default == '"kubernetes_pod_name"'
```
NaaS: Conclusions (for now)
Tags: kubernetes, multitenancy, tips
Published: 2022-07-13 04:50:12

After evaluating multiple solutions these are the conclusions at this time:

**NaaS with vanilla kubernetes objects** - for a shoestring budget with limited expertise
- Excellent starting point
- No CRDs
- Requires some support scripts (atleast a helm chart) to provide an overall solution
- No auditing
- Edits and updates are not straight forward

---
**Hierarchical namespaces** - step-up over the above solution, use it if you just want inheritance of limits, quotas and rbac objects
- Very limited overhead
- Almost any resource can be inherited
- Took a long time to come to 1.0 => there is a lot of deliberation (don't know the specifics of why it took time)
- Not much in-terms of auditing and RBAC levels
- Hierarchical and normal namespaces dont play well at times (could be my setup issue)

---
**vCluster** - kubernetes in kubernetes; soft cluster as a service solution 
- Excellent candidate for developing and testing CRDs
- Full fledged isolation
- Cross namespace communication is *apparently* hard

---
**Kiosk** - multitenancy with strong and complex templating
- Can be very powerful with templates
- Templating is not easy to master (needs more real-world examples in my case)

---
**Capsule** - simpler than *Kiosk*
- All in one tenant definitions
- Not sure on extensibility w.r.to custom objects (CRDs)
- Needs a tenant admin to set things up and monitor => a dashboard necessary at some point of time

---
##### TODO
We could not get to test how [okteto](https://github.com/okteto/okteto) is implementing multi-tenancy and could not get to testing [kubeslice](https://github.com/kubeslice) yet. These are much more than multi-tenancy solutions so are of interest to us