teleren/devto huggingface dataset:
Array.prototype.pop(), push(), shift(), and unshift()
Published: 2021-10-12 02:29:31

In this tutorial I am going to cover an important topic regarding different Array’s methods that a lot of us get confused when using it. I am going to cover the difference between pop(), push(), shift(), and unshift().

**1.Pop( ):**

pop() is an array method will return the last element in the array and actually delete it from the array, which will decrease the elements length by 1. If the array has only one Element, then the returned value will be “undefined”. This method can be used either with array of variables or Array of objects. The method Syntax is pop( ).

	Example:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sz5ai3gwasvw0a45wlia.png)

Output:
 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xxwpyj9qiw7gfw8eahpf.png)


**2.Push( ):**

Unlike pop(), the push( ) method will insert a new element(s) to the Array and place it at its end, and will return the new Array length. This will increase the Array length by adding the number of the inserted elements to the number of the original Array’s element(s) length. Means it can push only single element or number of elements at once. And like pop(), this method can be used either with array of variables or Array of objects The method Syntax is push(element0, …, elementN  ).

	Example:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ij7f0gs5noatu83mia6b.png)
 
Output:
 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8cg2zflghxxg5c30y9fv.png)


**3.shift( ):**

Opposite to pop( ), The shift( ) method will return the first element in the array and also delete it from the array. This will decrease the elements length by 1. If the array has only one Element, then the returned value will be “undefined”. This method can be used either with array of variables or Array of objects. The method Syntax is shift( ).

	Example:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1cw0lfs8qquadiqkmrx1.png)
 
Output:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odif8mfoh7k4mns504p4.png)


**4.unshift( ):**

unshift( ) method will insert a new element(s) to the Array and place it at its beginning. It will return the new Array length. The method will increase the Array length by adding the number of the inserted elements to the number of the original Array’s element(s) length. Means it can add only single element or number of elements at once. And again, this method can be used either with array of variables or Array of objects The method Syntax is unshift(element0, …, elementN  ).

	Example:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mgq6dbshgsv0ghbkkbi7.png)
 
Output:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/empozgfhp23m8b59xxyk.png)
Parte 2 Mi nueva startup - Mensajería y paquetería express en Mérida, Yucatán
Tags: startup, webdev, nextjs, news
Published: 2021-10-12 02:12:11

Seguimos continuando...

## Ya esta lista la primera versión funcional (MVP) de la plataforma pero todavía faltan bastantes cosas más.


### El nombre y dominio ya esta: [Uayenvios](https://www.uayenvios.com)

Así se ve la app:
![App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lko9fxq5ztaxcgkp6d4r.png)

y la landing:
![www.uayenvios.com_top](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0gehsdwthp8wt9gu6911.png)
![www.uayenvios.com_mid](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/utgrdar6f3duzivi32ri.png)
![www.uayenvios.com_bottom](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2978iqadrzx08rki6tbf.png)

La plataforma fue creada con NextJS principalmente. Para el backend utilizamos el CDK de AWS y los servicios utilizados fueron AppSync para el BAAS, DynamoDB como base de datos, Cognito para la gestión y autorización de usuarios.
Para los mapas utilizamos Mapbox y para la búsqueda de direcciones lo que se uso fue la API de Google Maps de Autocomplete, para el cálculo de las rutas y distancia utilizamos el servicio de Amazon Location. 

Me tomo casi 8 días de desarrollo pero con esto ya se tiene la base para meter las funciones que se vayan requiriendo e integrar nuevas aplicaciones.

Ya también se adquirieron 2 motocicletas propias para poder ir comprando las cajas de reparto y brandearlas. 
Se esta definiendo el uniforme que deberán portar los mensajeros, para hacer entregas siempre presentables.

### Algunas cosas pendientes para comenzar:
- Agregar términos y condiciones, ya las esta trabajando un abogado para que esta parte este en orden.
- Una página de ayuda y preguntas frecuentes.
- Agregar una burbuja en la parte inferior con el WhatsApp para estar en contacto en tiempo real de forma fácil por cualquier duda o comentario.
- Crear las redes sociales.
- Mejorar y testear el SEO de la landing page.
- Definir las campañas y publicaciones en redes sociales.

