teleren/devto huggingface dataset:
Adicionar um novo mapeamento de porta a um cluster K3D existente
Tags: kubernetes, k3d, docker, postgres
Published: 2023-08-10 15:05:27

Considerando que o seguinte serviço foi criado:

```yaml
apiVersion: v1
kind: Service
metadata:
  name: postgres-outside-cluster
  namespace: default
spec:
  type: NodePort
  selector:
    app: postgres
    replicationRole: primary
  ports:
  - name: port-5432
    protocol: TCP
    port: 5432
    targetPort: 5432
    nodePort: 30543
```

Ao executar o comando abaixo será possível acessar, no host, o postgres via localhost:5432: 

`k3d cluster edit k3s-default --port-add 5432:30543@server:0`

Onde `k3s-default` é o nome do cluster, `5432` é a porta do host e `30543` é a porta do node.
Linux - SYMLINKS
Tags: linux, scor32k
Published: 2023-08-10 15:03:47

# Symlinks
In Linux, the equivalent of **shortcuts** are **symbolic links** (or soft links or symlinks).

*Symlinks allow us to link to another file by its filename*. 

Another type of links found in Linux are **hardlinks**, these are actually another file with a link to an inode

## Create a soft link
```bash
ln -s myfile myfilelink
```
You can see that I've made a symbolic link named myfilelink that points to myfile.

