teleren/devto huggingface dataset:
Async and Await
Tags: charp, beginners
Published: 2023-06-27 11:04:53

```
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // Start multiple event loops asynchronously
        Task eventLoop1 = EventLoopAsync("Event Loop 1");
        Task eventLoop2 = EventLoopAsync("Event Loop 2");

        // Continue with other tasks
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Main Loop: Doing some other work...");
            await Task.Delay(1000); // Simulate other work
        }

        // Wait for event loops to complete
        await Task.WhenAll(eventLoop1, eventLoop2);

        Console.WriteLine("All event loops completed.");
    }

    static async Task EventLoopAsync(string name)
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine($"{name}: Iteration {i}");

            // Pause the event loop for some time
            await Task.Delay(2000); // Simulate async operation

            Console.WriteLine($"{name}: Resuming after pause");
        }
    }
}
```

In this code example, we have the Main method as the entry point of our program. Inside Main, we start two event loops asynchronously by calling the EventLoopAsync method twice. These event loops are represented by the eventLoop1 and eventLoop2 tasks.

After starting the event loops, we proceed with some other tasks represented by the for loop. In this case, we simulate other work by printing a message and waiting for 1 second using await Task.Delay(1000).

While the Main loop is executing other work, the event loops are running concurrently. Each event loop runs its own iteration, printing messages and simulating pauses with await Task.Delay(2000).

The key point to note here is that the event loops are asynchronous, which means when the await Task.Delay(2000) is encountered within an event loop, it pauses the execution of that specific event loop. However, the event loop is only paused within itself, not affecting the progress of other event loops or the Main loop.

As a result, while one event loop is paused and waiting for the delay to complete, other event loops or the Main loop continue their execution. This allows the program to handle multiple tasks concurrently without blocking.

Once the delay is complete, the event loop resumes its execution, and the next iteration begins. This continues until all iterations of the event loops are completed.

In the Main method, we use await Task.WhenAll(eventLoop1, eventLoop2) to wait for both event loops to complete before proceeding. Finally, a message is printed indicating that all event loops have completed.
Perl Weekly Challenge #223 - Count Primes? I've Never Met the Man
Tags: perl, perlweeklychallenge, prime
Published: 2023-06-27 10:54:32

Hello everybody! It's another week with a new Perl Weekly Challenge. This week I'm only doing the first challenge, not because of time, but because the second challenge makes absolutely no sense to me. Perhaps a clarification will come out, but I'm not going to bother at the moment.

This week the challenge is to find the number of primes under the provided number. This is a challenge that really isn't worth rewriting, and so I would recommend using [Math::Prime::Util](https://metacpan.org/pod/Math::Prime::Util). You have to know when to just trust the professionals and use modules. With the use of M::P::U, we can essentially do the challenge in one line.

    use Math::Prime::Util 'primes';
    say scalar @{primes(shift)};

primes() returns an array reference, so we have to dereference the array after calling the function. We shift the number that is entered, call primes (which provides an array of the primes under that number), and dereference it and count it to print the answer.

It's that simple! This is a case where I definitely wouldn't recommend writing your own custom prime finder. I'll hopefully see you next week with the next challenge!
Cron Job with NodeJS
Published: 2023-06-27 10:38:22

Hi All,  Suppose we want to execute a task in nodejs on everyday morning at 10AM. Cron job helps us to perform the above task in very easy way. 

``````let app = require('express')(),
server = require('http').Server(app),
bodyParser = require('body-parser'),
express = require('express'),
CronJob = require('cron').CronJob;
 
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
 
app.use(function(err, req, res, next) {
return res.send({ "errorCode": 403, "errorMessage": "Something went wrong!" });
});
 
// catch 404 and forward to error handler
app.use(function(req, res, next) {
res.send({ "errorCode": 404, "errorMessage": 'Page not found!' })
});
 
/*first API to check if server is running*/
app.get('/', function(req, res) {
res.send('hello, jsonworld!');
});
 
new CronJob('1 * * * * *', function() {
console.log("staring cron");
}, null, true, 'America/Los_Angeles');
 
