teleren/devto huggingface dataset:
This week’s newsletter is out! (12-11-2022) - Magic Money All The Way Down
Tags: javascript, tech, webdev
Published: 2022-11-12 06:02:30

---
title: This week’s newsletter is out! (12-11-2022) - Magic Money All The Way Down
published: true
description: Another week of great javascript, tech and web development links.
tags: javascript, tech, webdev, discuss
---

Magic Money All The Way Down

https://markjgsmith.substack.com/p/mark-smiths-newsletter-12-10-2022

Would love to hear any comments and feedback you have.

[@markjgsmith](https://twitter.com/markjgsmith)
How to Send Mail using nodemailer in node js ?
Tags: javascript, express, mail, coding
Published: 2022-11-12 05:36:59

**Folder Structure :**

![Folder Structure of Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hi4joddi0kg5e44h6ews.png)

**App.js Code:**

``` javascript
const express = require('express');
const ejs = require('ejs');
const transporter = require("./config/emailConfig.js");

const app = express();
const PORT = 8000;

// Set Template Engine 
app.set('view engine', 'ejs')
app.use(express.urlencoded({extended: false}))

app.get("/", (req, res) => {
    return res.render("index");
});

app.post("/", async (req, res) => {
    const { email } = req.body;

    try {
        let info = await transporter.sendMail({
            from: "laughtercomedy708@gmail.com", // sender address
            to: email, // list of receivers
            subject: "Express - Nodemailer", // Subject line
            text: " Email Send Successfuly.", // plain text body
        })
        return res.json({ "status": "success", "message": "Password Reset Email Sent... Please Check your Email."})
    } catch (error) {
        return res.json({ "status1": "failed", "message": error.message })
    }
})

app.listen(PORT, () => {
    console.log(`Server is Listening at ${PORT} Port.`);
})
```

**package.json code:**

``` javascript
{
  "name": "q.11",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "dev": "nodemon app"
  },
  "keywords": [],
  "author": "aksh desai",
  "license": "ISC",
  "dependencies": {
    "ejs": "^3.1.8",
    "express": "^4.18.2",
    "nodemailer": "^6.8.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.20"
  }
}

```

**emailConfig.js code:-**

``` javascript
const nodemailer = require("nodemailer");

let transporter = nodemailer.createTransport({
    host: "smtp.gmail.com",
    port: 587,
    // secure: false, // true for 465, false for other ports
    auth: {
        user: "laughtercomedy708@gmail.com", // generated ethereal user
        pass: "your app password", // generated ethereal password
    }
})

module.exports = transporter;
```

**index.ejs code:**

``` html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1> Hello World </h1>

    <form action="/" method="post"> 
        <input type="email" name="email" required> <br>
        <input type="submit" value="submit">
    </form>

</body>
</html>
```
**Output Image:-**

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

Thank You.
You can follow us on:
[Youtube ](https://www.youtube.com/c/ULTIMATEPROGRAMMING)
[Instagram](https://www.instagram.com/full_stack_web_developer1/)
Terraform Null Resource
Tags: terraform, cloud, tutorial, devops
Published: 2022-11-12 05:29:01

Terraform Null Resource it’s one of the several features that Terraform provides us. Once you have learned how to use null_resource, it’s mind-blowing because you immediately visualize several possibilities to use it to resolve complex problems and provisioning your resources.

[Terraform Null Resource](https://www.bitslovers.com/terraform-null-resource/)
2 Solutions for Unexpected token “u” in JSON at position 0
Tags: webdev, javascript, beginners, tutorial
Published: 2022-11-12 05:23:32

## 2 Solutions for Unexpected token “u” in JSON at position 0

The [Unexpected token u in JSON at position 0] error message happens when you see an undefined value to $.parseJSON or JSON.parse functions. To fix the problem, check the value you’re attempting to convert and ensure that the JSON is valid before converting it.

Read: [Unexpected token “u” in JSON at position 0](https://www.bitslovers.com/2-solutions-for-unexpected-token-u-in-json-at-position-0/)
295. Leetcode Solution in Java
Tags: java
Published: 2022-11-12 05:21:14

``` java
class MedianFinder {

    PriorityQueue<Integer> smallerHalf; // one more than larger half, or equal to larger half
    PriorityQueue<Integer> largerHalf;

    /** initialize your data structure here. */
    public MedianFinder() {
        smallerHalf = new PriorityQueue<Integer>(new MaxComparator());
        largerHalf = new PriorityQueue<Integer>(new MinComparator());
    }

    // below addNum() with too many condition checks
    // @note: simple logic: always add to larger half, and if larger half 1 more than smaller half, then re-balance

    public void addNum(int num) {
        // 2 polls() and 3 offer(), total 5 operations, each logN => 5 * logN ~= logN
        // https://stackoverflow.com/questions/28819327/time-complexity-of-inserting-in-to-a-heap

        // always to smaller half first
        // can check if num bigger than smallerHalf.peek, to directly offer to biggerHalf
        smallerHalf.offer(num);

        // now smaller half get additional int, re-balance by smaller half giving its max to smaller half
        largerHalf.offer(smallerHalf.poll());

        if (smallerHalf.size() < largerHalf.size()) { // only for the 1st time initial num being added
            smallerHalf.offer(largerHalf.poll());
        }
    }

    public double findMedian() {
        if (smallerHalf.size() == largerHalf.size()) {
            return (smallerHalf.peek() + largerHalf.peek()) / 2.0; // @note: double division
        } else { // smaller half is one more
            return smallerHalf.peek();
        }
    }


    class MaxComparator implements Comparator<Integer> {

        @Override
        public int compare(Integer o1, Integer o2) {
            return o2 - o1; //max first
        }
    }

    class MinComparator implements Comparator<Integer> {

        @Override
        public int compare(Integer o1, Integer o2) {
            return o1 - o2; // min first
        }

    }
}


class MedianFinder_NlogN {

    List<Integer> list;

    /** initialize your data structure here. */
    public MedianFinder_NlogN() {
        list = new ArrayList<>();
    }

    public void addNum(int num) {
        list.add(num);
        Collections.sort(list); // maintain a sorted list
    }

    public double findMedian() {

        int length = list.size();

        if (length % 2 == 1) {
            return list.get(length / 2);
        } else {
            return (list.get(length / 2) + list.get(length / 2 -1)) / 2.0; // @note: if x / 2, then will be an int, 3/2==1, 3/2.0==1.5
        }
    }
}
```

#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/find-median-from-data-stream/submissions/711743467/
How to use Babel's new addExternalDependency API
Tags: javascript, reactnative, opensource, node
Published: 2022-11-12 05:10:04

The story begins with me as a clout-chasing, NPM library maintainer. The library is a Babel plugin, known as `react-native-dotenv`.

The problem? Babel was caching the non-Javascript files the library was meant to load. The real problem? My ego was being obliterated by developers who were replacing my library as a dependency because they needed a functional way to load environment variables into their react native apps.

To solve it, I scoured the Babel feature pipeline, a.k.a. random draft PRs people had created to add any file to the Babel watchlist. I bumped it, did no extra work, watched the Babel team pick it up and do an epic job on it, and planned to write a blog to take full credit for my prod.

When addExternalDependency was born, the release had so many other amazing features, the docs were not up to par of the other Babel docs. So I made a pact with the devs that I would write some documentation in exchange for help on fixing up my library and this is my lousy attempt at it.

So to begin, in my `module.exports` function, I made sure to tell Babel what and how to cache the alien files that are dear to my library. I use a function to verify if they've been updated recently

```javascript
function mtime(filePath) {
  try {
    return statSync(filePath).mtimeMs
  } catch {
    return null
  }
}
```

and for each file path I'm checking I add:

```javascript
api.cache.using(() => mtime(options.path))
```

Now we tell Babel to watch for changes and recompile:

```javascript
api.addExternalDependency(path.resolve(options.path))
```

And for the hardest part? Convince every library to upgrade their versions of Babel. Or tell your users to add the following to their `package.json`:

```javascript
"resolutions": {
  "@babel/core": "^7.20.2",
  "babel-loader": "8.3.0"
}
```

As of writing this article I am searching for a job. If I've tricked you into thinking I'm a half-decent Javascript developer, please tell a hiring manager near you because I'm competing against other exceptional devs from Twitter and Meta.
Adding automated tests to rost_gen
Published: 2022-11-12 04:56:41

This week, I added some automated testing to my static site generator project, [rost_gen](https://github.com/Eakam1007/rost_gen). As the project is built using rust, it was quite easy to get started as I did not need to use any additional frameworks.

All of the code for my project is currently contained within one main.rs file. It would be better to eventually split this up into multiple files for better organization. However, it allowed me to set up a test module at the end of the main.rs file and write all of my tests in there:
```rust
#[cfg(test)]
mod tests {
  ...tests
}
```
From there, I added functions to test different parts of my project. For example, the following tests a function that checks that a txt file is a supported file type for conversion:
```rust
#[test]
fn converts_txt_files() {
  let input_file_path = path::Path::new("sample.txt");
  assert!(conversion_file_path_valid(input_file_path));
}
```
The function returns true or false depending on if the extension of a file is supported.

Eventually, I had to test reading of input file and generation of the html file. To do this, I would need to create test files for input and output for this scenario. However, this could cause problems unless I named all the test files differently as tests usually run in parallel. So, I decided to use the [tempfile](https://crates.io/crates/tempfile) crate to create a temporary test directory for each test (where needed):
```rust
let temp_dir = tempfile::tempdir().unwrap();
let test_input_path = temp_dir.path().join("parse_title_test.txt");
```
This ensures that a different test directory is used for each test and also makes the post-test clean up easier.

While writing tests, I also discovered a bug in my function for parsing link markdown into `<a>` tags. The function would only convert a maximum of one link per line. Quite an obvious issue but I had not considered it when I implemented this feature. So, I [created an issue for this](https://github.com/Eakam1007/rost_gen/issues/49) to address it in the future.

I have written tests for ruby on rails projects before. During that, and while writing tests for my rust project, I have found that tests help discover bugs that are not obvious otherwise. Thus, I believe it can be better to write tests before changing existing code or adding new features whenever possible.
Write test cases in JS
Tags: testcases, jest, webdev, javascript
Published: 2022-11-12 04:46:47

Writing the test cases in JS is not nexus until we find the right way of less code with more concepts.
**Is it possible to write test cases in a short time?**

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

Let's get started this.

I am using the Jest library to write test cases. Jest is a delightful JavaScript Testing Framework with a focus on simplicity.

First, you need to integrate the Jest library, so do this by command-

(If you choose yarn)

```
yarn add --dev jest
```
(If you choose npm)

```
npm install --save-dev jest
```
Next, add the following section to your `package.json`

```
{   
   "scripts": 
      {
         "test": "jest" 
      }
}
```

Now create a directory of name `tests` and create two files inside it which will have names `multiply.js` and `multiply.test.js`.

Drop the below code snippets in respected files-

**multiply.js**

```
export const doMultiply = function (num1, num2) {
   return num1 * num2;
}
```

**multiply.test.js**

```
import {doMultiply} from './multiply';
test('Multiplies 2 * 2 to equal 4', () => { 
    expect(doMultiply(2, 2)).toBe(4);
});
test('Multiplies 3 * 2 to equal 6', () => { 
    expect(doMultiply(3, 2)).toBe(6); 
});
```

Let’s understand the definitions of the keywords we have used here.

**expect-** This is a function that will be in use every time you want to test value, and it will take the function name (with or without arguments) you want to test.

**toBe-** This is the matcher. When Jest runs, it will track all the failing matchers so that it can print out apt error messages.

In the above code, you can also use, “toStrictEqual” matcher. For example-

```
test('Multiplies 2 * 2 to equal 4', () => { 
    expect(doMultiply(2, 2)).toStrictEqual(4);
});
```
Now, it’s time to grab the fruit of our efforts. Let’s run the last following command to see the output-

(If you are using yarn)

```
yarn test
```

(If you are using npm)

```
npm run test
```

you will see that Jest has printed the testing results for you, it should be-


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

Let’s add one more test case and pass the wrong result expectations into it.

```
test('Multiplies 3 * 3 to equal 6', () => { 
    expect(doMultiply(3, 3)).toBe(6);
});
```
After running the same test commands either `yarn test` or `npm run test` , you should see the following result-

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

You just successfully wrote your first test using Jest!

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

Hope you have finished with much satisfaction.

With love,

Neha Soni
Find Median from Data Stream
Tags: leetcode, python
Published: 2022-11-12 04:40:26

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.

For example, for arr = [2,3,4], the median is 3.
For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.
Implement the MedianFinder class:

MedianFinder() initializes the MedianFinder object.
void addNum(int num) adds the integer num from the data stream to the data structure.
double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.


```py

import heapq
class MedianFinder:
    def __init__(self):
        self.big, self.small = [], []

    def addNum(self, x: int) -> None:
        even = len(self.big) == len(self.small)
        heapq.heappush(self.big if even else self.small, -heapq.heappushpop(
                self.small, 
            -heapq.heappushpop(self.big, x)) * (1 if even else -1)
            )      

    def findMedian(self) -> float:
        return self.big[0] if len(self.big) > len(self.small) else (self.big[0] - self.small[0]) / 2


```
Introducing TF WhatsUp, a Tool for Better Terraform Notes
Tags: terraform, opensource, dotnet, nuget
Published: 2022-11-27 03:12:00

---
title: Introducing TF WhatsUp, a Tool for Better Terraform Notes
published: true
date: 2022-11-12 03:00:00 UTC
tags: terraform,oss,dotnet,nuget
canonical_url: https://seankilleen.com/2022/11/introducing-tf-whatsup/
cover_image: https://seankilleen.com/images/overlays/unsplash/ant-rozetsky-SLIFI67jv5k-unsplash.jpg
---

I had a great excuse to get to dig into and publish a .NET Global Tool recently, so I figured I’d announce it here!

[`TF-Whatsup`](https://github.com/seankilleen/tf-whatsup), which provides the `whatsuptf` command, is currently at v0.5.0 on [NuGet](https://www.nuget.org/packages/TFWhatsUp.Console/#versions-body-tab)

## What it Does

Terraform has a phenomenal pace of updates, and really great, verbose release notes. But sometimes the updates I need to pay attention to can get lost in the noise from the updates of the entire ecosystem.

`TF-Whatsup` shows you the pending release notes for any Terraform provider you use, and highlights the notes that pertain to the resources that you use.

## How it Works

`TF-Whatsup` does the following:

- Pulls the current versions of your current providers from the Terraform lock file.
- Detects the resources you’re using
- Finds the GitHub URLs for the providers
- For each provider: 
  - Finds releases after yours (in terms of date and semantic versioning)
  - Parses the release notes & highlights lines that talk about resources you’re using
  - Displays the parsed release notes back to you, in order of closest release to newest release.

## This Was Fun.

I had a few hours and was able to pull together the tool, get it working, and get it published to NuGet. It felt good to do that, and made me happy.

## I Need Your Feedback!

This is very early days but I feel like it could be useful and I’d love your feedback. Please open an issue on the GitHub repository or leave a comment here. Thanks!
Functions
Tags: beginners, javascript
Published: 2022-11-12 02:51:47

Hello, today I just want to chat about functions and how useful they are. Functions are tool that we can use that make our code more dynamic and are like the a swiss army knife of coding. Functions are  fun to set up and reusing them is satisfying especially when you can just slot them in and everything flows. Functions are very good tool to learn and understand. Here is the function syntax to get you started: 
function someFunction(parameter){ return something }
Function even have their own scope and you can write code that only deploys when that function is invoked. This tool can save you a ton of time when coding if you know that you will be reusing that code. have to pull something from the DOM write a function for that process! Functions also return something so there is an input and an output.  Over all just want to gush about functions for a bit since they are so neat and handy!
Object Pool
Tags: beginners
Published: 2022-11-12 02:28:13

## What is Object Pool design pattern?
- Object pool pattern is a software creational design pattern which is used in situations where the cost of initializing a class instance is very high. 
- Basically, an Object pool is a container which contains some amount of objects. So, when an object is taken from the pool, it is not available in the pool until it is put back. 
- Objects in the pool have a lifecycle: 
  1. Creation
  2. Validation
  3. Destroy

---

## UML Diagram

![UML Diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2io424oq8o6ox3ydc5v2.png)

---

## Participants
- Client
This is the class that uses an object of the PooledObject type.

- ReuseablePool
The PooledObject class is the type that is expensive or slow to instantiate, or that has limited availability, so is to be held in the object pool.

- ObjectPool
The Pool class is the most important class in the object pool design pattern. ObjectPool maintains a list of available objects and a collection of objects that have already been requested from the pool.

--- 

## Advantages
- It offers a significant performance boost.
- It manages the connections and provides a way to reuse and share them.
- Object pool pattern is used when the rate of initializing an instance of the class is high.

---

## When to use Object Pool design pattern
- When we have a work to allocates or deallocates many objects
- Also, when we know that we have a limited number of objects that will be in memory at the same time.

---

## References
- https://sourcemaking.com/design_patterns/object_pool
What is a file?
Tags: beginners, programming, opensource, codenewbie
Published: 2022-11-12 02:06:48

For all the zoomers out there that don't know what a file is?

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9xzeb291n7bd8dlbfru1.jpg)
A file is a collection of data or information that is related each other for example it is a collection of related documents or papers that are arranged so that they can be consulted easily 

Computer file:it is a digital data that contains stored information and  stored in a computer readable form.it is a digital information stored in a computer format(electronic format) which is available to a computer programmer and is based on some kind of durable storage.

Field: it is also called "attributes" is an area reserved for each piece of individual data(each data) such as student's number,address and number.

Record: is a group of related file pertaining to one person's place or thing

Data item: is a single member of a data element.it's a unit stored data to a field.

Types of data item
- Numeric data
- Alphabetic data
- Graphical data
- Alphanumeric data
- Audio data
🗞 Rapyd Developer Newsletter: October, 2022
Published: 2022-11-10 20:02:52


[**Complete this survey**](https://rapyd.sjc1.qualtrics.com/jfe/form/SV_6sVd0n93fIs2Y3c) and share your input to help improve the Rapyd Developer Community. 

Hi everyone, 

Here is our October newsletter with notable updates and news from around the Rapyd global developer community. 

Leverage fintech to help build an emerging tool to impact climate change. Sign up and submit your project for the hackathon now until Thursday, December 8 @ 5:00 pm EDT. 

Be sure and check out our brand makeover. 

[**Rapyd Hackathon: Build an app for Climate Fintech**](https://rapyd.hackerearth.com/) ended December 8 @ 5:00 pm EDT. 

## Changelog ♻️
[Client Portal Updates]
[**Payment Links**](https://docs.rapyd.net/client-portal/docs/payment-links) has been added to the Client Portal to generate a reusable link to accept payments from your customers. You can create a set amount or an open amount where the customer can edit their own amount to pay.

The Client Portal has been updated to include a Report Settings page, which allows clients to edit the reconciliation report type and format of the CSV document. 

The [**Plugins page**](https://docs.rapyd.net/works-with/docs) has been redesigned in the Client Portal. Refer to the Plugins Guides for more details.

---

[**Join 50K+ Devs talking FinTech.** 🤓](https://community.rapyd.net)

---

## Discover 🔍
[**Seamless Payment Messaging App**](https://community.rapyd.net/t/seamless-payment-messaging-app/55266) `/community`
Learn how to create a secure PCI-compliant payment using credit cards, then save the tokens of the card and create a payment using these tokens.

[**How to Issue a Card In Sandbox**](https://community.rapyd.net/t/how-to-issue-a-card-in-sandbox/55455) `/community`
Learn how to Issue a Card in the Sandbox Environment with Rapyd. 

[**Rapyd Hack the Galaxy: Meet Mission One Winner Omri**](https://youtu.be/UqH_XNkcy2s) `/videos`
“This is all due to the hard work of developers…we make things smarter, better, easier. This is what we do”.

 
[**Hosted Checkout Page with additional fees**](https://www.youtube.com/watch?v=aOEz01f-BjA) `/videos`
Learn how to generate a hosted checkout page and include additional fees to accept from customers.

---

Want an email of Rapyd Developer Newsletters? ⏩
Click [**here**](https://go.rapyd.net/dev-newsletter) to subscribe.

---

###### Rapyd is an API first, developer focused company. The Rapyd Dev Community makes it easier to get started building payment and fintech experiences that makes global commerce possible.