teleren/devto huggingface dataset:
Rails JavaScript Ecommerce SPA
Published: 2021-12-14 02:26:55

#Introduction

[TLTR: Feel free to get the source code.](https://github.com/mwpenn94/AmaZing-Deals-Ecommerce-SPA)

##Requirements
-The application must be an HTML, CSS, and JavaScript frontend with a Rails API backend. All interactions between the client and the server must be handled asynchronously (AJAX) and use JSON as the communication format.

-The JavaScript application must use Object Oriented JavaScript (classes) to encapsulate related data and behavior.

-The domain model served by the Rails backend must include a resource with at least one has-many relationship. For example, if you were building an Instagram clone, you might display a list of photos with associated comments.

-The backend and frontend must collaborate to demonstrate Client-Server Communication. Your application should have at least 3 AJAX calls, covering at least 2 of Create, Read, Update, and Delete (CRUD). Your client-side JavaScript code must use fetch with the appropriate HTTP verb, and your Rails API should use RESTful conventions.

##App Design
The overall plan for this single page application was to design a web site with a full-stack design using a Rails backend with a JavaScript frontend.

Based on the requirements, the app allows users CRUD functionality across multiple objects involved in a large-scale ecommerce marketplace application -products, reviews, carts, lineitems, orders, etc.

Similar to large scale counterparts, it is designed for straightforward use with minimal explanation required for the user.

##Data Design
See the schema for more info.

##Controller Design
See the controllers folder for more info.
Containerization Vs Virtualization, which is better and why?
Tags: containers, virtualmachines, beginners, tutorial
Published: 2021-12-14 02:17:07

In the last post, I described that what are the differences between Private and Public clouds (here is the link to it [private-vs-public-cloud-computing](https://dev.to/akdevcraft/private-vs-public-cloud-computing-5b74)). As a next step, I'm going to talk about the differences between Containerization and Virtualization (Virtual Machines). So, let's dive deep in.

## Virtualization
The virtual machine is virtualization where one or more virtual machine runs on the same physical hardware, this way you get the advantage of utilizing more resources as compared to running application on a single hardware. In the case of virtual machine (VM), we have the underlining hardware and on top of it hypervisor (a component that creates an abstraction on top of the actual hardware that lets you run the virtual machine).
Then, as a part of the virtual machine, you package the operating system, OS dependencies, runtime libraries. The application code is deployed on it. Below is an illustration of VM.

![Virtual Machines](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pu2t7c2me9ul6k28a27d.jpg)

## Containerization
When compared to the virtualization, containerization is lightweight as operating system (OS) is not packaged as a part of the container. You have the hardware, OS, Docker (there are other abstractions similar to Docker, but it’s the popular one). On top of Docker, you deploy the container where you package just the runtime libraries and the application code.

![Containers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0btu69ud2qhos68p0mta.jpg)

## Comparison
|Parameters|Virtualization |Containerization|
|--|--|--|
|CPU and Memory Utilization|Because OS consumes a lot of resources, and every VM has its own OS. That results in higher utilization of CPU and memory|OS is shared across all containers. That results in lower utilization of resources|
|Disk Space Consumption|Again, as every VM has its own OS, resulting in more disk space consumption|Shared OS results in lower disk consumption|
|Boot time|Little slower, mostly in minutes|Faster boot time, mostly in seconds|
|Isolation|As an advantage, independent OS results in more isolation|Less isolation due to shared resources|

## My Other Blogs:
- [Private Cloud Vs Public Cloud Computing](https://dev.to/akdevcraft/private-vs-public-cloud-computing-5b74)
- [Log4J zero-day vulnerability demystified - Log4Shell](https://dev.to/akdevcraft/log4j-zero-day-vulnerability-demystified-log4shell-1f0h)
- [Why we need multiple code analysis tools?](https://dev.to/akdevcraft/why-we-need-multiple-code-analysis-tools-3d9o)
- [What is WAI-ARIA and why we need it?](https://dev.to/akdevcraft/aria-beginner-s-guide-17p)
- [React Application Testing Strategy](https://dev.to/akdevcraft/react-application-various-testing-options-543d)

_If you have reached here, then I did a satisfactory effort to keep you reading. Please be kind to leave any comments or ask for any corrections. **Happy Learning!**_
C# : How to unit test Graph SDK with Select Query
Published: 2021-12-14 02:13:57

I post [Unit testing Microsoft Graph SDK Client with moq library](https://dev.to/kenakamu/unit-testing-microsoft-graph-sdk-client-with-moq-library-4l24) the other day, but I encounter a challenge when I need to write a bit more complex query.

# Graph SDK with SELECT query

I use following code to get GraphUser object, which I specify several fields explicitly by using SELECT Linq.

```csharp
Microsoft.Graph.User graphUser = await this.graphServiceClient.Users["<userId>"]
    .Request()
    .Select(u => new
    {
        u.Id,
        u.BusinessPhones,
        u.GivenName
    })
    .GetAsync();
```

# Unit Test

This is the mock I use to cover above code. There maybe better way to do it but it's working anyway :)

```csharp
Mock<IAuthenticationProvider> mockedIAuthenticationProvider = new ();
Mock<IHttpProvider> mockedIHttpProvider = new ();
Mock<GraphServiceClient> mockedGraphServiceClient = new (mockedIAuthenticationProvider.Object, mockedIHttpProvider.Object);
mockedGraphServiceClient.Setup(x => x.Users[It.IsAny<string>()]
    .Request()
    .Select(It.IsAny<Expression<Func<Microsoft.Graph.User, object>>>())
    .GetAsync(It.IsAny<CancellationToken>()))
    .ReturnsAsync(new Microsoft.Graph.User() { Id = Guid.NewGuid().ToString(), BusinessPhones = new List<string>(), GivenName = "Test" });
```

I use ``It.IsAny<Expression<Func<Microsoft.Graph.User, object>>>()`` as an argument to Select method which covers any combination of properties.

Hope this article will help myself in the future as I shall forget this sooner or later.
How to create ormconfig.{json/yml} for Typeorm for all kinds of database with just one command!!
Tags: typescript, node, typeorm, cli
Published: 2021-12-14 02:09:55

Tired of copying and pasting the contents of ormconfig.json every time you create a project?? 

Just run, ```npx ormconfig.json``` and with just one command, you can create *ormconfig* file for PostgreSQL, MongoDB, and MySQL. 

On top of that, you can choose between *yml* and *json* extension.

[Link To The Package](https://www.npmjs.com/package/ormconfig.json)
Blog Post 10: Final Project
Published: 2021-12-14 01:32:04

**Final Project: Project #3**

*Overview*
During the last few weeks of class we began our third and final project. The goal of this project was to Contribute to HAX The Web through a series of open ended issues and project requirements. My group, IST402j, was assigned to the trading card element.[Trading Card Here](https://github.com/elmsln/issues/issues/880). Our goal by the end of this project is to have our card resemble something like this:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j5kmlh869i8jtcunoiqt.png)
 
*What We Have Completed So Far*
Our project has incorporated NodeJS, HTML, and CSS. We have used imported elements from LitElement, HTML, and CSS as we tried to build and format this project. Through the implementation of our code we have been able to successfully render four different trading cards on our page and adjust the formatting of our cards to fit our holiday theme. 

*What Steps Are Left*
As we come close to the project deadline, our group has a few requirements to complete for this project. We are making last minute formatting issues. We are working on HAX wiring, and uploading the project onto storybook. After that, we need to upload to npm and submit both the GitHub and npm links. Our project is coming along great!

[Find Our Project Here](https://github.com/ist402groupj/project-3)
Data Structures and Algorithms (Pt. 2-Intro to Algos)
Published: 2021-12-14 01:26:45

What’s an algorithm? An algorithm is an unambiguous specification of how to solve a class of problems. It is a set of rules that precisely define a sequence of operations. This seems pretty easy to understand, right? However, until you’ve practiced on repeat, algorithms can be tricky to really understand. Solving problems with an algorithm helps us to break it down into smaller, easier to tackle pieces. 

Here is a good visual for breaking down the pieces and characteristics of an algorithm: 

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


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

There are some commonly used types of algorithms in JavaScript: 

**Brute Force Algorithms** — look at all the possibilities and selects the best solution 
**Greedy Algorithms** — choose the best option at the current time, without any consideration for the future 
**Divide and Conquer Algorithms** — divide the problem into smaller parts and then solve those parts 
**Dynamic Programming Algorithms** — build up to a solution using previously found sub-solutions
** Backtracking Algorithms** — similarly to brute force try to generate all possible solutions but each time you generate a solution test if it satisfies all conditions, and only then continue generating subsequent solutions. Otherwise, backtrack and go on a different path of finding a solution.
** Recursive Algorithms** - This follows a loop, in which we follow a pattern of the possible cases to obtain a solution. 

And when practicing solving algorithms another concept to keep in mind is time and space complexity. What? Big O Notation, that's what. 


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


**Time Factor**: Time is measured by counting the number of key operations such as comparisons in the sorting algorithm.

** Space Factor**: Space is measured by counting the maximum memory space required by the algorithm.

**Space Complexity**: Space complexity of an algorithm refers to the amount of memory that this algorithm requires to execute and get the result. This can be for inputs, temporary operations, or outputs.

**Time Complexity**: Time complexity of an algorithm refers to the amount of time that this algorithm requires to execute and get the result. This can be for normal operations, conditional if-else statements, loop statements, etc.

There is so much more to talk about with algorithms and even more with Big O Notation. I think this may be more than just two parts. Already you should see how important data structures and algorithms concepts are to have at least a general understanding of. And if space and time complexities make your head want to explode, you're not alone! Still important to have some idea of how much space and time your solution will require and being able to think about how to downsize those needs, you’re well on your way to grasping these concepts. Thanks for reading!
100 días de código: 39, 40 y 41, ser encargado del hogar y programador.
Tags: spanish, 100daysofcode, webdev, javascript
Published: 2021-12-14 00:42:03

Foto cover de [benjamin lehman](https://unsplash.com/@benjaminlehman?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) en [Unsplash](https://unsplash.com/s/photos/snow-ball?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
  

¡Hey hey hey!

Bienvenidos a este lunes que tanto cambia la motivacion, para unos puede ser desastroso comenzar la semana pero para otros puede ser un buen comienzo para las tareas. Para mi fue un dia atareado porque tuve que mantener el balance entre limpiar el hogar y ser programador.

Hoy comencé a darme cuenta que el desorden de  mi familia( yo incluido) no se iba a recoger solo, entonces empece a organizar y limpiar el ambiente y con ello llego para mi una idea de hacer un sistema que te permita realizar un inventario de todo lo que tienes en casa y que, con ayuda de redes sociales se pueda compartir de una forma rápida.

Esta aplicación puede tener un agregado que permita identificar donde están los productos con ayuda de la cámara, ubicación y el giroscopio de un smartphone. Suena como una aplicación interesante pero ahora mismo no me siento con los conocimientos suficientes para llevarla a cabo asi que les pregunto... ¿Que tal les parece la idea?

Bien ahora comencemos con el fin de semana.

### Antier:
- Practique 30 minutos de Touch typing.
- Continué avanzando en The Odin Project.
- Comencé a aprender un poco mas sobre IA y los tipos que existen.
- Investigue sobre seguridad web y cuales son las pautas recomendables para la creación de sitios web seguros.

### Ayer:
- Practique 30 minutos de Touch typing, ahora comienza a ser mas sencillo y menos doloroso el escribir durante grandes periodos de tiempo.
- Avance en The Odin Project.
- Sali con la familia para despejarme un poco. Siempre es bueno darse un descanso.

### Hoy:
- Avance hasta la sección formularios de The Odin Project.
- Practique 30 min de Touch Typing. Mi promedio de palabras por minuto rosa las 40 palabras en ciertas pruebas.
- Maquete una prueba de formulario para reforzar los conocimientos que adquirí en The Odin Project.

Y listo eso es todo lo que realice en este fin de semana, la verdad es que me ha venido bien el descanso. Espero que tengan mucho éxito en sus proyectos y animo con todo!

Adiós mundo!
How Deno Deploy Changes the Game for JS Server Hosting
Tags: deno, webdev, javascript
Published: 2021-12-14 00:28:15

[Deno Deploy](https://deno.com/deploy) is a “multi-tenant JavaScript engine running in 25 data centers across the world.” It’s a way to effortlessly deploy JavaScript without any need for config or maintenance. Deno Deploy obviously runs [Deno](deno.land), a “simple, modern and secure runtime for JavaScript and TypeScript” and an alternative to Node and even made by the same person. Deno is steadily growing in popularity and stability and the developers are very serious in [its future](https://news.ycombinator.com/item?id=26620116).
What Deno Deploy does is makes deploying simple Deno scripts extremely simple with an online code editor and simple GitHub integration so that you can test your code quickly. For Node applications, I used [Glitch.com](glitch.com) and [Heroku](heroku.com) to test and deploy my API’s. They’re both free but the free plans have limits, having to warm up half a minute and with limited requests. Also, getting the packages in Node to be compatible was a bit of a pain sometimes.
Deno Deploy is almost too good to be true for Deno users. Although it’s in the beta phase it has astoundingly great limits for a free tool. There is currently no paid plans but they say they are to have one in the future.
[Pricing:](https://deno.com/deploy/docs/pricing-and-limits)


Request count: 100k req/day, 1000 req/min
Memory: 512 MB
CPU Time per request: 50 ms
Environment variable size: 8 KB
ES modules per deployment: 1000
Deployment script size: 20 MB
Deployments per hour: 30
Custom domains: 50
Crash Reports: 10 crash reports per deployment, 100 logs per crash report
BroadcastChannel: 64KB/sec send rate per isolate, no limit on receive

I think that one of the reasons for the creation for Deno Deploy is to promote using Deno as a now “deployable” and stable replacement for Node however, Deno has yet to really gain significant popularity among developers and may not be ready to used in production. What do you think?
[Deno Deploy docs here](https://deno.com/deploy/docs)
[Try Deno Deploy](https://deno.com/deploy)
How to find the PID of a process using a specific port
Tags: linux
Published: 2021-12-14 00:20:37

---
title: How to find the PID of a process using a specific port
published: true
description: To find out what processes are using a specific port, use lsof. lsof -i :PORT
tags: linux
canonical_url: https://1ma.dev/how-to/2021/12/12/how-to-find-processes-by-port
---

To find out what processes are using a specific port, use `lsof`.

```bash
lsof -i :PORT
```

<!--more-->

## Examples

List all processes using the 5432 port (commonly used by postgres)
```bash
$ lsof -i :5432
COMMAND  PID   USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
postgres 777    1ma    7u  IPv6 0x0123456789abcdef 0t0  TCP localhost:postgresql (LISTEN)
postgres 777    1ma    8u  IPv4 0x1123456789abcdef 0t0  TCP localhost:postgresql (LISTEN)
```

List all processes using the 4000 port (this blog in development)
```bash
$ lsof -i :4000
COMMAND   PID   USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
ruby    59182    1ma   10u  IPv4 0x2123456789abcdef      0t0  TCP localhost:terabase (LISTEN)
```

## Alternatives

`netstat` can be used with grep to look for the port, but not possible in macOS as `netstat` won't output the process ID.

`ps -ef` can be used with grep too, but we'll need some bash sorcery to keep the first line of the `ps` output (the headers line).
Embed responsive YouTube videos in 2021
Tags: webdev, tutorial, css
Published: 2021-12-14 00:16:10

---
title: Embed responsive YouTube videos in 2021
published: true
description: Web developers can now rely on a new CSS property to embed YouTube videos without any obscure tricks
tags: webdev, tutorial, css
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8r03wu1gol4nwz06hlhc.png
---
  

If you just want the code, [scroll down](#using-the-aspectratio-property).

## The history

For a long time, web developers have had to rely on obscure CSS tricks to embed responsive YouTube videos on their website.

If you've ever had to do this yourself, you probably relied on a trick similar to this:

```css
.video-container {
  position: relative;
  padding-bottom: 56.25%;
}

.video-container iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
```

Combined with markup like this:

```html
<div class="video-container">
  <iframe
    src="https://www.youtube.com/embed/msizPweg3kE"
    frameborder="0"
    allow="accelerometer; autoplay; encrypted-media; gyroscope;"
    allowfullscreen></iframe>
</div>
```

What's the `56.25%` number? It represents of the aspect ratio of the video, which is usually 16/9 on YouTube (9 is 56.25% of 16.)

## Using the aspect-ratio property

Create a class and use the `aspect-ratio` property to automatically set the width and height of your video based on its container:

```css
.video {
  aspect-ratio: 16 / 9;
  width: 100%;
}
```

In your HTML, apply the class you created (`.video`, in my case) to your iframe:

```html
<iframe
  class="video"
  src="https://www.youtube.com/embed/msizPweg3kE"
  frameborder="0"
  allow="accelerometer; autoplay; encrypted-media; gyroscope;"
  allowfullscreen></iframe>
```

And that's it! No need for fancy tricks anymore.

## Browser support

This feature is safe to use in all modern browsers, as you can see on [caniuse.com](https://caniuse.com/mdn-css_properties_aspect-ratio). If you need to support older browsers, I recommend using the `supports` media query to make your UI consistent:

```css
@supports not (aspect-ratio: 1) {
  /* ... implement your fallback here */
}
```

Header image by <a href="https://unsplash.com/@christianw?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Christian Wiediger</a> on <a href="https://unsplash.com/s/photos/youtube-video?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
Prototype Pattern
Tags: algorithms, computerscience, java, beginners
Published: 2021-12-13 23:23:11

> Prototype(Clone) pattern allows copying an object using a prototypical instance

## Motivation

Consider an application which requires using the same object numerous times. To create an exact clone of the existing object, you could create a new instance from the class and copy all the values. But this creates a problem if the object contains private properties and methods, so an exact copy might not be possible. In some cases, you might only know the interface and not the concrete class of the object. 

The Prototype pattern solves this problem by implementing a clone method that allows creating an exact copy of an existing object without being dependent on the class of the object. 

## Applicability

The Prototype pattern can be used in cases where:

- duplicating an object is favorable instead of building from scratch
- the code is independent of any other third-party code


## Structure


![Prototype pattern class diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxcizalasylgbq6ce3ut.png)

### Participants
- **Prototype:** declares an interface for cloning itself
- **ConcreteProtoype:** implements cloning operation
- **Client:** creates a new object by asking a prototype to clone itself

### Collaborations

- A client initiates the prototype clone operation

## Advantages

- Allows clients to add and remove prototype at run-time by registering a prototypical instance.
- Allows us to avoid subclass hierarchy by using clone method.

## Disadvantages

- Cloning might be difficult when the existing class internals doesn’t support cloning or if there is a complicated nested structure.

## Implementation

It is common to implement the prototype pattern using a prototype manager. A prototype manager is an associative store that returns the prototype matching a given key.


## Demo

> The waiters that serve at the cafe all have the same uniform and salary but different tables. The owners of the cafe want an easy way of getting new waiters, without going through the trouble of starting from scratch.

To solve this problem, we first create an abstract Prototype class with a `copy` method to enable cloning the object. We then create a `Waiter` class extending the Prototype class, implementing the cloning method. After that we create a `WaiterFactory` class that will use a Waiter object as a preset and clone it with different table numbers.

{% replit @eyuelberga/Prototype-Pattern %}
My Sorting Table
Tags: javascript
Published: 2021-12-13 23:20:26

A light simple class to perform the table sort: was created specifically to compensate for the fact that - sometimes - sorting datatables cannot be applied.

The other usefulness is that it's a single file. It does not depend on any other file (css, javascript, etc.)

[https://github.com/DavidRevenge/mysortingtable](https://github.com/DavidRevenge/mysortingtable)