server.listen('3000',function(){
console.log('Server running on port 3000');
});``````

In the above working code, The task will perform in every minute. We have just performed basic  stuff to create a basic app in nodejs. For cron job working we have  included cron module and then created new object to perform the actual task.

**Now lets understand how to set time interval as per  requirement.**

The placing of each asterisk represents a time value. No try to understand how they represent.

Seconds : 0-59

minutes  : 0-59

Hours   : 0-23

Days of Month : 1-31

Months : 0-11

Day of week : 0-6 

**Cron syntax:**

new CronJob(‘00 00 07 * * 1–5’, func...

**Example:**
``````
'* * * * * *' - runs every second
'*/5 * * * * *' - runs every 5 seconds
'10,20,30 * * * * *' - run at 10th, 20th and 30th second of every minute
'0 * * * * *' - runs every minute
'0 0 * * * *' - runs every hour (at 0 minutes and 0 seconds)
``````
The above code will repeat our task at 00 seconds, 00 minutes, at hour 7, on every day of the month, from days 1(Monday) through 5(Friday). So i will not repreat on Saturdays and Sundays.

Hope this was helpful to you! Thanks alot.

This article is originally posted over [jsonworld](jsonworld.com)
Storytelling - Depth vs Width
Tags: storytelling, design
Published: 2023-06-27 10:37:17

When you tell a story of fiction, you are asking the audience to suspend their disbelief. To temporarily believe the imagined world of the story. This suspension of disbelief can only go so far. If the story is too unbelievable. If the storyteller pulls them too far from reality, they will disengaging from the story. 

Depth vs width is an indicator of whether a story will maintain the suspension of disbelief or not. How deep the storyteller explores idea(s) vs how many ideas are being communicated. For details, see https://garden.bradwoods.io/notes/design/story-depth-vs-width
#LearnedToday!
Tags: webdev, programming, javascript, learnedtoday
Published: 2023-06-27 10:29:49

## I’ve been thinking of contributing to the dev social community for years...

...but I’ve always been putting it off for reasons that nowadays seem trivial.

### Current situation

As a senior developer, I’ve stored a lot of information and knowledge and I’ve always shared it only with my close
colleagues, and everytime I teach or just talk about something I know, it sounds like it’s a bit too obvious or not worth sharing it with a wider audience.
But the older I get the more I feel the urge to share my knowledge, moreover, in the last few years, I noticed that what I used to share was not so bad.

> This is why I decided to start sharing some knowledge ***TODAY!***

I wish I had started with a “sexier” date like 1st January but if I had kept postponing it, I never would have started
it!

Writing technical articles takes time, so I decided to start with something less demanding but that requires perseverance:

### I’m going to publish something I learned _every day_.

It could be an article, a coding tip, an idea, a piece of documentation or who knows what the future holds for myself!

I’m going to use [my LinkedIn account](https://www.linkedin.com/in/danielzotti) with the hashtag *`#LearnedToday`* and I’m going to write an article on [Dev.to](https://dev.to/danielzotti) (a community that I’ve been reading passively for years but I’ve never posted anything) in order to collect all the progresses together, with the possibility of adding further notes and thoughts.

I’m also going to create a [GitHub repository](https://github.com/danielzotti/LearnedToday) since I love to use GitHub to save my entire development career and who knows if I develop an app on top of this list, like a UI to filter articles or just to show some analytics.

As far as my own goals are concerned, firstly I hope that this will help me to get used to **posting on a daily basis**
and being **more confident about writing my own technical articles** (spoiler alert: I have three drafts in my Dev.to
account).
Secondly, I would love to **inspire and encourage devs** to do the same, as other devs have inspired me in these years.

To wrap things up, here is a bullet point list, which is always cool to have it in a post, and it's also super
effective:

- Being more fluent writing in English
- Getting used to posting on a daily basis
- Inspiring other devs to do the same
- Learn something new every day

### Do you think I’ll make it?

To start off on the right foot, here is my first tip: [balancing a text with CSS](https://developer.chrome.com/blog/css-text-wrap-balance/) aka `text-wrap: balance`
Title: Network Speed Test: Measuring the Pulse of Your Internet Connection
Tags: network, speed, ping
Published: 2023-06-27 10:24:22

How Network Speed Tests Work

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

[Network speed tests ](https://wordpress.com/post/network65.wordpress.com/13) typically operate by measuring the time it takes to transfer a specific amount of data to and from a remote server. Here's a simplified breakdown of the process:

Selection of Test Server: The speed test tool selects a server located in close proximity to your physical location. This server acts as the endpoint for data transfer, enabling a more accurate representation of your connection's performance.

Data Transfer: The speed test tool initiates the transfer of data packets between your device and the selected server. It measures the time taken to complete the transfer, calculating both the download and upload speeds.

Latency Measurement: To determine latency, the speed test tool sends small packets of data back and forth between your device and the server, measuring the time it takes for each round trip.

Analysis and Results: The tool analyzes the data collected during the test and presents the results, including download and upload speeds, latency, and sometimes jitter. These results provide insights into the quality of your connection and can be used for further analysis or comparison.
Boxing vs Unboxing in C#:A Dramatic Dance of Performance and Convenience
Tags: dotnet, csharp, tutorial, programming
Published: 2023-06-27 10:21:23

Hey there, knights of the keyboard! 🖐️

In this post, we'll be exploring two fundamental but often misunderstood concepts in C#: Boxing and Unboxing. We will investigate their impact on performance, their convenience, and their correct use. So, let's get started!

**Part 1: The Process of Boxing**
Boxing in C# is the process of converting a value type to an object type. It's a convenient mechanism that allows for a unified view of the type system at the potential cost of performance. Here's an example:

```
int i = 123;
object o = i; // Boxing
```
In this snippet, we're converting an integer i into an object o, which is an instance of boxing. While boxing provides convenience and flexibility, it carries a hidden performance cost because it involves creating a new object on the heap.

**Part 2: The Procedure of Unboxing**
Unboxing, conversely, is the operation that converts an object back into a value type. While unboxing, type safety is crucial because an incorrect cast can lead to runtime errors. Here's how unboxing works:

```
object o = 123;
int i = (int) o; // Unboxing
```

In this example, we're transforming an object o back into an integer i. Although unboxing can be helpful, it requires explicit type casting, which, if not correctly handled, can result in an InvalidCastException at runtime.

**Part 3: Performance Implications**
Both boxing and unboxing operations come with some performance implications. Boxing operations involve heap allocation and memory copying, which could impact performance in scenarios where boxing occurs frequently or in large quantities.

Unboxing, on the other hand, requires explicit type casting, which can lead to runtime errors if not correctly handled. Hence, it is advisable to use unboxing judiciously, keeping type safety in mind.

**Conclusion**: Choose Wisely

So, when it comes to boxing and unboxing, it isn't so much a question of which is superior. Instead, it's about understanding the purpose of each operation and their impact on performance. Boxing offers flexibility and a unified view of the type system but at the potential cost of performance. Unboxing allows you to reclaim the original value type, but it requires explicit casting and could lead to runtime errors if not correctly managed.

In your development journey, you'll likely encounter situations where boxing and unboxing are necessary. The key is to understand these operations, their advantages and their potential drawbacks, to make informed decisions about when to use them.

 Keep those fingers dancing on the keyboard! 🖖💻
NGXS State Management: Beginner's Guide.
Tags: angular, redux, webdev, tutorial
Published: 2023-06-27 10:21:08

#### Discover the simplicity of handling the state of your #Angular application through #NGXS and grasp the knowledge of integrating NGXS.

## State Management
State Management involves utilizing a Design Pattern to effectively utilize a single data source across various components of an application. This approach offers advantages like data reliability, simplified code maintenance, and more.

## NGXS
[NGXS](https://www.ngxs.io/) is an Angular-centric State Management Pattern that serves as a centralized data source for your application's state, offering straightforward implementation. In my view, NGXS is easier to adopt compared to NGRX

 In NGXS, there are four key concepts to incorporate:


## Store
The store in NGXS acts as a central state manager, allowing for action dispatching and enabling the selection of specific data slices from the global state.



## Actions
Actions in NGXS represent specific tasks or operations that can be performed to achieve desired outcomes. For instance, we can dispatch a "Get Books" action to retrieve books. When defining actions, it is necessary to specify a type that describes the nature of the action.

---

## State
States in NGXS are responsible for defining the container that holds the application's state. It is possible to have various fundamental states that are commonly utilized in applications, such as:

1.✌️ An initial state 
2.🔃 A loading state
3.👎 An error state
4.☑️ A success state

---

## Select
Selects in NGXS are functions that enable us to retrieve specific data from our store. There are two approaches to perform this:

Using decorators:

```
export class NameYourComponent {

  @Select(TodosState) todos$: Observable<Todos[]>;
}

```
Using store selection functions:

```
export class NameYourComponent {
todos$: Observable<Todos[]>;

  constructor(private _store: Store) {
    this.todos$ = this._store.select(state => state.todos.todos);
  }
}
```

---


With a fundamental understanding of State Management, NGXS, and its underlying concepts, we are now ready to apply it in a practical application!

---

## To begin, install the necessary dependencies by following these steps:
(NGXS): Install on the project:

```
npm i @ngxs/store
```

## Helper plugins

- devtools plugin

```
npm i @ngxs/devtools-plugin
```
To Use it Install this Extension

```
https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=pt
```

- logger plugin

```
npm install @ngxs/logger-plugin --save
```
Or if you are using yarn:

```
yarn add @ngxs/logger-plugin
```
Now, we just have to add the module to our imports in the @NgModule of our application like this:

```
import {NgxsLoggerPluginModule} from '@ngxs/logger-plugin';

@NgModule({
  imports: [
    ...
    NgxsLoggerPluginModule.forRoot({
       disabled: environment.production
     }),
  ],
  ...
})
export class AppModule { }
```

---

[**Part Two..**](www.face book.com)
No tests? No problem: Automating NodeJs testing
Tags: node, testing, express
Published: 2023-06-27 10:07:48

Record and Replay, otherwise known as codeless automation, is a way to run tests without programming knowledge. This is done using a tool, like CodeParrot, that allows you to record requests coming to your service. You can then take this and rerun it with a click, making regression testing infinitely faster.

Record and Replay is the lightweight solution for test automation. The value is the most prominent for teams that are still transitioning from mostly manual testing to include some automation in order to speed up testing and help integrate it earlier in the software development lifecycle.


## CodeParrot Node Js Setup

We'll use the repository https://github.com/Code-Parrot-ai/codeparrot-examples/ for this article. This repository shows example of using CodeParrot for nodejs language with express framework. 

```
git clone https://github.com/Code-Parrot-ai/codeparrot-examples.git

cd nodejs-express
npm i
```

## Phase I: Record

Run the npm 'record' script, all requests coming to this service will be recorded.

```
npm run record
```


Close the script. You can now go to dashboard to generate unique requests on the dashboard https://dashboard.codeparrot.ai/dashboard . Select your service and click on "Regenerate Unique Requests". You would be able to see number of unique requests.




## Phase II: Replay 

Ideal way to run replay is through Github CI App, but can be run on local machine using the 'replay' script 

```
npm run replay
```


You would be able to see link of change report in the log, like 

```
Report will be available at: https://dashboard.codeparrot.ai/diff/nodejs-agent-for-internal@innate-actor-378220.iam.gserviceaccount.com/demo-calc-app/a60fbb9
```

Report might take upto a minute to generate, refresh page if needed.
Build native NodeJS / Bun addons with Nim language, in seconds 👑
Tags: napi, node, bunjs, nim
Published: 2023-06-27 10:01:22

[This is DENIM!](https://github.com/openpeeps/denim) a little CLI monster and library that provides Nim bindings for writing safe and fast native NodeJS/Bun modules.

```nim
import denim

init proc(module: Module):
  proc hello(name: string): string {.export_napi} =
    return %*("Hello, " & args[0].getStr)
```

In JavaScript:
```js
const {hello} = require('./my.node');
console.log(hello("World!")) // Hello, World!
```

That's it!

Check GitHub:
https://github.com/openpeeps/denim
Amazon Verified Permissions
Tags: aws, cloud, security, cloudskills
Published: 2023-06-27 09:35:12

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

[14/30] #30DaysOfAWS Today, Amazon Verified Permissions.

**Amazon Verified Permissions (AVP)** is a scalable, fine-grained permissions management and authorization service for custom applications built by you. It enables your developers to build secure applications faster by externalizing authorization and centralizing policy management and administration. It uses the **Cedar policy language** to define fine-grained permissions for application users. Once you have defined your permissions, you can use the AVP APIs to create, update, and delete them. You can also use the AVP APIs to authorize user actions.

## Benefits of using Amazon Verified Permissions

- **Accelerate application development** - AVP decouples authorization from business logic, so developers can focus on building applications without having to worry about the complexities of authorization.

- **Protect application resources** - AVP helps you protect application resources by enforcing fine-grained access controls. This helps you implement the principle of least privilege, which reduces the risk of unauthorized access to sensitive data.

- **Simplify compliance audits** - AVP provides automated analysis of your permissions, which can help you simplify compliance audits. This can save you time and money, and help you reduce the risk of regulatory violations.

- **Build applications aligned with Zero Trust principles** - AVP helps you build applications that are aligned with Zero Trust principles. Zero Trust is a security model that assumes that no user or device is trusted by default. AVP can help you implement Zero Trust by enforcing fine-grained access controls and continuous real-time authorization decisions.

## Use cases for Amazon Verified Permissions

1. Defining fine-grained access controls for HR systems
2. Enforcing access controls for banking applications
3. Building applications that are aligned with Zero Trust principles
4. Simplifying compliance audits

Amazon Verified Permissions step-by-step workshop -  [URL](https://catalog.workshops.aws/verified-permissions-in-action/en-US)

Thanks for reading the Article.

[LinkedIn](https://www.linkedin.com/in/lasanthasilva)

[Twitter](https://twitter.com/LasanthaSilva96)
APACHE AGE | How To Use AGE Viewer
Tags: apacheage
Published: 2023-06-27 09:20:45


Welcome Back!

So we had successfully installed AGE Viewer in the last blog. Let's see how to use it.

So when we open it, we get this screen:


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

Fill in the fields according to your configurations and it shall send you to the main transactions page where we will write queries and get results.

In the query tab, we can write any query we want, as shown in the snap below, and press the Arrow button to get results.

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

When the results are ready, they are displayed below in graphs composed of nodes and edges if there are any relations between the nodes. An example snap is displayed below.


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


So this is all for the working of Apache AGE Viewer. A helpful tool to graphically view and understand your schemas and their intra-relationships.

https://age.apache.org/
https://github.com/apache/age

GoodBye!
Apache AGE | AGE Viewer (Setup)
Tags: apacheage
Published: 2023-06-27 09:04:08

Hi Guys!

In this blog we will learn about a Graphical tool for Apache AGE. AGE Viewer is a GUI based tool to send cypher queries to databases and getting results in graphical form which are displayed in a combination of nodes and edges, the result a graph as a result of the query.

In this blog, we shall see how to setup AGE Viewer on our systems.

Let's get started!

First open terminal from inside a database folder like we created in the previous blogs for PostgreSQL. We'll assume its name to be 'demo' here.

So inside 'demo' directory on terminal, we have to clone AGE Viewer repository.

Here's the link for that,
                    **https://github.com/apache/age-viewer**

And the command will be,

**git clone https://github.com/apache/age-viewer**


After cloning is done, move inside the cloned directory.

**cd age-viewer/**

Now, an essential requirement is that you have NodeJS installed on your system. If you don't have it, install it before proceeding.

Now run,

**npm run setup**

and when it's done,

**npm run start**


And that's it. You've successfully installed AGE Viewer on your system. We'll see how to use it in the next blog. Till then...

https://age.apache.org/
https://github.com/apache/age

Stay Tuned!