teleren/devto huggingface dataset:
[Go] Generate File Tree
Tags: go
Published: 2023-09-24 17:18:16

[Go] Generate File Tree

## Intro
This time, I try getting files and sub directories from the root directory.


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

I also can use "filepath.Walk" to get directories and files.
But it returns paths like below.

```
/home/example/go/pkg/mod/cache/download/golang.org/x/xerrors
```

Because I don't want to reproduce the folder structure myself, I will use "os.ReadDir".

## Samples
#### FileProps.go
```go
package main

type FileProps struct {
	Name         string
	RelativePath string
	IsDir        bool
	Children     []FileProps
}
```

#### main.go
```go
package main

import (
	"encoding/json"
	"log"
	"os"
	"path/filepath"
)

func main() {
	readDirResult, err := readDir("/home/example/go")
	if err != nil {
		log.Fatal(err.Error())
	}
	readDirResultData, _ := json.Marshal(readDirResult)

	file, _ := os.Create("readdirresult.json")
	file.Write(readDirResultData)
	file.Close()
}

func readDir(rootDir string) (FileProps, error) {
	result := FileProps{
		Name:         rootDir,
		RelativePath: "[ROOT_DIR]",
		IsDir:        true,
	}
	err := addChildPropsByReadDir(rootDir, result.RelativePath, &result)
	return result, err
}
func addChildPropsByReadDir(baseDir string, relativeDir string, parent *FileProps) error {
	files, err := os.ReadDir(baseDir)
	if err != nil {
		return err
	}
	parent.Children = make([]FileProps, len(files))
	for i, f := range files {

		parent.Children[i].Name = f.Name()
		if f.IsDir() {
			parent.Children[i].IsDir = true
			parent.Children[i].RelativePath = filepath.Join(relativeDir, parent.Children[i].Name)
			addChildPropsByReadDir(filepath.Join(baseDir, parent.Children[i].Name), parent.Children[i].RelativePath, &parent.Children[i])
		} else {
			parent.Children[i].IsDir = false
			parent.Children[i].RelativePath = relativeDir
		}
	}
	return nil
}
```

