teleren/devto huggingface dataset:
Building Portfolio: Install Next.js and Tailwind with pnpm
Tags: webdev, buildinpublic, nextjs, tailwindcss
Published: 2023-07-10 18:43:04

Hello Friends 👋,

As I learn and build my portfolio website with Next.js and Tailwind in public, I will write the process and progress.

This time, I will write them down in a different format than my other blog posts. This series will be personal notes of what I did and the blockers, if any, instead of thorough explanations of the steps and concepts. I will also share the next plan. Expect many bullet points and super short posts in this series 😁!

## Installation

I installed Next.js with [`pnpm`](https://pnpm.io/). But you can install it with `npx` or `yarn`. Check out [the installation section](https://nextjs.org/docs/getting-started/installation) on Next.js documentation for more information.

* Run this command to create the project with `pnpm` :
    
    ```powershell
    pnpm create next-app project-name
    ```
    
* Fill out the prompts.
    
    ![create next-app prompts on terminal](https://cdn.hashnode.com/res/hashnode/image/upload/v1688985952078/3470636b-edfe-41b2-9210-d45feb446a47.jpeg)
    
    * For now, I don't use TypeScript for this project.
        
    * It's great that there's an option to include Tailwind, so I don't have to install it separately and configure it myself 😁.
        
    * I ticked yes for all the yes/no prompts except for creating the `src/` directory. I will add it myself later if necessary.
        
    * My [import alias](https://nextjs.org/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases#module-aliases) configuration is `~/*`. Some people use `~`, and some use `@`. It's all about personal preference.
        

## Next Plan

* Add pages to the website—About Me, Blog, and Contact Me. These pages don't have to have content for now. But they should have a link to go back to the Homepage.
    

## Starter Kits

My friends suggested these starter kits if you want to save time on installation and configuration.

* [Next.js, React Query, and Tailwind](https://starter.dev/kits/next-react-query-tailwind/) starter kit — thank you, [Jessica Wilkins](https://twitter.com/codergirl1991)!
    
* [T3 — Full-stack, typesafe Next.js app](https://create.t3.gg/) — thank you, [Joe Karow](https://twitter.com/JoeKarow)!
    

## Resources

* [Next.js docs](https://nextjs.org/)
    
* [How to install nextjs with pnpm](https://medium.com/frontendweb/how-to-install-nextjs-with-pnpm-a958f1b3e9ad) by Rajdeep Singh
    

---

Thank you for reading! Last, you can find me on [**Twitter**](https://twitter.com/@AdiatiAyu), [**Mastodon**](https://hachyderm.io/@AdiatiAyu) and [**BlueSky**](https://bsky.app/profile/adiati.ayu.bsky.social). Let's connect! 😊
Ocupando reduce() y some() en JavaScript
Tags: javascript, programming, spanish
Published: 2023-07-10 18:18:43

Hoy revisaremos dos funciones que están disponibles cuando estamos trabajando con arreglos dentro de #JavaScript y que las puedes ocupar para otras cosas que normalmente no se nos ocurrirían. Vamos a revisar dos en esta ocasión son:

- Reduce
- Some

Reduce: se ocupa la gran mayoría de las veces para realizar sumatorias como vemos en la siguiente imagen, el primer parámetro es un arrow function con sum que es la variable que lleva el resultado y el segundo es el valor inicial de la variable sum.


![Ejemplo de reduce()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/obblpo3vh48s101zjlmj.png)

Supongamos que tenemos el siguiente arreglo de objetos.


![Arreglo de objetos](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ibknnfzc9tem09rnlxhy.png)

Podemos generar un histograma de frecuencias de cuentas personas son mayores de edad y cuantas son adolescentes, podemos ocupar la función reduce y en vez de tener un valor primitivo también podemos ocupar un objeto como el valor inicial, en el segundo parámetro de la función.


![Reduce con objetos](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sjwsroxm7bop2ua4a27o.png)

Some: verifica si dentro de un arreglo alguno de los elementos cumple con una condición dada, el resultado regresa un valor booleano. Si tenemos el siguiente arreglo, podemos verificar el día de hoy alguien es su cumpleaños.

![Arreglo de objetos para some](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/44bc53siuo2adkxlhyf1.png)

Podemos recorrer el arreglo, elemento por elemento obtener la propiedad birthday y después compararla con la fecha de hoy, el resultado de la función some() nos dará si alguna fecha coincide y ya podemos generar mas acciones en caso de que sea positivo el resultado.

![Some con arreglos](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vpn8nxm2g8j5l80pb37g.png)

Si este articulo te gusto o aprendiste algo nuevo te agradecería que me siguieras y compartieras mi contenido para que mas personas puedan aprendes de estos temas.
How to get file* input value in Vue.js (Vue3)
Published: 2023-07-10 17:17:01

In Vue.js, accessing the value of an input element is typically straightforward thanks to the v-model directive. However, when it comes to file input fields, the v-model directive doesn't work directly. This can be a bit puzzling for developers who want to retrieve the selected file from a file input field in a Vue.js 3 application.

In this article, we will explore an approach to tackle this challenge and find a solution for getting the file input value in Vue.js 3. By the end, you will have a clear understanding of how to extract the selected file from a file input field and use it within your Vue.js application.

_Composition API, script setup_

Here my HTML input file.
`<input class="form-control" type="file" id="formFile">`

Now let's go directly in the component's script section.
Create a reactive value reference for our input using **ref** 
`const myFileInputValue = ref(null);`
Don't forget to import **ref** on top of our script section.

Create a function to get the input value.

```
const getFileInputValue = (event) => {
    //get the file input value
    const file = event.target.files;
    //assign it to our reactive reference value 
    myFileInputValue.value = file[0] 
}
```
_**file[0]** is used to assign the first selected file to myFileInputValue._

Great !! now we have to call this function every time our input value change.
We can use the **v-on** vue.js directive also know as **@** in the component template with the **change** event.
_**change** is the equivalent of the **onchange** native event handler_
`v-on:change="getFileInputValue"` or `@change="getFileInputValue"`

Our input code look like this now.

```
<input v-on:change="getFileInputValue" class="form-control" type="file" id="formFile">

or

<input @change="getFileInputValue" class="form-control" type="file" id="formFile">
```

Now that you have learned how to retrieve file input values in Vue.js 3, you can confidently handle file inputs in your own projects. Take advantage of the versatile file input capabilities offered by Vue.js 3 and explore the possibilities. Enjoy coding and happy file handling!
Resend Azure Service Bus topic message
Tags: azure, servicebus
Published: 2023-07-10 17:11:03

In this post I'm going to take a look at one of the implications of resubmitting azure service bus subscription dead letter messages and how it can be solved.

Azure service bus has two kind of messaging entities, queues and topics. We wont go deep into the difference of the two here but basically a queue has a single logical consumer while a a topic can have multiple logical consumers (subscriptions). Microsoft docs available [here](https://learn.microsoft.com/en-us/dotnet/api/overview/azure/messaging.servicebus-readme?view=azure-dotnet#key-concepts).

A message sent to a topic is distributed to all configured subscriptions. And each subscription has its own dead letter queue where messages are placed if the can't be consumed within the specified retry count.

It would be nice to resend a dead letter message back to its subscription but that can't be done. No messages (new or dead letters) can be sent directly to a subscription, they have to be sent to the topic.

But this means that the message will be distributed to both subscriptions. If you have written your message handlers to be idempotent, meaning that they can handle the same message twice, there is no problem and you can stop reading now but if that isn't something you can guarantee you're in a bit of a problem. As we were.

[Filters](https://learn.microsoft.com/en-us/azure/service-bus-messaging/topic-filters) to the rescue.

Filters can be applied to a subscription to make sure that only messages that fulfills a given criteria is handled by the subscription (messages that don't fulfill the criteria are dropped).

We applied filters to all our subscriptions so that it only process messages where a header called `TargetSubscription` either doesn't exist or contains the name of the subscription.

Since we use [bicep](https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/overview?tabs=bicep) to deploy our azure infrastructure it was fairly easy to create a module for this.

```bicep
resource r 'Microsoft.ServiceBus/namespaces/topics/subscriptions/rules@2021-11-01' = [for subscription in subscriptions: {
  name: '${namespace}/${subscription.topicName}/${subscription.name}/default'
  dependsOn: [
    s
  ]
  properties: {
    filterType: 'SqlFilter'
    sqlFilter: {
      sqlExpression: 'TargetSubscription is null or TargetSubscription = \'\' or TargetSubscription = \'${subscription.name}\''
    }
  }
}]
```

With this in place it now becomes fairly trivial to send messages to a specific subscription.
Currying Step-By-Step
Tags: currying, closure, javascript
Published: 2023-07-10 17:06:14

**Definition**

Transform a function that takes multiple arguments into a series of functions that take a single argument each. 

**Reason**

The main advantage of currying is that the new function can be partially applied to its arguments.

**Instead of:**

```
function sum(x, y, z) { 
    return x + y 
} 
sum(1, 2, 3); //LOGs: 6
```

**We have:**

```
function sum(x) { 
    return (y) => { 
        return (z) => { 
            return x + y + z;
        } 
    } 
} 
sum(1)(2)(3); //LOGs: 6
```

Although currying can be achieved via other techniques, for example .bind(), this article focuses on utilizing closures. 
**Closures enables us to allocate each closure for a returned function to a specific variable:** 

```
function sum(x) { 
    return (y) => { 
        return (z) => { 
            return x + y + z;
        } 
    } 
} 
const addOne = sum(1)
const addTwo = addOne(2)
console.log(addTwo(3)) //LOGs: 6
```


**1.** When execution of the code comes to "const addOne = sum(1)", JS creates a closure for the returned function that captures the value of x as 1 in the Heap memory: 

```
In HEAP: x = 1

In Stack:
(y) => { 
        return (z) => { 
            return x(1) + y + z;
        } 
    } 

```


**2.** when execution of the code comes to "const addTwo = add(2)", JS creates a closure for the returned function that captures the value of y as 2 in the Heap memory: 

```
In HEAP: x = 1, y = 2

In Stack:
(z) => { 
            return x(1) + y(2) + z;
        } 

```

**3.** when execution of the code comes to "console.log(addTwo(3))", JS creates a closure for the returned function that captures the value of z as 2 in the Heap memory:
```
In HEAP: x = 1, y = 2, z = 3;

In Stack:
x(1) + y(2) + z(3);
```

All that is left is the execution of the final return:

```
function sum(1) { 
    return (2) => { 
        return (3) => { 
            return 1 + 2 + 3;
        } 
    } 
} 
const addOne = sum(1)
const addTwo = addOne(2)
console.log(addTwo(3)) //LOGs: 6
```
Javascript Polyfill Array.flat #5
Tags: javascript, programming, react, polyfill
Published: 2023-07-10 16:59:49

## This problem was asked by Meta

**What is a polyfill ?**

In web development, a polyfill is code that implements a feature on web browsers that do not natively support the feature

**Please implement your own Array.prototype.flat()**

**Example**

```
const arr = [1, [2], [3, [4]]];
flat(arr) // [1, 2, 3, [4]]
flat(arr, 1) // [1, 2, 3, [4]]
flat(arr, 2) // [1, 2, 3, 4]
```

**Follow up: Are you able to solve it both recursively and iteratively?**

## Solution

**Recursion implementation**

```
if (!Array.prototype.flat) {
  Array.prototype.flat = function (depth = Infinity) {
    const result = [];
    function flatten(arr, currentdepth) {
      for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i]) && currentdepth < depth) {
          flatten(arr[i], currentdepth + 1);
        } else {
          result.push(arr[i]);
        }
      }
    }
    flatten(this, 0);
    return result;
  };
}
```

**Iterative implementation**

```
if (!Array.prototype.customFlat) {
  Array.prototype.customFlat = function (depth = Infinity) {
    const arr = [...this];
    const result = [];
    while (arr.length) {
      const current = arr.shift();
      if (Array.isArray(current) && depth > 0) {
        --depth;
        arr.unshift(...current);
      } else {
        result.push(current);
      }
    }
    return result;
  };
}
```
We made a thing....
Tags: webdev, gpt3, ai, podcast
Published: 2023-07-10 16:32:01

My buddy and I decided to sit down once a week and talk about our software jobs. We're not sure exactly what direction we are going to take this, but it was important for us to start documenting our journey in hopes that we might help others along the way.

{% youtube -LwsQB7pH4A %}
Using object properties in v-model?
Tags: beginners, vue, help
Published: 2023-07-10 16:30:53

I'm trying to learn about Vue and see if it's a worthwhile system to use.
I'm exclusively ignoring the Options API and using the Component API.

When I try to use v-model="object.property", I get warnings in the console about "invalid prop" and the text value on the html is "[object Object]". This makes no sense to me as I'm still just using a ref().

What is happening?

If I change it to "object.property.value", it appears to work just fine. Is this really how we're supposed to use this?
Rust transpose method
Tags: rust, option, result
Published: 2023-07-10 16:18:45

Rust has a [transpose](https://doc.rust-lang.org/std/option/enum.Option.html#method.transpose) method, sometimes useful, works especially well with `anyhow`:

```rust
use std::str::FromStr;
use anyhow::Context;

fn add(a: Option<&str>, b: Option<&str>) -> anyhow::Result<f32> {
    let a = a.map(f32::from_str).transpose()?.context("not a value")?;
    let b = b.map(f32::from_str).transpose()?.context("not a value")?;
    Ok(a + b)
}

fn main() {
    println!("{:?}", add(Some("12"), Some("1.2")));
    println!("{:?}", add(Some("a"), Some("1.2")));
    println!("{:?}", add(None, Some("1.2")));
}
```

output:
```
Ok(13.2)
Err(invalid float literal)
Err(not a value)
```

## My links

I'm making my perfect todo, note-taking app Heaplist, you can try it here [heaplist.app](https://heaplist.app/)
And I have a twitter [@rsk](https://twitter.com/rsk)
Conditional building of Ruby Array and Hash
Published: 2023-07-10 16:18:34



[].tap do |a|
  a << :first if true
end

{}.tap do |h|
  h[:first] = 1 if true
end

{ 
  a: 'a', 
  b: ('b' if true) 
}.compact

[1, 2, *(3 if true)]
👨‍💻 Why passing GIFs in HTML's <img /> tag is acceptable by browsers but not the video file? 🗃
Tags: webdev, javascript, programming, beginners
Published: 2023-07-10 16:17:55

🔺 When it comes to web development, we often encounter the need to display different types of media content.
GIF (Graphics Interchange Format) is an image file format that supports animation, making it an ideal choice for short, looped animations.

🖊 Actually, it consists of a sequence of images displayed in a specific order to create the illusion of motion. Since GIF is essentially a series of static images, it can be displayed using the "img" tag just like any other image.T

🔺 However, videos are a different story. Unlike GIFs, videos consist of both audio and visual data, requiring dedicated video players for playback. To accommodate this, HTML provides the <video> tag, specifically designed to handle video playback. With the <video> tag, you can include multiple source files, such as MP4 or WebM, within <source> tags, specifying different formats for browser compatibility.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/afopy8pejlfqh3xfv84v.png)
What is IIFE in Javascript ? (important interview question)
Tags: javascript, webdev, opensource, interview
Published: 2023-07-10 16:13:25

An IIFE, or Immediately Invoked Function Expression, is a JavaScript function that executes immediately after it is defined. It provides a way to create self-contained blocks of code that don't interfere with the global scope. By invoking the function immediately, it allows for encapsulation and private variable scope.
```js
(function() {
    //write any code , it will automatically run 
  console.log("Hello world");
})();
```
in this example, an anonymous function is defined and invoked immediately by wrapping it in parentheses. It executes instantly without requiring explicit invocation elsewhere in the code.
```js
(function(name) {
  console.log("Hello, " + name + "!");
})("Diwakar");

```
in this example, the IIFE takes a "name" argument and logs a personalized greeting. the argument "Diwakar" is passed when invoking the IIFE. 

**use case:-**

1- Avoiding global namespace pollution

2- compatibility with older javascript

3- Encapsulating code

4- Modular Pattern

Thank you for reading, please follow me on Twitter, i regularly share content about Javascript, and React and contribute to Opensource Projects 

Twitter-https://twitter.com/Diwakar_766 

Github-https://github.com/DIWAKARKASHYAP
Creating a Rad Telegram Bot with Python
Tags: python, bots, beginners, programming
Published: 2023-07-10 15:49:17


Yo, ever thought about making your own bot for Telegram? Well, today's your lucky day! In this post, we're gonna show you how to create a super chill Telegram bot using Python. Trust me, it's gonna be a breeze. So, let's dive right in and get this bot party started!

**Step 1: Getting Set Up with Telegram Bot API**
First things first, you gotta have a Telegram account and grab a bot token. Just open up Telegram and search for the BotFather. Follow the simple steps to create a fresh new bot and score yourself a unique API token. That token is like the secret handshake for your bot to talk with the Telegram Bot API.

**Step 2: Installing the Cool Libraries**
Next up, make sure you've got Python installed on your machine. We're gonna use the awesome python-telegram-bot library, which makes building Telegram bots a piece of cake. Fire up your command prompt and type in `pip install python-telegram-bot` to get it all set up.

**Step 3: Writing Some Bot Magic**
Now comes the fun part! Grab your favorite code editor (or just use a notepad, no judgment here) and start writing some Python code. Import the necessary modules, initialize your bot using the API token, and then let your creativity flow. Create functions to handle different types of messages or commands and make your bot do cool stuff.

**Step 4: Let the Bot Loose**
Time to set your bot loose in the wild! Save your Python file with a .py extension and run it from the command line or your trusty IDE. Keep that program running, my friend, to keep the bot alive and kicking. You'll see a sweet message telling you that your bot is up and running.

**Step 5: Chatting It Up with Your Bot**
Now the real party begins! Open up Telegram, search for your bot using the username you set up with the BotFather, and start a conversation. Test out your bot's skills by sending commands or messages, and watch it respond like a pro. You're the boss, and your bot is ready to chat!


Boom! You've just created your very own Telegram bot using Python. With the Telegram Bot API, python-telegram-bot library, and your coding skills, you've mastered the art of bot-making. Now go ahead, have fun, and unleash your creativity to make your bot the coolest one in town. Chat on, my friend!



PSss, on my GitHub, I have the code. Just saying.😏
What are your goals for the week of July 10?
Tags: discuss, motivation
Published: 2023-07-10 15:34:26

## What are your goals for this week?


- What are you building? 
- What will be a good result by week's end?
- Are you attending any events this week? 
  * Any suggestions of events to attend?
- Did you meet your goals last week?


I'll start with how I did last week. It was a short week for the holiday.

### Last Week's Goals


- [:white_check_mark:] Continue Job Search.
- [:white_check_mark:] Blog I wrote it. I'm going back to reread it. It will post Tuesday or Wednesday.
- [:white_check_mark:] Code Challenges did some CSS Challenges
- [:white_check_mark:] Project work.
- Events
  * [:x:] Attend Virtual Coffee(VC) Thursday.
  * [:x:] Other VC events if I can.
  * [:white_check_mark:] Attended Networking event.

Added to my list.
- [:white_check_mark:] Content updates for a couple sites.


### This Week's Goals

- Continue Job Search.
- Blog
- Code Challenges
- Project work
- Events
  * Attend Virtual Coffee(VC) Thursday.
  * Other VC events if I can.
  * Attend Other events. 
- Build some LEGO sets. 

### Your Goals for the week


You've read my goals so I'll throw the questions back to you.


- What are you building? 
- What will be a good result by week's end?
- Are you attending any events this week? 
  * Any suggestions of events to attend?
- Did you meet your goals last week?



```html
-$JarvisScript git push
```
Mastering the Linux Command Line: Essential Tips and Tricks pt.1
Tags: linux, commandline, terminal, tutorial
Published: 2023-07-10 15:23:15

## 1. Mastering the `grep` Command

The `grep` command is a powerful tool for searching text patterns in files. Some useful options include:

- Searching for a pattern in a file: `grep "pattern" file`
- Searching recursively in directories: `grep -r "pattern" directory`
- Ignoring case sensitivity: `grep -i "pattern" file`
- Displaying line numbers: `grep -n "pattern" file`

## 2. Navigating the File System with `cd` and `ls`

- Changing directories: `cd directory_name`
- Going back to the previous directory: `cd ..`
- Listing files and directories: `ls`
- Displaying detailed file information: `ls -l`
- Sorting files by modification time: `ls -lt`

## 3. Stream Editing with `sed`

`sed` (stream editor) is a command-line utility for performing text transformations. Here are a few examples:

- Replacing text in a file: `sed 's/old_text/new_text/g' file`
- Deleting lines that match a pattern: `sed '/pattern/d' file`
- Printing specific lines: `sed -n '2,5p' file`

## 4. Efficient File Transfers with `rsync`

The `rsync` command allows efficient synchronization and file transfers between directories or across networks. Some useful options include:

- Synchronizing directories: `rsync -av source_dir/ destination_dir`
- Transferring files over SSH: `rsync -avz -e "ssh" source_file user@host:destination`
- Excluding specific files or directories: `rsync -av --exclude 'file.txt' source_dir/ destination_dir`

## 5. Monitoring System Resources with `top`

The `top` command provides real-time monitoring of system resources. It displays information about CPU usage, memory, processes, and more. Some useful options include:

- Sorting processes by CPU usage: Press `Shift + P`
- Sorting processes by memory usage: Press `Shift + M`
- Renicing a process: Press `r` and enter the process ID

These are just a few examples of Linux command line tips and tricks to enhance your productivity and efficiency. Experiment with these commands and explore the vast capabilities of the Linux command line!

These additional tips and tricks will further enhance your command line skills. Feel free to explore and experiment with these commands to become a Linux command line expert!

Stay tuned for more tips and tricks in future updates!

For more resources and examples, you can visit my [GitHub page](https://github.com/PythonPlumber).