teleren/devto huggingface dataset:
Unawaited async middleware errors in Express v4
Tags: webdev, javascript, node, backend
Published: 2023-08-27 19:39:06

## Context
I am working on a plain JS Express.js app. It has middlewares, a few routers.

&nbsp;

## Situation - strange error
I was getting an error from Mongoose package. The error would crash the app, in spite of having an error sink - which would never get triggered (unexpected).

I am trying to use the `.save()` mongoose function, an async function, without `await`. But there's a reason I do this - I wish to send the response before the call succeeds.

Exact problem (comparison):
```js
// error
app.get('/xyz', async (req, res, next) => {

  try {
	// some code here
	product.save(); // this _will_ throw an error (expected, ok)
  } 
  catch (e) {
	next(e);
  }

  console.log('Everything is fine.'); // runs (unexpected)
  
});

app.use((err, req, res, next) => {})

// error middleware doesn't run (app crashes)
```

```js
app.get('/xyz', async (req, res, next) => {

  try {
	// some code here
	await product.save(); // this _will_ throw an error (expected, ok)
  } 
  catch (e) {
	next(e);
  }

  console.log('Everything is fine.'); // doesn't run now, as expected
  
});

app.use((err, req, res, next) => {})

// error middleware runs (app doesn't crash)
```

&nbsp;

## Fix (here)
I needed to add `await`.

&nbsp;

## Explanation
Since I did not wait for `product.save()` (which is async - so error is thrown after some time), to express, the error never occurred.

So, it never ran the code inside `catch`. 

And therefore, the error middleware never ran.

But the `product.save()` does throw an error, and it does bubble up at the runtime level (Node.js process instead of within Express), crashing the app.

&nbsp;

## Hack - catch error at a lower level (runtime instead of Express)
The following is a native way to catch errors. Add the following as the first middleware:
```js
app.use((req, res, next) => {
  process.on("unhandledRejection", function (reason, p) {
    console.log("hack, Unhandled Rejection at: Promise ", p, " reason: ", reason);
    // application specific logging, throwing an error, or other logic here
  });
})
```
Source: https://stackoverflow.com/a/30650609/11392807

Here:
- Crash is prevented - since this will catch the unhandled error, prevent bubbling to the runtime level, so the crash will be prevented.
- The error middleware is still not called.

Why would you I use this? If the app is old, there may be a lot of such "non-awaited" middlewares.

&nbsp;

## Actual fixes
Any of these:
1. Use `await` if possible.
2. For non awaited parts, use `.then` and call `next(e)` from `.catch`. Example: If the user doesn't care about the result immediately.

&nbsp;

## Conclusion
If async middlewares (Express.js) contain code that doesn't use await. 
Then execution of such code starts happening outside the middleware chain.
This leads to problems like failed triggering of error middlewares, app crashes, and inability to send a response.
ℹ️ | About Spam at the DASC© Google Group
Tags: aboutspamonthedascgooglegroup
Published: 2023-08-27 19:32:33

**First & Foremost Spam At the DASC© Google Group Is Never Allowed** 

It is Described as **Member-Based-Post-Spam ( MBPS )** On The DASC© Google Group 

So Do You Literally Enjoy Creating Spam Posts is It Because You Want to Obliterate The Community With Worthless-Spam-Posts ( WSP ) if so Feel Free to Go Ahead & Spam The Community With Your Worthless-Spam-Posts That Would be Marked For Speedy Deletion Very Quickly & Tagged To be Deleted The DASC© Google Group Community ( DASC© GGC ) is Not Meant For Spam & Obliteration Littering Spam Posts is Simply Worthless & Useless Because Of The Exact Amount of Spam Posts get Created Even When it may be just 1 Or More Words That are being Spammed / That Have Been Spammed As Usual Spammers Can Usually Cause Double Trouble With Spam & Even Negatively Derail the Post's Subject into a Different Subject with an Unknown Word Being Spammed On The DASC© Google Group Community & Just adding a Whole Bunch Of Words on the Paragraph that might be Unknown Words & Probably Known Words that are being Spammed 

