teleren/devto huggingface dataset:
C# Get JWT Token from Request
Tags: csharp, jwt, dotnet
Published: 2023-08-07 13:42:27

This blog post will explore extracting a JWT token from incoming requests using C#.

We will explore two methods using Minimal APIs, but it's the same process for MVC Controllers.

JSON Web Tokens (JWT) have become famous for securing web applications and APIs. JWTs provide a way to transmit claims between parties securely and are widely used for authentication and authorization purposes.

## Table of Contents

- [Method 1: Parsing using Request Context](#method-1-getting-jwt-from-authentication-context)
- [Method 2: Parsing directly from HTTP Headers](#method-2-parsing-jwt-token-from-http-headers)
- [Conclusion](#conclusion)

## Method 1: Getting JWT from Authentication Context

This is the best way because it doesn't rely on the HTTP Headers. It uses the Authentication process instead.

PS.: The Authentication pipeline should be processed at this time.

```csharp
using Microsoft.AspNetCore.Authentication;

app.MapGet("/jwt-token/context", async (HttpContext ctx) =>
{
	//get the access token from the HttpContext
    string token = await ctx.GetTokenAsync("access_token");

    return TypedResults.Ok(new { token = token });
});
```

_Get Access Token from Authentication Context_

## Method 2: Parsing JWT Token from HTTP Headers

To retrieve the JWT token from a request, we need to access the request headers and extract the value of the "Authorization" header.

Here's a second example of how to parse the JWT token from a request:

```csharp
app.MapGet("/jwt-token/headers", (HttpContext ctx) =>
{
    if (ctx.Request.Headers.TryGetValue("Authorization", out var headerAuth))
    {
        var jwtToken = headerAuth.First().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[1];
        return Task.FromResult(
        	TypedResults.Ok(new { token = jwtToken })
        );
    }
    return Task.FromResult(
    	TypedResults.NotFound(new { message = "jwt not found" })
    );
});
```

_Get Access Token from Headers_

### Source Code

[https://github.com/ricardodemauro/Labs.JwtAuthentication](https://github.com/ricardodemauro/Labs.JwtAuthentication?ref=rmauro.dev)

## Conclusion

Extracting a JWT token from a request is a fundamental step in securing web applications and APIs.

Remember to handle error scenarios and follow best practices to ensure the security of your application.
Day 20: Event Loop
Tags: day20, javascript, 100daysofcode
Published: 2023-08-07 13:30:00

<img src="https://media.giphy.com/media/3ov9jQX2Ow4bM5xxuM/giphy.gif" loading="lazy">

🌐 **What is the Event Loop?**

The event loop is a critical component of JavaScript's runtime environment that enables asynchronous behaviour without blocking the main thread. It continuously checks the message queue for pending tasks and processes them one by one, ensuring that your application remains responsive. 


🔄 **Event Loop Phases**

- **Call Stack**:
The call stack is a data structure that records the execution context of functions. When a function is called, it's added to the top of the stack, and when it completes, it's removed from the stack. 

- **Web APIs**:
Web APIs are provided by the browser or the environment in which JavaScript runs. They include features like setTimeout, setInterval, DOM events (click, scroll, etc.), fetch, and more. 

- **Message Queue**:
The message queue holds tasks sent by the Web APIs. Each task consists of a callback function waiting to be executed. 

- **Event Loop**:
The event loop continuously checks the call stack and the message queue. If the call stack is empty, it moves tasks from the message queue to the call stack for execution. 

📷 **Example**

```javascript
const foo = () => console.log("First");
const bar = () => setTimeout(() => console.log("Second"), 500);
const baz = () => console.log("Third");

bar();
foo();
baz();
```

<img src="https://res.cloudinary.com/practicaldev/image/fetch/s--dhjH4Wt---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://devtolydiahallie.s3-us-west-1.amazonaws.com/gif14.1.gif" loading="lazy" width="720" height="405">

Credit: Lydia Hallie


Here is the js visual execution: [view here](https://www.jsv9000.app/?code=Y29uc3QgZm9vID0gKCkgPT4gY29uc29sZS5sb2coIkZpcnN0Iik7CmNvbnN0IGJhciA9ICgpID0%2BIHNldFRpbWVvdXQoKCkgPT4gY29uc29sZS5sb2coIlNlY29uZCIpLCA1MDApOwpjb25zdCBiYXogPSAoKSA9PiBjb25zb2xlLmxvZygiVGhpcmQiKTsKCmJhcigpOwpmb28oKTsKYmF6KCk7)

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


💡 **Explanation**

- First, the `bar()` function is called. This function contains setTimeout, which is an asynchronous function. It schedules the execution of its callback function (**Second**) after a delay of 500 milliseconds. The event loop adds this task to the message queue and moves on.
- Next, the `foo()` function is called. It logs **First** to the console immediately and returns.
- After that, the `baz()` function is called, which logs **Third** to the console immediately and returns.
- Now, the call stack is empty, and the event loop starts processing the tasks in the message queue.
- The event loop picks the first task from the message queue, which is the callback function of setTimeout from the `bar()` function. The callback logs **Second** to the console.

## 📚 **Homework**
1. what is the difference between task queue & micro task queue?
2. Give me the example with micro & macro task queue.

Write the answers in the comment section
🎉 Experience the React-iPod Magic! 🎧
Published: 2023-08-07 13:28:32

iPod

🚀 Dive into nostalgia with my new React project – a modern iPod adventure! 🎶

📋 Highlights:

🔹 Interactive Menu & Funky Navigation
🔹 Smooth Transitions & Spin Action
🔹 Backstage Pass for Quick Moves
🔹 Optional Submenus for Extra Groove

📺 Catch the Beat:
Watch the project in action: Project Live Link:- https://ashuraa16.github.io/iPod/ 

💡 Tech Takeaways:
State, Props, Events, and More!

📁 Check Out the Code:
GitHub: https://github.com/Ashuraa16/iPod 

Unleash your inner coding rockstar and groove with React-iPod magic! 🎸🎉 #ReactiPodMagic #TechGroove#ReactiPodMagic
#InnovationUnleashed #TechGroove #ModernNostalgia #CodeJamming #UIInnovation #InteractiveDesign #ReactAdventures #TechRetro #CodingFun #CreativeCoding #DigitalInnovation #UIExperience #ModernTech #CodingJourney
K8s operator - Synchronize resources outside Kubernetes cluster
Tags: devops, sre, kubernetes
Published: 2023-08-07 13:09:00

When we automate tasks/resources in a Kubernetes Cluster, we first think about managing Kubernetes resources. But we must not forget that we are not limited to what is presented to us.

Like every post since the begining of this serie, we will talk about the Operator SDK, the Go framework to create operators. And who says Go, says that we can : 
- **read into a database**
- **call an API**
- **write a message in a queue**
- ...

Indeed, **everything which is possible in Go is possible in your operator**.

> *Why it is interesting?*

For a simple reason, **you are not limited to your Kubernetes cluster context to automate tasks and resources management.**

Here is a simple example: You manage Prometheus and/or Thanos instances in your cluster with your operator, but you have a single Grafana instance for all these Prometheus/Thanos instances and it's outside of your cluster. In this case, if you want to manage the datasource in Grafana, you must do it through the API.
And here the operator power skyrockets because you can use any API or service which manage resources. You don't need to implement something particular or migrate it into your Kubernetes cluster.

For sure, it won't be useful for everyone but think about the following example :
You are in a compagny which offer several services to your clients, including :
- a metric collector with Promtheus
- a Grafana instance to monitor all the metrics
The issue is that each element is managed by a dedicated operator on a dedicated Kubernetes cluster. How can you automate the management of a customer stack ?

Answer : **With APIs !**

With dedicated APIs to manage your resources *(by using the [Python Kubernetes](https://learning.oreilly.com/home/) library for example)* or by using the [Kubernetes API](https://kubernetes.io/docs/reference/using-api/api-concepts/), you can have an operator which can manage all the stack by calling all the other operators with these APIs.
From this, all the spread stack can be automated!

---

I hope it will help you and if you have any questions *(there are not dumb questions)* or some points are not clear for you, don't hesitate to add your question in the comments or to contact me directly on  [LinkedIn](https://www.linkedin.com/in/maxime-guilbert-14b6a5128/).

---

<center><h3>You want to support me?</h3></center>
<a href="https://www.buymeacoffee.com/mxguilbert7" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>
What is Stack? Important Data Structure
Tags: webdev, programming, career, tutorial
Published: 2023-08-07 13:08:57

A stack is a particular kind of abstract data type or collection that is used in computer science. Elements are added to and removed from a stack using a principle known as "LIFO" (Last In, First Out), meaning that the most recently added elements are the first to be removed.


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

Here are the main operations associated with a stack:

- Push: This operation is used to insert an element into the stack. If the stack is full, then it is said to be an Overflow condition. In a stack, the new element is always added at the top.

- Pop: This operation is used to remove an element from the stack. Elements are always removed from the top. If the stack is empty, then it is said to be an Underflow condition.

- Peek or Top: This operation helps to get the topmost element of the stack. It does not delete the element; it only returns the value of the topmost element.

- isEmpty: This operation checks if the stack is empty.

- isFull: This operation checks if the stack is full.

One of the most intuitive real-world examples of a stack is a pile of plates. When you add a plate, it goes on the top of the pile (push). When you need a plate, you take it from the top of the pile (pop). And when you want to know what plate you will get, you just check the top plate (peek/top).

In computing, stacks are used in many areas, including managing function calls, parsing expressions, backtracking algorithms, undo functionality in software programs, memory management, etc.

A stack can be implemented using various underlying data structures such as an array, linked list, or a dynamically resizing array (like ArrayList in Java or vector in C++). The choice of underlying structure can affect the efficiency of different stack operations

Thank you for reading. I encourage you to follow me on Twitter where I regularly share content about JavaScript and React, as well as contribute to open-source projects. I am currently seeking a remote job or internship.

Twitter: https://twitter.com/Diwakar_766

GitHub: https://github.com/DIWAKARKASHYAP

Portfolio: https://diwakar-portfolio.vercel.app/
Synchroniser des ressources hors cluster
Tags: sre, kubernetes, french, devops
Published: 2023-08-07 13:08:00

Quand on automatise des tâches avec un opérateur Kubernetes, on va surtout penser au fait que l'on peut gérer des ressources Kubernetes. Cependant il ne faut pas oublier qu'on n'est pas forcément limité à ce qui nous est présenté.

Comme depuis le début de cette série, on va se concentrer sur le framework Go d'Operator SDK. Et qui dit projet en Go, dit que l'on peut :
- **lire dans une base de données**
- **faire appel à une API**
- **écrire un message dans une queue**
- ...

En effet, **tout ce qui est possible en Go est finalement possible à intégrer dans un opérateur**. 

> *En quoi c'est intéressant de faire ça?*

Pour une raison simple, **vous n'êtes plus limité au contexte de votre cluster Kubernetes pour automatiser des éléments**.

Prenons un exemple simple, vous créez des instances de Prometheus ou Thanos dans votre cluster Kubernetes via votre opérateur, mais il n'y a qu'un seul Grafana qui est utilisé dans toute votre entreprise et il ne se trouve pas dans votre cluster. De ce fait, si vous voulez automatiser la gestion des datasources dans ce Grafana, vous devrez passer par son API.
Et c'est là que la puissance de l'opérateur se décuple, car vous pourrez utiliser toutes les APIs et autres services qui gèrent des ressources dans votre compagnie. Pas besoin d'avoir à réinventer la roue ou de migrer le système en question pour qu'il soit dans Kubernetes.

C'est sûr que ça ne sera pas forcément utile à tous, mais imaginez l'exemple suivant:
Vous êtes dans une compagnie qui offrent un ensemble de services pour vos clients. Cela comprend un système de récupération de métriques via Prometheus et une instance de grafana dédiée. Chacun de ces éléments sont gérés par des opérateurs distincts, sur des clusters séparés.
Comment pourriez-vous faire pour gérer automatiquement vos ressources dans tous ces clusters ?

Réponse : **Grâce aux APIs !** 

En créant des APIs dédiées pour gérer vos ressources *(en utilisant une librairie comme celle pour dédiée [Python](https://github.com/kubernetes-client/python))* ou en utilisant l'[api kubernetes](https://kubernetes.io/docs/reference/using-api/api-concepts/),  vous pourriez avoir un opérateur qui va s'occuper d'appeler les apis sur vos différents clusters afin de s'assurer que toutes les ressources demandées sont bien créées.
A partir de là, des infrastructures divisées et potentiellement compliquées à être automatisées toutes ensemble peuvent le devenir!

---

J'espère que ça vous aidera et si jamais vous avez des questions, quelles qu'elles soient *(Il n'y a jamais de questions bêtes!)* ou des points qui ne sont pas clairs pour vous, n'hésitez pas à laisser un message dans les commentaires ou à me joindre directement sur [LinkedIn](https://www.linkedin.com/in/maxime-guilbert-14b6a5128/) *(même pour parler d'autres sujets!)*.

---

<center><h3>Vous voulez me supporter?</h3></center>
<a href="https://www.buymeacoffee.com/mxguilbert7" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>
My Process for Submitting Pull Requests
Tags: tips, process, opensource, pullrequests
Published: 2024-01-22 02:42:50

---
title: My Process for Submitting Pull Requests
published: true
date: 2024-01-22 13:00:00 UTC
tags: tips,process,oss,pullrequests
canonical_url: https://seankilleen.com/2023/08/my-process-for-submitting-pull-requests/
---

I’ve been asked a lot of times about my process for submitting pull requests, so I figured I’d write it up!

## First – A Few Caveats

- **This is my style; yours might vary, and that’s fine!** I think there are a lot of ways to do this well, and there’s no sense in being dogmatic about it.
- **I don’t follow this 100% every time**. I don’t think you have to do these things exactly in order to be successful. It’s better to adapt to your situation/context.
- **I’m assuming you’re familiar with pull requests and how they work.** If you’re not yet familiar with that, I recommend searching around and finding some great articles on that first, or some of the contents of this article might be confusing.
- **This assumes you _want_ pull requests.** Many teams prefer to forego them because they feel they add unnecessary overhead. I disagree; I think they build historical context and communication skills that pay off in the long run. My point is, if you doubt pull requests in general, then this post isn’t for you.

## Why Use Pull Requests at All?

I’m a big fan of working out loud. To me, pull requests represent a way of sharing your thoughts and code as early as possible. They also allow you to make notes on your thoughts as you go and make it easier for others to review. To be clear, I think that making things easier to review is great, but I think PRs are powerful even if there’s no review process in place.

[Read the rest at SeanKilleen.com](https://seankilleen.com/2023/08/my-process-for-submitting-pull-requests/)
Music Monday — What are you listening to? (Chill Edition II)
Tags: watercooler, discuss, music
Published: 2023-08-07 13:00:00

_cover image source: [Giphy](https://giphy.com/gifs/guitar-landscape-xT0xeislUw6TMhAyAg)_

**Well, I'm officially out of ideas this week, so I thought why not revisit [a previous edition](https://dev.to/music-discussions/music-monday-what-are-you-listening-to-chill-edition-nj0)? I absolutely love chill music. Lo-fi hip hop beats were my jam during COVID and really kicked off a whole exploration into music with chill vibes. In any case, I really wanna hear what kinda music you all like to chill to. Whether you tend to throw on lofi instrumental stuff or ya like to kick back and relax to some heavy death metal... whatever floats your boat and soothes your soul, I wanna hear it.**

![cartoon woman standing outside on a rock face listening to a boom box at dusk](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w585u8hdecemoao6eneq.gif)

***

## How we do 

In this weekly series, folks can chime in and drop links to whatever it is they've been listening to recently + browse others suggestions.

If you like talking about music, consider following the org [#music discussions](https://dev.to/music-discussions) for more conversations about music!

{% embed https://dev.to/music-discussions %}

***

Let's hear those chill-vibey tunes? _Note: you can embed a link to your song on most platforms using the following syntax `{% embed https://... %}`._

I look forward to listening to y'all's suggestions! 👂 🎶
Caption This! 🤔💭
Tags: watercooler
Published: 2023-08-07 13:00:00

Alright folks! We got another image and could use y'all's minds captioning it.

![a man's body in a suit... he is clicking a button that says "tech support"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bairiqpiinn2zfh2mnlq.jpg)

Follow the DEVteam for more online camaraderie!

{% embed [https://dev.to/devteam](https://dev.to/devteam) %}
Weekly AI News and Discussion Thread
Tags: ai, discuss, news
Published: 2023-08-07 13:00:00

Hey everyone, the past few months have been pretty electric in terms of advancements in AI and actual/imagined changes to our workflow and industry.

This is a regular open thread where everyone is encouraged to share...

* Notable news in the field of AI
* Personal experiences and insights
* Concerns and fears
* Success stories and demos
* And any other related discussions you'd like to bring to the table

This thread will go out every week.
Site Ground Cron Job
Published: 2023-08-07 12:47:21


I recently ran to this task so after search and support I thought about posting it here.


![Where you should be](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5fgryxvrhmc8l48vu48e.PNG)
This is were you should be you can find it in 
> (Site Tools -> Sidebar -> Dev Section -> Cron Jobs)
or
> https://tools.siteground.com/cron-job?siteId={YourSiteId}


## 1- Path

```
cd /home/customer/www/domain/public_html/path/ && php filname.php
```
Pretty self explanatory

## 2- Interval
You can use the easy dropdown or if you want to add manually This is some info

1. Use UTC time
2. Use 24-hour format
3. if you want test set it after 5 or 10 minutes

That's It.
Software Learned
Published: 2023-08-07 12:26:20

Just beginning the learning of full-stack software engineering. There is a long way to go, but as someone has stated about making this journey, think about how much you have learned so far. This way we won’t dwell so much on all that is needed to learn (and get discouraged). So this is my list of software, programs, or apps I’ve had to learn (or learn again) so far, and I’ll update this as I go along.

Some of these I had familiarity with or have used in the past but not in an effective way for learning software engineering.

Anki
CSS
HTML
JavaScript
LinkedIn (networking processes, not just looking around)
VS Code
Notepad++
Discord
Twitch
Hashnode
Command Line
OBS Studio
Youtube (for uploading videos and live streaming)
Twitter (didn’t use much before, still learning how to be effective)
Git Bash
GitHub
Also, I’m forcing myself to learn to touch type numbers on the number line on the keyboard instead of using the 10-key number pad (a habit learned from being a CPA), to be more efficient. Additionally, it is helpful to use keyboard shortcuts, so I’m adding that to my daily learning to wean myself off of so much mouse use.

What is on my list to learn next (that I know of)?

Vim
macOS
Ubuntu
When I started learning, I would realize I need to learn new software to do a new task. My first thought was, “Oh no, not another program.” Then, I thought, well, this is what I wanted to do, learn new things all the time. And this is what it feels like. You see a wall (New Unfamiliar Software), and you have to push through the uncomfortable to gain knowledge. Now, after a few months of learning so many new things, my thought process is different. I see it more as, “Oh, let’s see what this program does and how it works. I don’t know it yet, but I will as soon as I gain familiarity.”

The other observation I see as motivating is that there are videos I watch on various topics, and I understand and know more about what they are talking about. Whereas before, the videos seemed over my head, mumbo-jumbo. It’s exciting to think, “I know what that is!” And even sometimes form my own opinion on things.

Now, on to get those 12 photos for the site I’m currently working on.

Happy day!!