teleren/devto huggingface dataset:
Simple MATLAB Intro. Getting to Know the Interface
Tags: matlab, beginners, tutorial
Published: 2022-07-21 07:23:23

MATLAB is a very used programming language among engineers, so I decided to give it a shot and start learning and practising it. In this post, I will talk about the first steps I learned in MATLAB: options for using MATLAB, different windows in the interface and how to change the current working folder. So let's get to it!

## Options for using MATLAB

At the moment of writing this post, there are two different ways of using MATLAB: the desktop program and the online version (called MATLAB Online).

The desktop program requires you to have a licence and to have installed MATLAB on your computer.

The online version doesn't require you to install anything, but it needs you to have a licence also and an internet connection. The downside of this version is that it lacks some functions that the desktop program has.

In this post, I will focus on the desktop version.

## Windows in the MATLAB interface

When you open MATLAB, you will see three different interfaces: The Current Folder window, the Command Window and the Workspace.

We can also customize the position of these windows as we prefer by clicking on the top bar of each window and dragging it.

![MATLAB Desktop](https://cdn.hashnode.com/res/hashnode/image/upload/v1658349156862/Y6UGTgT8-.png)

### Current Folder Window

In the current folder window, we can access the files in the current folder we are working on with the program. We can also access another folder inside the current one.

### Command Window

In this window, we introduce the commands for our program after the >> sign.

### Workspace

In this window, we can check the values of the variables we have created and the value of the data we have imported.

## Travelling Between Folders

As previously mentioned, we can access files and folders inside the working folder through the Current Folder window. But there are also different ways of moving between folders.

If we want to go to the previous folder, we can click the "Up one level" button (located above the Current Folder window).

We can also open a folder we choose directly by clicking the "Browse for Folder" button (located above the Current Folder window too).

![Up One Level Button and Browse for Folder Button](https://cdn.hashnode.com/res/hashnode/image/upload/v1658349756820/L-LHWWHhB.png)

Above the three windows, we also have the address bar, where we can see the address of the current folder. By clicking on one of the folders of that address, we will make that folder the working folder.

![Address Bar](https://cdn.hashnode.com/res/hashnode/image/upload/v1658349858775/iFhD-j66s.png)

If we click on the small triangle on the right of the bar, we can select any of the folders that we have recently opened.

## Conclusion

I hope you have enjoyed this small tutorial about the interface of MATLAB and that you find it useful.

Now you should be able to choose the folders you want to work in and move between them, which is the first step to starting writing various programs in MATLAB.
Windows restore system environment variables
Tags: windows
Published: 2022-07-21 06:59:27

Windows System 內建許多系統環境變數，一般在安裝軟體時，有時候會需要手動將軟體安裝位置的根目錄加入到 Environment Variable 裡，前一篇介紹了如何增刪修環境變數，這篇主要介紹萬一手殘不小心刪掉變數該怎麼還原？

由於圖形介面沒有一個快速還原的按鈕，必須使用其他的方法來還原它

打開登錄編輯程式（regedit）

![win-001](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/60ht94xd78ltl0wsn5pp.png)

找到路徑 `HKEY_LOCAL_MACHINE > SYSTEM > CurrentControlSet > Control > Session Manager > Environment`


![win-002](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gdedxkzdvs9truvr3pz5.png)

在右邊視窗的名稱欄位找到要還原的變數名稱，我的狀況是要找 `Path` 變數，故以此為例，資料欄位是變數的內容，該內容就是之前被刪除的變數值，將此內容複製，再依照上一篇的作法將變數添加回去就完成了！

> _該方法有一個限制，必須在修改後的設定值還沒寫回去才可使用_

---

Thanks for reading the article :tulip: :sunflower: :blossom:

If you like it, please don't hesitate to click heart button :heart:
or follow my [GitHub](https://github.com/FakeStandard) :star:
or buy me a coffee :arrow_down: I'd appreciate it.

[![Buy-me-a-coffee][1]][2]

[1]: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h077sxd0vx1hix4t7lw8.png
[2]: https://www.buymeacoffee.com/FakeStandard

---
Playwright & dropdown
Published: 2022-07-21 06:55:05

Hello Playwright Experts,

could someone give me an example how to read the selected value/option from a dropdown, please?

I have tried this **syntax (JAVA)**, but it returns all the options of the dropdown.

`page.locator("//xpath to dropdown webelement").textContent()`

I only want to read what is **selected option**? :-) Could you give an example how to do this with **JAVA + playwright**

Thank you very much

Cheers, Loren
Random Password generator - Easiest way { Python }
Tags: programming, python, tutorial, beginners
Published: 2022-07-21 06:52:28

In this post I will help you build a random password generator in the most easiest and efficient way.

How can we build this 🤔?
1. First thing we will do is to ask the user what is the length of the string
2. We will get random values from a list containing all the alphabets(both uppercase and lowercase), numbers and special characters like #,@,#... 

## ⚠️⚠️⚠️ Mistake we need to avoid ⚠️⚠️⚠️
Most of the people generally makes this mistake while doing this project. they will create a list and they will start writing all the characters, numbers manually... like below code 👇👇 

```python
characters = ['a','b','c','d',......,'A','B','C'....]
```
This will definitely not make you a good programmer.

## Instead do this ✅✅ 
There is a module named `string` in python which will give you all the alphabets and special characters.

Create a list which contain all the alphabets, numbers and special characters as shown below.

```python
import string

# getting all the alphabets
characters = list(string.ascii_letters)

# adding numbers from 0 to 9
characters.extend(list(x for x in range(0,10)))

# adding all the special characters
characters.extend(list(string.punctuation))
```
`characters` list will look as shown below.

```python
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']
```

## 🚀 Complete Code for creating random password generator using Python.

```python
import string
import random

num = int(input('Enter the length of password : '))

# getting all the alphabets
characters = list(string.ascii_letters)

# adding numbers from 0 to 9
characters.extend(list(x for x in range(0,10)))

# adding all the special characters
characters.extend(list(string.punctuation))

password = ''

for i in range(num):
    password = password + str(random.choice(characters));

print(password)
```

Thanks for Reading 💖💖
Like and Follow.
Explain why the following doesn't work as an IIFE: "function foo(){ }();". What needs to be changed to properly make it an IIFE?
Tags: javascript, webdev, node, beginners
Published: 2022-07-21 06:46:00

This code returns a token error:

```JavaScript
function foo(){ }(); // Error: Unexpected token ')'
```

### Parens
If we place an expression inside the second parens (the grouping operator, which expects an expression to be evaluated), the error goes away.

```JavaScript
function foo(){ }(1);
```

So, we know the token error is due to the second parens, which did not have any expression to evaluate.

But... it still doesn't work as an IIFE.

### Breakdown
Let's change `foo()` to log a greeting. As you can see, nothing gets logged to the console.

```JavaScript
function foo(){ console.log('Hello from foo!') }(1); // Nothing logged to the console
```

This is because `foo()` is never invoked.

In fact, we are wrong in expecting `foo()` to be invoked like this:

```JavaScript
function foo(){ console.log('Hello from foo!') }();
```
Because, the second parens does not stand for invoking `foo()` here. And that is because the function declaration left to it, `function foo(){ }`, is not an expression. It's just a definition.

The parser sees the code above as:

```JavaScript
function foo(){ console.log('Hello from foo!') };
();
```
### Fix
In order to make the second parens (immediately) invoke `foo()`, we need to make the function declaration evaluate to a function expression first. And guess what, we do it with another parens.

```JavaScript
(function foo(){ console.log('Hello from foo!') });
```

We can then go ahead and apply the invocation parens:

```JavaScript
(function foo(){ console.log('Hello from foo!') }(); // "Hello from foo!"
```
Another fix would be to wrap the entire code in an overarching parens. This will also make it work as an IIFE:

```JavaScript
(function foo(){ console.log('Hello from foo!') }()); // "Hello from foo!"
```
Here, everything, including the last parens is considered part of one expression and so `foo()` gets invoked.


---
References

1. [Immediately-Invoked Function Expression (IIFE)](https://benalman.com/news/2010/11/immediately-invoked-function-expression/)
2. [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE)
1593. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-21 06:18:28

```
class Solution {
 public:
  int maxUniqueSplit(string s) {
    size_t ans = 0;
    dfs(s, 0, {}, ans);
    return ans;
  }

 private:
  void dfs(const string& s, int start, unordered_set<string>&& seen,
           size_t& ans) {
    if (start == s.length()) {
      ans = max(ans, seen.size());
      return;
    }

    for (int i = 1; start + i <= s.length(); ++i) {
      const string cand = s.substr(start, i);
      if (seen.count(cand))
        continue;
      seen.insert(cand);
      dfs(s, start + i, move(seen), ans);
      seen.erase(cand);
    }
  }
};

```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/
2343. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-21 06:15:45

```
class Solution {
public:
    static bool compare(pair<string, int>&a, pair<string, int>&b){
        int len = a.first.size();
        for(int i=0;i<len;i++){
            if(a.first[i]<b.first[i]){
                return true;
            }else if(a.first[i] > b.first[i]){
                return false;
            }
        }
        return a.second<b.second;
    }
    vector<int> smallestTrimmedNumbers(vector<string>& nums, vector<vector<int>>& queries) {
        vector<int>ans;
        for(int i=0;i<queries.size();i++){
            int k = queries[i][0];
            int t = queries[i][1];
            vector<pair<string, int>>val;
            int l = 0;
            for(auto str:nums){
                string cur = str.substr(str.size()-t, t);
                val.push_back({cur, l++});
            }
            sort(val.begin(), val.end(), compare);
            ans.push_back(val[k-1].second);
        }
        return ans;
    }
};
```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/query-kth-smallest-trimmed-number/
1605. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-21 06:13:58

```
class Solution {
public:
    vector<vector<int>> restoreMatrix(vector<int>& rowSum, vector<int>& colSum) {
        int m = rowSum.size(), n = colSum.size();
        vector<vector<int>> mat(m, vector<int>(n, 0));
        
        do{
            int min_row = min_element(rowSum.begin(), rowSum.end()) - rowSum.begin();
            int min_col = min_element(colSum.begin(), colSum.end()) - colSum.begin();
            
            // cout << min_row << ", " << min_col << endl;
            
            if((rowSum[min_row] == INT_MAX) && (colSum[min_col] == INT_MAX)) break;
            
            int val = min(rowSum[min_row], colSum[min_col]);
            
            // cout << "val: " << val << endl;
            
            mat[min_row][min_col] = val;
            rowSum[min_row] -= val; if(rowSum[min_row] == 0) rowSum[min_row] = INT_MAX;
            colSum[min_col] -= val; if(colSum[min_col] == 0) colSum[min_col] = INT_MAX;
            
            // cout << "rowSum" << endl;
            // for(int i = 0; i < m; ++i){
            //     cout << rowSum[i] << " ";
            // }
            // cout << endl;
            
            // cout << "colSum" << endl;
            // for(int j = 0; j < n; ++j){
            //     cout << colSum[j] << " ";
            // }
            // cout << endl;
        }while(true);
        
        return mat;
    }
};
```

#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/
ENV vars with Angular & Nx
Tags: angular, nx, env, typescript
Published: 2022-07-21 06:13:11

Primeiro, instale `@types/node` para que possamos usar `process.env` em nosso código.

```bash
npm install --save-dev @types/node

# Or with yarn
yarn add --dev @types/node
```

Em seguida, atualize os targets `build` e `serve` (no arquivo `project.json` ou `angular.json`), para o seguinte.

```json
{
  "build": {
    // NOTA: altere o executor para um que suporte configurações personalizadas do webpack.
    "executor": "@nrwl/angular:webpack-browser",
    // recorte
    "options": {
      // NOTE: This file needs to be created.
      "customWebpackConfig": {
        "path": "apps/myapp/webpack.config.js"
      }
      // recorte
    }
  },
  "serve": {
    // NOTA: altere o executor para um que suporte configurações personalizadas do webpack.
    "executor": "@nrwl/angular:webpack-server"
    // recorte
  }
}
```

Então, podemos usar `DefinePlugin` em nossa configuração webpack personalizada.

```js
// apps/myapp/webpack.config.js
const webpack = require('webpack');

function getClientEnvironment(configuration) {
  // Grab NODE_ENV and MY_APP_* environment variables and prepare them to be
  // injected into the application via DefinePlugin in webpack configuration.
  const MY_APP = /^MY_APP_/i;

  const raw = Object.keys(process.env)
    .filter((key) => MY_APP.test(key))
    .reduce(
      (env, key) => {
        env[key] = process.env[key];
        return env;
      },
      {
        NODE_ENV: process.env.NODE_ENV || configuration,
      }
    );

  // Stringify all values so we can feed into webpack DefinePlugin
  return {
    'process.env': Object.keys(raw).reduce((env, key) => {
      env[key] = JSON.stringify(raw[key]);
      return env;
    }, {}),
  };
}

module.exports = (config, options, context) => {
  config.plugins.push(
    new webpack.DefinePlugin(getClientEnvironment(context.configuration))
  );
  return config;
};
```

Agora, quando definimos variáveis ​​em nosso arquivo `.env`, como...

```env
# apps/myapp/.env
MY_APP_API_URL=http://localhost:3333
```

Finalmente, podemos usar variáveis ​​de ambiente em nosso código. Por exemplo:

```ts
// apps/myapp/src/main.ts
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

if (process.env['NODE_ENV'] === 'production') {
  enableProdMode();
}

// This is defined in our .env file.
console.log('>>> MY_APP_API_URL', process.env['MY_APP_API_URL']);

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .catch((err) => console.error(err));
```

Você também deve atualizar os arquivos `tsconfig.app.json` e `tsconfig.spec.json` para incluir tipos do node.

```json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    // recorte
    "types": ["node"]
  }
  // recorte
}
```

Agora basta servir a aplicação e sua variável estará no console do browser : )

---

> Nota:
> Isso foi testado em ambiente com versões:
> ```
>   "@nrwl/angular": "^14.4.3",
>   "@nrwl/workspace": "14.4.3"
> ```

---


valeu
[]s
2270. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-21 06:05:46

```
class Solution {
 public:
  int waysToSplitArray(vector<int>& nums) {
    int ans = 0;
    long prefix = 0;
    long suffix = accumulate(begin(nums), end(nums), 0L);

    for (int i = 0; i < nums.size() - 1; ++i) {
      prefix += nums[i];
      suffix -= nums[i];
      if (prefix >= suffix)
        ++ans;
    }

    return ans;
  }
};
```


#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/number-of-ways-to-split-array/
670. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-21 05:59:36

```
class Solution {
 public:
  int maximumSwap(int num) {
    string s = to_string(num);
    vector<int> lastIndex(10, -1);  // {digit: last index}

    for (int i = 0; i < s.length(); ++i)
      lastIndex[s[i] - '0'] = i;

    for (int i = 0; i < s.length(); ++i)
      for (int d = 9; d > s[i] - '0'; --d)
        if (lastIndex[d] > i) {
          swap(s[i], s[lastIndex[d]]);
          return stoi(s);
        }

    return num;
  }
};

```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/maximum-swap/
1830. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-21 05:54:45

```
class Solution {
    int mod = 1e9 + 7;
    
    long pow(long a, long p, long mod) {
        long ans = 1;
        while (p > 0) {
            if (p & 1) {
                ans = ans * a % mod;
            }
            a = a * a % mod;
            p = p >> 1;
        }
        return ans;
    }
public:
    
    int makeStringSorted(string s) {
        map<int, int> freq; 
        for (char ch: s) {
            freq[ch - 'a']++;
        }
        
        int n = s.length();
        vector<long> fact(s.size() + 1, 1);
        for (int i = 1; i <= s.size(); i++) {
            fact[i] = (fact[i - 1] * i) % mod;
        }
        
        long ans = 0;
        for (char ch : s) {
            long freq_sum = 0;
            long duplicates = 1;
            for (int i = 0; i < 26; i++) {
                if (i < (ch - 'a')) {
                    freq_sum += freq[i];
                }
                duplicates = (duplicates * fact[freq[i]]) % mod;
            }
            ans += (freq_sum * fact[n - 1] % mod) * pow(duplicates, mod - 2, mod);
            ans %= mod;
            n--;
            freq[ch - 'a']--;
        }
        return ans;
    }
};
```

#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/minimum-number-of-operations-to-make-string-sorted/
1639. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-21 05:52:51

```
class Solution {
 public:
     typedef long long ll;
     int numWays(vector<string>& words, string target) {
         int N = words[0].size();
         vector<vector<int>> cnt(26, vector<int>(N));
         for (auto w : words) {
             for (int i=0; i<N; i++) {
                 cnt[w[i]-'a'][i]++;
            }
        }
        int T = target.size();
        int MOD = 1e9 + 7;
        vector<vector<ll>> dp(T+1, vector<ll>(N+1));
        for (int i=0; i<=N; i++) dp[0][i] = 1;
        
        for (int i=1; i<=T; i++) {
            for (int j=1; j<=N; j++) {
                dp[i][j] = dp[i-1][j-1]*cnt[target[i-1]-'a'][j-1] + dp[i][j-1];
                dp[i][j] %= MOD;
                if (dp[i][j] < 0) dp[i][j] += MOD;
            }
        }
        return dp[T][N];
    }
};
```

#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/
1489. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-21 05:50:33

```
class UnionFind {
    vector<int> id;
    int size;
public:
    UnionFind(int N) : id(N), size(N) {
        iota(begin(id), end(id), 0);
    }
    int find(int x) {
        return id[x] == x ? x : (id[x] = find(id[x]));
    }
    bool connect(int x, int y) {
        int p = find(x), q = find(y);
        if (p == q) return false;
        id[p] = q;
        --size;
        return true;
    }
    int getSize() { return size; }
};
class Solution {
    int kruskal(int n, vector<vector<int>> &E, int include = -1, int exclude = -1) {
        int cost = 0;
        UnionFind uf(n);
        if (include != -1) {
            auto &e = E[include];
            uf.connect(e[0], e[1]);
            cost += e[2];
        }
        for (int i = 0; i < E.size(); ++i) {
            if (i == include || i == exclude) continue;
            int u = E[i][0], v = E[i][1], w = E[i][2], id = E[i][3];
            if (!uf.connect(u, v)) continue;
            cost += w;
            if (uf.getSize() == 1) break;
        }
        return uf.getSize() == 1 ? cost : INT_MAX;
    }
public:
    vector<vector<int>> findCriticalAndPseudoCriticalEdges(int n, vector<vector<int>>& E) {
        for (int i = 0; i < E.size(); ++i) E[i].push_back(i);
        sort(begin(E), end(E), [](vector<int> &a, vector<int> &b) { return a[2] < b[2]; });
        int cost = kruskal(n, E);        
        vector<int> c, p;
        for (int i = 0; i < E.size(); ++i) {
            if (kruskal(n, E, -1, i) > cost) c.push_back(E[i][3]);
            else if (kruskal(n, E, i) == cost) p.push_back(E[i][3]);
        }
        return { c, p };
    }
};
```

#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree
Bypass Transparent DNS Proxy
Published: 2022-07-21 05:48:24

Since some days ago, I can not update my Devuan box. The error is "Temporary failure in name resolution". This is strange provided that Brave Browser can access deb.devuan.org. Later, I figured out that my ISP (Indihome - https://www.indihome.co.id/) uses transparent DNS proxy and Brave Browser has **Secure DNS** (also known as **DNS Over HTTPS**) so I can access deb.devuan.org from Brave Browser, but I can not access deb.devuan.org from command line. 

This is why eventhough I use 8.8.8.8 in my /etc/resolv.conf, all request to DNS server is intercepted by them and then the request will be directed to ISP for whatever they want. This is unacceptable behaviour but well, complaints won't be heard, so I choose to use DNS over https.

I search for tools and found [dns-over-https](https://github.com/m13253/dns-over-https). This tool uses Go (1.13 or newer) so it's not a big deal for me since I already use Go. Just clone the repo and compile and then execute doh-client ([Go](https://go.dev/) should be available on your system):

```bash
$ git clone https://github.com/m13253/dns-over-https
$ cd dns-over-https
$ make
```

I don't use systemd, So just go to doh-client and run it:

```bash
$ cd doh-client
$ ./doh-client
```

Change /etc/resolv.conf to use 127.0.0.1 as nameserver:

```bash
nameserver 127.0.0.1
```

Then I can use **apt** from shell like before.