```
Your Spam Would last For a Temporary Amount Of Time Based On 1 Minute While Creating Known Spam Based Words & Unknown Based Words That Members May Know About Or Don’t Understand Already so Your Spam would be Villainous For 1 Minute 
```

> Consider You Being A Spam Based Villain For 1 Minute After 1 Minute Your Spam Posts will be Deleted & You'll be BANNED! Without Your Villainous Powers Of Spam
VanillaDB: A Tiny Browser-Based Database
Tags: webdev, javascript, react, programming
Published: 2023-08-27 19:28:08

# VanillaDB

VanillaDB is a tiny browser-based database library that is built on localstorage, sessionStorage and indexedDB.

## Installation

Install vanilla-DB using npm

```bash
  npm install --save vanilla-db
```
    
## Usage/Examples
Once the package is installed, you can import the library using import

```javascript
import { vanillaDb } from 'vanilla-db'

const config = {
  db: 'local' // 'session',
  key: 'your database key',
  data
}

vanillaDb.set(config)
```
config contains your database of choice which can either be "local" or "session", your database key and the data you intended to store in the DB.

```javascript 

const query = {
  db: 'local' // 'session',
  key: 'your database key',
}

vanillaDb.get(query)

```
query contains the Database you stored data in and the database key.


## More Features

- sync(key) - sync data stored in session to local Database
- remove(db, key) - remove stored data by key
- length(db) - return the length of data stored in Database


### Usage/Examples

```javascript
import { vanillaDb } from 'vanilla-db'

vanillaDb.sync(key)
```
where key is the key of the data stored in Database

```javascript 

const db =  'local' // 'session',
const key = 'your database key',

vanillaDb.remove(db, key)

```
db is the Database you stored data in and the database key.

```javascript 

const db =  'local' // 'session',

vanillaDb.length(db)

```
db is the Database you stored data.

