teleren/devto huggingface dataset:
[Basic] Python age calculator
Tags: python, beginners
Published: 2022-07-11 12:10:41

🙋‍♂️ Hey there!
I hope you are doing well.

Here, I'm sharing the knowledge I gained from creating basic python projects for beginners.

After all 

> "The best way to learn things is getting hands dirty!"
😃 

**Show me the code:** [python basic project with source code](https://github.com/iamjaydev/python_age_calculator)

**1) What I Built**

![Python age calculator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/49mni7fve51t77h0ehz2.png)

- Reusable Choices loop
- Simple Age input with format validation (dd-mm-yyyy)
- Age calculation logic to calculate age in various units
- Print Age Calculation data

**2) How I Built**

- Whole calculation logic is separate from UX
- Code split is managed through a reusable manner
    - Common Logic is separate from app-specific logic
    - Logic is written in separate reusable function chunks

**Conclusion**
As per I believe, this blog post is helpful to those who are looking for python project ideas for beginners.
Add sign-in and sign-up to ReactJS application with no back-end code using DoTenX
Tags: react, authentication, nocode, dotenx
Published: 2022-07-11 12:04:12

In this video, I show you how to add sign-up and sign-in to your ReactJS application without a single line of back-end code using [DoTenX](https://dotenx.com).

DoTenX helps you build powerful and scalable back-end for you applications that you can customise with as much custom code as you want.

Also, when you use DoTenX, you don't have to worry about the database, hosting and deployment as it provides all of that out of the box!

You can find the source code of the React project here:

https://github.com/dotenx/react-todo-list

{% youtube https://youtu.be/3SH-AWxElqk %}
Cherry Pickup II Leetcode Problem
Tags: java, alogorithm, dynamicprogramming
Published: 2022-07-11 11:35:05

You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell.

You have two robots that can collect cherries for you:

- Robot #1 is located at the top-left corner (0, 0), and
- Robot #2 is located at the top-right corner (0, cols - 1).

Return the maximum number of cherries collection using both robots by following the rules below:

- From a cell (i, j), robots can move to cell (i + 1, j - 1), (i + 1, j), or (i + 1, j + 1).
- When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
- When both robots stay in the same cell, only one takes the cherries.
- Both robots cannot move outside of the grid at any moment.
- Both robots should reach the bottom row in grid.

`
Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
Output: 24
Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.
`

```java
class Solution {
    // we will use 3dp for optimizing this problem
    public int cherryPickup(int[][] grid) {
        // since both the robots are moving simultaneously hence they will 
        // be at the same row all the time.
        // hence only one row index is needed .
        // j1 is for robot1 and j2 is for robot2
        int dp[][][] = new int[grid.length][grid[0].length][grid[0].length];
        for(int i =0;i<dp.length;i++){
            for(int matrix[] : dp[i]){
                Arrays.fill(matrix,-1);
            }
        }
        return solve(grid,0,0,grid[0].length-1,dp);
    }
    public int solve(int[][] grid, int i,int j1,int j2,int [][][] dp){
        if(j1<0 || j2<0 || j1>=grid[0].length || j2 >= grid[0].length) return 0;
        if(i == grid.length-1) {
            // here are two cases , either both robot1 and robot2 have arrived at the same cell in the last row or different cells in the last row
            if(j1==j2) return grid[i][j1];
            else return grid[i][j1] + grid[i][j2];
        }
        if(dp[i][j1][j2]!=-1) return dp[i][j1][j2];
        int maximum = 0;
        /*
        for every move of robot1 robot2 has the chance to move either rightdiagonal or down or left diagonal
        hence the below code will run for 9 times 
        3*3
        */
        for(int a = j1-1;a<=j1+1;a++){
            for(int b = j2-1;b<=j2+1;b++){
                if(j1==j2) { // since j1 and j2 are same that means robot1 and robot2 are at the same cell . Hence take current cell value + solve() again we can take index j1 or j2 any one as the value at the cell is same
                    maximum =Integer.max(maximum,grid[i][j1]+solve(grid,i+1,a,b,dp));
                }
                else {
                    maximum =Integer.max(maximum,  grid[i][j1]+grid[i][j2] + solve(grid,i+1,a,b,dp));
                }
            }
        }
        return dp[i][j1][j2] = maximum;
    }
}
```
[Challenge] Multiply 2 numbers without '+-*/' operators and 'for' and 'while' keywords
Tags: challenge, programming, fun, watercooler
Published: 2022-07-11 11:13:14

Following on the previous challenge, I thought of doing a similar challenge but for multiplication. 

Can you multiply 2 numbers without using the following operators and keywords?

**Rules:**
* Multiply a and b
* Don't use operators: +-*/
* Don't use keywords: for/while

**Pseudocode:**
```
a = 2
b = 32

multiply(a, b) => 64
```

**Test:**
```
multiply(a, b) == a * b
```

You can use any language you want, additionally you can add a note indicating which language it is, so people not familiar with the language can know!


That's all, have fun!!

My solution:
{% codepen https://codepen.io/keff/pen/JjLKLYj %}
[WIP] Lessons from 8 months of Leetcode
Tags: career, algorithms, leetcode
Published: 2022-07-11 11:08:55

Been writing for a month now, but I think it would be more meaningful to write posts that are actually useful to you guys out here. Feel free to ask questions in the comments and I will get to answering them in this post!

Leetcode Profile: https://leetcode.com/c6z3h/

## 1. What do you actually do?
* Leetcode Daily, every day
* Leetcode Weekly Contests
* Google Kick Start (if I don't have other plans).

## 2. What is your motivation to keep at it?
A love of algorithms. I'm quite impressed by the diverse ways to solve a problem.

Also, that I just commit to 1 Leetcode Daily within 30 minutes per day. If I cannot solve it I just look at the answer. But I make sure to spin my wheels for that long each day. This comes from a philosophy I once heard on ["The Ground Up Show" with a fitness expert Nate Green](https://www.youtube.com/watch?v=wN95JXN435s) -- just find the "minimum laughable amount" you'd do as a habit and start there. So like, if spending 10 minutes on Leetcode a week makes you go
> "Bah, of course I can do that, it's so easy"

Start there. You'll be surprised how far you go with that. This is a philosophy I mention to friends looking for exercise tips too. It's far more effective to keep a small habit than to force yourself into overdrive, only to relapse.

## 3. The main thing you learnt?
That some days are bad, but its part of the journey. Some days I'd just be unable to solve the question. But these moments are precious. They highlight a gap in understanding, and offers an opportunity to get better.

**[Keep the questions coming!...]**
One-person Online Business.
Tags: productivity, beginners, career, startup
Published: 2022-07-11 11:06:59

👉Need a logo? Use **[Looka](https://looka.com/)**

👉Need a designer? Use **[Canva](https://www.canva.com/)**

👉Need a copywriter? Use **[CopyAI](https://www.copy.ai/)**

👉Need a web developer? Use **[Carrd](https://carrd.co/)**

👉Need an online store? Use **[Gumroad](https://gumroad.com/)**

👉Need a social media manager? Use **[Buffer](https://buffer.com/)**.

You can start a one-person online business and make $100K/year.
[Stack] The Heart of APP Navigation
Tags: beginners, reactnative, mobile
Published: 2022-07-11 10:46:42

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

Developing an APP with many pages can sometimes get confusing, so today I explored some fundamentals. How does app navigation work? Like a stack of pancakes. Yes, the data structure **<u>stack</u>**, which is Last In First Out (LIFO). In non-technical terms, it just means that you can only remove the latest item added to the stack, each time (so no sliding out a pancake from underneath the rest). 


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

> No really, please don't

It seems both [React Native](https://reactnavigation.org/docs/stack-navigator/) and [Flutter](https://api.flutter.dev/flutter/widgets/Navigator-class.html) uses the same stack navigation.

## What does this mean?
It means that in APP, homepage is the bottom-most page (or ‘pancake’). Everything else is built upon it, and at each time you can only view / interact with the topmost page. To return to homepage, you can [pop()](https://reactnavigation.org/docs/stack-navigator/#pop) pages off, or even just pop all with [popToTop()](https://reactnavigation.org/docs/stack-navigator/#poptotop).

## Protecting the stack
Disable [gestures](https://reactnavigation.org/docs/stack-navigator/#gestureenabled). Gestures are like swipe, or triple tap. Different phones / OEMs come with different variations. So disabling it ensures more stability of usage.
dYdX permissioned addresses
Published: 2022-07-11 10:33:23

## [Bridge](https://etherscan.io/address/0xD54f502e184B6B739d7D27a6410a67dc462D69c8) 

### Who can upgrade the implementation?
- `onlyGovernance` - [Governance Contract](https://dev.to/antooni/dydx-governance-mechanism-3mp7)

What are the implications?
- code can be substituted with arbitrary code which in the worst case scenario means your funds can be stolen

### Who can update state?
- `onlyOperator` - [EOA](0x8129b737912e17212C8693B781928f5D0303390a) designated by governance

### Who manages verifiers and operators
- `onlyGovernance` - [Governance Contract] (https://dev.to/antooni/dydx-governance-mechanism-3mp7)

## [GPS Statement Verifier](https://etherscan.io/address/0xC8c212f11f6ACca77A7afeB7282dEBa5530eb46C)

### Who can upgrade the implementation? 
- `onlyGovernance` - [EOA](0x3DE55343499f59CEB3f1dE47F2Cd7Eab28F2F5C6) in this case it is EOA, I wonder why they haven't used governance mechanism here also

What are the implications?
- implementation can be upgraded so the method `verifyProofAndRegsiter()` can return true every time which means that the fraudulent state can be commited to the rollup

## [Memory Page Fact Registry](https://etherscan.io/address/0xEfbCcE4659db72eC6897F46783303708cf9ACef8)

### Who can upgrade implementation?
- no one, contract is not upgradable

### Who can `registerContinuousMemoryPage()`
- anyone, method is public 

## [FRI Statement](https://etherscan.io/address/0xf6b83CcaDeee478FC372AF6ca7069b14FBc5E1B1)

### Who can upgrade implementation?
- no one, contract is not upgradable

### Who can `verifyFRI()`
- anyone, method is public 

## [Merkle Statement](https://etherscan.io/address/0x0d62bac5c346c78DC1b27107CAbC5F4DE057a830)

### Who can upgrade implementation?
- no one, contract is not upgradable

### Who can `verifyMerkle()`
- anyone, method is public 


---

We can clearly see that current dYdX implementation is far from being decentralised
Hackerrank - Sherlock and Array Solution in Python
Tags: python, array, hackerrank, arraysolution
Published: 2022-07-11 10:13:47

Time Complexity of the program O(n).
if the middle value is q and the sum is p then we can write the equation as follow

1. p + q + p = sum   [as the left and the right sum are same]
2. 2p = sum - q

According to that Mathematical Logic The code can be written as follow:

```
def balancedSums(arr):
    # Write your code here
    left_sum = 0
    arr_sum = sum(arr)

    for i in arr:
        
        if (2 * left_sum) == arr_sum - i:
            return "YES"
        
        left_sum += i
        
    return "NO"
```
Node.js Connection to MongoDB
Tags: node, mongodb, javascript, mern
Published: 2022-07-11 10:13:27

Mongodb Node.js Driver allow Node application to connect to Mongodb and preform crude operation. Most cases we use 'mongoose' ORM to connect to mongodb. Here we will see how we can connect to mongoDB without mongoose. 

_mongodb version 4.7.0 is used_

```
const client = new MongoClient(url);
client
  .connect()
  .then((db) => {
    let database = db.db("newDb");
    let collection = database.collection("thenewCollection");
    collection.insertOne({ state: "successfull" });
  })
  .catch((err) => {
    console.log(err);
  });
```
How to calculate keyword frequency and draw the bar chart in PHP
Tags: php, webdev, programming, tutorial
Published: 2022-07-11 10:09:34

This post shows you how to calculate the keyword frequency from text and draw the bar chart by using the JpGraph library.

## Calculate the keyword frequency

Suppose we have a string like this:

```php
$str = "There are two cats on the table. One on the left side is eating an apple, the other on the right side is eating a fish.";
```

It is easy to calculate the keyword frequency by using the PHP built-in functions.

First, we convert all text to lowercase.

```php
$str = strtolower($str);
```

Then, we can extract all words from text by using the function `str_word_count()`.

```php
$words = str_word_count($str, 1);
```

By setting the second parameter's value to be `1`, the function `str_word_count()` returns an array `$words` with all the words in the string `$str`.
After that, use the function `array_count_values()` to count all the valules inside the array `$words`. 
Actually, it gets the frequency of all the words in the array `$words` and returns as an array `$keywords`.

```php
$keywords = array_count_values($words);
```

If we just want the top 5 keywords, use the function `arsort()` to sort the array `$keywords` from highest to lowest and get the first 5 elements by using the function `array_splice()`.

```php
arsort($keywords);
$keywords = array_splice($keywords, 0, 5);
```

Finally, calculate the percentage of each keyword like this:

```php
$total = count($words);

$frequency = [];
foreach ($keywords as $key => $value) {
    $frequency[$key] = number_format(($value / $total) * 100, 2);
}
```


## Draw the keyword frequency bar chart

In this example, we use the graph creating library, JpGraph, to draw the keyword frequency bar chart.
First, copy the library files under the root path of your website and include the JpGraph files:

```php
require_once ('jpgraph-4.4.1/src/jpgraph.php');
require_once ('jpgraph-4.4.1/src/jpgraph_bar.php');
```

Then create a graph and set it as autoscaling. 

...

For the rest of the content, please go to the link below:
[https://www.codebilby.com/blog/a44-calculate-keyword-frequency-and-draw-the-bar-chart-in-php](https://www.codebilby.com/blog/a44-calculate-keyword-frequency-and-draw-the-bar-chart-in-php)
What is one task you hate as a developer?
Tags: discuss, webdev, productivity
Published: 2022-07-11 09:45:22

As a developer I have felt that the whole development part is always easy 😇
It's the best and I love it !
But the bugs...ugh🤯
While development is my domain expertise, it has always been a complicated and less interesting task when it comes to bugs.
Trying to reproduce them with unclear reports, back and forth calls with the testers, asking testers to share screenshots of console logs, network logs and what not.
Over the years, it got more and more exhausting and extremely time consuming.
([Quick shoutout to Disbug, my amazing product that's on Producthunt today](https://www.producthunt.com/posts/disbug-2-0))
As I have always wanted to create something, this felt like the perfect problem to solve. Also, it would benefit me and my fellow software development teams 💻
COVID struck and I had some time to kill.
That's when I started to work on Disbug, the bug reporting tool for all software development teams.
I wanted it to not only improve the QA and UAT workflow, but also to make work less stressful and more fun.
Disbug did it 🎉
400+ companies use Disbug for internal bug tracking, client acceptance testing, user acceptance testing 💪
If you’re a fellow developer or a part of a software team, check out disbug.io and let us know your comments.
Best 9 Golang Frameworks That You Must Know In 2022-23
Published: 2022-07-11 09:44:00

Golang has a lot to offer when it comes to an efficient web development project, and to help you understand and utilize it deeply, we have brought you this blog post to pick the best golang framework. 
Read more: - [https://bit.ly/3NLG0gi](https://bit.ly/3NLG0gi)

#golang #golangdeveloper #programming #technology #go #node #javascript
Laravel how to test CSV download
Tags: test, laravel, csv
Published: 2022-07-12 06:20:30

---
title: Laravel how to test CSV download
published: true
date: 2022-07-11 09:41:00 UTC
tags: test, laravel, csv
canonical_url: https://dcblog.dev/laravel-how-to-test-csv-download
---

When you have a CSV generated how do you test it runs. Take this extract:

```php
public function export()
{
    $actions = $this->getData()->get();

    $columns = [
        'User',
        'Start Date',
        'End Date',
    ];

    $data = [];
    foreach ($actions as $action) {
        $data[] = [
            $action->user->name ?? '',
            $action->due_at,
            $action->completed_at,
        ];
    }

    $now = Carbon::now()->format('d-m-Y');
    $filename = "actions-{$now}";

    return csv_file($columns, $data, $filename);
}
```

The above collects data and sends it to a helper function called csv\_file which in turn will export a CSV file.

For completeness it contains:

```php
if (! function_exists('csv_file')) {
    function csv_file($columns, $data, string $filename = 'export'): BinaryFileResponse
    {
        $file = fopen('php://memory', 'wb');
        $csvHeader = [...$columns];

        fputcsv($file, $csvHeader);

        foreach ($data as $line) {
            fputcsv($file, $line);
        }

        fseek($file, 0);

        $uid = unique_id();

        Storage::disk('local')->put("public/$uid", $file);

        return response()->download(public_path("storage/$uid"), "$filename.csv")->deleteFileAfterSend(true);
    }
}
```

Now there are 2 tests I want to confirm first, I get 200 status response to ensure the endpoint does not throw an error and secondly, the response contains the generated file name for the CSV.

To cater for the 200 status code run the endpoint and **assertOk()** which is a shortcut for a 200 instead of **assertStatus(200)**

Next check the header of the response and read the content-disposition header this will contain an attachment followed by the filename. ** ** Doing an assert true and comparing the header with the expected response;

```php
test('can export actions', function () {
    $this->authenticate();

    $response = $this
        ->get('admin/reports/actions/csv')
        ->assertOk();

    $this->assertTrue($response->headers->get('content-disposition') == 'attachment; filename=actions-'.date('d-m-Y').'.csv');
});
```

Another way would be to use Pest's expect API:

```php
$header = $response->headers->get('content-disposition');
$match = 'attachment; filename=actions-'.date('d-m-Y').'.csv';

expect($header)->toBe($match);
```
Database Passwords in Containers
Tags: docker, faq
Published: 2022-07-11 09:30:24


We all know databases usually need passwords, but since the dawn of Docker, the postgres image (and a few others like redis) has allowed you to do a simple docker run on it and it starts without a password. Sure you could set a password but it didn't require one.

In Feburary 2020 that changed, and will affect using postgres in this course (and my others). When running postgres now, you'll need to either set a password, or tell it to allow any connection (which was the default before this change).

For docker run, and the forthcoming Docker Compose sections, you need to either set a password with the environment variable:

POSTGRES_PASSWORD=mypasswd

Or tell it to ignore passwords with the environment variable:

POSTGRES_HOST_AUTH_METHOD=trust

Note this change was in the Docker Hub image, and not a change in postgres itself.

Also note if I or you were pinning versions, as we should, this wouldn't have surprised us. I tend to only pin to the minor version in this course (9.6) rather than the patch version (9.6.16) to keep you a bit more secure in the course. In the real world, I always pin my production apps to the patch version. It's the only safe way to operate. By pinning to the minor version in the courses, I prevent any major changes from breaking the course (in theory ha ha), yet also ensure you're running the latest patches (which would fix any bugs or security problems). In this, *very rare case*, the maintainer of the official postgres decided to introduce a breaking change in the *image* to a patch release of the app. The two aren't related, and it kinda shows off a weakness of the Docker Hub model... that there is no version of the Docker Hub image really, it's just tracking the upstream postgres versions... so then if any Docker Hub change would break something, it can't easily be tracked as a separate version from the app itself. Oh well, just remember to always pin the whole image version for things you care about.
Docker series (Part 13): Edit codes running in containers using Bind Mounts
Tags: docker
Published: 2022-07-11 09:29:41

The tasks we will complete in this blog

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/liaqxohstiyy7ych01bp.png)
 
So for this assignment, we will use [this repository](https://github.com/bretfisher/udemy-docker-mastery) 

Let's fork it and clone it in our system. Then go to the bindmount-sample-1 folder

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iczd0bvl6mg6zy5ghwoi.png)
You can also see files  within it


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

Oh! by the way if you don't know what is Jekyll, here it [is ](https://jekyllrb.com/) 

1. First we will go to the folder and create a container from [this image](https://hub.docker.com/r/bretfisher/jekyll-serve)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/124v3xwsdnv5daivicno.png)
 
```
docker container run -p 80:4000 -v $(pwd):/site bretfisher/jekyll-serve
```
here we set the port from 80 to 4000 

volume had set to current directory using $(pwd) . Also we used /site to specify the  images volumes to be directed to local directory $(pwd)

You can know more from [here](https://github.com/BretFisher/jekyll-serve) 

Now you can see the server up and running

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

Go to localhost and you can see this

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

  
2. GO to the "Welcome to Jekyll " link 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kayxigwtorf4rquvemsx.png)

You can also view this from VS code

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

3. Now lets change something from this file. We are changing the title from "title:  "Welcome to Jekyll!" to "title:  "Welcome to Jekyll! by Mitul" and save it

If you go to the terminal, you can see changes

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

4. Refresh the website page (localhost)

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

<img src="https://media0.giphy.com/media/Nfs5y1kzJKfu/giphy.gif?cid=ecf05e472d3w835ptrri5m1p6ifnwl9mi7ope9pifvhpcxf6&rid=giphy.gif&ct=g">