teleren/devto huggingface dataset:
Adding Swagger to ASP.NET Core Web API Project
Tags: net, webapi
Published: 2024-02-04 09:20:02

---
title: Adding Swagger to ASP.NET Core Web API Project
published: true
date: 2024-02-03 18:30:00 UTC
tags: NET,WebAPI,NET,WebAPI
canonical_url: http://www.codetolive.in//.net/web%20api/Adding-Swagger-to-ASP-NET-Core-Web-API-Project/
---

### 1. What is swagger?

Swagger is an open-source set of rules and specifications. It is used for API documentation and testing the API endpoints. Swagger UI generates documentation based on the Swagger specification and provides an interactive UI for testing APIs and experimenting with different parameters and options.

### 2. How to enable the swagger in .NET Core or .NET 7/8?

1. Go to the startup.cs file or program.cs file
2. Add the Swagger services under the ‘ConfigureServices’ method.
3. Add the following middleware under the ‘Configure’ method i.e, Swagger and Swagger UI.
4. Build and run the API.
5. Go to http://localhost:8080/swagger to view your API documentation from Swagger.

### 3. Adding swagger in ASP.NET Core WEB API Project

```
public void ConfigureServices(IServiceCollection services)
{
  // Swagger
  services.AddEndpointsApiExplorer();

  services.AddSwaggerGen(c =>
  {
      //c.SwaggerDoc("v1", new Info { Title = "API title", Version = "v1" });
      c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
      {
          Description = @"JWT Authorization header using the Bearer scheme.
            Enter 'Bearer' [space] and then your token in the text input below.
            Example: 'Bearer xyztokenabc'",
          Name = "Authorization",
          In = ParameterLocation.Header,
          Type = SecuritySchemeType.ApiKey,
          Scheme = "Bearer"
      });

      c.AddSecurityRequirement(new OpenApiSecurityRequirement() {
      {
        new OpenApiSecurityScheme
        {
          Reference = new OpenApiReference
          {
            Type = ReferenceType.SecurityScheme,
            Id = "Bearer"
          },
          Scheme = "oauth2",
          Name = "Bearer",
          In = ParameterLocation.Header
        },
        new List<string>()
      }
  });

}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI();
  }
  etc...
Format Time Ago Function - Time Differences in TypeScript
Tags: datetime, formatting, humanreadable
Published: 2024-02-03 18:23:00

---
title: Format Time Ago Function - Time Differences in TypeScript
published: true
description: This TypeScript function, `formatTimeAgo`, takes a Date object or string and formats the time difference between the input date and the current date in a human-readable format. It returns a string representing the time elapsed in years, months, days, hours, or minutes ago.
tags: #datetime #Formatting #HumanReadable
# cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cr7bsgo8ri8dx4iqetov.png
# published_at: 2024-02-03 18:10 +0000
---

# Function Explanation

The following TypeScript function, `formatTimeAgo`, is designed to format a given date or string into a human-readable "time ago" format. 
The function calculates the time difference between the provided date and the current date, presenting the result in terms of years, months, days, hours, minutes, or seconds.

```
export function formatTimeAgo(date: Date | string): string {

    // Initialize a default date as the current date
    let _date: Date = new Date();

    // Check if the input is a string and convert it to a Date object
    if (typeof date === "string") {
        _date = new Date(date)
    } else {
        _date = date
    }

    // Calculate the time difference in seconds
    const seconds: number = Math.floor((new Date().getTime() - _date.getTime()) / 1000);

    // Define intervals for different time units in seconds
    const intervals: Record<string, number> = {
        year: 31536000,
        month: 2628000,
        day: 86400,
        hour: 3600,
        minute: 60,
    };

    // Iterate through the intervals and determine the appropriate unit
    for (const [unit, secondsInUnit] of Object.entries(intervals)) {
        const interval: number = Math.floor(seconds / secondsInUnit);
        if (interval > 1) {
            return `${interval} ${unit}s ago`;
        } else if (interval === 1) {
            return `${interval} ${unit} ago`;
        }
    }

    // If no larger unit is found, return "just now"
    return "just now";
}
Getting Started with Helm Charts
Published: 2024-02-03 17:54:38

I happen to come across Helm Chart concept recently and It was very new to me. I had to go through lot of study materials to get basic .I would like to share the same here with you all . 