### De parte de la aplicación: 
- Falta desarrollar la app para los mensajeros, en la cual se reciban las entregas asignadas.
- En esta app para mensajeros, ellos podrán llevar el control de sus entregas aceptadas, pendientes, rechazadas, etc. El control de pagos y datos personales. 
- La app servirá para que los clientes puedan monitorear sus entregas en tiempo real. 
- Panel de facturación de entregas y facturación automática cuando el cliente ingrese los datos desde la solicitud del servicio.
- Mejorar la interfaz para que ademas de monitorear en mapa en tiempo real la entrega, también se pueda ver diferentes status de la entrega de forma más visual.


Por el momento es todo.

Espero poder comenzar a promocionar el servicio para la siguiente semana.
Enjoy Programming-Themed Humor? Here's today's daily developer joke!
Tags: jokes, dailydeveloperjokes
Published: 2021-10-12 00:43:17

---
title: "Enjoy Programming-Themed Humor? Here's today's daily developer joke!"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
published: true
tags: #jokes, #dailydeveloperjokes
---

Hi there! Here's today's Daily Developer Joke. We hope you enjoy it; it's a good one.

![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e1259082460c.png)

---

For more jokes, and to submit your own joke to get featured, check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/). We're also open sourced, so feel free to view [our GitHub Profile](https://github.com/dailydeveloperjokes).

### Leave this post a ❤️ if you liked today's joke, and stay tuned for tomorrow's joke too!

_This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit._

<!--
Joke text:
___Q:___ Why do kayakers make bad programmers?

___A:___ Because they're afraid of waterfall.
 -->
Aura Theme v2.0.0 is out now! 🥳 🎉
Tags: javascript, typescript, vscode, theme
Published: 2021-10-12 00:32:54

Hi folks, I'm glad to share with you Aura Theme v2.0.0 with a lot of cool new features.

1. The entire project was recreated from scratch using TypeScript
2. Color schemes have been improved
3. Added Aura CLI
4. Added Aura API
5. New ports have been added, the current full list of ports is:
   - Visual Studio Code
   - Sublime Text
   - CodeSandbox
   - Hyper
   - Windows Terminal
   - Alacritty
   - iTerm
   - rxvt-unicode
   - Terminal.app
   - GNOME Terminal
   - Kitty
   - Chrome
   - Firefox
   - Vivaldi
   - Insomnia
   - Telegram Desktop
   - Slack

And more ports will come soon! 🚀

You can find all themes at:
https://github.com/daltonmenezes/aura-theme

Now, let's take a look at some of the available ports:

#### Visual Studio Code
![Visual Studio Code Preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ogqdsne7dx6d7rdhtgw3.png)

#### Hyper terminal
![Hyper Preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0lyisbkhjramjbzovu90.png)

#### Insomnia
![Insomnia Preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ule0dy4bz5iahnn9qpq.png)

#### Firefox
![Firefox Preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/07z5mbxcg8r63j1nirw2.png)

I hope you guys enjoy it as much as I do 💜

