teleren/devto huggingface dataset:
Safe reflection using TypeScript
Tags: typescript, webdev, programming, tutorial
Published: 2022-12-22 19:44:31

## Reflection

Reflection is a good way to avoid redundant code. I give you an example, imagine that we have the following code:

```typescript
if(object.propertyA != null){
    console.log(object.propertyA);
}

if(object.propertyB != null){
    console.log(object.propertyB);
}

if(object.propertyC != null){
    console.log(object.propertyC);
}
```
A good way to improve it is avoiding the repeated code as follows. We create an array of strings with the properties on which we want to execute the action

```typescript
const properties: string['propertyA', 'propertyB', 'propertyC'];

properties.forEach(property => {
    const value = Reflect.get(obj, property)
	if(value != null){
	    console.log(value);
	}
});
```

So far so good, but what happens if we modify the name of the variables of the type of the object? Code we implemented in the past would fail and we wouldn't notice when we made the change.

How can we solve this? Creating a **Proxy** class

## Proxy

What is a proxy? A proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.

First of all we must retrieve the type we are using from the original object which is the following:

```typescript
class ObjectType {
	propertyA: string;
	propertyB: number;
	propertyC: boolean;
}
```

How do we extract the properties of the object? Using the next function:

```typescript
private proxiedPropertiesOf<TObj>() {
	return new Proxy({}, {
		get: (_, prop) => prop,
		set: () => {
		throw Error('Set not supported');
		},
	}) as {
		[P in keyof TObj]?: P;
	};
}
```

This allows us to extract the types safely and the code would look like this:

```typescript
const typeProperties = this.proxiedPropertiesOf<ObjectType>();

const properties: string[] =
	[
		typeProperties.propertyA, 
		typeProperties.propertyB, 
		typeProperties.propertyC
	];			
```

From now on, if we make any changes to the ObjectType model, if we modify the name of any property or remove it, the TypeScript compiler itself will show us the error.

I hope it has been useful, thank you for your time :)