Helms helps a lot where the need of architecture includes multiple service (Backend ,Frontend ,database) where each layers are designed as independent entity.If Each service needs to be deployed in K8s cluster and to be accessed ,We may need following services.
For Frontend: 
1. a Deployment. 
2.  Replica sets/Replication Controllers
3. Config Map
5. A service (Nodeport ,ClusterIp ,LoadBalancer)

For Backend: 
1. a Deployment. 
2. Replica sets/Replication Controllers
3. Secrets
3. Config Map
5. A service (Nodeport ,ClusterIp ,LoadBalancer)

For DB:
1. a Deployment. 
2.  Replica sets/Replication Controllers
3. Secrets
4. Persistent Volume Claim(PVC) & PV
5. A service (Nodeport ,ClusterIp,LoadBalancer)


As you can see each layer uses different k8s services maintaining yaml file for each of them will be very tedious work . If we need to update new version/ modify something we have to test each of the services to make sure nothing of existing code breaks.
Helm chat comes with handy features to maintain and manage all of these service for us and all we do is to deal with Helm configurations for any kind of upgrades or modification. This is same as package manager like NPM,PIP or Maven.
apt commands fail (Connection timed out) in Debian based containers on Windows
Tags: docker, windows, debian
Published: 2024-02-03 19:22:40

---
title: apt commands fail (Connection timed out) in Debian based containers on Windows
published: true
cover_image: https://www.mcartoixa.me/assets/images/header-keyboard.jpg
date: 2024-02-03 17:23:00 UTC
tags: docker, windows, debian
canonical_url: https://www.mcartoixa.me/blog/software-craftsmanship/2024/02/03/apt-commands-fail-connection-timed-out-in-debian-based-containers-on-windows.html
---

