teleren/devto huggingface dataset:
Weekly Challenge 174
Tags: perl, python, theweeklychallenge
Published: 2022-07-24 05:13:08

[Challenge](https://theweeklychallenge.org/blog/perl-weekly-challenge-174/), [My solution](https://github.com/manwar/perlweeklychallenge-club/tree/master/challenge-174/sgreen)

Just doing one task this week. The second one is nothing more than copying and pasting code from the mentioned website, so I cannot see the point. YMMV.

## Task: Disarium Numbers

Write a script to generate first 19 Disarium Numbers.

A disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.

### My solution

This is pretty straight forward. Have a list (array in Perl) called `solutions`. Keep iterating a `number` until their are nineteen items in that list. Add the number to the list if the number is disarium.

To determine disarium numbers I loop over each digit using `enumerate(str(n))`. The enumerate function is roughly equivalent to using the each function over an array in Perl (the first value is the counter, the second value is the digit at that position).

If the sum is the original number, return `True` otherwise return `False`.

The Perl code is similar to the Python code. The code to calculate the sum is slightly different.

### Examples

```
$ ./ch-1.py 
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 89, 135, 175, 518, 598, 1306, 1676, 2427, 2646798

$ ./ch-1.pl 
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 89, 135, 175, 518, 598, 1306, 1676, 2427, 2646798
```
Git Principais Comandos
Tags: git, github, beginners, tutorial
Published: 2022-07-24 05:12:00

## Primeiro vamos configurar o git na sua máquina

```
git config --global user.email "seu_email_aqui"
```
##Agora vamos definir seu nome

```
git config --global user.name "seu_nome_aqui"
```
##Clonando repositório
Você acabou de criar um repositório remoto, e quer clona-lo na sua máquina:
```
git clone link_do_repositório
```
###Adicionando um repositório em um projeto já existente
Você está trabalhado em um projeto, mas criou o repositório depois. 

```
git init      --Inicia o repositório na sua máquina
git add .     --Faz com que os gir observe os arquivos
git commit -m "Primeiro commit"    --Salva as modificações
git remote add origin Link_do_repositório    --Adciona os arquivos no repositóro remoto
```

##Se o repositório estiver vazio
Se o repositório remoto estiver vazio então vamos executar 
```
git push origin master 
```

##Se o repositório NÃO estiver vazio
```
git pull origin master
git push origin master
```

##Mostrando estado do diretório

Mostra o estado do diretório atual e da área de staging. Perite ver quais mudanças estão ou não prontas para serem commitadas e arquivos que não estão endo rastreados pelo git

##Desfazer algo que você adicionou

Se você executou:

```
git add <arquivo> ou git add.
```

E você **quer desfazer** porque acabou adicionando a arquivo errado, então execute:

```
git reset <arquivo>
```

Ou se você **quer desfazer todos os arquivos** adicionados, execute apenas:

```
git reset
```

##Desfazer o último Commit

Você fez um commit, então percebeu que **algo estava errado** com ele. Para desfazê-lo, basta executar:

```
git reset ~HEAD
```

Você também pode executar: 

```
git revert HEAD
```

A diferença é que git **revert** adicionará um novo commit que reverterá **o último** commit (**é melhor utilizar o reset, porque é mais especifico, o que está errado pode não ser o último commit**)

##Editando o último commit

Para editar o último commit ou a última mensagem de commit execute:

```
git commit --amend -m "nova mensagem"
```

##Fez alterações, mas quer voltar para a versão anterior

```
git checkout .
```

Para remover alterações **locais** de **arquivos específicos** em vez de todas as alterações, você pode executar:

git checkout <arquivo>

##Criar uma nova branch

```
git branch <nova_branch>
```

##Mudar de uma branch para outra

```
git checkout <nome_da_branch>
```

##Crie uma nova branch e mude instantaneamente para ela

```
git checkout -b <nome_da_branch>
```

##Deletar uma branch

```
git branch -d <nome_da_branch>
```

##Unir branchs

Esteja na branch que você quer unir com a outra e execute:

```
git merge <nome_da_branch>
```

#Remover arquivo de um repositório Git

```
git rm <arquivo>
```

Para remover esses arquivos **apenas do Git sem removê-los localmente**:

```
git rm --chached <arquivos>
```

Para remover **diretórios,** basta adicionar a  a opção **-r**
Fixing Malayalam Issue in Firefox
Tags: malayalam, firefox, linux
Published: 2022-07-24 05:03:00

# Intro
I was having issues on using some websites. It was not getting rendered properly.

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

# Fixes

## 1. Installing a Firefox Addon

Actually, installing this add-on did fix the issue.
https://addons.mozilla.org/en-US/firefox/addon/instant-malayalam/

## 2. Fixing by installing fonts at system level

`sudo apt install fonts-smc`

Above package is meta package, it install a lot of fonts. Just use `apt search fonts-smc-*` to find individual font name.

# Conclusion

![Correct Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/229nyg1pnt88bl7jx2e9.png)
 

Doing either Fix 1 or 2 solves the problem for me. But, 2nd one seems to be good one if you're on Linux.
Developer daily routine job Guide
Tags: webdev, javascript, beginners, guide
Published: 2022-07-24 05:00:00


This is just experience i would like to share with community how to execute daily tasks as a (Web Developer), i have shared some code templates also which will make your life easier 🚀. 

Whenever you receive any task from your manager/ Senior. divide that thing into small parts try to complete 1 thing at a time don't start writing code, think first and then comment it maybe what your are going to do and then start writing. 

Even before dividing task into smaller things you have to do most important part here i.e. understand the problem what exactly you are trying to solve, if you have doubts ask your Senior they will be happy to help, but if you did not understood problem well you will end-up with wrong solution or with no solution at all, so 

understand -> think -> comment flow -> code 

now i am going to give some solid time saving scripts here that will help in your daily job , starting with

...

👉 REST setup with php + mysql 🔗 [link](https://github.com/pavandeore/rest-php)

 
👉 Copy text functionality from webpage 🔗 [link](https://github.com/pavandeore/copy-text-using-javascript)


👉 Embed CSS efficiently (Optimized Way) 🔗 [link](https://github.com/pavandeore/css-rendering-technique)


👉 Check if Div is on screen or not 🔗 [link](https://github.com/pavandeore/inviewport)


👉 How to send xhr request 🔗 [link](https://github.com/pavandeore/xhr)


👉 HTTP POST request using async-await with error handling 🔗 [link](https://github.com/pavandeore/javascript-async-await-http-post-with-error-handling)


👉 Git reset/ revert guide 🔗 [link](https://dev.to/pawandeore/ultimate-guide-for-git-revert-getting-your-changes-back-3kco)


👉 Scroll to Top of page from bottom 🔗 [link](https://github.com/pavandeore/scroll-to-top)


👉 Rapid Development tips🔗 [link](https://dev.to/pawandeore/rapid-development-tips-4dp3)


👉 Optimize your CSS with CSSO 🔗 [link](https://css.github.io/csso/csso.html)


👉 Optimize your JS with google closure compiler 🔗 [link](https://closure-compiler.appspot.com/home)


👉 Use Squoosh for Image minification 🔗 [link](https://squoosh.app/)





If you like the tips, and would like to share your dev tips connect with me on [Github](https://github.com/pavandeore) OR [Linkedin](https://www.linkedin.com/in/pawan-deore-0bb60b1a4/)

...

[Buy me a Coffee](https://www.buymeacoffee.com/pawandeore)
240. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-24 04:25:37

```
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m = matrix.size();
        if(m == 0) return false;
        int n = matrix[0].size();
        if(n == 0) return false;
        int r = n;
        // cout << m << " " << n << " " << r << endl;
        
        for(vector<int>& row : matrix){
            //upper_bound: Unlike lower_bound, the value pointed by the iterator returned by this function cannot be equivalent to val, only greater.
            //the search range becomes smaller and smaller
            auto it = upper_bound(row.begin(), row.begin() + r, target);
            //if we've found an element larger than target, we can shrink the range
            //o.w. the range remains the same
            if(it !=  row.begin() + r){
                r =  it - row.begin();
            }
            //r is the position where row[r] > target(notice it's not >= !!)
            // cout << r << endl;
            /*
            row[r] is the minimum element we can find, 
            and it is larger than target, 
            so we will not find target in the remaining part of the matrix
            */
            if(r == 0) return false;
            if(row[r-1] == target) return true;
        }
        
        return false;
    }
};
```


#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/search-a-2d-matrix-ii/
Flutter: 🔴 How to Create and Read data || Future Builder || Part - 3
Tags: flutter, supabase, nextdev
Published: 2022-07-24 04:16:00

Hey there 👋, in this blog post, you will learn how to create and read the data in supabase using flutter packages (supabase_flutter).

If you understand Hindi 👇
{% embed https://youtu.be/LIwo8ylJElc %}
Firstly, you need to set up supabase in a flutter. So for that, you need to read this 👇 article.
[**How to use supabase database in flutter || 🔴 Part — 1**](https://medium.com/@nextdevelopment1111/how-to-use-supabase-database-in-flutter-part-1-56c87668d0f0)

Step1: You need to make a table for the supabase database

![](https://cdn-images-1.medium.com/max/5120/1*ndGHIMFbah3yJf_9v36jVw.png)

Step2: Now you need to make a todo.dart file
{% gist https://gist.github.com/nextdev1111/d437e5985cbd8c52dda7c331f84cc1eb.js %}
You can make models.dart file in the **model **folder.

    export 'todo.dart';

Step3: Now, you need to make a supabase_data_manager.dart’ in the **data folder** in the **utils folder. eg 👇**

![](https://cdn-images-1.medium.com/max/3840/1*QE2W5YQrTzYUUWx28utshg.jpeg)

Now you can use this code 👇
{% gist https://gist.github.com/nextdev1111/8cdb7c39a49b86c4bc5b824c99dea509.js %}
Then you can make a utils.dart file in the utils folder.

    // from data

    export 'data/supabase_data_manager.dart';

Now, you need to make a screens folder.

there are 3 files in the screens folder

 1. Create Screen — ‘create_screen.dart’

 2. Read Screen — ‘read_screen.dart’

 3. screens.dart for exporting the above screens
{% gist https://gist.github.com/nextdev1111/da1e5299422454d4b9c19390b9aedd50.js %}{% gist https://gist.github.com/nextdev1111/9adb497006e9363091adc9611cfcf944.js %}

{% gist https://gist.github.com/nextdev1111/35ac4b3633d6c74305ae4fd05d34116a.js %}


Now, you can switch the screens in the main. dart.

Example
{% gist https://gist.github.com/nextdev1111/266e3524bd3704ac9ce61c7dfd2e6416.js %}
Thanks for reading this blog. You can now try it out.

If you want to how to update and delete data 👇 

[https://medium.com/@nextdevelopment1111/flutter-how-to-update-and-delete-data-in-supabase-part-4-675bf3f8fcbc](https://medium.com/@nextdevelopment1111/flutter-how-to-update-and-delete-data-in-supabase-part-4-675bf3f8fcbc)

If you have any questions, feel free to ask here 👇
[**Join the Next Dev Discord Server!**](https://discord.gg/hN4Wc5VR4M)
Does Manifest v3 accept script-src?
Tags: chrome
Published: 2022-07-24 04:10:11

its says that the directives, one of them being script-src, may have "only the following values" which then goes on to list "self" however I used that in my code and I still got the error "
'content_security_policy.extension_pages': Insecure CSP value  "https://js.pusher.com/4.2/pusher.min.js" in directive 'script-src'."
`   
    {
      "manifest_version": 3,
      "name": "Real-time NFL score",
      "version": "1.0",
      "description": "A simple Chrome extension to simulate the NFL scores in real-time",
      "content_security_policy": {
	  "extension_pages": "script-src 'self' https://js.pusher.com/4.2/pusher.min.js https://stats.pusher.com; object-src 'self'"
	  },
      "action": {
        "default_icon": "./img/icon.png",
        "default_popup": "popup.html"
      },
      "permissions": ["notifications", "activeTab"]
    }`
Depth first search GeeksForGeeks
Published: 2022-07-24 02:33:36

Given a connected undirected graph. Perform a Depth First Traversal of the graph.
Note: Use recursive approach to find the DFS traversal of the graph starting from the 0th vertex from left to right according to the graph..

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

Example 1:

Input:

Output: 0 1 2 4 3
Explanation: 
0 is connected to 1, 2, 4.
1 is connected to 0.
2 is connected to 0.
3 is connected to 4.
4 is connected to 0, 3.
so starting from 0, it will go to 1 then 2
then 4, and then from 4 to 3.
Thus dfs will be 0 1 2 4 3.
 

**For a single component**:
```java

class Solution {
    // Function to return a list containing the DFS traversal of the graph.
    public ArrayList<Integer> dfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {
        // Code here
        
        ArrayList<Integer> dfs = new ArrayList<>();
        boolean visited[] = new  boolean[V];
        if(!visited[0])
        dfsUtil(0,dfs,adj,visited);
        return dfs;
    }
    public void dfsUtil(int node, ArrayList<Integer> dfs, ArrayList<ArrayList<Integer>> list,
    boolean[] visited){
        dfs.add(node);
        visited[node] = true;
        List<Integer> deepNodes = list.get(node);
        for(Integer n : deepNodes){
            if(!visited[n])
            dfsUtil(n,dfs,list,visited);
        }
    }
}

```
**For more than one component**:
Time complexity : O(n) +O(n)  i.e. O(n) for runnig for loop and another o(n) for `dfsUtil()` (remember the TC is not O(n^2) as `dfsUtil()` will not be called for every iteration in the for loop, it will be called only if there are other component, as in single `dfsUtil()` call all the nodes in that components will be visited.
```java
class Solution {
    // Function to return a list containing the DFS traversal of the graph.
    public ArrayList<Integer> dfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {
        // Code here
        
        ArrayList<Integer> dfs = new ArrayList<>();
        boolean visited[] = new  boolean[V];
        for(int i =0;i<V;i++)
        if(!visited[i])
        dfsUtil(i,dfs,adj,visited);
        
        return dfs;
    }
    public void dfsUtil(int node, ArrayList<Integer> dfs, ArrayList<ArrayList<Integer>> list,
    boolean[] visited){
        dfs.add(node);
        visited[node] = true;
        List<Integer> deepNodes = list.get(node);
        for(Integer n : deepNodes){
            if(!visited[n])
            dfsUtil(n,dfs,list,visited);
        }
    }
}
```
How to set caret on a node in a contenteditable element
Tags: tutorial, javascript, typescript
Published: 2022-07-24 02:22:00

## Secret

You **CANNOT** set the caret on a contenteditable element only by `foucs()` on the element.

## Code Sample

### JavaScript
```javascript
const setCaret = (
  contenteditableElement,
  node,
  position
) => {
  const selection = window.getSelection();
  if (!selection) return;

  // Create a new range
  const range = document.createRange();
  range.setStart(node, position);
  range.collapse(true);

  // Remove the current range
  selection.removeAllRanges();

  // Add the new range
  selection.addRange(range);

  // Focus on the contenteditable element instead of the node if needed.
  contenteditableElement.focus();
};
```

### TypeScript
```typescript
const setCaret = (
  contenteditableElement: HTMLElement,
  node: Node,
  position: number
): void => {
  const selection = window.getSelection();
  if (!selection) return;

  // Create a new range
  const range = document.createRange();
  range.setStart(node, position);
  range.collapse(true);

  // Remove the current range
  selection.removeAllRanges();

  // Add the new range
  selection.addRange(range);

  // Focus on the contenteditable element instead of the node if needed.
  contenteditableElement.focus();
};
```

## Detail

```javascript
range.collapse(true);
```
sets [Range.collapsed](https://developer.mozilla.org/en-US/docs/Web/API/Range/collapsed) to true, which means the start and end points of the Range are at the same position.

## References
- [Selection](https://developer.mozilla.org/en-US/docs/Web/API/Selection)
- [Window.getSelection()](https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection)
- [Document.createRange()](https://developer.mozilla.org/en-US/docs/Web/API/Document/createRange)
- [Range.collapsed](https://developer.mozilla.org/en-US/docs/Web/API/Range/collapsed)
- [Range.collapse()](https://developer.mozilla.org/en-US/docs/Web/API/Range/collapse)
- [Range.setStart()](https://developer.mozilla.org/en-US/docs/Web/API/Range/setStart)
- [Selection.removeAllRanges()](https://developer.mozilla.org/en-US/docs/Web/API/Selection/removeAllRanges)
- [Selection.addRange()](https://developer.mozilla.org/en-US/docs/Web/API/Selection/addRange)
- [HTMLElement.focus()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus)
Menghitung Batas Maksimal Ukuran File di JavaScript
Published: 2022-07-24 02:15:23

Di dalam framework JavaScript modern, ketika kita upload file, biasanya kita bikin function handler untuk menangani jika terjadi perubahan pada isi dari input bertipe file. Misalnya di **Vue JS** seringnya seperti ini:

```javascript
async fileChange(e) {
  if (e.target.files[0].size / (1024 * 1024) > 10) {
    this.fileError = "File size is too large (max 10 MB)";
  } else {
    this.file = e.target.files[0];
  }
},
```

Maksud dari code di atas adalah, jika ukuran file yang dipilih lebih dari 10 MB, maka akan muncul pesan error. Jika ukuran file kurang dari atau sama dengan 10 MB, maka file akan ditaruh di dalam state.

***

Kenapa kita harus tulis code **(1024 * 1024)** di code kita? Kenapa kita gak langsung tuliskan **1048576**?

Karena ada perbedaan perhitungan ukuran file di sistem operasi yang berbeda. Misal perhitungan ukuran file di **Windows** berbeda dengan **Linux Ubuntu**.

***

Perhitungan file di Windows:

![Windows file calculation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/97fcflyx3mglc35oia90.jpeg)

Perhitungan file di Ubuntu Linux:

![Ubuntu Linux file calculation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dwwdaf2hd75pz3upwscj.png)

***

![Stackoverflow explanation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bf8xysszpry0pgx2jz0q.png)

Baca lebih lanjut:

*https://askubuntu.com/questions/341143/why-same-file-shows-different-sizes-in-different-operating-systems*

Dengan solusi ini, perbedaan perhitungan di OS yang berbeda bisa diatasi, solusi menurutmu kaya gimana?
My Scrimba Front End Developer Journey — Entry 1
Tags: scrimba, javascript, beginners
Published: 2022-07-24 02:11:00


I’m a week into Scrimba’s Front End Developer Path and I’ve never been more motivated to learn to code. I’ve attempted to learn programming in the past but never felt it click. Their guided tutorials with hands-on training in a built in IDE is so perfect for my learning style that I’m optimistic I can finish by the end of the year. It’s an ambitious goal, but I’ve heard it can be done in 3 to 6 months. Which means early next year I may be job hunting. I plan to document my journey here as I go. Fingers crossed…

As of now, I’ve only completed the HTML and CSS portion, modules 1 & 2. I blazed through them though because I’m fairly familiar with both already. I’ve been working in email marketing for a few years and have dabbled in web design periodically, so I have a good foundation in those already. I also did a few freeCodeCamp HTML & CSS tutorials before joining Scrimba as well, which helped. I’m sure the rest of the modules, which all focus on JavaScript, will go much slower and not leave me feeling so confident.

It wasn’t all easy though. Flexbox is a bit new to me, so I’m still wrapping my head around that. In fact, my last project in module 2 didn’t end up the way I wanted because I couldn’t get a flexbox within another flexbox to center properly when on a smaller screen. It was a bit outside of the scope of the project anyway so I wasn’t too worried about it. I googled quite a bit but still couldn’t figure it out. I ended up completing it and submitting it for peer code review to see if someone else could help figure it out. I really like the peer code review feature that Scrimba has built into their curriculum. It really helps to feel engaged with other learners and keep you motivated. They have a dedicated Discord server with lots of channels where students and teachers can interact.

Next up, JavaScript. I’m honestly a little nervous about starting this next module and getting into actual programming. I’ve tried python before and liked it, but I found the program I was in at the time wasn’t a good fit for me. It was more traditional in teaching, but also online, so I just felt like I was watching a YouTube video. I feel like Scrimba is a good fit for me now and I really enjoy how interactive it is, so I’m optimistic about getting through it. Having someone walk you through each step then giving you a chance to practice it immediately is so helpful. It’s so much better than watching videos or sitting through lectures.

That’s about it for this initial post. I’ll try to get one of these up a week with updates on my progress. Thanks for reading!

Oh, this was originally posted by me on Medium (https://medium.com/p/f83dc89a714a), but I thought I'd share it here too.
Calculating Maximum File Size Limit in JavaScript
Tags: javascript, vue, nuxt
Published: 2022-07-24 02:09:49

In modern JavaScript frameworks, when we upload a file, we usually create a function handler to handle if there is a change in the contents of the input file type. For example in **Vue JS** it's often like this:

```javascript
async fileChange(e) {
  if (e.target.files[0].size / (1024 * 1024) > 10) {
    this.fileError = "File size is too large (max 10 MB)";
  } else {
    this.file = e.target.files[0];
  }
},
```

The purpose of the code above is, if the selected file size is more than 10 MB, an error message will appear. If the file size is less than or equal to 10 MB, then the file will be put in state.

***

Why we need to calculate **(1024 * 1024)** in our code? Why don't we just replace the code with **1048576**?

Because there are differences in file size calculations in different operating systems. For example, the calculation of file size in **Windows** is different from **Ubuntu Linux**.

***

File calculation in Windows:

![Windows file calculation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/97fcflyx3mglc35oia90.jpeg)

File calculation in Ubuntu Linux:

![Ubuntu Linux file calculation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dwwdaf2hd75pz3upwscj.png)

***

![Stackoverflow explanation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bf8xysszpry0pgx2jz0q.png)

More on this matter:

*https://askubuntu.com/questions/341143/why-same-file-shows-different-sizes-in-different-operating-systems*

With this solution, the difference in calculations in different OS can be overcome, what do you think is the solution?