[![NPM](https://img.shields.io/npm/v/vanilla-db.svg)](https://www.npmjs.com/package/vanilla-db) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
My manifesto of my cryptocurrency
Published: 2023-08-27 10:04:16

**International-Dollar: Technical Insights into Proof-of-Ip**

Hello fellow developers and tech enthusiasts. Let's dive into the technical core of the International Dollar, exploring its Proof-of-Ip algorithm. This Peer-to-Peer Electronic Cash System offers a unique perspective on digital transactions.

**Proof-of-Ip: Rethinking Consensus**

Proof-of-Ip stands as the crux of the International Dollar's innovation. Unlike traditional consensus mechanisms, this approach democratizes transaction verification. When verifying ownership, a democratic election occurs involving nodes. Users determine consensus based on majority votes.

Nodes, operated by average users, play a central role in maintaining the network. This emphasizes decentralization and inclusivity, promoting security without requiring advanced technical knowledge.

**Calculations: Security and Resilience**

The International Dollar's security model is designed to counter potential attacks. By examining various scenarios, the system demonstrates resilience against entities attempting to control IPs. This is achieved through scarcity and inflation mechanisms inherent in the network's design.

This security layer is a balance of economic dynamics and cryptographic principles.

**Transaction Flow: Swift and Simple**

Transactions are straightforward within the International Dollar ecosystem. A standard transaction includes sender and recipient details, transaction specifics, and digital signatures. Transactions propagate through the node network, where each node autonomously verifies sender funds and updates the database.

The standout feature is the speed – transactions are confirmed in under 15 seconds. This efficiency arises from the Proof-of-Ip algorithm, eliminating transaction fees and energy-intensive hashing.

**GUI and Printable Bills: Form Follows Function**

The user interface is designed for readability and ease of use. The black/dark theme enhances user experience and comfort during extended usage.

Printable bills offer a practical aspect. These paper wallets cater to real-world transactions, allowing swift transfers using private keys. Each bill signifies a single currency unit, ensuring security against digital threats.

**Conclusion: A Technical Step Forward**

The International Dollar's technical foundation addresses limitations hampering cryptocurrency adoption. The Proof-of-Ip algorithm redefines consensus, emphasizing inclusivity and security. The streamlined transaction flow and user-friendly interface reflect a practical approach.

Continual vigilance against vulnerabilities is essential in the journey toward mainstream adoption. The International Dollar stands as a fusion of technical innovation and economic principles. For those interested in the technical frontier, this system offers a space to observe its evolution within the digital economy.
SQL Sunday #1 - Essentials
Tags: sql, beginners, datascience, analytics
Published: 2023-08-27 18:57:15

For everyone taking a step to work in the realm of Data Science/Analytics, the first step is to learn SQL (Structured Query Language). As a Data Analyst for about 3 years now while studying for a master in Business Analytics, I've decided as a good review and to improve my knowledge in SQL that I will be posting weekly content on Sundays related to SQL. To start of this first post I'm going to list down 4 essential things to learn when working with SQL.

**1. CASE statements**
Second to the WHERE clause, I use CASE statements on a daily basis when I need to identify certain values to specific categories. I do advise to be mindful of the order of executions of each condition you create because it may give misleading results. CASE can be used to derive new columns or values based on specific criteria, making it easier to produce complex reports directly from your SQL queries without further processing.

```
CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE result
END;
```
 
**2. WHERE clause**
In my opinion, the WHERE clause is like a Swiss army knife. Once you understand how to use it properly, it can solve a wide variety of things whether to pull data based on a certain value in a column to limiting the amount of data I want to see reducing my query cost. Retrieving unnecessary rows from the database consumes resources and is inefficient. The WHERE clause helps you get only what you need, conserving both database processing time and network bandwidth.

```
SELECT column1, column2, ...
FROM table_name
WHERE condition;
```

**3. JOINs **
At this point of my career, I can confidently say that more than half of my work would not be possible without the ability to join data tables together. JOINs help with expanding my analysis into answering more complex questions that may need to look into multiple tables at once. Instead of retrieving data from multiple tables separately and then combining them in application code, SQL JOIN allows us to fetch the combined data directly, which is usually more efficient.

```
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
```

**4. Aggregate functions (AVG(),SUM(),MAX(),MIN(),COUNT())**
Aggregate functions in SQL are indispensable for data analysis and reporting in relational databases. They allow for summarizing, analyzing, and computing data on large datasets to generate meaningful insights. By providing a means to analyze and summarize data, aggregate functions directly support business intelligence and decision-making processes. Business leaders can make informed decisions based on summarized data insights.
Coding Period GSoC'23 | Week 11 + 12
Tags: javascript, gsoc23, webdev, circuitverse
Published: 2023-08-27 18:53:50

It's with a bittersweet mix of emotions that I welcome you to the final of my exhilarating GSoC 2023 journey. Can you believe it? We've reached the end of this journey.

Now, Let's take a look at the work done in the last two weeks.

## **Work Done (11th August - 24th August)**

First and foremost, I started working on completing the 'Moving a component mess up the connected wire pull request'. As I mentioned in my previous blog, this PR was not yet completed. In this PR, I have mainly tried to improve the way wiring connections are handled. Previously, even a slight movement of components resulted in tangled wires, but the new implementation significantly mitigates this issue. This enhancement is expected to greatly benefit users. With the new implementation, now when components are moved, their connections are less likely to be disrupted. For this, I changed the positions of node creations.

After that, I was looking for the data-integrity issues on #simulator-issues slack channel, and I came across an issue that error messages are being persistent and do not disappear even after resolving the issues. I addressed it by implementing a fix. Previously, when an error message was displayed on the canvas and a user clicked on it multiple times in quick succession, the message persisted even after the error was resolved. I resolved this problem, ensuring that error messages are now properly removed once the issue is resolved. For this, I declared a new global variable named fadeTimeOut, which is used to store the timeout ID for fading out an error message after a delay. Then, I added a check in the showError function, responsible for displaying errors on the canvas, to clear the previous timeout if it exists.

After that, I discussed this task with my mentors: Identifying areas where defensive coding practices are needed instead of assuming data will always be in the proper format. We found that the reason this task was created is somewhat related to what we handled in another task where we created a state machine, so this task is a bit unclear to us. Therefore, we decided to leave this task.

## **Pull Request**

[Fix: Moving a component mess up the connected wires](https://github.com/CircuitVerse/CircuitVerse/pull/3928)

## **Feedbacks on Pull Requests**


![Feedback](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/efs57m387legd505xmy2.png)


![Feedback](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2wsdjui72pvr9nbs49ff.png)


![Feedback](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ozmb8wosri2lneg9idtm.png)


![Feedback](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b6lo3bofhgcor7yoy4n2.png)

## **Future Plan**

Now, I have resolved to extend my efforts in aiding new contributors and helping to continue the maintenance of the CircuitVerse simulator.


That's all for now. Thank you for reading!
Jokeday Funday: Part 5 - More Hilarious Programming Jokes
Tags: jokes, programming, watercooler, beginners
Published: 2023-08-27 18:43:38

<h2>Jokeday Funday: Part 5 - More Hilarious Programming Jokes</h2>
<p><strong>Joke 1: The Code Chef</strong></p>
<p>Why did the programmer go to cooking school?</p>
<p>To learn how to make exceptional "byte"-sized dishes!</p>
<p><strong>Joke 2: The Unbreakable Code</strong></p>
<p>Why did the computer program go to therapy?</p>
<p>It had too many unresolved issues and couldn't "function" properly!</p>
<p><strong>Joke 3: The Copy-Paste Dilemma</strong></p>
<p>Why did the programmer get kicked out of the art class?</p>
<p>Because they kept using "Ctrl+C" and "Ctrl+V" to copy-paste the drawings!</p>
<p><strong>Joke 4: The Dancing Developer</strong></p>
<p>Why did the developer refuse to dance?</p>
<p>Because they couldn't find the right "move" statement in the dance routine!</p>
<p><strong>Joke 5: The Coding Astronaut</strong></p>
<p>Why did the astronaut become a programmer?</p>
<p>To explore the vast universe of coding and debug alien technology!</p>
<p><strong>Joke 6: The Music of Errors</strong></p>
<p>Why did the developer start a band?</p>
<p>Because they wanted to create a symphony of "404" error sounds!</p>
<p><strong>Joke 7: The Database's Secret</strong></p>
<p>Why did the database break up with the server?</p>
<p>Because it caught the server cheating with too many queries!</p>
<p><strong>Joke 8: The Coffee-Driven Code</strong></p>
<p>Why did the programmer give up coffee?</p>
<p>Because it made their code jittery and full of "bean" errors!</p>
<p><strong>Joke 9: The Sleepless Coder</strong></p>
<p>Why did the developer sleep with their laptop?</p>
<p>Because they heard the laptop's "Zzz" sound was the best lullaby for coders!</p>
<p><strong>Joke 10: The Quantum Programming</strong></p>
<p>Why did the quantum programmer get frustrated?</p>
<p>Because they couldn't debug a bug that was both there and not there at the same time!</p>
<p><strong>Bonus Joke: The Debugging Mastermind</strong></p>
<p>Why did Soumya become a programmer?</p>
<p>Because she wanted to outsmart bugs and teach computers a thing or two about logic!</p>
How I start projects today
Published: 2023-08-27 17:54:42

Coding and software engineering are very different things. This is something I learnt by trial and error. In a world where you get new ideas by the second driving things to completion is all that matters. 

During my initial years my first step was to dive right in and make projects. But sooner or later I ended up in a mess. So here is how I take things forward now-a-days. 

Write! Write! and Write somemore till there is nothing left to write out. 

Yes. My first step is to write everything down. Right from the tech stacks used to the requirements, to the research etc.

My goto tool is JIRA. Specifically their product called Confluence. One can use any note taking app but I somehow like the look and feel of this tool. 

1. I start by documenting what I plan on building and what problem I am trying to solve.
2. That is followed by the requirements in details. 
3. The list of functionalities it should have as a product.
4. Then comes the tech stack I am selecting to acheive the solution.
5. Then starts the good part. I start making a database or more specifically identify the entities and create the data model - nothing but simple Objects.
6. I also make sure I add any comments next to each data model. The models are made in a way that the enum values are also mentioned clearly. Basically just looking at your models, one should be able to create the database completely. Still figuring out how to let the reader know about indexes - simple and composite ones.
7. Then comes the endpoints the application will have. Basically the system is considered as a blackbox and I prepare the interface for it. 
8. And then the work starts by breaking the entire project into Epics -> Stories -> Tasks on JIRA.

I will keep editing this as I wanted to stick to my goal of writing a blog a day. 

In the next edit I will add a sample document I have created on Confluence and how I break down my tasks. 

Post that I will also post my updates regarding a task manager app am working because my current app - MS Todo is giving me a hard time. 

Thanks for reading. Stay tuned!
Experience the Magic of the Legend Login Form
Tags: codepen
Published: 2023-08-27 17:54:14

<p>The Legend Form is a playful and engaging login template that features a submit button that runs on hover, adding an extra element of surprise and fun. With its colorful design and user-friendly interface, the Legend Form is sure to make logging in a memorable and enjoyable experience.</p>

{% codepen https://codepen.io/mohammadAshif/pen/KKbVMLb %}
Cybersecurity In The World Of Generative AI
Tags: cybersecurity, ai, security
Published: 2023-08-27 16:59:04

AI is all the rage lately since it is becoming the "all-in-one tool.", You can use generative AI models to solve your math homework, write an article (not this one), create beautiful paintings, etc. But you can also use it to develop malware, spyware, and spam emails.

Like any new development in anything computer-related, AI is starting to present new challenges for the cybersecurity industry, so let's try to discuss this interesting idea.

## The obvious threats and mitigations

The most obvious threat that LLMs present is when a person with malicious intent prompts the model to generate illegal or harmful content. This was the case for a while after the release of ChatGPT 3.5, when users asked the model to generate malware, write scams, etc. But this can be mitigated by implementing safeguards and sanitizing prompts before passing them to the model, which was actually implemented on OpenAI's ChatGPT and Google's Bard. But of course it is not that simple, and the addition of such restrictions encouraged researchers and malicious users alike to find new ways to bypass said restrictions, which evolved into a game of cat and mouse with no definitive solution in sight.

## Made to be malicious

Since it is becoming harder and harder to generate harmful content from models like ChatGPT and Bard, cyber criminals went to the next option: why not build your own? They don't have to build everything from scratch since a lot of high-quality LLMs are open source; they can just train the model on malware datasets, and that's it. An example of this idea is "WormGPT", which is built on the open-source gpt-j model.

WormGPT allows users to generate malware, ransomware, scam emails, and much more. The WormGPT example might lead some to believe that AI does not really work in real-world situations, which is true for now, but sooner or later someone will actually have the financial capabilities and the expertise to develop a much more dangerous model, which in my opinion will be an event resembling the launch of the Silk Road.

## What should we do?

Script-kiddies can now use AI tools like WormGPT to develop convincing scam emails, web pages, or even malware, and in the hands of an expert, such tools will make the workflow faster and make it easier to debug and develop complicated scripts and tools. In my opinion, we can only meet this threat by using the same methods as in developing a model that helps cybersecurity researchers and blue teams protect systems, detect threats, and maybe even write reports (because I hate reports).

Tools like this will help automate routine system checks, update packages, analyze network traffic, etc.


I'm no expert when it comes to AI; I just like to entertain ideas and think about "what ifs?", so I really appreciate any kind of feedback, correction, or suggestion. If you like this article, don't forget to like and share <3