Much of the information comes from the following [link](https://stackoverflow.com/questions/33547583/safe-way-to-extract-property-names)
How JavaScript Works?
Tags: javascript, beginners, programming, webdev
Published: 2022-12-22 19:32:48

**Everything** in JavaScript happens inside an **Execution Context**.
Now, What is **Execution Context**?

While reading through HTML, if the browser encounters JavaScript code to run via a `<script>` tag or an attribute that contains JavaScript code like `onClick`, it sends it to its JavaScript engine.
The browser's JavaScript engine then creates a special environment to handle the transformation and execution of this JavaScript code. This environment is known as the **Execution Context**.

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

**How JavaScript Code is executed?**
JavaScript is a **Synchronous Single-Threaded** Language,
as soon as the whole JavaScript program is run the **Global Execution Context** is created and it is created in two phases.

The Global Execution Context has two phases:-
1. **MEMORY CREATION PHASE**
2. **CODE EXECUTION PHASE**

1. **MEMORY CREATION PHASE** - In the memory creation phase the memory allocation is done, variables are allocated firstly with "undefined" and in the case of functions it allocates the whole function to it which was written in the program. 

2. **CODE EXECUTION PHASE** - In this phase, the JavaScript program is executed line by line, when we invoke the function it creates the execution context again (with two phases memory and code), then the code processes and the value which was allocated earlier with "undefined" changes to the value which was written in the code.

If there is a case where a function is invoked inside a function then the execution context will create inside the code execution phase, again and again, depending upon how many times it is invoked.

**Now**, you must be thinking that how JavaScript manages these processes smoothly.
JavaScript manages this whole process beautifully by managing the stack which is known as **Call Stack**.

**Call Stack** is like a stack, every time at the bottom of the stack we have our "global execution context", whenever the program is run the whole execution context is pushed into the stack.


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

as shown in the image it is an example of a call stack process,
in the **fig(1)** call stack is created and at the bottom of the stack, we have a global execution context[GEC], **fig(2)** shows the execution context[E1] is created in the stack just above the global execution context[GEC] and control goes to [E1], **fig(3)** once the role of [E1] is completed it moves out of the stack and all the control again goes back to global execution context[GEC], **fig(4)** now when the whole execution is done then the global execution context[GEC] is also deleted.

Call Stack maintains the "**Order of execution**" of the execution context.

**Call Stack** is also named such as:-
- Execution Context Stack
- Program Stack
- Control Stack
- Runtime Stack
- Machine Stack
What is a Load balancer
Tags: beginners, programming, tutorial, productivity
Published: 2022-12-22 19:31:04

A load balancer is a system that distributes incoming traffic across multiple servers or other computing resources, in order to improve the performance, reliability, and availability of a network application. Load balancers are commonly used in web applications, to distribute incoming requests from clients across multiple back-end servers, to ensure that the application can handle a large number of users without performance degradation.

Load balancers use various algorithms and techniques to determine how to distribute traffic among the available servers or resources. For example, a load balancer might use a round-robin algorithm to evenly distribute traffic among the servers, or a more advanced algorithm that takes into account the current load and performance of each server.

Load balancers can also provide other features and benefits, such as SSL/TLS termination, caching, compression, and security. Overall, load balancers are an important component of any large-scale network application, as they help to ensure that the application is scalable, available, and performant.

{% embed https://youtu.be/SL6ZUUiHE9I %}

There are many different load balancer solutions available, both commercial and open-source. Some examples of popular load balancers include:

- NGINX
- HAProxy
- F5 BIG-IP
- AWS Elastic Load Balancer (ELB)
- Azure Load Balancer
- Google Cloud Load Balancer
Working with Operators and Expressions in JavaScript
Tags: webdev, javascript, programming, tutorial
Published: 2022-12-22 19:23:58

Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. For example, the addition operator (`+`) adds two numbers and the multiplication operator (`*`) multiplies two numbers.

JavaScript has a wide range of operators, including arithmetic, assignment, comparison, logical, and more. Let's take a look at some examples:

##Arithmetic Operators
The most common arithmetic operators are `+`, `-`, `*`, `/`, and `%`.

Here's an example of how to use them:

```js
let a = 10;
let b = 5;

console.log(a + b); // Output: 15
console.log(a - b); // Output: 5
console.log(a * b); // Output: 50
console.log(a / b); // Output: 2
console.log(a % b); // Output: 0
```
##Assignment Operators
Assignment operators are used to assign values to variables. The most common assignment operator is the equal sign (`=`), which assigns the value on the right to the variable on the left.

Here's an example:

```js
let x = 10;
let y = 5;

x = y;
console.log(x); // Output: 5
```
JavaScript also has compound assignment operators, which combine a math operation and assignment. 
For example, `x += y` is the same as `x = x + y`.

##Comparison Operators
Comparison operators are used to compare two values and return a boolean value (`true` or `false`). The most common comparison operators are `==`, `!=`, `>`, `<`, `>=`, and `<=`.

Here's an example:

```js
let x = 10;
let y = 5;

console.log(x == y); // Output: false
console.log(x != y); // Output: true
console.log(x > y); // Output: true
console.log(x < y); // Output: false
console.log(x >= y); // Output: true
console.log(x <= y); // Output: false
```
##Logical Operators
Logical operators are used to combine conditional statements. The most common logical operators are `&&` (and), `||` (or), and `!` (not).

Here's an example:

```js
let x = 10;
let y = 5;

console.log(x > 0 && y > 0); // Output: true
console.log(x > 0 || y > 0); // Output: true
console.log(!(x > 0)); // Output: false
```
Expressions are combinations of values, variables, and operators that produce a result. 
For example, the expression `x + y` is a combination of the values of `x` and `y`, and the operator `+`.

In JavaScript, you can use expressions as stand-alone statements or as part of a larger statement. 
For example:

```js
let x = 10;
let y = 5;

let result = x + y;
console.log(result); // Output: 15

if (x > y) {
  console.log('x is greater than y');
}
```
Where `x > y` and `x + y` are expressions. 

![Conclusion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8hf9rr9vvprllhn3iwn0.jpg)

I hope this tutorial has been helpful in introducing you to operators and expressions in JavaScript. **Happy coding**!
How AI is Helping Private Investigators Get To The Truth.
Tags: ai, programming, datascience, beginners
Published: 2022-12-22 19:13:51

Artificial intelligence (AI) is transforming many industries, unlocking new horizons, and sadly, posing threats to millions by potentially stealing away their jobs.

Whether humanity’s future is dystopian or utopian with AI’s ongoing development, we can’t say for sure. But one thing is certain. It has unlocked opportunities for people of all professions, by making their day-to-day tasks less tedious, to say the least.

One such profession that AI gods have immensely rewarded is private investigation services.

AI helps private investigators focus on what truly matters (finding the truth) by automating tasks, analyzing large amounts of data, and providing valuable insights and predictions. Here's a closer look at how AI is helping private investigation services:

## **Automating tasks** 
One of the major benefits of AI is its ability to automate tasks. For private investigators, this means that they can spend less time on mundane tasks such as data entry and analysis, and more time on higher-level tasks such as strategy development and client interaction. This can help private investigators be more efficient and effective in their work.

## **Analyzing large amounts of data**
Private investigators often have to sift through large amounts of data in order to find relevant information. This can be a time-consuming process, especially when the data is unstructured or comes from multiple sources. AI can help private investigators by analyzing this data and providing insights and predictions that would be difficult for a human to uncover on their own.

## **Providing valuable insights**
AI can help private investigators by providing valuable insights and predictions that would be difficult for a human to uncover on their own. For example, an AI system might be able to analyze social media data and predict the likelihood of a person's involvement in a crime. This can help private investigators, especially [infidelity investigators](https://bradshawsprivateinvestigationservices.com/), narrow down their list of suspects and focus their investigation on the most promising leads.

## **Enhancing security**
AI can also help private investigators enhance security by providing real-time monitoring and alerts. For example, an AI system might be able to detect suspicious activity in a client's home or business and alert the private investigator to the potential threat.

## **Improving communication**
Finally, AI can help private investigators improve communication with their clients. For example, an AI chatbot might be able to answer frequently asked questions, freeing up private investigators to focus on more complex tasks.

Overall, AI is helping [private investigation services](https://bradshawsprivateinvestigationservices.com/) by automating tasks, analyzing large amounts of data, providing valuable insights, enhancing security, and improving communication. By leveraging the power of AI, private investigators can be more efficient and effective in their work, helping them discover the truth quickly and effectively.
GraphQL support has landed in Bruno
Tags: graphql, webdev, api, javascript
Published: 2022-12-22 19:12:59

Hey everyone!

I'd like to share some updates on the project Bruno.

Bruno now supports connecting to and exploring graphql api's.
This also marks the 0.4.0 release for bruno. 


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

I made a demo video: https://www.youtube.com/watch?v=bGD4i21Kx9M

The next focus item is going to be supporting running the app via docker, sorting requests in the collection, and syntax highlighting env variables in the url.

In case you are hearing the project for the first time, bruno is an opensource api client (its a lightweight opensource alternative to postman). You can read about the project at https://www.usebruno.com/

The holiday season is here.
Wishing you all a beautiful 2023 🥂
Middleware & Project structure.
Tags: javascript, node, express
Published: 2022-12-22 19:09:34

**Middleware:**
Middleware is a handler or we can say controller function . We sent request to server and server gives a response. Middleware are thoose functions which appears in the middle of request and response bellow shown the structure of a middleware : 



![middleware](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ntostlyl0pn72wlam2e.png)

The middleware function looks like , 
```javascript
(req, res, next) => {
  ....
} 
```
It has access to request and response object also it has next   function . When client sents request to server that server sents  that request to middleware then middleware gives back that  response to client . Middleware runs it functionality to give  response. We can write custom middlewares : 

```javascript
const myLogger = function (req, res, next) {
  console.log('LOGGED')
  next()
}
```
created a middleware called myLogger which just prints LOGGED . We can see there's a next function it basically passes myLogger response to next middleware . In a server it can has multiple middlewares or could be have single . So now we know what is middleware but why we use it.

**Why to use middleware:** 
Middleware are used to add logging and authentication functionality. If we want to record the number request we get we can use middleware. 

**Project Structure:** 
When we create projects most of the time we don't look at the structure of project. We just create the project but after some day when we get back to that same projects we may ran into bugs and any other errors at that time it becomes difficult to solve that issue because our project remains unorganized . If we organize our project it becomes easier to get to know that files . Sharing a project structure which feels organized for me you may keep your files in your own way , 
>app
>config
>controller
>db
>error
>lgos 
>middleware
>routes
>test
>util

.env
.gitignore
server.js

for particular work created separated directory which helps to know the workflow and it becomes easier to debug error.

That's all for today . Thank you for reading !!
Jupyter and bash, better than peanut butter and chocolate
Published: 2022-12-22 19:07:33

As a developer advocate, I fall into the "show me" camp. That means I like to show code when writing about a service or feature. In articles, code is presented as copy and paste blocks, such as this:

```python
text = "World!"
print("Hello",text)
```

If I was doing a live demo, I could use a REPL if the language supported it.

```
Python 3.10.9 (main, Dec 15 2022, 18:18:30) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> text = "World!"
>>> print("Hello",text)
Hello World!
```

I'm a terrible typist and standing behind a podium while speaking to the audience is painful to watch. One way I've approached this problem on the command line is to use `read` command in bash to display text, then execute the command or program when the enter/return key is pressed.

```bash
echo "This is a python program"
echo ""
echo "text = "World!"
echo "print("Hello",text)
echo ""
read -p -t 500 ""
python hello.py
```

This works fairly well, especially when using the command line to demonstrate setting up a service. There are two drawbacks, first, depending on the complexity of the demonstration the bash script can be very long. The second drawback is that if a command fails, then you can't repeat it. For example, if you create a cloud service, then try to move to the next step before the service is deployed, the demonstration fails.

What I want is the functionality of a [Jupyter notebook](https://jupyter.org/). The default Jupyter notebook only includes a Python kernel, which supports executing [simple shell commands](Shell commands in IPython), e.g.:

```
!echo "Hello World!"
```

However, you can install a [bash kernel](https://pypi.org/project/bash_kernel/) for Jupyter notebooks.

```bash
$ python -m bash_kernel.install
$ jupyter notebook
```

In the notebook interface, choose the `Bash` and away we go.


![menu item](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ev2847y3btd5xgh9oubh.png)

The Python dependency and Jupyter setup can be a drawback. Aside from that, there are advantages. First, if a command fails, it can be repeated. Second, notebooks can be shared with the audience after the demonstration. The third and most import advantage is, your audience doesn't have to watch you type commands. If you have to give a live demonstration, consider using a Jupyter notebook.
Older people starting out in tech...
Tags: beginners, programming, community, computerscience
Published: 2022-12-22 19:04:22

Lets set the stage a bit. I am creeping up on turning 45 in a couple months, so, I guess that I could point this at the coders, programmers, and the like that are in the over 40 crowd. 

A little about myself: I had worked the same job for over 20 years and decided I needed a change, I had gotten as far up the ladder as I could, and I started looking for ideas. I found that the ever evolving world of tech is the new path I wanted to get involved in. I have sense started a boot camp and am enjoying it, and the community that it has created being there.

Now, what I am really looking for is tips and tricks that people have picked up, or know of that can help in the learning process, I really want to get the most out of this experience as I can. 

I want to hear any thoughts that you have on getting a good start in this field. 

Thanks in advance!
Matthew
Compute AWS VPC Subnet CIDRs in Terraform
Tags: terraform, aws, cloud, cloudskills
Published: 2022-12-22 19:00:00

Subnetting is the process of dividing a larger network CIDR e.g. `10.0.0.0/16` into smaller subnets e.g. `10.0.1.0/24`, `10.0.2.0/24`.

A CIDR consists of two parts

- the host part of the CIDR
- the subnet mask part of the CIDR

The subnet mask is the `/16` value behind the CIDR IP and determines how many bits of the IP are host part. The `/16` is a short notation for the bit mask `255.255.0.0` which is another short notation for `11111111.11111111.00000000.00000000`

Do a logical and with the CIDR IP to find the host part, in our case it is the first half of the IP which determines the stable part of the subnet range. The second half of the IP is a wildcard and refers to the dynamic part of our CIDR IP.

This means that our network defined through `10.0.0.0/16` spans the network `10.0.0.0` - `10.0.255.255` which is around ~65k IPs.

So the network mask determines the amount of IPs spanned over the network. A higher subnet mask refers to a smaller network size.

## Subnetting in Terraform

Subnetting is the process of breaking a larger CIDR range down to a smaller subnet CIDRS. E.g. we have a network CIDR `10.0.0.0/16` and break it down to multiple subnets `10.0.0.0/24` , `10.0.1.0/24`

This is often necessary for the context of e.g. VPCs in AWS or other cloud providers.

Terraform offers a function called `cidrsubnet` that makes it possible to calculate subnets based on the 

- base CIDR - network CIDR that we divide into subnets
- netnum - Offset that we use for the subnet
- newbits - base CIDR net mask + newbits determines new subnet mask for subnet

```jsx
resource "aws_subnet" "subnet_computing" {
  vpc_id                  = aws_vpc.main.id
  map_public_ip_on_launch = false

  count      = local.azs_count
  cidr_block = cidrsubnet(var.cidr, var.cidr_offset, count.index + local.computing_offset)
  availability_zone = element(var.availability_zones, count.index)

  tags = {
    Name        = "${var.vpc_name}-subnet-computing-${count.index}"
    Environment = var.environment
  }
}
```

The example above uses the VPC cidr `var.cidr` e.g. `10.0.0.0/16` and adds the newbits netmask offset to it `16 + 8 = 24` which results in the new subnet bit mask `/24`

Finally, we add the netnum which is the current index `count.index` + the offset `local.computing_offset` that we already used to compute subnet CIDRs for other AWS VPC subnets.

The result is a subnet CIDR e.g. `10.0.12.0/24` that we use for the VPC subnet.

Using the Terraform `cidrsubnet` function makes it obsolete to define lists of subnet CIDRs ranges for each subnet that you want to create. You just have to define a base network CIDR range and an newbits value.