The last few years have given me several opportunities to discover the Ruby language, and its ecosystem. I am very much a .NET guy, and I had wondered for a long time what the hype was all about. Now I can see how it inspired many modern platforms (like node.js or .NET ~~Core~~ ), but boy is the operations side of it hard! I am maintaining this very blog [on GitHub Pages](https://pages.github.com/), which is based [on Jekyll](https://jekyllrb.com/), and even a simple usage like this requires [a development container](https://containers.dev/). Especially as a Windows guy, although [managing Ruby dependencies on Linux is a mess](https://talk.jekyllrb.com/t/new-video-develop-jekyll-or-github-pages-using-docker-containers/7199) by itself.

Anyway, I am not creating those containers every day, but I have had a lot of trouble lately trying to create new ones, that happen to be based on Debian images (Buster and Bullseye), like [ruby:2.7.8](https://hub.docker.com/layers/library/ruby/2.7.8/images/sha256-f4420f957a9b4fae91a8d8c7fab8ba43e5a76bd640c87cb2b20ef669039e1319?context=explore) for instance. Part of the container creation involves running `apt-get update && apt-get upgrade` to have an image that is already up to date. These commands would invariably fail, preventing me (or VS Code for that matter) to create the container. The errors showed many `Connection timed out` while trying to fetch packages from _deb.debian.org_ or _security.debian.org_… And it happened with different Debian versions, on different (Windows) hosts.

Part of the debugging process was trying to reach mirrors of the Debian repositories, [using `netselect-apt`](https://manpages.debian.org/testing/netselect-apt/netselect-apt.1.en.html). But the same thing happened with the mirrors. And the first step of using `netselect-api` was installing it, by downloading the package directly with `wget` (can’t use `apt` there 😁), thus proving that the container had proper access to Internet…

Long story short, it seems that under my conditions (Debian running in a container in Docker Desktop on Windows using WSL), and for some reason, the connections established by `apt` are quite unstable. The trick was to configure `apt` so that it retries many times before giving up: I added `echo 'Acquire::Retries "100";' > /etc/apt/apt.conf.d/99custom` as the first command in all my `Dockerfile` descriptions.

That’s it. I can create brand new Debian based development containers again. 🥳
#1 Pure NodeJs: simple server (Part 1)
Tags: backend, node, tutorial, beginners
Published: 2024-02-03 17:20:02

In this tutorial you will learn how to create simple Node Js server with no packages at all just pure Node Js core modules.

programs and versions: 
nodejs: v18.19.0
npm:    v10.2.3
vscode: v1.85.2

should work on any nodejs > 14

### Now lets start:

I assume that you had node js installed on your device if not go to [nodejs](https://nodejs.org/en) and download and install LTS version (20.11.0 On the date of writing this article)

#### create server.js: 
first we need to create new file named server.js then copy this code:
```javascript 
const http = require('http');

const server = http.createServer((req, res) => {
  res.end('Hello World!');
});

const PORT = 2121;
server.listen(PORT, 'localhost', () => {
  console.log(`server run on port ${PORT}`);
});

```

first line we required "http" core module to create our node js server by use it in this code:

```javascript
http.createServer((req, res) => {
  res.end('Hello World!');
});
``` 
* "http.createServer" to create the server
* the callback function (req, res) => { ... } is called every time a request is made to the server.
* The "req" parameter represents the request object, and "res" represents the response object.
* "res.end" Ends the response by sending the specified string as the response body. In this case, it sends the string "Hello World!".

and to run the server we call "server.listen" with port 2121 

now to run and test the server just write this code in terminal:
```shell
node server.js
```
if everything is right you should see in terminal;
```shell
server run on port 2121
```
and to test the server open the browser and go to [localhost:2121](http://localhost:2121) and you will see "Hello World!" in the browser.

simple right :)

### Conclusion:
it's very easy and simple to create server with node js without any package but if you want to build big more complex application it will be better to use very common used packages like [Express.js](https://expressjs.com/) or [Koa.js](https://koajs.com/) (this packages i use)

But I will continue to write a few articles on how to build nodejs server in the next articles i will show you how to serve an html and Json data as response.
Build Chat PDF app in Python with LangChain, OpenAI, Streamlit | Full project | Learn Coding
Tags: langchain, python, openai, chatgpt
Published: 2024-02-03 17:16:34

In this tutorial, you’ll learn how to build a project by using Langchain and Streamlit to develop GUI-based ChatGPT for your PDF documents. We’ll create an application that enables you to ask questions about PDFs and receive accurate answers.

{% embed https://www.youtube.com/watch?v=WYzFzZg4YZI %}

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Link to the code: https://github.com/strongSoda/chat-with-pdf-tutorial

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Learn how to use OpenAI and the power of Langchain, an open-source Python (and Javascript) framework, to create intelligent applications. In this tutorial, I’ll guide you through building a fully functional Streamlit application. Train GPT on PDF documents. You can upload PDFs, ask questions, and receive prompt answers from the LLM. Take your natural language processing skills to the next level. Start building powerful applications with Langchain today! 
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

## About Me

I’m a Senior Product Engineer from India, working in web and mobile development. I enjoy turning complex problems into simple, beautiful, and intuitive software. I blog to share my software knowledge with others.

My job is to build your idea so that it is functional and user-friendly but at the same time attractive. Moreover, I add a personal touch to your product and make sure that is eye-catching and easy to use. I aim to help you validate and scale your startup most creatively.

### Quick Links
- [Hire Me](https://imran.wiki/)
- [Coding YouTube Channel](https://www.youtube.com/@JutsuPoint)
- [LinkedIn](https://www.linkedin.com/in/imrankhan001/)
- [Twitter](https://twitter.com/EhThing)
- [🎁 Screen Recording Software](https://screen.studio/@Xenr1)
에볼루션카지노 라이브
Tags: webdev, javascript, 에볼루션카지노, beginners
Published: 2024-02-03 16:43:06

[에볼루션카지노](https://joinevolutioncasino.wixsite.com/eolutiontypesgame/post/evolutioncasino-live).플러스카지노.스페이스맨카지노.프리카지노.로즈카지노.샌즈카지노.더킹플러스카지노Evolution Casino. Spaceman Casino. Plus Casino. Free Casino. Rose Casino. Sands Casino.
Mini site for recommending songs using Svelte & Deno
Tags: webdev, javascript, svelte, showdev
Published: 2024-02-03 16:31:29

Introducing a new way to recommend a song to your friends: [listn.fyi](https://listn.fyi/)! Simply create a public Spotify playlist and name it **"listn.fyi"** (without quotes) then head to the URL for your Spotify username (e.g. [listn.fyi/combatfetus](https://listn.fyi/combatfetus)). Et voilà! The link is shareable and any changes to your playlist will reflect immediately on the website.

I figure this could be a fun and easy way to share what you're currently into and see what others are recommending as well. Maybe a cheeky addition to a Twitter bio, etc.

Behind the scenes is a simple [Sveltekit](https://kit.svelte.dev/)-powered server function to fetch a Spotify client token then find a user's recommendation playlist and its track information. A [Deno](https://deno.com/) edge function to performs this data fetch and renders server-side Svelte.

And shoutout to Rob for the beautiful [CSS record player](https://codepen.io/robrehrig/pen/AooLxK), which I borrowed (with credits) and made some modifications to. Long live skeuomorphism!

I must admit, the Sveltekit developer experience in 2024 is a lot nicer to work with than what I'm used to in the React/Vue/Next world. The filesystem-based router seemed like it would be a pain but was pleasantly surprised by how simple and clean it is to actually use. Looking forward to using it more for projects like this.

Check out the source below & let me know what you think!

{% github brycedorn/lstnto no-readme %}
How Do You Declare Custom Classes in a Tailwindcss-React-ts project?
Tags: tailwindcss, react, typescript, css
Published: 2024-02-03 16:27:23

Hey fellow developers,

So, picture this: knee-deep in my project, I hit the classic developer's roadblock - the need for custom classes. Here's my journey, a tale of trials and triumphs that might just save you some precious coding time!

## The Dilemma of Custom CSS in Tailwind
In the vast tapestry of React Tailwind projects, customizing styles can feel like a puzzle. I explored three paths, each with its quirks and perks. Let's dive in!

##1. Wrangling Tailwind Classes in a Variable!
First up, I tried corralling those repetitive Tailwind classes into a variable tucked away in a cozy `.ts` file. Everything seemed peachy until the day I wanted a little flair, a touch of customization. Spoiler alert: couldn't pull it off. My dreams of a unique twist were dashed. It's like committing to a tattoo; changing your mind becomes a tad complicated.

##2. Global Stylesheet Declaration
Moving on, I experimented with declaring a class in a global stylesheet. A good practice, you'd think. Worked like a charm, until I craved more control. Trying to finesse the styles proved trickier than juggling flaming torches. Need a smaller font? Tough luck! And let's not even start on the exclamation marks – felt like I was in a shouting match with my styles. Ugh!

##3. The @layer Revelation in `index.css`!

And here comes the star of the show—the class declared as a component layer. This, my friends, is the holy grail. Why? Because it behaves like any default Tailwind CSS class, and you can customize it without breaking a sweat.

![code snap- an example of using @layer for custom class](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v6p53qy0ywb2xtpjbbo2.png)

##The Unmatched Prowess of Component Layer Classes
Why do I vouch for the third approach? Brace yourself for the pros:

- **Seamless Overrides:** No more banging your head against the wall with `!important`. The component layer class gracefully accepts overrides like a seasoned actor playing multiple roles.

- **Scoped and Neat:** Your styles remain scoped within the component, keeping your project neat and tidy. No more global chaos!

- **Dynamic Customization:** Embrace dynamic styles effortlessly. This approach opens the door to a world where your styles adapt and evolve based on dynamic content.

- **Integrates Like a Charm:** Remember, it's Tailwind CSS. Your custom class integrates seamlessly, like it was always meant to be there.

So, fellow coders, spill the beans! How do you deck out your project with custom CSS? Let's swap war stories and share the coding wisdom. 

*Hint: Feel free to sprinkle in some more details if your secret sauce involves extra flair!
Cloudflare Pages NextJs + D1 Database ᐧ My experience developing sharejson
Tags: nextjs, webdev, development
Published: 2024-02-03 16:22:22

The biggest challenge I encountered during Next.js development was the lack of hot reloading when using a D1 database locally. We have to use `experimental-edge` when using `getServerSideProps`.

> Development is time consuming! `npm run dev` will not give D1 database bindings

I have to rebuild the entire project every time I make a change, even a minor one. This can be very time-consuming.

I managed to complete [sharejson.com](https://sharejson.com) because it's a single-page application with only one table. However, for larger projects with more tables, I wouldn't recommend using D1 due to the significant development time required. It simply doesn't feel efficient in these scenarios.

Test your Next.js application with hot reload while mocking database responses and test the database logic later to make development easier.

## Setting up Nextjs Pages & D1 Database 

```bash
npm create cloudflare@latest my-next-app -- --framework=next
```
Creates a new Next.js project with pages setup. Once we have the wrangler cli , we can directly deploy app.

We have to change the `env.d.ts` for bindings.
```ts
declare global {
  namespace NodeJS {
    interface ProcessEnv {
      [key: string]: string | undefined;
      DATABASE: D1Database;
    }
  }
}
export { };
```

After signing up with Cloudflare, you can create a database on their platform and access environment variables. Add `wrangler.toml` file with D1 details. 
```
[[d1_databases]]
binding = "DATABASE"
database_name = "db"
database_id = "database-id-from-website"
```
I've isolated database operations in the `src/server` folder. However, the `db` variable remains `undefined` during `npm run dev` as hot reloading isn't supported. For database access, use `npm run pages:dev`, but be aware that this disables hot reloading.

```ts
const db = process.env.DATABASE

export const selectFromJsons = async (id: string) => {
  const stmt = db.prepare(`select * from jsons where id = ?1`).bind(id)
  const results = await stmt.first()
  return results
}
```

Overall, using D1 and Pages has been a positive experience, as it currently runs everything for free.

---
شركة نقل عفش
Published: 2024-02-03 16:20:55

شركة [نقل عفش](https://malekclean.com/%D9%86%D9%82%D9%84-%D8%B9%D9%81%D8%B4-%D8%A7%D9%84%D9%83%D9%88%D9%8A%D8%AA/) الكويت لها مزايا عديدة تنقل شركة نقل عفش بالكويت لك عفشك بأقل سعر وبسرعة عالية مستخدمين في ذلك أحدث شاحنات النقل لأي منطقة تريدها مع المحافظة عليه سليم دون ضياع أي قطعة أو جزء منه نتميز بالمصداقية في الحفاظ على مقتنيات العميل. نستعين بأوناش قوية في العمل لكي ننقل بها الأثاث عبر المصاعد والنوافذ بفضل أيدي عاملة ماهرة تقوم على نقله وتركيبه
Brainstorming Trending API Projects: Let's Build Something Awesome!
Tags: webdev, python, api
Published: 2024-02-03 16:18:26

Hey developers, 

I'm itching to dive into a new API project, but I'm struggling to find that perfect spark. What about you? Are you on the hunt for an inspiring API idea that taps into current trends and solves a real problem?

Instead of going solo, I thought it would be awesome to **collaboratively brainstorm** and get feedback on potential projects. So, let's leverage the power of the dev.to community and share our thoughts!

**Here are some trending API areas to get us started:**

* **AI/ML Integration:** APIs that utilize AI for tasks like sentiment analysis, image recognition, or text generation are exploding. Could we build something that simplifies access to these powerful tools?
* **IoT and Edge Computing:** Connecting devices and processing data at the edge is the future. Could we create an API that streamlines data collection and analysis for IoT projects?
* **Blockchain and Web3:** The decentralized revolution is here! Could we build an API that makes interacting with blockchain networks and dApps easier for developers?
* **Sustainability and Climate Action:** APIs that support environmental initiatives, like carbon footprint tracking or renewable energy data, are gaining traction. Could we contribute to a greener future through code?
* **Accessibility and Inclusivity:** APIs that promote accessibility and cater to diverse user needs are becoming increasingly important. Could we build something that makes technology more inclusive for everyone?

**Beyond these trends, feel free to share your own ideas!** What problem do you see in the developer community that an API could solve? What exciting possibilities are you passionate about exploring?

**Let's discuss:**

* **Specific project ideas:** Share your detailed concepts, no matter how early-stage they are!
* **Technical feasibility:** What technologies would you use? Are there any potential challenges?
* **Community interest:** Would other developers find this project useful and engaging?
* **Collaboration opportunities:** Are you open to teaming up on a project? Let's find our perfect match!

Remember, there are no bad ideas in this brainstorming session. Let's throw everything out there and see what sparks fly! 

I can't wait to see what awesome API projects we can come up with together. Let's get creative and build something amazing!

**P.S.** Don't forget to upvote and share this post to get more developers involved!

**#APIprojects #devto #brainstorming #collaboration #trendingtech**