teleren/devto huggingface dataset:
Merge array-like objects by Array.prototype.concat()
Tags: javascript
Published: 2024-06-27 14:49:26

Let's dive into the Array.prototype.concat() method in JavaScript. This handy method helps you merge arrays, creating a new array with elements from the arrays you provide. Here's a quick example:
```js
const arr0= [], arr1 = [1,2], arr2 = [3,4];
const resultArray = arr0.concat(arr1, arr2);
// [1,2,3,4]
```

Now, let's switch things up and try to concatenate some array-like objects:
```js
const arr0 = [];
const arr1 = {0:1, 1:2, length:2};
const arr2 = {0:3, 1:4, length:2};
const resultArray = arr0.concat(arr1, arr2);
// [{...}, {...}]
``` 
When you use array-like objects, Array.prototype.concat() doesn't flatten them like it does with arrays. Instead, it treats each array-like object as a single element.

So, is there a way to force Array.prototype.concat() to flatten array-like objects too? Sounds like a challenge for the JavaScript geeks! Let's figure it out together.

Array.prototype.concat() description from [ECMAScript specification](https://tc39.es/ecma262/#sec-array.prototype.concat):

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

Let's pay attention to step5.a. There is a boolean variable _spreadable_ which defines how Array.prototype.concat() treats its arguments. If _spreadable_ is false (step 5.c) then an argument is added in resulting array as it is without been flatten. But if _spreadable_ is true (step 5.b) then the argument can be flattened! 

Function _IsConcatSpreadable_ defines value of _spreadable_ variable:
> 1. If O is not an Object, return false.
2. Let spreadable be ? Get(O, @@isConcatSpreadable).
3. If spreadable is not undefined, return ToBoolean(spreadable).
4. Return ? IsArray(O).

In step 2 - _@@isConcatSpreadable_ is just a specification name of build-in Symbol **Symbol.isConcatSpreadable**. 
The function _IsConcatSpreadable_ returns true in 2 two cases: either the object is an array or it has the property with the name **Symbol.isConcatSpreadable** and the property value is not falsy. 

This looks exactly like what we need! Let's add **Symbol.isConcatSpreadable** in array-liked objects we tried to concatenate:

```js
const arr0 = [];
const arr1 = {0:1, 1:2, length:2, [Symbol.isConcatSpreadable]:true};
const arr2 = {0:3, 1:4, length:2, [Symbol.isConcatSpreadable]:true};
const resultArray = arr0.concat(arr1, arr2);
// [1,2,3,4] 
```
Solved! Now Array.prototype.concat() flattens our array-like objects just like it does with regular arrays.

P.S. **Symbol.isConcatSpreadable** is used exclusively by the Array.prototype.concat() method. No other build-in methods uses it.
As I reflect on my journey with JavaScript
Published: 2024-06-28 00:46:09

As I reflect on my journey with JavaScript, I'm reminded of the incredible power of its operators. I've seen how the arithmetic operators have helped me build robust digital structures, one calculation at a time. The assignment operators have been my trusted guardians, keeping my data organized and secure. The comparison operators have been my guides, helping me navigate the complexities of algorithms and conditional statements.

The logical operators have empowered me to create intricate decision structures, and the bitwise operators have allowed me to optimize performance and process data with precision. And let's not forget the string operator, which has enabled me to craft engaging narratives and user interfaces.

My experience has shown me that with these operators, I can tackle even the most daunting challenges. They've become my tools, my allies, and my friends. And I want to encourage you to explore them too! With practice and patience, you'll discover the incredible things you can achieve with JavaScript. So don't be afraid to dive in, experiment, and learn. The world of coding is full of wonders, and I'm excited for you to discover them!
Iniciando en el mundo de la programación con C
Published: 2024-06-28 00:29:55

Hace ya bastante tiempo decidí aprender a programar con la finalidad de cambiar de carrera profesional. Las primeras recomendaciones que encontré en internet y en algunas escuelas online fue empezar a estudiar HTML, CSS y JavaScript. Sin embargo, para ser honesto algunos cursos que tomé sobre estos temas se me hicieron algo tediosos y para nada me sentí motivado, incluso llegué a pensar que esto de la programación no era para mí. También debo aclarar que cuando hice los cursos estaba en medio de una fuerte depresión.

Ahora que estoy más estable y feliz he decidido darle una segunda oportunidad a la programación, pero esta vez usaré una ruta y un enfoque diferente. En esta ocasión estoy dispuesto a disfrutar el camino. Hace algunos años me recibí de la carrera de matemáticas por lo que encuentro más divertido estudiar algoritmos, fórmulas y cosas relacionadas. Por lo anterior he decidido aprender a programar pero en C, quiero aprender las bases de la programación, estructuras de datos, implementar algoritmos, arquitectura de computadoras, etc.

Espero este sea el inicio de un gran viaje y al menos aprenda muchas cosas.
Enhancing React Form Handling with useTransition
Tags: nextjs, react, webdev, javascript
Published: 2024-06-28 00:22:43

The `useFormStatus` hook in React can be used to retrieve the status of the most recent form submission. It provides information such as the pending property, indicating if the form is currently submitting. This can be used to, for example, display loaders or disable submit buttons during submission.

However, there are a few notable caveats with this hook:

- **Component Placement**: The hook must be called from a component rendered within the form. This often necessitates creating a separate component to be rendered inside the form, which some might find cumbersome.  

- **Action Dependency**: The hook functions correctly only if the form uses the action attribute. This poses a challenge if you prefer using the form's onSubmit event handler, especially for implementing client-side validations prior to submission.

To circumvent these issues, I've found that the `useTransition` hook can be used as an alternative. The `isPending` property returned from the hook can be used to track the form action's pending state.

```
const { register, handleSubmit } = useForm({
    resolver: zodResolver(CreatePostSchema),
  });

  const [isPending, startTransition] = useTransition();
  const onSubmit = async (data) => {
    startTransition(async () => {
      const res = await createPost(data);
      if (res?.error) {
        toast.error(res?.error as string);
      }
    });
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("title")} placeholder="Title" />
      <button disabled={isPending}>Submit</button>
    </form>
  );
};
```

Also, using the tried and tested technique of creating a loader state to keep track of the submission state of an action can also work, but it also has a slight caveat. This is explained well in Coding In Flow's short video [here](https://www.youtube.com/watch?v=GN-aVYSt3Ec)

Next.js is rapidly improving its API so the present issues might be fixed soon. `useTransition` provides a viable turnaround in the meantime.
Let's Stop Asking "Why Do You Want To Work for Us?" in Interviews
Tags: beginners, career
Published: 2024-07-07 03:46:48

---
title: Let's Stop Asking "Why Do You Want To Work for Us?" in Interviews
published: true
date: 2024-06-28 00:00:00 UTC
tags: beginners, career
canonical_url: https://nelson.cloud/lets-stop-asking-why-do-you-want-to-work-for-us-in-interviews/
---

_“Why do you want to work for us?”_

I have run into this question many times as I’ve been applying to and interviewing with lots of companies.

99% of the reason people want to work for a company is **because they need money**. That’s it. They want to be able to pay off debt. They want to be able to pay their bills. They want to be able to pay rent or their mortgage. They want to be able provide for their family. They want to be able to afford a better life. And so on.

Sure, the tech stack might be exciting. Or the product may be compelling. The work-life balance may be good. But I promise you that the biggest reason is still money.

If you don’t believe me, find your most passionate engineers, cut their compensation in half, and see if they stick around. I guarantee you they won’t.

Let’s stop beating around the bush and be real with each other. Do you really want to to be lied to by every candidate?

It’s okay to be motivated by money. That’s the world we live in. An engineer can do amazing work for your company even if they are only motivated by money. Also, companies are only motivated by making money. What’s wrong with the average person being motivated by the same thing?

You may have come across my application to your company at some point. I may have said something about wanting to work with bright people and looking for growth opportunities. While that is still true, you should know that 99% of the reason I applied to your company is to earn money so I can buy food, pay rent, and provide for my family.

Let’s stop asking this question in the application and interview process. We all know the real answer.
DevX Status Update
Tags: puppet, community, devrel
Published: 2024-07-01 15:26:16

---
title: DevX Status Update
published: true
date: 2024-06-28 00:00:00 UTC
tags: puppet, community, devx
canonical_url: https://puppetlabs.github.io/content-and-tooling-team/blog/updates/2024-06-28-devx-status-update/
---

## Yo

Hey all, it’s been another week of behind the scenes work getting ready for the next phase of our work but now that the entire team is back from their holidays and with the news shared just below, I’d like to think we are ready to come out strong and get some good work done!

Either way hope you are all continuing to enjoy the summer heat.

## New Team Member!!

Some good news to announce is that we now have a new member in the DevX team, [Dána Doherty](https://github.com/danadoherty639) has joined us from another team within Puppet by Perforce and based on all the good things that we have heard from them she will quickly become another vital part of our work going forward so I hope you are all as welcoming as can be.

> I'm Dána, Ive been working at Puppet for 3 years now. I'm really looking forward to getting more involved in the developer experience and open-source community within Puppet. Outside of work I enjoy staying active, spending time outdoors, going dancing and travel.

## GitHub Pages

Finally, as part of ongoing work in order to improve and customize our documentation [Gavin](https://github.com/gavindidrichsen) has put in work over the last week in order to launch some new GitHub Pages, specifically pages for [puppet-lint](https://puppetlabs.github.io/puppet-lint/) and [puppet-strings](http://puppetlabs.github.io/puppet-strings/) and while these are simply copys of the readme for now, depending on how they are recieved, or even through community contributions, they may very well grow to contain a wealth of information for our users.

## Community Contributions

We’d like to thank the following people in the Puppet Community for their contributions over this past week:

- [`puppet-modulebuilder#93`](https://github.com/puppetlabs/puppet-modulebuilder/pull/93): “Use Dir.glob with base parameter in acceptance tests”, thanks to [ekohl](https://github.com/ekohl)

- [`puppet_litmus#567`](https://github.com/puppetlabs/puppet_litmus/pull/567): “Removed some extraneous whitespace”, thanks to [puppet-webteam](https://github.com/puppet-webteam)
Modules Status Update
Tags: puppet, community
Published: 2024-07-01 15:24:54

---
title: Modules Status Update
published: true
date: 2024-06-28 00:00:00 UTC
tags: puppet, community
canonical_url: https://puppetlabs.github.io/content-and-tooling-team/blog/updates/2024-06-28-modules-status-update/
---

## Friday Again!!

Here we conclude another week at our Pune office. It was a relatively calm period with no significant updates in our modules. However, our focus throughout the week remained on fulfilling Forge commitments that were started at the beginning of the quarter.

Stay tuned for updates on the new features that our team has been working on…

## Community Contributions

We want to express our gratitude to the community contributors for their valuable contributions, even though last week saw a relatively quiet period in terms of new contributions.

## New Module Releases

- [`puppetlabs-acl`](https://github.com/puppetlabs/puppetlabs-acl) (`5.0.1`)
Run Redis Locally
Published: 2024-06-27 23:34:25

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams.

To run the redis install any latest version of redis . We did the cluster setup on redis 4.0.14

First we need to create the conf file for the replication .port` we are going to use 3 master nodes and 3 slave nodes .

```
create 6 config files with port ranging from 7001 to 7006 .
config file for each node should be different like the below
dbfile name should be unique
port 7001                       
cluster-enabled yes                       
cluster-config-file cluster-node-1.conf                       cluster-node-timeout 5000
appendonly yes                       
appendfilename node-1.aof                       
dbfilename dump-1.rdb
```
Now we run all the redis-server by using the “redis-server” command.

```
redis-server node1.conf 
redis-server node2.conf 
redis-server node3.conf 
redis-server node4.conf 
redis-server node5.conf 
redis-server node6.conf
```

You can see all nodes are running , but there is no communication between the nodes


Run the below command from the “src” folder of redis server

```
./redis-trib.rb create --replicas 1 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005 127.0.0.1:7006
Once it asks for the nodes to join , please opt of “Yes” . We can see it choose node 1,2,3 as master nodes and node 4,5,6 as slave nodes
```

Stop one of the master node , Lets stop node 1 .


As node 1 is stopped now , we will see that one of the slave node promoted master node . for our case node 5 becomes master .


Once we start the node 1 , it will be re considered as slave node as we have already 3 master nodes available .


Similarly when you do the data replication , data will be moving from master to slave accordingly
Top 5 reasons why choose React.js for your web projects:
Tags: webdev, javascript, programming, react
Published: 2024-06-27 23:54:26


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

Component-Based Architecture: React.js uses a component-based architecture, allowing you to break down your UI into small, reusable pieces. Each component manages its own state, making it easier to build and maintain complex user interfaces. This modularity enhances code reusability and scalability, saving time and effort in development.

Declarative Syntax with JSX: React's use of JSX (JavaScript XML) allows you to write components using a syntax that closely resembles HTML. This declarative approach makes your code more readable and easier to understand, as it clearly defines how your UI should look based on the current application state.

Virtual DOM for Efficient Updates: React introduces a virtual DOM, a lightweight representation of the actual DOM. React's reconciliation algorithm efficiently updates the virtual DOM and applies only the necessary changes to the real DOM, minimizing browser reflows and enhancing application performance. This approach results in faster rendering and smoother user experiences.

Strong Ecosystem and Community Support: React.js benefits from a vast ecosystem of tools, libraries, and resources supported by a large and active community. Whether you need routing (React Router), state management (Redux, MobX), or UI components (Material-UI, Ant Design), you can find robust solutions and community-driven support to accelerate your development process.

Backed by Facebook and Community: React.js is developed and maintained by Facebook, ensuring robustness, reliability, and continuous improvement. Additionally, its popularity has fostered a strong community of developers who contribute to its growth and share best practices, making React.js a solid choice for building modern web applications.

These reasons collectively make React.js a preferred framework for front-end development, offering developers powerful tools and techniques to create dynamic, interactive, and scalable user interfaces efficiently.
How to use the If...else conditional statement in Bash
Published: 2024-06-27 23:24:00

In this article, I will walk you through the basics of the bash if...else statement and how to use it in your shell scripts to automate system processes.

Decision-making is one of the most fundamental concepts of computer programming. Like in any other programming language, if, if...else, if...elif...else, and nested if statements in Bash are used to execute code when a specific condition is met.

Bash if...else Statement

This article will walk you through the basics of the bash if...else statement and explain you how to use it in your shell scripts.

Decision-making is one of the most fundamental concepts of computer programming. Like in any other programming language, if, if...else, if...elif...else, and nested if statements in Bash are used to execute code when a specific condition is met.

## The if Statement

Bash if conditionals can have different forms. The most basic if statement takes the following form:

```
if TEST-COMMAND
then
  STATEMENTS
fi
Copy
```

The if statement starts with the if keyword followed by the conditional expression and the then keyword. The statement ends with the fi keyword.

If the TEST-COMMAND evaluates to True, the STATEMENTS are executed. If the TEST-COMMAND returns False, nothing happens; the STATEMENTS are ignored.

Generally, it is always good practice to indent your code and separate code blocks with blank lines. Most people choose to use either 4-space or 2-space indentation. Indentations and blank lines make your code more readable and organized.

Let’s look at the following example script that checks whether a given number is greater than 10:

```
#!/bin/bash

echo -n "Enter a number: "
read VAR

if [[ $VAR -gt 10 ]]
then
  echo "The variable is greater than 10."
fi
```

Save the code in a file and run it from the command line:

```
bash test.sh
```

Enter a number for example 12 to test the If statement.

```
The variable is greater than 10.
```

## The `if...else` Statement

The Bash if...else statement takes the following form:

```
if TEST-COMMAND
then
  STATEMENTS1
else
  STATEMENTS2
fi
```

If the TEST-COMMAND evaluates to True, the STATEMENTS1 will be executed. Otherwise, if TEST-COMMAND returns False, the STATEMENTS2 will be executed. You can have only one else clause in the statement.

Let’s add an else clause to the previous example script:

```
#!/bin/bash

echo -n "Enter a number: "
read VAR

if [[ $VAR -gt 10 ]]
then
  echo "The variable is greater than 10."
else
  echo "The variable is equal or less than 10."
fi
```

Now, let's run the script again.

```
bash test.sh
```

This time around, enter a number less than 10 and notice the output changes to the else message.

```
The variable is equal or less than 10.
```

Enter a number greater than 10.

```
The variable is greater than 10.
```

If you run the code and enter a number, the script will print a different message based on whether the number is greater or less/equal to 10.
ZTA Revolutionizing Cybersecurity with Zero Trust
Tags: zta, zerotrust, cybersecurity
Published: 2024-06-27 23:17:26

## What is ZTA?

💻 Zero Trust Architecture (ZTA) operates on a simple principle: never trust, always verify. Unlike traditional security models that assume everything inside an organization&#x27;s network is safe, ZTA assumes breach and verifies every access request, no matter its origin.

## The Need for ZTA

💥 In today&#x27;s complex digital landscape, threats can emerge from both outside and inside an organization. Insider threats, compromised devices, and sophisticated cyber-attacks make it clear that trusting any entity by default can be perilous.

## Pillars of ZTA

🛡️ Zero Trust is built on certain foundational pillars:

- 🔥 **Identity Verification:** Ensure that users are who they claim to be.
- 🌍 **Constant Monitoring:** Continuously monitor network traffic for signs of malicious activity.
- 💻 **Least Privilege Access:** Grant users only the access they need to perform their job functions.

## Implementing ZTA Effectively

To maximize the benefits of ZTA:

- 🔄 Adopt multi-factor authentication (MFA) for all users.
- 🔒 Segment your network to limit lateral movement of potential intruders.
- 🕵️ Ensure real-time monitoring and rapid response capabilities.
- 📚 Continuously update and review access policies.

## Conclusion

💻 ZTA is more than just a buzzword; it&#x27;s a transformative approach to cybersecurity. By assuming that threats can emerge from anywhere, ZTA ensures that every access request is scrutinized, creating a robust security environment. Embrace the future of cybersecurity with Zero Trust! 🚫🔒
IntersectionObserver
Published: 2024-06-09 07:35:45

This memo from 'The Complete JavaScript Course 2024: From Zero to Expert!' on Udemy.



```
const header = document.querySelector('.header');
const navHeight = nav.getBoundingClientRect().height;


const stickyNav = function (entries) {
  const [entry] = entries; // entries[0]

  if (!entry.isIntersecting) nav.classList.add('sticky');
  else nav.classList.remove('sticky');
};

const headerObserver = new IntersectionObserver(stickyNav, {
  root: null,
  threshold: 0,
  rootMargin: `-${navHeight}px`,
});
headerObserver.observe(header);
```


Bad way(The performance of the app on mobile devices is affected by the firing of an event on every scroll.)

```
const initialCoords = section1.getBoundingClientRect()

window.addEventListener('scroll', function(e) {
  console.log(window.scrollY);
  if(window.scrollY > initialCoords.top) nav.classList.add('sticky');
  else nav.classList.remove('sticky')

})

const obsCallback = function (entries, observer) {
  entries.forEach(entry => {
    console.log(entry);
  });
};

const obsOptions = {
  root: null,
  threshold: [0, 0.2], // [0, 1, 0.2] (100%)
};
```


Scroll revealing
```
const allSections = document.querySelectorAll('.section')

const revealSection = function(entries, observer) {
  const [entry] = entries;

  if(!entry.isIntersecting) return; // Guard

  entry.target.classList.remove('section--hidden')
  observer.unobserve(entry.target) // for paformance
}

const sectionObserver = new IntersectionObserver(revealSection, {
  root: null,
  threshold: 0.15,
})

allSections.forEach(function(section) {
  sectionObserver.observe(section)
  section.classList.add('section--hidden') // for everyone can see the section including person who block JS
})
```