teleren/devto huggingface dataset:
Using data transfer object as the model in MVC
Tags: webdev, programming, aspdotnet, asp
Published: 2023-07-05 19:01:28

In the Model-View-Controller (MVC) pattern, a Data Transfer Object (DTO) is a useful concept for transferring data between different components of the application. It is often used to encapsulate data and pass it between the Model, View, and Controller.

Let's assume you have a Model named "Mudassar" representing a person's information. To use a DTO in this scenario, you can create a separate class to represent the data transfer object. Here's an example:

```csharp
public class MudassarDTO
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
    // Additional properties can be added as per your requirements
}
```

In this example, the `MudassarDTO` class is a simple DTO that contains properties for name, age, and email.

Now, in your MVC application, you can use this DTO to transfer data between different components. For instance, in the Controller, you might have an action method that retrieves the data from the Model and transfers it to the View using the DTO:

```csharp
public class MudassarController : Controller
{
    public ActionResult Details()
    {
        // Assuming you have a Mudassar model object with data
        Mudassar mudassarModel = GetMudassarFromDatabase();

        // Creating a DTO and mapping the data from the model
        MudassarDTO mudassarDTO = new MudassarDTO
        {
            Name = mudassarModel.Name,
            Age = mudassarModel.Age,
            Email = mudassarModel.Email
        };

        return View(mudassarDTO);
    }

    // Other controller actions
}
```

In the above example, the `Details` action method retrieves the data from the Model (assuming you have a method `GetMudassarFromDatabase` that fetches the Mudassar model from the database). It then creates a `MudassarDTO` object, maps the relevant data from the model to the DTO, and passes the DTO object to the View.

Finally, in the corresponding View, you can access the properties of the DTO to display the data:

```csharp
@model MudassarDTO

<h1>Mudassar Details</h1>

<p>Name: @Model.Name</p>
<p>Age: @Model.Age</p>
<p>Email: @Model.Email</p>
```

In the above View, `@Model` represents the `MudassarDTO` object, and you can access its properties (`Name`, `Age`, and `Email`) to display the details.

This example demonstrates how you can use a DTO to transfer data between the Model, Controller, and View in an MVC application.
Deleting database records using post request in mvc
Tags: webdev, beginners, programming, opensource
Published: 2023-07-05 18:49:47

In MVC (Model-View-Controller) architecture, the recommended approach for deleting database records is to use the HTTP DELETE method rather than the POST method. Here's an example of how you can delete a database record using a DELETE request in an MVC application:

1. Define a route: In your application's route configuration, define a route that maps to the appropriate controller action for deleting a record. For example:
   ```
   DELETE /records/{id}  => RecordsController.Delete(id)
   ```

2. Create a controller action: In your `RecordsController`, create a `Delete` action method that handles the DELETE request and deletes the record based on the provided `id`. The specific implementation may vary depending on the technology you are using, but here's a generic example in C#:
   ```csharp
   [HttpDelete]
   public ActionResult Delete(int id)
   {
       // Logic to delete the record from the database using the provided ID
       // ...

       // Return an appropriate response, such as a success message or a redirect
       // ...
   }
   ```

3. Invoke the DELETE request: To delete a record, you can invoke a DELETE request from your client-side code or any tool that can send HTTP requests, such as cURL or Postman. Make sure to include the record's ID in the URL. For example:
   ```
   DELETE /records/123
   ```

By following this approach, you align with the HTTP method semantics and RESTful principles, making your code more maintainable, predictable, and consistent with standard conventions.
Why deleting database records using get request is bad
Tags: webdev, programming, aspdotnet, aspnet
Published: 2023-07-05 18:48:45

Deleting database records using a GET request is considered bad practice for several reasons:

1. Semantics: According to the HTTP protocol, GET requests are intended for retrieving data, while DELETE requests are meant for deleting data. Using a GET request to delete records violates the intended semantics of the HTTP methods, leading to confusion and potential misinterpretation by other developers or systems interacting with your API.

2. Idempotence: One of the key principles of RESTful APIs is the concept of idempotence. A method is considered idempotent if making multiple identical requests has the same effect as making a single request. GET requests are generally expected to be idempotent because they should only retrieve data without causing any changes. In contrast, DELETE requests are inherently non-idempotent as they result in the permanent removal of a resource. Therefore, using GET to delete records violates this principle.

3. Caching: GET requests are often cached by browsers, proxies, and other intermediate systems. Caching is beneficial for performance and reducing server load, but it can have unintended consequences when applied to deletion operations. If a GET request that deletes a record is cached, subsequent requests to the same URL may inadvertently trigger deletion actions, leading to data loss or corruption.