The repo is participating in the Hacktoberfest, so If you would like to [contribute](https://github.com/daltonmenezes/aura-theme#contributing) by creating new ports, you can open an issue or get an existing one asking for it and reading [the docs](https://github.com/daltonmenezes/aura-theme#documentation), also you can reach me here or on GitHub if you need some help. 💜
Como crear Pull request template y en español
Tags: github, spanish
Published: 2021-10-12 00:13:28

Esta vez será poco texto, la idea de este post es dejar un template para tus pull request, sea en proyectos propios con en el de la empresa en la que trabajas.

Lo primero que realizaremos es crear un archivo con el nombre `PULL_REQUEST_TEMPLATE.md` este archivo va dentro de la carpeta `.github`.

```jsx
# Descripción

Por favor, incluya un resumen del cambio y qué problema se soluciona. Incluya también la motivación y el contexto pertinentes. Enumere las dependencias necesarias para este cambio.

Correcciones # (problema)

## Tipo de cambio

Por favor, elimine las opciones que no sean relevantes.

- [ ] Corrección de errores (cambio no radical que soluciona un problema)
- [ ] Nueva característica (cambio no rompedor que añade funcionalidad)
- [ ] Cambio de ruptura (arreglo o característica que causaría que la funcionalidad existente no funcionara como se esperaba)
- [ ] Este cambio requiere una actualización de la documentación

# ¿Cómo se ha probado?

Describa las pruebas que ha realizado para verificar sus cambios. Proporcione instrucciones para que podamos reproducirlos. Enumere también los detalles relevantes de la configuración de las pruebas

- [ ] Prueba A
- [ ] Prueba B

* Lista de comprobación:

- [ ] Mi código sigue las directrices de estilo de este proyecto
- [ ] He realizado una auto-revisión de mi propio código
- [ ] He comentado mi código, especialmente en las áreas difíciles de entender
- [ ] He realizado los cambios correspondientes en la documentación
- [ ] Mis cambios no generan nuevas advertencias
- [ ] He añadido pruebas que demuestran que mi arreglo es efectivo o que mi característica funciona
- [ ] Las pruebas unitarias nuevas y existentes pasan localmente con mis cambios
- [ ] Cualquier cambio dependiente ha sido fusionado y publicado en los módulos posteriores
```
y eso es todo.
Espero te ayudara este post.

Gracias por leer, nos vemos en la próxima.
Has Facebook outgrown "Move fast and break things"?
Tags: facebook, stability, reliability, uptime
Published: 2021-10-22 10:08:18

---
title: Has Facebook outgrown "Move fast and break things"?
published: true
date: 2021-10-12 00:00:00 UTC
tags: facebook,stability,reliability,uptime
canonical_url: https://jhall.io/archive/2021/10/12/has-facebook-outgrown-move-fast-and-break-things/
---

Facebook’s famous motto, “Move fast and break things” officially [left the buliding](https://en.wikipedia.org/wiki/Facebook,_Inc.#History) in 2014, but that hasn’t stopped a large number of people on social media from criticizing Facebook for this old motto in light of recent major outages.

Since Facebook no longer lives by this motto, it’s a bit of a straw-man argument to begin with. But I want to defend this straw man anyway, with a bit of a contrarian view.

The assumption being made by those criticizing the “move fast and break things” motto is that the cost of a 6-hour outage is too high—that _too many_ things broke.

Is this justified?

I don’t know. And neither do you, unless perhaps you work closely with Mark Zuckerberg.

You see, this type of judgement is the result of an ad-hoc [ROI](https://en.wikipedia.org/wiki/Return_on_investment) calculation. The problem with this [armchair quarterbacking](https://www.urbandictionary.com/define.php?term=Armchair%20quarterback) is that the public is only privy to one piece of data necessary for that calculation: We know (or can estimate) the cost of a single failure.

In ROI terms, that is part of the _investment_ variable. Let’s simplify with round numbers, since we’re defending a straw man anyway, and say that a single outage costs US$1 billion.

“Oh my stars! That’s too expensive! It’s obviously a bad idea!” some might say (are saying).

If it’s not clear yet, the problem with this is that _we have no idea of the return_.

If Facebook can lose $1B in, it stands to reason that their earnings potential is also astronomical. What if the fast moving that caused the broken things also earned $50B that would not have been earned by acting more cautiously?

In this light, a $1B “investment” (in the form of an outage) to earn $50B seems like a bargain.

In mature businesses, outages are expected. There’s a failure or outage budget. Management works to keep reliability at expected levels. Not too unreliable, because then business suffers, but importantly: _also not too reliable_ because reliability is expensive.

Jown Allspaw and Paul Hammond make this point in their famous presentation [10+ Deploys Per Day](https://youtu.be/LdOe18KhtT4?t=223) by referencing World of Warcraft’s at-the-time dismal uptime:

> If the business requires that the site go down every 2 weeks, even though you’re the largest online gaming platform and you have millions of paying customers, those paying customers might be quite fine for you to have availability of 97%.

* * *
_If you enjoyed this message, [subscribe](https://jhall.io/daily) to <u>The Daily Commit</u> to get future messages to your inbox._
Making Comments Count
Tags: codestylecomments, code, style, comments
Published: 2023-07-07 14:13:04

---
title: Making Comments Count
published: true
date: 2021-10-12 00:00:00 UTC
tags: codestylecomments,code,style,comments
canonical_url: 
---

A generally accepted practice for writing software is leaving comments. These comments will hopefully be helpful to the next person that reads through the code. My overall goal when I comment code is to either describe the purpose of a method/class/file or the reasoning behind a decision that was made in the code.

Some comments describe what the code is doing verbatim. These work really well in coding tutorials or when I’m learning a new language and I need to remind myself of the function of a particular operator. Outside of those scenario’s I haven’t found them as useful since they are telling me something I already know by reading the code.

```
// Post-increment x and assign to y
var y = x++;

```

An exception to my previous statement, is when I find myself using a more esoteric operator, but in that case it is also nice to leave an explanation why the task couldn’t be accomplished with a simpler approach.

My preferred type of comments provide context to future contributors (including myself once I’ve forgotten everything about that piece of code in about a week). These are the comments that save time down the road by helping future contributors avoid pitfalls that have already been found and remedied.

```
// Using a loop instead of recursion due to intermittent StackOverflowExceptions
// when processing deeply nested objects
while(condition)
{
    // ...
}

```

Happy commenting!
Fixing validation error in NestJS when using forbidUnknwonValues in validation pipe
Tags: webdev, nestjs
Published: 2021-10-14 00:29:01

---
title: Fixing validation error in NestJS when using forbidUnknwonValues in validation pipe
published: true
date: 12/10/2021
tags: #webdev #nestjs
canonical_url: https://darraghoriordan.com/2021/10/12/nestjs-fix-unexplained-validation-error-400-forbidunknownvalues/
---

If you get unexplained validation errors (http status 400) when calling a NestJS api you might want to check your `Query()` parameters. Parsing and validating these the wrong way can cause issues.

<!-- end excerpt -->
## Parsing Query parameters in NestJs

There are two ways to parse query strings in Nest Js. You can parse each variable separately or parse an object. Complex parameters cause issues when parsing from query strings. I would always recommend parsing via an object if you use any kind of non-string parameters.

e.g.

```
@Controller('myController')
export class MyControllerController {
  @Get()
  async myMethod(
    @Query('param1') param1?: string,
    @Query('param2', new ParseArrayPipe({ items: String, optional: true }))
    param2?: string[]
  ): Promise<void> {}
}
```

The `param2` there will break forbidUnknownValues. Class validator can’t parse it correctly.

Instead you can define an object that describes all the parameters. Define the required transforms and tell nest to run both validation and transformation on the query string to get the right values out.

Create a model that describes the parameters.

```
import { Type, Transform } from 'class-transformer'
import { IsArray, IsDate, IsDefined, IsEnum, IsOptional } from 'class-validator'

export default class QueryParams {
  @IsString()
  @IsOptional()
  public param1!: string

  @IsOptional()
  @IsArray()
  @IsString({ each: true })
  @Type(() => String)
  @Transform((value: string) => value.split(','))
  public param2?: string[]
}
```

and then change the controller to use this model instead of individual query string parameters.

```
@Controller('myController')
export class MyControllerController {
  @Get()
  async myMethod(
    @Query(new ValidationPipe({ transform: true })) allQueryParams: QueryParams
  ): Promise<void> {}
}
```

## Conclusion

You should be able to use the `forbidUnknownValues` setting in the validation pipe configuration as expected now. In general once I have more than 2-3 query parameters in an api method I think it’s easier to use a query object.
Cloud Driven Development - Episode #001
Tags: aws, cdk, testing
Published: 2021-10-11 20:24:30


Last week, I launched [Cloud Driven Development](https://cdd.show) (CDD) as a Youtube channel - a somewhat regular live coding series covering the topic of cloud development from various point of views. The sessions are usually in a pair programming setting, with changing guests & topics for each episode.

With CDD I want to explore developer focused tools, services and workflows beyond "Cloud Native" (which always translates to Kubernetes in my head). So, let's embrace that vendor lock-in, forget about containers for the most part and dive into a world without a local dev or testing environment.

If you're up for some casual talking / live coding about a topic which fits this category, I'd be more than happy to hear from you. I explicitly want to learn about new things outside of the CDK bubble as well and have some super exciting topics in the pipeline already.

## Async Testing with AWS CDK

For the first episode I was super happy to have [Matt Morgan](https://mattmorgan.cloud) as a guest, who wrote a very interesting [blog post](https://dev.to/aws-builders/testing-the-async-cloud-with-aws-cdk-33aj) about "Async Testing with AWS CDK".

As the title suggests, Matt has been exploring cloud testing strategies. The approach we're talking about in this episode, leverages Cloudformation and Custom Resources. The best part, it's not just an academic excercise but it's actively being used at his current employer [PowerSchool](https://www.powerschool.com/).

{% youtube 4wtgKbNbzHo %}

## Technical Notes

- [Example](https://github.com/elthrasher/cdk-async-testing-example)
- [sls-test-tools](https://github.com/Theodo-UK/sls-test-tools)
- [aws-testing-library](https://github.com/erezrokah/aws-testing-library)
 
### Custom Resource
 
- [Custom Resource Docs](https://docs.aws.amazon.com/cdk/api/latest/docs/custom-resources-readme.html)
- [Provider Framework on Github](https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/custom-resources/lib/provider-framework)

## Next Episode

The next episode is scheduled already, where [Ben Force](https://twitter.com/theBenForce) and I will build a really simple Alexa Skill with the AWS CDK. In this context particularly interesting: How to keep iteration cycles small, get fast feedback and can tests help there?
  
{% youtube D9CN7GYjuWI %}
Lógica de programação é fundamental
Tags: beginners, programming, fundamentals, webdev
Published: 2021-10-11 23:49:26

Da hora que acordamos até a hora de dormir, mesmo sem percebermos, tudo que fazemos obedece uma sequência lógica de passos. Ações que nos levam a outras ações, grandes ou pequenas, que por sua vez nos levam a alguma resolução ou decisão final.

Aquele exemplo clássico: "O que você faz ao acordar?" Já parou para pensar na sequência de passos da sua rotina matinal? Pense aí enquanto eu relato a minha:
1 - Acordo e levanto da cama (penso na vida por uns minutinhos como a mera mortal que sou rsrs)
2 - Vou a cozinha e verifico se tem café pronto. Se não tiver, começo o preparo.
3 - Enquanto o café me espera ou está sendo preparado, tomo banho e me organizo.
4 - Café prontinho? Começo o meu desjejum.
5 - Após esta sequência, estou pronta para começar minhas atividades.

Eu poderia detalhar mais. Poderia relatar detalhadamente todo o meu processo de preparar o meu café ou todas as coisas que organizei enquanto meu cafezinho passava na cafeteira, entre outras coisas. Mas, em resumo, esta é minha rotina básica e você acabou de ler o algoritmo da minha rotina matinal.

**Sintetizando**: lógica de programação seria então uma forma estruturada e sequencial de organizar instruções para a resolução de um problema.

Acredito ser superimportante estudar lógica de programação antes de estudar alguma linguagem específica. Infelizmente não foi o meu caso. Comecei com Python e mesmo esta sendo uma linguagem amigável para iniciantes, senti dificuldades justamente por me faltar essa base fundamental em LP. Ainda bem que percebi a tempo e corri atrás do prejuízo.

Geralmente o ensino da LP é feito em uma pseudo-linguagem, que para nós seria algo mais próximo do Português. O foco é justamente aperfeiçoar o raciocínio lógico sem se preocupar nesse primeiro momento com a sintaxe mais complexa das linguagens de programação.

Entender sobre os dados (tipos, estrutura), variáveis, operadores lógicos, estruturas condicionais e repetições, funções, procedimentos de resolução de algoritmos, entre outros temas fundamentais, é de extrema importância na formação do programador/desenvolvedor.

Com essa base bem feitinha, aprender linguagens como Javascript, Python, Java, C#, entre outras mais, será um processo um pouco mais agradável e estimulante. Então, não fuja desse tema. Uma base bem feita nos permite construir de maneira mais sólida.

Bons estudos!

<h6><a href='https://www.freepik.com/photos/man'>Man photo created by 8photo - www.freepik.com</a></h6>