![soft symlink](https://imgur.com/dk0ijwG.png)

 Symbolic links are denoted by **->**
 
Notice, how I got a new inode number though, symlinks are just files that point to filenames. 

When you modify a symlink, the file also gets modified. 
[Inode numbers](https://dev.to/scorcism/linux-inode-1a2g) are unique to filesystems, you can't have two of the same inode number in a single filesystem, meaning you can't reference a file in a different filesystem by its inode number. 
![inode](https://imgur.com/EsYRnsd.png )
However, if you use symlinks they do not use inode numbers, they use filenames, so they can be referenced across different filesystems.

## Create a hard link
```bash
ln myfile2 myhardlink
```
A hardlink just creates **another file** with a link to the same inode. 

![](https://imgur.com/tLpo7xd.png)

So if I modified the contents of myfile2 or myhardlink, the change would be seen on both, but if I deleted myfile2, the file would still be accessible through myhardlink. 

Here is where our **link count** in the ls command comes into play. 

`The link count is the number of hardlinks that an inode has, when you remove a file, it will decrease that link count. `

The inode only gets deleted when all hardlinks to the inode have been deleted. 

When you create a file, it's link count is 1 because it is the only file that is pointing to that inode. 
Unlike symlinks, hardlinks do not span filesystems because inodes are unique to the filesystem.

If the article helps you, leave a like, follow, or anything 🙂.  
You can follow me on [LinkedIn](https://www.linkedin.com/in/abhishekpathak32/) and [GitHub](https://github.com/scorcism).
If_Else If Statements: The Quick Guide For Beginners
Tags: javascript, beginners, tutorial
Published: 2023-08-10 15:00:00

_(See The Header Image For How An If_Else If Statement Is Basically Written In A Function)_

## JavaScript likes to "solve" If_Else If Statements like flipping through a catalog... 
_...in search of something to buy - "If you don't want thing1, move on to thing2, and if you don't want thing2, move on to thing3, etc. Finally, if nothing else works, just get the basic model". Let's explore this a little more:_

Our function starts out by checking the condition with the block of code to the right of the "if". This is our starting place, so it get's the special "if" name. If the condition is true (it matches exactly with the thing we've defined to the right of the ===), the function will return something from this block of code, then exit the function.

BUT, if the condition is FALSE, (it DOESN'T match exactly with the thing we've defined to the right of the ===), the function will move on and run the "else if" part of the code. If the condition is true (it matches exactly with the thing we've defined to the right of the ===), the function will return something from that block of code, then exit the function.

We can have multiple "else if" parts of the code - one for each option we want - and if the previous "else if" statement returns false, the next "else if" statements will be checked. This will continue until either 1)one of the "else if" statements returns true, or 2)there are no more "else if" statements left, in which case we move on to the last part of our code:

If nothing has returned true by the time we reach "else" (notice, this is the last part of the code and is NOT written "else if"), then the "else" part of the code will run and return something from that block of code.

It is important to remember that SOMETHING will be run: we have many options for what to run _if_ something matches our "if" or "else if" parts of the code... but if nothing matches these parts, the "else" part of the code WILL run.

## You can remember when to use If_Else If Statements like this:
**If not Option1 or Option2 or Option3 (etc.), do the Final Option.**
My Journey In The Open Source World - Contributing to other libraries #4
Tags: javascript, typescript, opensource, github
Published: 2023-08-10 15:00:00

[Follow me on Github!](https://github.com/Cadienvan)

As mentioned in my previous posts about contributing to other libraries, here are some of my efforts to improve some JavaScript libraries!

---

[kv.js](https://github.com/HeyPuter/kv.js)
I added TypeScript support thanks to the awesome tsc library doing all the work when JSDoc is used.  
This is a simple, yet powerful addition because JavaScript developers nowadays expect a good TypeScript support and a .d.ts file can hugely improve developer experience.
10 tips to prevent cross-site attack in .NET.
Tags: dotnetcore, beginners
Published: 2023-08-10 14:59:59

Preventing Cross-Site Scripting (XSS) attacks in a .NET Core project involves implementing proper input validation, output encoding, and security configurations. 
Here are some steps to help you prevent XSS in your .NET Core project.

**1. Validate Input Data:**
Valiate and sanitize all user inputs, including query parameters, form data, and cookies. Reject or sanitize any input that doesn't meet the expected format or content.

**2. Use Parameterized Queries:**
When interacting with databases, use parameterized queries or an Object-Relational Mapping (ORM) library that automatically escapes input values. This prevents SQL injection attacks, which can lead to XSS vulnerabilities.

**3. Output Encoding**
Always encode dynamic data before displaying it in the HTML. .NET core provides HTML encoding functions that you should use when rendering data in views. For example, in Razor views, use @Html.Raw to output content as raw HTML, and use @Html.Encode to HTML-encode content.

**4. Content Security Policy (CSP):**
Implement a Content Security Policy to restrict the sources from which your application can load content (e.g., scripts, styles, images). This can mitigate the impact of malicious scripts injected into your pages.

**5. Use Razor Views Property:**
Be careful with Razor Views. Avoid using @Html.Raw unless you're certain the content is safe. Use Razor's automatic HTML encoding by default.

**6. Avoid Dangerous APIs:**
Be cautious when using potentially dangerous APIs that can execute scripts. For example, when using innerHTML in javascript or the @Html.Raw method in Razor views, ensure that you're not inadvertently executing scripts. 

**7. Sanitize Rich Content:**
If your application allows users to enter rich content (e.g., comments, descriptions), consider using a trusted and well-maintained HTML sanitizer library to sanitize the content before rendering it.

```
using Ganss.XSS;

string unsafeHtml = "<script>alert('XSS!');</script><p>This is safe.</p>";
var sanitizer = new HtmlSanitizer();
string safeHtml = sanitizer.Sanitize(unsafeHtml);

// Now, the safeHtml variable contains sanitized HTML
// that can be safely displayed.

```

**8. Ragular Security Updates:**
Keep your .NET core framework and packages up-to-date. Updates may include security patches that address known vulnerabilities.

**9. Security Headers:**
Use appropriate HTTP security headers, such as X-XSS-Protection, to instruct browsers to prevent or mitigate XSS attacks.

**10. Security Testing:**
Conduct regular security testing, including automated and manual security assessments, to identify and fix potential vulnerabilities, including XSS.

By following these best practices, you can significantly reduce the risk of XSS attacks in your .NET Core project. Stay informed about the latest security updates and practices to keep your application secure.
[Discord] Send message through Bot
Tags: discord, beginners, curl
Published: 2023-08-10 14:57:58

I am a newbie to Discord. Recently, my friend and I started a discord channel for a live talk session to interview people and share our experiences with interested people.

When sending a message, I'm thinking about a way to send a message through a bot instead of using my account, so my friend taught me a way to do that. And today, you will know it too!!
<hr>
First of all, you have to be an admin of that server. Then, visit the server setting > integration > webhook.

![Webhook-setting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h7oeih99uyde4tf5zhyu.png)

Then, click "New Webhook" and choose the channel that you want to send message to
![Create-webhook](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nq3psmo0a1uu9ilrxpx8.png)

Later on, click on the button "Copy Webhook URL" to copy the webhook URL

Lastly, you can send a message by inputting it into the curl.
```
curl --location --request POST '{YOUR_WEBHOOK_URL}' \
--header 'Content-Type: application/json' \
--data-raw '{
    "content": "{YOUR_MESSAGE}",
    "username": "{SENDER_NAME}",
    "avatar_url": "{PICTURE_URL}"
}
'
```

Please feel free to share interesting bot and command in discord with me 👾
Android Studio 2022.3.1 (Mac Intel) cannot create Flutter projects
Published: 2023-08-10 14:36:36

Android Studio 2022.3.1 (Mac Intel) cannot create Flutter projects
------------------------------------------------------------------

Software development can be a rollercoaster ride, with its fair share of ups and downs. One such downer is when you encounter an issue with your favorite development tool. If you are a Flutter developer using Android Studio 2022.3.1 on a Mac with Intel processor, you might have run into a frustrating problem: the inability to create Flutter projects. Don't worry, you're not alone in this struggle!

Flutter, Google's UI toolkit for building natively compiled applications for mobile, web, and desktop, has gained immense popularity among developers. However, it seems that the latest version of Android Studio has hit a roadblock when it comes to creating Flutter projects on Macs with Intel processors.

When you try to create a new Flutter project in Android Studio 2022.3.1, you might encounter an error message that says, "Unable to create Flutter project. Please check your installation." This error can be frustrating, especially when you're eager to dive into your next Flutter project.

But fear not, there are a few workarounds you can try to get past this roadblock:

1.  **Use an older version of Android Studio:** While it may not be the ideal solution, downgrading to a previous version of Android Studio might help you create Flutter projects on your Mac with an Intel processor. Sometimes, older versions are more stable and compatible with certain hardware configurations.
2.  **Try using Visual Studio Code:** If Android Studio continues to give you trouble, you can always switch to Visual Studio Code, a popular lightweight code editor. Visual Studio Code has excellent support for Flutter development, and many developers find it to be a reliable alternative.
3.  **Patience is a virtue:** As frustrating as it may be, sometimes it's best to wait for a bug fix or an update from the Android Studio team. Software development is an ever-evolving field, and issues like these are often resolved in subsequent releases.

Remember, software development is not always smooth sailing. It's important to keep a sense of humor and not let these hiccups discourage you. As they say, "A programmer's life is full of bugs, but laughter can be the best debug tool!"

So, if you find yourself facing the "Unable to create Flutter project" error in Android Studio 2022.3.1 on your Mac with an Intel processor, don't panic. Try one of the workarounds mentioned above, and hopefully, you'll be back to fluttering in no time!

### References:

*   [Flutter Official Website](https://flutter.dev/)
*   [Android Studio Documentation](https://developer.android.com/studio)
*   [Visual Studio Code Official Website](https://code.visualstudio.com/)
Failed verify the JWT: There is no issuer named https://sts.windows/{tenant}/
Published: 2023-08-10 14:35:55

Have you ever encountered the error message "Failed to verify the JWT: There is no issuer named https://sts.windows/{tenant}/" while working on your software development project? Don't worry, you're not alone! This error can be quite frustrating, but fear not, we're here to help you understand what it means and how to resolve it.

First, let's break down the error message. JWT stands for JSON Web Token, which is a compact, URL-safe means of representing claims to be transferred between two parties. In simple terms, it is a way to securely transmit information between a client and a server. The issuer, in this case, refers to the entity that issued the JWT, which is typically a trusted authentication server.

Now, why would you encounter an error stating that there is no issuer named "https://sts.windows/{tenant}/"? Well, this error usually occurs when the JWT token you are trying to verify does not have a valid issuer or the issuer URL is incorrect. The "{tenant}" part in the error message represents a placeholder for your specific tenant ID or domain.

To resolve this issue, you need to ensure that you have the correct issuer URL in your code or configuration. Double-check the URL and make sure it matches the one provided by your authentication server. It's also worth verifying that you have the necessary permissions and access to the authentication server.

Now, let's add a little humor to lighten the mood. Imagine your JWT token as a lost passport, desperately searching for its issuer in a crowded airport. It wanders around, asking everyone it meets, "Excuse me, have you seen an issuer named 'https://sts.windows/{tenant}/'?". Unfortunately, nobody seems to have any clue, and the token gets more and more frustrated.

But fear not, dear token! We are here to guide you on your quest. We'll help you find your rightful issuer and get you back on track to authenticate yourself with the server. Just follow our instructions, and soon you'll be flying high again!

Remember, when dealing with JWT verification errors, it's important to double-check your code, configuration, and the issuer URL. Sometimes, a simple typo or a missing character can lead to hours of frustration. So, stay calm, take a deep breath, and debug with a smile!

References:

*   [Introduction to JSON Web Tokens (JWT)](https://jwt.io/introduction/)
*   [Microsoft Azure - Access Tokens](https://docs.microsoft.com/en-us/azure/active-directory/develop/access-tokens)
*   [Microsoft Azure - OpenID Connect](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc)
Better Bogo Sort
Tags: sorting
Published: 2023-08-10 14:34:52

This algorithm chooses 2 random numbers and, if the items in those two positions aren't ordered, swaps them. Then, it checks if the entire array is sorted.

WCS: Time O(inf), Space O(1)

Rust code:
```rust
fn better_bogo<T: Copy>(arr: Vec<T>, cond: fn(T, T) -> bool) -> Vec<T> {
    let mut arr2 = arr;
    'sort: loop {
        let i = (rand::random::<f32>() * (arr2.len() as f32)) as usize;
        let j = (rand::random::<f32>() * i as f32) as usize;
        if cond(arr2[j], arr2[i]) {
            let tmp: T = arr2[i];
            arr2[i] = arr2[j];
            arr2[j] = tmp;
        }
        for i in 0..(arr2.len()-1) {
            if cond(arr2[i], arr2[i+1]) { continue 'sort; }
        }
        break 'sort;
    }
    return arr2;
}
```
Kubernetes - Monitor custom application metrics using Prometheus and Istio.
Published: 2023-08-10 14:32:19

Kubernetes pod level metrics are captured by out of the box combination of Istio, Prometheus and Grafana components. In order to get your application metrics (e.g.: jvm metrics, custom counter metrics etc) onto Grafana, we can configure the existing setup in such a way that Istio will capture the metrics from pod and applications and merge them before sending to prometheus.

In order to do this, we need to have the application expose its metrics on some endpoint  (eg: springboot provides out of the box facility to expose jvm/app metrics on actuator/prometheus api. )

Once this is setup, we can configure the deployment yaml to add annotations to the pod which help istio to scrape the metrics from the application, merge them with pod metrics and send to prometheus.

`      annotations:
        prometheus.io/path: "/actuator/prometheus"
        prometheus.io/port: "80"
        prometheus.io/scheme: "http"
        prometheus.io/scrape: "true"
`
With this setup, the application metrics will be scraped from the pod and be available along with other metrics on Grafana dashboard.
Failed verify the JWT: There is no issuer named https://sts.windows/{tenant}/
Published: 2023-08-10 14:29:26

So you're working on a software development project and you encounter the error message "Failed to verify the JWT: There is no issuer named https://sts.windows/{tenant}/". Don't panic! This article will guide you through understanding and resolving this issue.

First, let's break down the error message. JWT stands for JSON Web Token, which is a standard for securely transmitting information between parties as a JSON object. In this case, the JWT is failing to verify because it cannot find the issuer named "https://sts.windows/{tenant}/". The issuer represents the entity that issued the token, and it is necessary for the verification process.

Now, there are a few possible reasons for this error. Let's explore some of the common causes and their solutions:

1.  **Invalid issuer URL:** Double-check the URL of the issuer in your code. It should be in the format "https://sts.windows/{tenant}/". Ensure that you have replaced "{tenant}" with the appropriate value. If the URL is incorrect or incomplete, it will result in the "Failed to verify the JWT" error.
2.  **Missing or incorrect configuration:** Verify that your software development environment is properly configured. Make sure you have set up the necessary libraries, dependencies, and configurations to handle JWT verification. Check your code for any missing or incorrect configurations related to the issuer.
3.  **Authentication server issues:** The error message could also indicate a problem with the authentication server. It is possible that the server is experiencing downtime or is misconfigured. In such cases, you may need to reach out to the server administrator or support team to resolve the issue.

Now, let's add a touch of humor to lighten the mood. Imagine your code is a detective trying to solve a mystery. The detective receives a clue (the JWT) but gets stuck because they can't find the issuer. It's like searching for a missing person without any information about their whereabouts. Don't worry, though, our detective (you) will crack the case and find the issuer, ensuring the JWT verification process runs smoothly!

In conclusion, the "Failed to verify the JWT: There is no issuer named https://sts.windows/{tenant}/" error can be resolved by checking the issuer URL, verifying the configuration, and investigating any potential issues with the authentication server. With a little detective work and a touch of humor, you'll be able to overcome this challenge and continue with your software development project.

**References:**

*   JWT Official Website: [https://jwt.io/](https://jwt.io/)
*   Microsoft Azure Active Directory Documentation: [https://docs.microsoft.com/en-us/azure/active-directory/develop/](https://docs.microsoft.com/en-us/azure/active-directory/develop/)
basics of java. part 1.
Tags: programming, java, basics
Published: 2023-08-10 14:29:00

```

```
_***** _What is Java?**_**_
Java is a popular programming language, created in 1995.It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
1. Mobile applications (specially Android apps)
2. Desktop applications
3. Web applications
4. Web servers and application servers
Games
5.Database connection

_**Java Syntax**_
public class Main {
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}



_**Java Comments**_
*Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by Java (will not be executed).

*Multi-line comments start with /* and ends with */.

## 

**__Java Variables_**_
In Java, there are different types of variables, for example:

1. _String_ - stores text, such as "Hello". String values are surrounded by double quotes.
2_. int_ - stores integers (whole numbers), without decimals, such as 123 or -123.

3. _float_ - stores floating point numbers, with decimals, such as 19.99 or -19.99.

4._ char_ - stores single characters, such as 'a' or 'B'. Char 
values are surrounded by single quotes.

5. boolean - stores values with two states: true or false.

**_Declaring (Creating) Variables: syntax  :-

type variableName = value;

**_Java Data Types_**
Data types are divided into two groups:

**_Primitive data types_** - includes byte, short, int, long, float, double, boolean and char.

**_Non-primitive data types_** - such as String, Arrays and Classes.

Data Type	Size	          Description
byte	       1 byte	        Stores whole numbers from -128 to 127.
short	       2 bytes	       Stores whole numbers from -32,768 to 32,767
int	       4 bytes	        Stores whole numbers from -2,147,483,648 to 2,147,483,647

long	       8 bytes	        Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

float	      4 bytes	        Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double	      8 bytes	       Stores fractional numbers. Sufficient for storing 15 decimal digits

boolean	       1 bit	               Stores true or false values

char	      2 bytes	         Stores a single character/letter or ASCII values.

**_Java Type Casting_**
Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

1.Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double

2.Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte


























5_.  boolean _-_** stores values with two states: true or false.