teleren/devto huggingface dataset:
834. Leetcode Solution in Java
Tags: java
Published: 2022-07-03 16:55:04

```
class Solution {
  public int[] sumOfDistancesInTree(int N, int[][] edges) {
    int[] ans = new int[N];
    int[] count = new int[N];
    Set<Integer>[] tree = new Set[N];

    Arrays.fill(count, 1);

    for (int i = 0; i < N; ++i)
      tree[i] = new HashSet<>();

    for (int[] e : edges) {
      final int u = e[0];
      final int v = e[1];
      tree[u].add(v);
      tree[v].add(u);
    }

    postorder(tree, 0, -1, count, ans);
    preorder(tree, 0, -1, count, ans);
    return ans;
  }

  private void postorder(Set<Integer>[] tree, int node, int parent, int[] count, int[] ans) {
    for (final int child : tree[node]) {
      if (child == parent)
        continue;
      postorder(tree, child, node, count, ans);
      count[node] += count[child];
      ans[node] += ans[child] + count[child];
    }
  }

  private void preorder(Set<Integer>[] tree, int node, int parent, int[] count, int[] ans) {
    for (final int child : tree[node]) {
      if (child == parent)
        continue;
      // count[child] nodes are 1 step closer from child than parent
      // (N - count[child]) nodes are 1 step farther from child than parent
      ans[child] = ans[node] - count[child] + (tree.length - count[child]);
      preorder(tree, child, node, count, ans);
    }
  }
}

```
1345. Leetcode solution in Java
Tags: java
Published: 2022-07-03 17:06:25

```
class Solution {
    public int minJumps(int[] arr) {
        if (arr.length == 1)
            return 0;
        int count = 0;
        int length = arr.length;
        Map<Integer, List<Integer>> graph = new HashMap<>();
        // populate the graph with index
        for (int i=0; i<length; i++)
            graph.computeIfAbsent(arr[i], x->new LinkedList<>()).add(i);
        // create the boolean array visited
        boolean [] visited = new boolean [length];
        // mark the first element as visited
        visited[0] = true;
        // since we do bfs, we need a queue
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(0);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i=size; i>0; i--) {
                int current = queue.poll();
                // if we reach the last index
                if (current == length - 1)
                    return count;
                // get the possible next values
                List<Integer> next = graph.get(arr[current]);
                // now lets add the previous, ie current-1, next ies, current + 1 into the list
                next.add(current-1);
                next.add(current+1);
                for (Integer j:next) {
                    if (j >= 0 && j<length && !visited[j]) {
                        visited[j] = true;
                        queue.offer(j);
                    }
                }
                next.clear(); 
            }
            count += 1;
        }
        return 0;
    }
}
```
1416. Leetcode solution in cpp
Tags: cpp
Published: 2022-07-03 17:05:23

```
class Solution {
 public:
  int numberOfArrays(string s, int k) {
    // dp[i] := # of arrays to restore s[i..n) w/ k
    dp.resize(s.length(), -1);
    return numberOfArrays(s, 0, k);
  }

 private:
  constexpr static int kMod = 1e9 + 7;
  vector<int> dp;

  int numberOfArrays(const string& s, int i, int k) {
    if (i == s.length())
      return 1;  // empty string """"
    if (s[i] == '0')
      return 0;  // leading zero
    if (dp[i] >= 0)
      return dp[i];

    int ans = 0;
    long num = 0;

    for (int j = i; j < s.length(); ++j) {
      num = num * 10 + (s[j] - '0');
      if (num > k)
        break;
      ans = (ans + numberOfArrays(s, j + 1, k)) % kMod;
    }

    return dp[i] = ans;
  }
};

```
1420. Leetcode solution in Cpp
Tags: cpp
Published: 2022-07-03 17:04:15

```
class Solution {
     long long ways[55][105][55];
      const int mod = 1000000007;
  public:
      int numOfArrays(int n, int m, int num) {
          memset(ways, 0, sizeof(ways));
          
          for (int j = 1; j <= m; ++j) ways[1][j][1] = 1;
        for (int i = 1; i <= n; ++i) {
             for (int j = 1; j <= m; ++j) {
                for (int k = 1; k <= num; ++k) {
                    long long s = 0;
                    s = (j * ways[i-1][j][k]) % mod;
                    for (int p = 1; p < j; ++p)                         s = (s + ways[i-1][p][k-1]) % mod;
                    ways[i][j][k] = (s + ways[i][j][k]) % mod;
                }
             }
        }
        long long ans = 0;
        for (int j = 1; j <= m; ++j) {
            ans = (ans + ways[n][j][num]) % mod;
         }
        return ans;
     }
 };
```
891. Leetcode Solution in Java
Tags: java
Published: 2022-07-03 17:01:26