4. Security: GET requests typically include parameters or data in the URL itself, making it more vulnerable to security risks such as exposure of sensitive information through server logs, browser history, or network monitoring. When deleting records, it's generally advisable to use methods that allow data to be sent in the request body, such as DELETE requests, which can be handled more securely.

To adhere to best practices, it is recommended to use the appropriate HTTP methods for their intended purposes. For deleting database records, the DELETE method should be used.
helix-editor gold mine ⛏️
Tags: hx, neovim, nvim
Published: 2023-07-05 18:42:54

---
title: helix-editor gold mine ⛏️
published: true
description: discussion
tags: discussion, hx, neovim, nvim
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-07-05 18:41 +0000
---

> Helix the DNA of your code vs. NeoJail aka NeoVim

What a rhyme, the hell dog! ... 

tl;dr: https://helix-editor.com

Do not forget your Ctrl+Z this is the one of the most common ancestors in shell use cases. The shell almost always reflect the underlying system and in this case if you use bash, zsh, ash or even sh, then take your time and imagine yourself a few years ago. A while ago. The time for no graphics. Only text processors. You still find
- events (or signals) and the underlying syscalls
- jobs (or processes) and the underlying multi user kernel

If you prefer GoLand, VSCode etc. You're also welcome!

Bests to you,

Malik

tl;dr An editor meant to be closed
software engineer interview questions specifically data structure
Tags: datastructures, interview, programming, tutorial
Published: 2023-07-05 18:29:43

1.  Explain the concept of time complexity and space complexity. How do they relate to data structures?

2. What is the difference between an array and a linked list? In which scenarios would you prefer one over the other?

3. Describe the process of reversing a linked list. What is the time complexity of your approach?

4. How would you check if a given linked list contains a cycle? Provide an efficient algorithm.

5. What is the difference between a static array and a dynamic array? How are they implemented?

6. Explain the concept of a binary search and its time complexity. When is it most effective?

7. Describe the process of implementing a stack using an array. What are the advantages and limitations of this approach?


8. How would you implement a queue using two stacks? Provide an efficient implementation.


9. What are the basic operations and time complexities of a binary search tree? How would you traverse a binary search tree in order?


10. Explain the concept of a hash table and its collision resolution techniques.

11. How would you implement a priority queue using a binary heap? What is the time complexity of the basic operations?

12. Describe the process of traversing a graph using depth-first search (DFS) and breadth-first search (BFS). What are their applications?

13. What is a self-balancing binary search tree, such as an AVL tree or a red-black tree? Explain how it maintains balance.


14. How would you find the kth largest element in an unsorted array? Provide an efficient algorithm.


15. Explain the concept of a trie and its use cases. How would you implement a trie?


16. Describe the concept of dynamic programming and provide an example problem where it can be applied.


17. What are some common sorting algorithms, such as bubble sort, merge sort, and quicksort? Explain their time complexities and trade-offs.

18. How would you efficiently find the median of a large dataset? Provide an algorithm with optimal time complexity.

19. Describe the process of finding the longest common subsequence between two strings. What is the dynamic programming approach for this problem?

20. Explain the concept of a skip list and its advantages over other data structures.
Crafting Interpreters
Tags: 100daystooffload, interpreters, book, compilers
Published: 2023-07-05 18:29:20