* [os package - os - Go Packages](https://pkg.go.dev/os)
* [filepath package - path/filepath - Go Packages](https://pkg.go.dev/path/filepath)
Kubernetes CKA Exam Question Bank .. 17 Questions with Complete Lab .. In 3 hours .. FREE!
Tags: kubernetes, cka, ckad, aws
Published: 2023-09-24 16:27:48


![Kubernetes CKA](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fp9vsoh6lme1ffk7dxzs.jpg)

Hello friends, 

let me share my journey with you in a way that's both relatable and exciting. It's a story about my experience preparing for the Certified Kubernetes Administrator (CKA) exam and how it led to something amazing.

Picture this: I was gearing up for the CKA exam, eager to conquer it. The only problem was, I had no clue about the type of questions that would pop up in the test. To make things challenging, there was hardly any content available on YouTube back in those days that could guide me. Frustrating, right?

So, I made a bold decision. I decided to bridge this gap myself. I thought, "Why not create a course that provides questions similar to those asked in the CKA exam, along with step-by-step lab sections to tackle them?" That way, aspiring CKA candidates could not only understand the problems but also learn how to solve them effortlessly.

As time rolled on, something incredible happened. People from all corners of the world started appreciating my efforts. They began clearing the CKA certification, all thanks to my "CKA Challenge Question Labs" course. You see, the CKA exam isn't a walk in the park, and my course wasn't just about questions. It was about boosting confidence.

I didn't stop there, though. I kept adding more and more questions to the course, and my YouTube subscribers grew by the day. People were tagging me on LinkedIn, celebrating their certification victories. Over a thousand of them! But here's the kicker – my reach was still somewhat limited.
 
That's when I had a vision. I needed to take my mission to the next level. So, I decided to transform my course into something bigger and better on Udemy. I put together a comprehensive CKA practice set course, and guess what? Friends from all over the world showed a keen interest and enrolled in the course.

But wait, there's more. I wanted to make sure that everyone had access to these valuable resources. So, I did something special. I distributed some of my courses for free and even hosted exciting giveaways. Of course, there were paid options too, for those who wanted to dive deeper.

In this video series, I cover a massive 17 challenging CKA exam questions. Each question is accompanied by a lab section right next to it, and they come in varying difficulty levels, all neatly packaged into one video. It's a breeze to watch and prepare for the exam.

Now, here's the deal: If you appreciate my dedication and want to tackle more of these challenging questions, I invite you to enroll in my Udemy course. I'm constantly adding fresh content, so you'll stay connected with me and continue to supercharge your CKA exam preparation.

Join me on this journey, and let's conquer the CKA exam together!

[Kubernetes CKA Exam Question Bank](https://youtu.be/udA3OWkmMUY)

[Full Course On Udemy](https://www.udemy.com/course/certified-kubernetes-administrator-cka-lab-course/?couponCode=CRACK-IT)
From Restaurant to Devops Introduction
Tags: devops, kubernetes, docker, development
Published: 2023-09-24 16:04:05

Devops can be explained as a simple break down development and Devops is not a job or a skill it is a cultural change which is opted by different company. Hence it is important to learn devops to increase productivity and efficiency of any company.

Let’s us understand it with a simple example of a Restaurant. Let us imagine the chef of a restaurant as development unit and the waiters as a operation unit. Now, if we don’t synchronise them both the whole working of a restaurant will be disturbed let us understand this.

Now if a customer came into restaurant and orders two burger and now the operation unit i.e waiter in our case takes the order and bring that order to development team i.e chef in our case which will make burger and give it to the waiter which will give it to the customer.

Now the waiter doesn’t know the recipe of making burger which can be related as developer’s code and chef doesn’t know to whom he’s making burger for and on which table he have to give the burger but still they both are connected in some way which will help the burger to reach from the chef to the right person.

Hence this whole procedure of the coordination of waiter (operation unit) and chef (development team) without actually knowing their work is known as DEVOPS.

Devops can be break down into three terms:

Methods

Tools

Cultural change

In all three people generally people focuses on methods and tools but the most important part is cultural change which should be opted in all companies after that they should focus on methods and tools.
What is YAML?
Tags: yaml, devops, programming
Published: 2023-09-24 16:03:39

- YAML is a data serialization language for storing information in a human-readable form.
- YAML stands for "YAML Ain't Markup Language."
- YAML is not a Markup Language.
- YAML is used to store complex data in a compact and readable format.
- YAML was originally designed as a configuration language but is now used in various applications.
- We can use YAML  to define key and value pairs like variables, lists and objects
- YAML is very similar to JSON (Javascript Object Notation) and XML (Extensible Markup Language)
- YAML primarily focuses on readability and user-friendliness.
- YAML is designed to be clean and easy to read.
- We can define YAML files with two different extensions.
- .yml
- .yaml
Step by Step instruction hosting on aks cluster for begineers
Tags: azuredevops, devops, dotnetcore, cicd
Published: 2023-09-24 15:47:17


Creating a web application on an Azure Kubernetes Service (AKS) cluster using Azure DevOps involves several steps, including defining your application, setting up Azure DevOps pipelines, and deploying your application to the AKS cluster. Here's a high-level overview of the process:

Pre-requisites:

Azure DevOps: Make sure you have an Azure DevOps organization and project set up.
Azure AKS Cluster: Create an AKS cluster in Azure if you haven't already.

Create Your Web Application:

Develop your web application code and containerize it using Docker. Ensure you have a Dockerfile that describes how to build your application into a container image.
Store your application code in a source code repository, such as Azure Repos or GitHub.
**Set up Azure DevOps Pipeline:**

In your Azure DevOps project, create a new pipeline to automate the CI/CD process for your web application.
Configure Build Pipeline:

Configure a build pipeline to build the Docker container image of your web application from the source code.
Use Azure DevOps tasks or scripts to build and push the Docker image to a container registry (e.g., Azure Container Registry, Docker Hub, or others).
**Configure Release Pipeline:**

Create a release pipeline to deploy your application to the AKS cluster.
Define the deployment stages, environments, and deployment triggers as needed.
**Deployment to AKS:**

Use Kubernetes manifests (YAML files) to describe your application deployment, services, and other resources.
Configure your release pipeline to apply these manifests to the AKS cluster using kubectl or Azure DevOps tasks designed for AKS.

Step by step 
https://github.com/jaganrajagopal/Jenkinswithdockercomposeup/tree/master#jenkinswithdockercomposeup

https://user-images.githubusercontent.com/8061469/270113719-aea14701-d419-4988-900c-633b43f61e0b.png
Use Common Table Expressions (CTEs) for Complex Queries
Tags: sql, programming, tutorial
Published: 2023-09-24 15:30:00

Common Table Expressions (CTEs) are an SQL feature that allows you to create temporary result sets within your query. They can make your SQL code more readable and maintainable, especially when dealing with complex queries. Here's how you can use CTEs:

- **Define a CTE:** To create a CTE, use the `WITH` keyword followed by a subquery enclosed in parentheses. Give the subquery a name and specify the columns it returns.

   ```sql
   WITH cte_name (column1, column2, ...) AS (
       -- Subquery here
   )
   ```

- **Reference the CTE:** After defining the CTE, you can reference it in the main query as if it were a regular table.

   ```sql
   SELECT *
   FROM cte_name;
   ```

Here are some benefits and use cases for CTEs:

- **Readability:** CTEs make your SQL code more readable by breaking down complex logic into smaller, named, and self-contained units.

- **Code Reuse:** You can reuse CTEs within the same query or in multiple queries, reducing redundancy and promoting consistency.

- **Simplifying Subqueries:** CTEs are particularly useful for simplifying subqueries and recursive queries, making them easier to understand.

Example: Suppose you want to find the employees who have been with the company for more than five years and earn more than a certain threshold. You can use a CTE to calculate their years of service and then filter the results:

```sql
WITH employee_years_of_service AS (
    SELECT
        employee_id,
        first_name,
        last_name,
        hire_date,
        EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM hire_date) AS years_of_service
    FROM employees
)
SELECT
    first_name,
    last_name,
    years_of_service
FROM employee_years_of_service
WHERE years_of_service > 5
AND salary > 50000;
```

By using a CTE, you break down the logic into two distinct parts: calculating years of service and then filtering based on that calculation. This makes the query easier to understand and maintain.

CTEs are a valuable tool for SQL developers, and they can help you write more efficient and maintainable SQL queries, especially when dealing with complex data manipulations or multiple levels of subqueries.
My Reflections on Andela’s EPIC Values.
Published: 2023-09-24 14:43:46


## **My Reflections on Andela’s EPIC Values**.

EPIC! an acronym for Excellence, Passion, Integrity, and Collaboration. Is obvious that the secret behind Andelans success is their ability to uphold these four values. Let’s go through it bit by bit.

**The ‘E’ in EPIC stands for excellence**

I have always believed that one has attended excellence when he stands out in a competition. This has left me with the mindset that even if the winner didn’t perform so great, as long as he/she emerged highest, that makes the person an excellent individual.
But from Andela point of view, excellence means when what is to be done is executed to it’s very best. Even if you are the only one doing it, it is expected that the best outcome is delivered. And the quality should not be location relative but should retain the same worth where ever is presented.

**The ‘P’ in EPIC stands for Passion**

![The top view is nice](https://cdn-images-1.medium.com/max/3000/1*6tHQXNrGWo2UT4e-u1pUbA.jpeg)

Most times people only have passion for what they can do with ease. They believe that they can’t be successful with anything that gives them trouble to achieve. But here in Andela, is completely different. Andela believes that everyone can make a difference when given the opportunity. Every Andelan is always eager to learn or teach. The long for new knowledge and never shy away from challenges. Here, challenge already got a new name “Blocker” and everyone spend time unblocking and looking for more blockers.
I have come to understand that true satisfaction comes when you decide to add more value to what you already know and discover more of what you can learn.

**The ‘I’ in EPIC stands for Integrity**

Integrity here at Andela is the most upheld value amongst the four values of the EPIC acronym. Andela starts from the first stage of application to advise applicants on the importance of being yourself. They even have an acronym “YOYO” meaning you own your own. Andela believes that you should learn from people not imitate them. Andela insists that you live your own life not someone else life. They frown at plagiarism so much that they can even lay-off their best staff if they should be a victim of plagiarism.

**The ‘C’ in EPIC stands for Collaboration**

![](https://cdn-images-1.medium.com/max/2400/1*BBWTW74PSTKU9Wp7UgsObg.jpeg)

I use to think that a programmer should always be indoor writing code and debugging. I also believed that when you encounter a blocker, You should remain on your own until you are able to figure it out. I also believed that what makes a programmer great is his ability to write codes only he can understand.
But Andela thinks different. Andela believes that no man is an Island of knowledge. Every person’s opinion should be put into considerations. That’s why in Andela eventually everything is grouped into teams. Andela has an uncountable number of resources online and many learning platform eg: Andela learning community (ALC). They believe that nobody is too big to need help.
And that we can attain excellence easier when we work as a team.
PSRule.Rules.AzureDevOps 0.0.11 Released
Tags: devops, azure, automation, opensource
Published: 2023-09-24 14:32:06

Version 0.0.11 of PSRule.Rules.AzureDevOps has just been released in the PowerShell Gallery. It boasts support for some of the latest new features in Azure DevOps. With this module for checking configuration best practices on your Azure DevOps project, you can now also check your service connections for use of the new Workload Identity Federation feature. You can also confirm you have the best repository security enabled through the new GitHub Advanced Security feature on Azure DevOps. 

Check out the source code and install instructions on [GitHub](https://github.com/cloudyspells/PSRule.Rules.AzureDevOps) or checkout the module in the [PowerShell Gallery](https://www.powershellgallery.com/packages/PSRule.Rules.AzureDevOps/)
Day 2 Function Basic in js
Published: 2023-09-24 14:30:44

## Basic of Function in js

```
function hello()
{
  console.log("hello")
}

hello()
```

With parameters

```
function hello(name,message)
{
  console.log(`hello ${name} ${message}`)
}

hello("Dev","Welcome")
```

With return
If we want the function to return the procesed value **return** is used
A function can contain only one return 

```
function hello(name,message)
{
  return `hello ${name} ${message}`
}

console.log(hello("Dev","Welcome"))
```

With Arrow Function (ES6)

```
const hello = () => {
return  `hello ${name} ${message}`
}

console.log(hello("Dev","Welcome"))
```
How to use the --haproxy-protocol option in Guzzle library?
Tags: php, programming, tutorial
Published: 2023-09-24 14:25:33

I needed the [--haproxy-protocol](https://github.com/curl/curl/commit/6baeb6df35d24740c55239f24b5fc4ce86f375a5) option from the `curl` library to call the request. Within curl this option works great. But how to achieve the same in the PHP library Guzzle?

First, we needed to verify that the option exists in the library itself. As of PHP version 7.3, there is a constant [CURLOPT_HAPROXYPROTOCOL](https://www.php.net/manual/en/function.curl-setopt.php) that does the same thing. The call then looks like this:

```php
$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_HAPROXYPROTOCOL, true);
// ...
```

The second question was how to use this option within the Guzzle library. While [documentation](https://docs.guzzlephp.org/en/stable/request-options.html) does not describe the option, it is possible to set the `curl` configuration. The library deliberately does not show this setting [because it breaks](https://github.com/guzzle/guzzle/pull/3160) the abstraction that Guzzle provides.

The whole call then looks like this
```php
$client->request('GET', $url, [
    'curl' => [CURLOPT_HAPROXYPROTOCOL => true],
]);
```

Other options can be added to the `curl` field, as described in the PHP documentation for the [curl_setopt](https://www.php.net/manual/en/function.curl-setopt.php) function.
A tool for detecting plagiarism of Github repositories in someone else's code
Tags: go, github, opensource, hiring
Published: 2023-09-24 14:22:25

I built this tool out of annoyance.

Someone submitted an assignment that looked too well-done for the amount of time given.

My suspicion made me CSI into Github.

Unfortunately for him, it led me to finding the repositories he cloned.

I was annoyed that he cloned a repository for my technical assignment, and vowed to not let this happen to me again.

I decided to build a tool to automate this process, for my own sake, and hopefully for other hiring managers out there.

https://github.com/ongteckwu/hercules

Sample output:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xclf050et1ekufdrkweu.png)
Resolving Parallel Branches
Tags: opensource, typescript, programming, beginners
Published: 2023-09-24 14:22:05

While working on the new feature set for my markdown converter application [TILvert](https://github.com/omalk98/TILvert), I started by refactoring the original mechanism I had in place for file processing. The reason I decided to refactor the procedure was to make it much easier for myself to update to the applications features without much of a hassle or trying to jump around code in strange locations.

## The Refactor

The major changes that happened to the codebase were mostly structural and procedural changes. Previously, the application would process the files in a slightly complicated manner (honestly it was just spaghetti code) and required a decent amount of work to get it to be more generic and easily maintainable. 
I made use of the strategy pattern from software design patterns. I implemented a file processor class which can be assigned a file processing strategy. Each strategy handles the file according to the coded procedure for that file, this can be changed by either supplying a different type of input file which the application will automatically attempt to detect the type of file. Or by changing the extension options to `md` or `txt` to switch between the 2 processing strategies.

## The New Features

After creating 2 issues in my repository to update the new features I wanted add to the code; [Adding Italic tag support](https://github.com/omalk98/TILvert/issues/9) and [Adding Bold tag support](https://github.com/omalk98/TILvert/issues/10), I began creating new branches for each of the features. 
While creating the branches, I branched twice off the main branch and began to work separately on each feature in their respective branch. Once the features were completed, I merged the [Italic tag commit](https://github.com/omalk98/TILvert/commit/ef0bb68d40bd257020ab4f292e6240758277b5d5) without any issues. However, when it came time to merge the [Bold tag commit](https://github.com/omalk98/TILvert/commit/9005b6abc9bb83b92cd7bee0edccaa9c8f170820), that resulted in a merge conflict (very common on large applications but rather rare when working alone on a particular branch) this to me was somewhat of a surprise as I expected it to not have any conflicts at all. 
I realized later on that the content of the code that has updated rarely matter to git, but it does care about which lines you edited within a given context, giving the illusion that git is able to differentiate between different functions. This was an interesting discovery for myself and will definitely help me avoid future conflicts and be more aware of what I code and where.

## Other Features

Since the refactoring of the code into multiple file processing strategies made it so much easier to maintain and update the code, I also decided to implement a few extra features into the markdown processor. The processor now also supports **Code Blocks** and **Inline Code Blocks** as well as **horizontal rules**, and customizable **language** support for the HTML document.
How Understanding Falsy Values Can Improve Your Javascript Code Readability
Tags: javascript, react, webdev, beginners
Published: 2023-09-24 14:13:27

In JavaScript, falsy values are values that are considered "false" when encountered in a boolean context.

Understanding the use of falsy values can help you reduce boolean checks in your code. The number 0 (including -0), null, undefined, false, NaN, and an empty string ("") are considered falsy values in JavaScript.

This is the only theory that needs to be known. Now, let's explore how to apply this concept in real-life examples. I will provide some real-life examples.

Suppose we have an array of users:

```js
const users = [
  {
    name: "Kushal",
    marks: 99
  },
  { name: "" },
  {
    name: "John"
  },
  { name: null, marks: 87 },
  { marks: 34 },
  {
    name: "Bob",
    marks: 0
  }
];
```

### Requirement 1
Print users whose name has at least 1 character.

The normal way to achieve this is:

```js 
for (let i = 0; i < users.length; i++) {
  if (
    users[i].name !== undefined &&
    users[i].name !== null &&
    users[i].name !== ""
  ) {
    console.log("User name is", users[i].name);
  }
}

```
However, using falsy values, you can simplify the code like this:

```js
for (let i = 0; i < users.length; i++) {
  if (users[i].name) {
    console.log("User name is", users[i].name);
  }
}
```
In this case, if the name comes from any of the falsy values like undefined, null, an empty string, or others, it will be considered false in the if block.

### Requirement 2
Print the user name if it exists; otherwise, print "N/A".

The normal way to achieve this is:

```js
for (let i = 0; i < users.length; i++) {
  if (
    users[i].name !== undefined &&
    users[i].name !== null &&
    users[i].name !== ""
  ) {
    console.log("User name is", users[i].name);
  } else {
    console.log("User name is N/A");
  }
}
```

Using falsy values, you can simplify the code like this:

```js
for (let i = 0; i < users.length; i++) {
  console.log("User name is", users[i].name || "N/A");
}
```

Hope you like the article, if you please consider to like and comment. 

And  you are on Twitter can you follow me there as well, I keep posted these kinds of stuff there as well => <a href="https://twitter.com/kushal_js?ref_src=twsrc%5Etfw" class="twitter-follow-button" data-size="large" data-show-count="false">Follow @kushal_js</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

 {% twitter 1704335992231244016 %}