```
class Solution {
    public int sumSubseqWidths(int[] A) {
        final int MODULO = 1000000007;
        Arrays.sort(A);
        int length = A.length;
        long[] pow2 = new long[length];
        pow2[0] = 1;
        for (int i = 1; i < length; i++)
            pow2[i] = pow2[i - 1] * 2 % MODULO;
        long sum = 0;
        for (int i = 0; i < length; i++)
            sum = (sum + (pow2[i] - pow2[length - 1 - i]) * A[i]) % MODULO;
        return (int) sum;
    }
}
```
829. Leetcode Soluiton in Java
Tags: java
Published: 2022-07-03 16:54:12

```
class Solution {
  public int consecutiveNumbersSum(int N) {
    int ans = 0;

    for (int i = 1, triangleNum = i; triangleNum <= N; ++i, triangleNum += i)
      if ((N - triangleNum) % i == 0)
        ++ans;

    return ans;
  }
}

```
Remember to whitelist your IP when you can't connect to Mongo DB 📡💡
Tags: webdev, mongodb, javascript, node
Published: 2022-07-03 16:51:48

I recently started looking into backend using the MERN stack, and sometimes it happens that I can't connect to a Mongo cluster, even though it worked in the past. In 99% of the cases this is because my IP adress changed and my current IP is not `whitelisted*`. This is nothing that can't be fixed but I never remember what causes it and I waste time until I get to the correct solution (this is pretty much like forgetting how to center a div). When I would try to connect to a cluster I would see someting like this in the terminal (in the past I think I've also seen some straight up errors, but this is the most recent message I got):

```
[nodemon] 2.0.16
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
connection <monitor> to 52.58.6.203:27017 closed
[nodemon] clean exit - waiting for changes before restart
```

The connection couldn't be established because my IP address changed since I initially set up the cluster (or the last time I whitelisted my IP address). So what I would need to do is go to MongoDB Atlas and on the left side of the page, chose `Security` and then `Network Access`.

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

I would press `ADD IP ADDRESS`, wait for your current IP to be whitelisted and then try to reconnect. Now everything should work again. MongoDB is pretty good at auto detecting your current IP but if the connection still can't be established, try a quick `"what's my ip"` on Google and compare if the IP you got back is the same as the one detected by Mongo. If it's not, you might want to add it manually again.

*MongoDB Atlas only allows connections to clusters from IP addresses that are matched by entries in our project’s IP whitelist
818. Leetcode Solution in Java
Tags: java
Published: 2022-07-03 16:50:20

```
class Solution {
  public int racecar(int target) {
    dp = new int[target + 1];
    Arrays.fill(dp, 1, dp.length, -1);
    return rc(target);
  }

  private int[] dp;

  private int rc(int i) {
    if (dp[i] >= 0)
      return dp[i];

    int ans = Integer.MAX_VALUE;
    int x = 1;            // xA: (2^x - 1) unit distance
    int j = (1 << x) - 1; // j = 2^x - 1, k = 2^y - 1

    // (xA + 1R) + (yA + 1R) + rc(i - (j - k))
    for (; j < i; j = (1 << ++x) - 1)
      for (int y = 0, k = 0; k < j; k = (1 << ++y) - 1)
        ans = Math.min(ans, (x + 1) + (y + 1) + rc(i - (j - k)));

    // xA || (xA + 1R) + rc(j - i)
    ans = Math.min(ans, i == j ? x : x + 1 + rc(j - i));
    return dp[i] = ans;
  }
}
```
805. Leetcode Solution in Java
Tags: java
Published: 2022-07-03 16:49:11

```
class Solution {
  public boolean splitArraySameAverage(int[] A) {
    final int n = A.length;
    final int sum = Arrays.stream(A).sum();
    if (!isPossible(sum, n))
      return false;

    List<Set<Integer>> sums = new ArrayList<>();

    for (int i = 0; i < n / 2 + 1; ++i)
      sums.add(new HashSet<>());
    sums.get(0).add(0);

    for (final int a : A)
      for (int i = n / 2; i > 0; --i)
        for (final int num : sums.get(i - 1))
          sums.get(i).add(a + num);

    for (int i = 1; i < n / 2 + 1; ++i)
      if (i * sum % n == 0 && sums.get(i).contains(i * sum / n))
        return true;

    return false;
  }

  private boolean isPossible(int sum, int n) {
    for (int i = 1; i < n / 2 + 1; ++i)
      if (i * sum % n == 0)
        return true;
    return false;
  }
}

```
CF_Timer: No Debugging IP Address Required; Introducing nanoTime
Tags: cfml, coldfusion, java
Published: 2022-07-03 16:48:33

While reviewing reports on Lucee's Dev Forum regarding [performance differences between using an application-based CFC singleton and a global UDF](https://dev.lucee.org/t/udf-performance-include-udf-cfm-vs-application-singleton-udf-cfc/10567), I thought I'd release our replacement for Adobe's [CFTimer](https://cfdocs.org/cftimer) that I wrote back in 2013.

## No more editing "Debugging IP Addresses"

If you wanted to use the built-in CFTimer function, Adobe required devs to specifically add their current IP address to the list of debugging IP addresses.  This is inconvenient given that the task that it performs shouldn't really require special security... unless it's possible that Adobe's implementation of it could be compromised somehow. (Not sure, just guessing as I can't see any reason why this function requires special rules when you should be able to pass an option to suppress output under desired conditions.)  Some third-party developers may not have access to CFAdmin or admin-based API functions, so they are left without any options other than to manually capture and output [`getTickCount()`](https://cfdocs.org/gettickcount).  (NOTE: I did have rules to pass a list of AllowedIPs, but the filter required a `ipUtils.cfc` library that is not available for public release yet due to third-party dependencies.)

## Not Supported: Type="Debug"

I don't believe that developers have any way of influencing or adding to the output of Adobe's debug output. I used debug mode "once" to see what it did and then immediately disabled it and never bothered to use it again. _(It can break too much if it is blindly enabled server or application-wide.)_

## Introducing nanoTime (already installed w/`java.lang.system`)

I didn't want to be required to loop over thousands or millions of iterations to compare performance differences, so the addition of __nanoTime__ proved to be extremely beneficial as it provides accuracy down to the "one billionth of a second". It's not perfect, but it is at least an option.

__Check out the differences between nanoTime and using millesconds.__

> __Java System.nanoTime() vs System.currentTimeMillis__
> https://www.geeksforgeeks.org/java-system-nanotime-vs-system-currenttimemillis/

## Use as CFScript

This can be called within CFScript by calling it using the following syntax.

```
cf_timer(type="outline", label="My timer test", nano=true){
	performAnythingThatYouWantToMeasure();
}
```

Anyway, here's the CFTag.  Enjoy!

https://gist.github.com/JamoCA/905c21d434cbef10b03cf799f9b93f16

{% gist https://gist.github.com/JamoCA/905c21d434cbef10b03cf799f9b93f16 %}
Value of Pi (π) to 10,000 Digits
Tags: codepen
Published: 2022-07-03 16:37:22

<p>An overambitious Pen displaying the number Pi up to 10,000 digits. It can even read the number (if your browser properly supports SpeechSynthesisUtterance API). You probably aren't going to listen to the entire number being read!</p>

<p>There are bugs... but it was fun to try different things out!</p>

{% codepen https://codepen.io/orvilleChomer/pen/mdxbvpo %}
Migrating data between two online MinIO instances
Tags: migration, devops, minio, s3
Published: 2022-07-03 16:28:45

# Introduction

I use [MinIO](https://min.io/) to store data for my personal Docker containers. It's super easy to use in applications and it solves problem data persistence in Docker (it's much more flexible than using volumes - sure, it also depends on the use-case).

Even though I am a quite satisfied developer I have to admit I struggled for a while trying to find out how to migrate data between two online MinIO instances. There is a [GitHub issue](https://github.com/minio/minio/issues/7403) for this situation but the response there is quite disappointing. I had to dig into documentation to find the response.

This article is for those who are lazy as I am and love quick straightforward solutions.

# Preparation

We are going to use an official MinIO client called [mc](https://github.com/minio/mc). I use macOS so installation is quite easy. The process supposes to be similar on different platforms.

In this example, we are going to migrate data from `my_source` to `my_destination`. We start with creating such a configuration. The default path is in your home directory of yours (`~/.mc/config.json`). The file is supposed to look like this (with your values).

```json
{
	"version": "10",
	"aliases": {
		"my_source": {
			"url": "http://<remote_ip>:9001",
			"accessKey": "my_access_key",
			"secretKey": "my_secret",
			"api": "S3v2",
			"path": "auto"
		},
		"my_destination": {
			"url": "https://data.example.com",
			"accessKey": "my_access_key",
			"secretKey": "my_secret",
			"api": "S3v4",
			"path": "auto"
		}
	}
}
```

# Migration

After configuration of your instances, the rest is quite simple. We are going to use a [mc mirror](https://docs.min.io/docs/minio-client-complete-guide.html#mirror) command.

```bash
mc mirror my_source my_destination
```

Simple as that!
Wonder why things do not go crazy when you deploy in the Cloud?AWS Security Groups to the rescue
Tags: authorize, security, awsidentityaccessmanagement, beginners
Published: 2022-07-03 16:12:06

Security should be of great importance in maintaining your workloads in the cloud in your aws environment.Whatsoever you deploy you got be covered and not worried right?This could be made possible by AWS as you are assured this by providing you with AWS security groups.



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

AWS security groups act as firewalls for your virtual servers and determine the accessibility of your instances .The security groups basically is an instance level firewall that allows and restricts both  traffic inflow and outflow .




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

They do this, by specifying which traffic should interact with them through . The traffic can be restricted by using the source of the traffic is coming out or in from or the port or by protocols.


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


An allow and deny system which determines the traffic flow as the default condition.This control the inflow and outflow of traffic
called ingress and egress.

The security groups also control  access to your instance,they have rules that enable this action.




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



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

A security group can be used in an instance within different subnets that is,one security group can be used in different subnets.




All this occur in the [VPCs ](https://aws.amazon.com/vpc/) who is created by default with security groups.
Pepper Valley: A Game Made for Kajam! 2022
Tags: showdev, p5js, gamedev, javascript
Published: 2022-07-03 16:07:48

This week, I participated in the second annual _Kajam!_, a game jam hosted by [Replit](https://replit.com/~). The theme was **"Spicy"**, and what nearly immediately came to mind was a farming game, like _Stardew Valley_, where you can grow different varieties of peppers and progress through farming levels.

I made the game in JS with p5.js, with the style being 2D top-down pixel art. Since, I was on vacation during the jam, I couldn't dedicate much time to the project, so I kept a decently small scope, and didn't create my own music. Otherwise, all the programming and art was done by me.

Here's the link to the game: https://kajam-2022-pepper-valley.stcollier.repl.co/
Note that it only works on a computer, it's not at all mobile friendly.

I also made a quick trailer for the game: https://www.youtube.com/watch?v=L20mmdMsjsA

Hope you enjoy!
AWS SDK does not upload files onto my s3 account using next js and clever cloud (Cellar)
Tags: nextjs, aws, s3, fileupload
Published: 2022-07-03 15:51:23

Hello Next community!
I'm facing a situation here, trying to upload files onto my s3 bucket in Cellar (Clever Cloud S3) using Next JS API system:
I have the correct files sent to the request and the incomingForm (thanks formidable), when processing data, my CLI logs are correctly logging the files name, no errors are shown anywhere, but nothing comes up to my bucket.
Here's the link of my api upload file issue on stackOverflow :
https://stackoverflow.com/q/72847611/19153888
Could someone help me on this case? Thank you for your time, and excellent day to you all.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gc432dplu330sb2w7voz.png)
Audio Based language classification using Tiny ML
Tags: machinelearning, tinyml, raspberrypipico, arduino
Published: 2022-07-03 15:40:22

The current project is on Audio Based language classification using Tiny ML or else we can say it as Machine Learning.
This identifies the language spoken by the audio received by the microphone. The audio signal is transmitted for the classification and then to the machine learning model, which splits them into training and testing datasets. 
The overall project works on the Tiny ML technology which embeds the hardware with machine learning tools such as TensorFlow Lite. 
This project is developed on the Edge Impulse website. It is an Embedded Machine Learning development site where users can quickly develop and deploy machine learning projects to their development boards.
Even there is a choice to deploy projects directly to the PC or Smart Phone without using any App.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sga73kk96oy0w0p9ywpt.png)
What are some Regular Expression concepts you find hard to grok?
Tags: regex, discuss
Published: 2022-07-03 15:31:28

I was reading a Tweet from my friend Amy on Twitter where they put out a Twitter poll that is currently going on.

{% embed https://twitter.com/AmyShackles/status/1543607768250060802 %}

to which I replied in my funny way.

{% embed https://twitter.com/nickytonline/status/1543614197094916103 %}

And this got me to thinking that many folks struggle with regular expressions. What are some things that trip you up when it comes to regular expressions?
Medium To Markdown Converter
Tags: nodej, markdown, webdev, javascript
Published: 2022-07-03 15:24:40

I create a basic nodejs application for converting medium posts to markdown. This provides an easy way to publish my articles with different platforms like dev.to.

**Git:** https://github.com/atakde/nodejs-medium-to-markdown
**Url:** https://nodejs-medium-to-markdown.vercel.app/
I Have a GitHub Resume!
Tags: github, resume, showdev
Published: 2022-07-03 15:08:29

I am proud to announce that not only this is my first post on this blog, but I have created my first resume on GitHub! I also decided to make the `README.md` file for the repository as my profile README!

I give my location, email address, summary, professional history, educational history, and skills in the resume. I decided not to give my phone number because I didn't want to have any random people call me. I also decided to have a `gh-pages` branch as the main branch because I also wanted my resume to be in the form of a website.

You can find the website for the resume [here](https://mrwolferinc.github.io/mrwolferinc/) and the repository for it [here](https://github.com/mrwolferinc/mrwolferinc).

I hope that people think my resume looks nice because I just created it yesterday and it still may look a bit off given the fact that I used Bootstrap to make the website, but honestly, I think that my resume is worth it!
Simple yet Fast QRCode Generator
Tags: webdev, javascript, programming, productivity
Published: 2022-07-03 15:02:12

![QRCode Generator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/94xvl5cc9yk4f7nscet2.png)

 I build my own QRCode Generator check it out: {% embed https://mrepol742.github.io/qrcode %}

Source Code are available here:
{% embed https://github.com/mrepol742/mrepol742.github.io %}
Advances in AI mean some tedious programming tasks will be replaced by programs
Published: 2022-07-03 12:34:10

Advances in AI mean some tedious programming tasks will be replaced by programs
Software engineers need not fear redundancy, using frameworks and libraries was a big advance from writing machine code and I am sure there were some machine code programmers who thought it was the slippery slope to their obsolescence.

When writing a feature in machine code it would take a tremendous amount of effort to to achieve the same result that would now be trivial to do in a modern language. The same was true of the early compiled languages, javascript without libraries and frameworks requires much more hand rolling that is just plain time consuming.

There are benefits from pure simple coding, the efficiency and sparsity in environments where resources are scant and where memory saving is essential, reducing the number of lines of code and pairing functionality to the minimum set does lead to some beautiful lean programs. But they do take a lot of effort and a comparatively long time to write and get right, they generally do not do very much and are difficult to read and therefore hard to maintain. To refine them takes acres of refactoring, bench testing, metrics and, yes years of experience. The same brute force that mere mortals needed to find solutions can now be done by machines that aid program synthesis and inductive programming.

Luddites take note I for one will not miss the work that machine learning replaces and have mused on ‘How Machine Learning Builds Your Applications For You’ elsewhere in this publication. Beyond generating code and hyperparameter tuning, machine learning will improve software by understanding the users, improving the reliability and performance of applications and testing procedures. Taking the leg work out of programing will allow software engineers to hang up their mountain boots and polish up their dancing shoes, oh and make better software.

Washing machines did not remove the drudgery of domestic work from many women's life, scullery maids are maybe from another era and the wealth that maintained them in those days has in fact trickled down, and to an extent democratised many of the distinctions derived from rich and poor. It is true it has not equalised society totally but the difference between rich and poor has dramatically narrowed due in large part to labour saving technologies which brought about the emergence of the middle classes and the decline of the monied aristocracy. Machine learning is but another one of these societal technologies and the benefits it will bring, to healthcare for instance, are worth losing a few low paid driving jobs along the way.