I just bought the book [Crafting Interpreters](https://a.co/d/bjMamei) by [Robert Nystrom](https://twitter.com/munificentbob) which is also available [online](craftinginterpreters.com). Many has recommended this book so my hopes are high 😀 and the goal is to read it during my summer vacation. I believe that the books title says all about its content.

I have managed to read the first two chapters so far. The first chapter is an overview and introduction to the book, and it has made a good first impression. I also love these small snippets of information

>Yacc wasn’t the first of its ilk, which is why it’s named “Yacc”—Yet Another Compiler-Compiler. A later similar tool is Bison, named as a pun on the pronunciation of Yacc like “yak”.

The second chapter walks us through all parts of an interpreter and compiler just to get an overview of their responsibilities, and there is a lot of terms that is brought up; IR, symbol table, front end, middle end, back end, p-code and single-pass-compilers, to just mention a few.

Looking forward to read the next 28 chapters.
Example of how you can use React Native Image Crop Picker in your React Native project
Published: 2023-07-05 18:25:38

Install the library using npm or yarn:

```
npm install react-native-image-crop-picker

```
Link the library to your project:

```
react-native link react-native-image-crop-picker

```
Import the necessary modules in your component file:


```
import React, { useState } from 'react';
import { View, Image, Button } from 'react-native';
import ImagePicker from 'react-native-image-crop-picker';
```

Create a component that allows the user to select and crop an image:

```
const ImageCropPickerExample = () => {
  const [selectedImage, setSelectedImage] = useState(null);

  const openImagePicker = () => {
    ImagePicker.openPicker({
      width: 300,
      height: 400,
      cropping: true,
    }).then(image => {
      setSelectedImage(image.path);
    }).catch(error => {
      console.log('Error:', error);
    });
  };

  return (
    <View>
      <Button title="Select Image" onPress={openImagePicker} />

      {selectedImage && (
        <View>
          <Image source={{ uri: selectedImage }} style={{ width: 200, height: 200 }} />
        </View>
      )}
    </View>
  );
};

```


In this example, we have a component called ImageCropPickerExample that renders a button to open the image picker. When the user selects an image and crops it, the selected image's path is stored in the component's state (selectedImage). The cropped image is then displayed using the Image component.

Please note that this is a basic example, and you can customize the options passed to ImagePicker.openPicker() based on your specific requirements. You can refer to the library's documentation for additional options and functionalities.
how you can use react-native-fs (rnfs) to download a file in React Native
Tags: reactnative, react, android, ios
Published: 2023-07-05 18:21:03

Step 1: Install the dependency

If you haven't already, install react-native-fs by running the following command:

```
npm install react-native-fs

```

Step 2: Link the dependency

Link the react-native-fs package to your project

```
npx react-native link react-native-fs

```

Step 3: Download a file

You can use the downloadFile method from react-native-fs to download a file. Here's an example:

```
import React, { useEffect } from 'react';
import { View, Button } from 'react-native';
import RNFS from 'react-native-fs';

const FileDownloadScreen = () => {
  useEffect(() => {
    // Optional: Delete the file if it exists before downloading
    const filePath = RNFS.DocumentDirectoryPath + '/example.pdf';
    RNFS.unlink(filePath)
      .then(() => {
        console.log('Previous file deleted');
      })
      .catch((err) => {
        console.log(err.message);
      });
  }, []);

  const downloadFile = () => {
    const url = 'https://www.example.com/example.pdf';
    const filePath = RNFS.DocumentDirectoryPath + '/example.pdf';

    RNFS.downloadFile({
      fromUrl: url,
      toFile: filePath,
      background: true, // Enable downloading in the background (iOS only)
      discretionary: true, // Allow the OS to control the timing and speed (iOS only)
      progress: (res) => {
        // Handle download progress updates if needed
        const progress = (res.bytesWritten / res.contentLength) * 100;
        console.log(`Progress: ${progress.toFixed(2)}%`);
      },
    })
      .promise.then((response) => {
        console.log('File downloaded!', response);
      })
      .catch((err) => {
        console.log('Download error:', err);
      });
  };

  return (
    <View>
      <Button title="Download File" onPress={downloadFile} />
    </View>
  );
};

export default FileDownloadScreen;

```
In this example, we first delete any existing file with the same name (example.pdf) if it exists. Then, when the "Download File" button is pressed, the downloadFile function is called. It uses RNFS.downloadFile to initiate the download process. The fromUrl property specifies the URL of the file to download, and the toFile property specifies the path where the downloaded file will be saved.

You can also track the download progress by providing a progress callback to the RNFS.downloadFile method. The callback receives an object with the bytesWritten and contentLength properties, which can be used to calculate and display the download progress.

Remember to replace 'https://www.example.com/example.pdf' with the actual URL of the file you want to download.

That's it! With this example, you can download files using react-native-fs in your React Native app.
A Guide to AWS VPC
Tags: aws, cloud, beginners, learning
Published: 2023-07-05 17:34:49

## Introduction to VPC

An logically isolated area of the Amazon Web Services (AWS) cloud where you can launch and use AWS resources can be created and managed using the AWS VPC (Amazon Virtual Private Cloud) web service offered by AWS. To put it simply, a VPC allows you to build your own private network inside the AWS cloud.

The IP address range, subnets, route tables, network gateways, and security settings of a VPC are completely under your control once you build it. With this level of control, you may design and set up the network environment to meet your individual demands and security requirements.
<br>

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

---
### Subnets 

Subnets in AWS VPC can be categorised as either public or private depending on how easily they can access the internet. Let's examine what distinguishes public from private subnets:

- **Public Subnet**: An Internet Gateway (IGW) route is what makes a subnet a public subnet. A public subnet allows for instances to have public IP addresses and enable direct internet communication. This enables outbound traffic to the internet and makes them accessible from it. For resources that require direct internet connectivity, like web servers or instances hosting publicly available apps, public subnets are often used.

- **Private Subnet**: An unconnected private subnet lacks a direct connection to the internet. To access resources on the internet, instances within a private subnet use a Network Address Translation (NAT) gateway or NAT instance because they lack public IP addresses. The fact that private subnets are inaccessible from the internet adds an extra layer of protection. They are frequently utilized for backend servers, databases, or other resources that demand internal VPC communication.


### Route Tables

The traffic routing within a VPC is managed by a route table. It includes directives (routes) that describe how traffic should be routed across subnets, NAT gateways, VPN connections, and other resources.

### Internet Gateway

 A horizontally scalable, redundant AWS service called an Internet Gateway (IGW) enables connectivity between instances inside of your VPC and the internet. It gives internet-bound traffic a target and enables resources on public subnets to connect directly to the internet.

### Security Groups

Security Groups act as virtual firewalls for your resources within a VPC. They control inbound and outbound traffic at the instance level by specifying rules that allow or deny traffic based on protocols, ports, and IP addresses.

To Explore more, visit [AWS Documentation](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)
Django File Manager - #FREE Sample
Tags: django, opensource, appseed
Published: 2023-07-05 17:23:34

---
title: Django File Manager - #FREE Sample
published: true
description: Open-source Django starter that provides an easy and intuitive way to manage the files saved in the MEDIA directory - Sources saved on GitHub.
tags: django, opensource, appseed
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2k460788v8ce1ap5vdnw.jpg
canonical_url: https://blog.appseed.us/django-file-manager-free-sample/
---
Hello Coders! 

This article presents an **open-source Django Starter** that provides an easy and visual way to [manage the files](https://github.com/app-generator/sample-django-file-manager) saved in the MEDIA directory. The basic actions like preview/download/upload and delete are controlled via a simple, intuitive UI, and the permissive (MIT) license allows you to copy or incorporate the code in other products for free. `Thanks for reading!`

- 👉 [Django File Manager](https://github.com/app-generator/sample-django-file-manager) - `source code` (published on GH)
- 🚀 [Free Support](https://appseed.us/support/?ref=blog.appseed.us) (email & Discord) for registered users

---

All these features can be visualized in this YouTube material where we can see how we can interact with the UI and manage all the files saved on the DISK.

{% embed https://www.youtube.com/watch?v=dBWGf-ZNUDI %}

---

> **Thank you!** For more resources, feel free to access:

- 👉 [Admin Dashboards](https://www.admin-dashboards.com/) - a huge index with templates and apps
- 🚀 [Custom Development Services](https://appseed.us/custom-development/) - provided by AppSeed
Mas allá de la programación.
Tags: writing, spanish
Published: 2023-07-05 17:18:10

Ser un profesional de las Tecnologías de la Información (TI) esta muy lejos de ser el tipo que sale en las películas tecleando enfrente de una computadora a una velocidad impresionante hackeando cualquier tipo de sistema con el poder del guion de su lado.

La verdad es que ser un profesional de las TI la gran mayoría del tiempo las personas te van a pagar para que te dediques a resolver problemas, ese es el ADN de cualquier profesión que tiene que ver con tecnología.

A pesar de lo que muchas personas piensas hay lugar para todos, las personas que no les gusta lidiar con problemas complejos o que son muy sensibles al fracaso no creo que sea conveniente estar en la parte de desarrollo, pero existen otras áreas como lo son ventas, QA, diseño de interfaces, experiencia de usuario, infraestructura, DevOps, etc. Busca y sé curioso no te quedes con que programar es lo único que esta para ti allá afuera si estas en esto de las TI. 

Considero que las personas que estamos dentro del desarrollo de software hemos desarrollado una tolerancia al fracaso un poco mas elevada y no estoy diciendo que los que estamos de este lado somos deidades inalcanzables sino que simplemente nos gusta enfrentarnos a retos y resolverlos.

Existen personas con grandes dotes para esto de la programación, y por el otro extremo existen personas que como yo, que no somos genios, y ni mucho menos las cosas se nos dan a la primera. Pero que somos extremadamente necios, cosa que me propongo aprender invierto mucho tiempo, atención, dinero e incomodidad. Eso es lo que muchas veces las personas no ven, ya que solo ven los resultados finales. He pasado de saber prácticamente nada a entrenar modelos de aprendizaje computacional, saber diferentes lenguajes de programación, configuración de servidores incluso ventas. Tu también puedes llegar a este nivel siempre y cuando te sientas cómodo y feliz  con lo que estés haciendo y sobre todo sé curioso y ve mas allá de las cosas evidentes.

-U.