teleren/devto huggingface dataset:
Hiring Coders
Published: 2022-09-04 23:24:29

That was the name of the bootcamp I dove into as the first step in coding studies. It was a great experience, I learned a lot about many technologies like, NodeJS, GraphQL and React, and other topics like REST API, HTTP methods and more, but the main thing I learned was learning to learn, these 3 months gave me the perception of how  difficult can be to learn something, but it also showed me how rewarding focus and effort on a mission can be.
Hostear un sitio estatico con CloudFront, SSL y Route53
Tags: aws
Published: 2022-09-04 22:27:48

---
title: Hostear un sitio estatico con CloudFront, SSL y Route53
published: true
description: Pasos para configurar y hostear un sitio estatico en un bucket de S3, con una distro de Cloudfront, SSL y Route53
tags: #aws
//cover_image: https://direct_url_to_image.jpg
---

Se que de estos hay mil articulos, pero como lo tuve que hacer para un sitio personal, lo dejo aca para el que le sirva.

En mi caso, el dominio es hyrule.com.ar

Nota: este articulo asume que tenes el sitio delegado a Route53

## Bucket
1. Crear un S3 bucket para nuestro dominio. Si es www.hyrule.com.ar, nuestro bucket se tiene que llamar hyrule.com.ar
2. Subir nuestros archivos. Vas a necesitar, al menos, un index.html y un error.html
3. Una vez creado el bucket, configurarlo para que permita hostear un sitio estatico (ir a Properties -> Static website hosting y habilitarlo)
4. Podes probar la URL que te da, deberia verse tu sitio. Nota: no es la misma que la del bucket, copiar esa URL a algun lado (la vamos a necesitar mas adelante)

## Certificate Manager
1. Ir a Request a new certificate
2. Poner nuestros dominios. Usualmente se ponen los dos (con y sin www). 
3. Elegir DNS validation
4. Va a quedar en estado Pending
5. Hacer click en el boton Create records in Route 53
6. Verificar que nos va a crear los dominios que necesitamos, hacer click en el boton Create Records
7. Listo, ya tenemos un certificado gratis para nuestro dominio

## Cloudfront
1. Crear una nueva distribucion de Cloudfront (desde ahora, CF)
2. En Origin Domain, pegar la URL que copiamos en el punto 4 del Bucket (algo como `http://[bucket].s3-website-us-east-1.amazonaws.com`)
3. Name: poner un nombre significativo
4. Alternate domain name: poner dominio.com y www.dominio.com (los dos). 
5. Custom SSL Certificate: elegi el certificado que creaste antes (lo deberias ver en el desplegable)
6. Viewer Protocol policity: usualmente es mejor redirigir HTTP a HTTPS 
7. Price Class: para que te salga mas barato, elegi "Use only North America and Europe". El Free tier tiene un monton de datos gratis, si no es un sitio grande no vas a tener problemas.

## Route 53
1. Click en Create Record
2. Elegir record type A
3. Habilitar Alias
4. Elegir Alias to Cloudfront Distribution
5. Deberia aparecer en el desplegable la distribucion que creaste en el punto anterior. Si no aparece, revisa que hayas hecho los puntos 4 y 5 de Cloudfront

Listo, una vez que se refresquen los DNS, deberias tener el sitio funcionando.
How to make Git ignore file permission (chmod) changes
Tags: webdev, github, git
Published: 2022-09-04 22:02:13

Have you ever made some changes in git, and then changed the files permissions too, only to realise you only want to publish the changes to the files, and not the file permissions? Or maybe you've updated the file permissions on a bunch of files, which you do not want to publish to your repository. This can happen if you [update a file's chmod](https://fjolt.com/article/linux-how-does-chmod-work) or file permissions. 

By default, if you do a `git push` or a `git commit` on these files, the file permissions will be uploaded too. Files which have restricted file permissions, will still have them when they are pulled from the repo.

That can be fine if you want a file's permissions to be published, but sometimes you only want to commit the **content**, and not the changes in file permission. If you want to ignore file permissions, then you can run the following command in git:
```shell
git config core.fileMode false
```

This will update the the git configuration for **this repository** to completely ignore file permission changes when doing a commit and push. **Note**, you can only switch this on or off for all files. To change it back to the default setting, so that file permissions will be committed and pushed to your repositories, you can run the command again with a value of `true`:
```shell
git config core.fileMode true
```

**Note**: be careful when using this. Although useful, make sure you set it back to `true`, so that you don't affect the future development of your repository in a negative way.
Day 148: Hello Travis CI
Published: 2022-09-04 21:42:52

Hi!
Change of plans today I shifted from Jenkins to Travis CI. I realized Jenkins will take me more time to learn and setup so I changed to Travis CI as the CI CD pipeline system as it's more like github actions that I'm familiar with.
The best thing about Travis CI is that it's easy to get started with just a few clicks and you are ready to go I hated the fact that you will get all your repo and your organization repos build direclty to your dashboard which can be very annoying and messy 
Tomorrow I have a lot to do outside the code ut if I spare some time I will be looking into it's setup with deployments.

Signing off...
Introdução a Algoritmos
Tags: algoritmos, braziliandevs, programming, beginners
Published: 2022-09-04 21:07:21

Essa é a introdução de uma série de matérias que têm como objetivo explicar de forma clara e intuitiva toda a disciplina de algoritmos. Surgiu da necessidade de ter um bom conteúdo em português que atenda nossa cultura. Eu me inspirei no Cormen (Introduction to Algorithms), que na minha opinião é o melhor livro para entender a matéria.

Aqui está uma visão geral resumida do que você precisa estudar para se aprofundar na matéria de programação e algoritmos.

- [Introdução a Algoritmos](https://dev.to/feministech/entenda-o-que-e-um-algoritmo-de-uma-vez-por-todas-1if1)
- [Análise de Algoritmos](https://dev.to/feministech/analise-de-algoritmos-para-iniciantes-pp3)
- [Notação Assintótica](https://dev.to/feministech/analise-assintotica-1h58)
- Design de Algoritmos
- Tipos de Algoritmos
- Insertion Sort
- Selection Sort
- Bubble Sort
- Recorrências
- Programação Dinâmica
- Algoritmos Gulosos
- Árvores de Busca
- Ordenações
- Estruturas de Dados

Antes disso tudo é importante que você conheça o básico de como funciona o Pensamento Computacional. É uma outra forma de ver a realidade que permitiu que a lógica de programação fosse desenvolvida.

Eu gravei vídeos explicando desde a história da programação até como desenvolver seu primeiro código em python, e isso tudo passando pelo pensamento computacional [neste link](https://www.youtube.com/watch?v=cH6jxtcRQ6Q&list=PLMe7sTNzPI0uZMiLFJYjPJvT36uiMkwpH&ab_channel=MagaTecnol%C3%B3gica). 

Todo domingo pretendo trazer um novo conteúdo seguindo o cronograma de tópicos acima! Comenta aqui se tem algo que você acha que não pode faltar!
How to fix the Content Security Policy directive with Strapi v4 and upload on AWS S3
Tags: strapi, webdev, javascript
Published: 2022-09-04 20:38:15

As I'm migrating from Strapi V3 with MongoDB to Strapi V4 with MariaDB/MySQL, I need to riconfigure the new instance of the CMS with the same configuration of the old one.
The issue is that some things (obviously) changed between the two version, and my old configuration for the [@strapi/provider-upload-aws-s3](https://www.npmjs.com/package/@strapi/provider-upload-aws-s3) plugin doesn't work anymore.

Well, not exactly.

When I tried to upload a file, that's what I saw:

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

One image was uploaded locally, while the other on S3, and what I found out is that the configuration works, and in fact the image is being uploaded on the bucket in AWS S3, but the CMS is refusing to show them.

So after spending some time on google I finally found the solution, which can be found at some point on [this GitHub issue](https://github.com/strapi/strapi/issues/11637#issuecomment-1090113953) and in this [other issue](https://github.com/strapi/strapi/issues/11637#issuecomment-1134444328).
I just needed to adapt it a bit to add the region to the s3 url in my case.

But essentially what you need to do is to update the `config/middlewares.js` file with the following configuration:

```javascript
// From this:

module.exports = [
  'strapi::errors',
  'strapi::security',
  ... //rest of middlewares
];

// To this
module.exports = ({ env }) => [
  'strapi::errors',
  {
    name: 'strapi::security',
    config: {
      contentSecurityPolicy: {
        useDefaults: true,
        directives: {
          'connect-src': ["'self'", 'https:'],
          'img-src': [
            "'self'",
            'data:',
            'blob:',
            'res.cloudinary.com', // cloudinary images
            'lh3.googleusercontent.com', // google avatars
            'platform-lookaside.fbsbx.com', // facebook avatars
            'dl.airtable.com', // strapi marketplace
            `https://${env('AWS_BUCKET')}.s3.${env('AWS_REGION')}.amazonaws.com`
          ],
          'media-src': ["'self'", 'data:', 'blob:', `https://${env('AWS_BUCKET')}.s3.${env('AWS_REGION')}.amazonaws.com`],
          upgradeInsecureRequests: null,
        },
      },
    },
  },
  ... //rest of middlewares
];
```

And now Strapi should finally work with files updated on S3.

> **Note**
> If you wonder why I had to add `res.cloudinary.com` and other domains, it's simply to allow icons and images to work in Strapi, like in the marketplace.
How can change the language of your video - Microsoft Azure Cognitive Services
Tags: python, azure, nlp, webdev
Published: 2022-09-04 20:09:37

Hello everyone,

For my course on Udemy, I created subtitles in 6 different languages using Microsoft Azure Cognitive Services' Speech-To-Text module and Google Cloud's Translation module.

Adding subtitles to your videos, which may include the hearing impaired among your viewers, is very effective in terms of both your SEO score and more views of your video.

1-Convert your video to "wav" format to use the Azure Speech To Text module: https://lnkd.in/dCjZGMS8

2-Online Azure Speech-To-Text : https://lnkd.in/dKDEcwza

3-Youtube Studio: You can perform "Automatic Timing" operations of the speech texts you obtained via Azure Speech To Text by turning on "Automatic Sync" via Youtube Studio.

4-Online Subtitle Translator : https://lnkd.in/dgKcDJq9

You can now buy me a coffe : https://lnkd.in/diGp8Q8U

#microsoft #azure #google #cloud #translation #udemy #ai
"😭 Escape from crazy boy friend!" explain Dependency Injection simplest way
Tags: javascript, beginners, programming
Published: 2022-09-04 19:53:49

## 🔥 Dangerous situation
Woman has crazy boy friend, but she can't escape from him. She doesn't have other choice. 

```javascript
class Woman {
  makeLover(){
    const bf = new CrazyMan()
    bf.stayWith()
  }
}

class CrazyMan {
  stayWith() {
    console.log('I am dangerous man, stay with me')
  }
}

const woman = new Woman()
woman.makeLover()

// I am dangerous man, stay with me
```

### 👦 There is good man !!
create GoodMan class
```javascript
class Woman {
  makeLover(){
    const bf = new CrazyMan()
    bf.stayWith()
  }
}

class CrazyMan {
  stayWith() {
    console.log('I am dangerous man, stay with me')
  }
}

// good man !!!!!!!
class GoodMan {
  stayWith() {
    console.log('I am good man, stay with me')
  }
}

const woman = new Woman()
woman.makeLover()

// 😰 But still she stays with dangerous man
// "I am dangerous man, stay with me"
```

Why she still stays with dangerous man ??
because she (Woman class) depends on dangerous man
```javascript
class Woman {
  makeLover(){
    // here, crazy man exists in Woman class, he is aaaaaaalways with her
    const bf = new CrazyMan()
    bf.stayWith()
  }
}
```

So help her !!  What should we do ???

```javascript
class Woman {
  // She does not depend on crazy man, she has choice now !!
  constructor(man) {
    this.man = man
  }
  makeLover(){
    this.man.stayWith()
  }
}

class CrazyMan {
  stayWith() {
    console.log('I am dangerous man, stay with me')
  }
}

class GoodMan {
  stayWith() {
    console.log('I am good man, stay with me')
  }
}

const man = new GoodMan()
const woman = new Woman(man)
woman.makeLover()

// I am good man, stay with me
```

We could help her by erasing dependency on crazy man 😀

---
This is simplest way to explain, from now you could easily get other articles about Dependency Injection😎
Send Email with Zip attachment having multiple files through Amazon SES using NodeJS
Tags: node, aws
Published: 2022-09-04 19:38:07


We want to send an email with the following requirements:
1. Email to have an Zip attachment.
2. Zip file containing multiple log files
3. Email needs to go through Amazon SES.
4. Implementation to be done using NodeJS

We can also zip other sources, such as files from file system or a remote file. We just have to convert it to a `Buffer` to zip it with `AdmZip`.

We will use the following NodeJS library
1. [NodeMailer](https://github.com/nodemailer/nodemailer)
2. [Adm Zip](https://github.com/cthackers/adm-zip)

PS: This whole operation is done in-memory. This should not be used on large files. In such case, `Stream` should be used.

Below is the code: 

```javascript
const NodeMailer = require("nodemailer");
const AdmZip = require("adm-zip");

const createSampleZip = () => {
  const zip = new AdmZip();

  zip.addFile("file1.txt", Buffer.from("content of file 1"));
  zip.addFile("file2.txt", Buffer.from("content of file 2"));

  return zip.toBuffer();
};

const sendEmail = () => {
  var sender = NodeMailer.createTransport({
    host: "email-smtp.eu-central-1.amazonaws.com",
    port: 587,
    secure: false, // upgrade later with STARTTLS
    auth: {
      user: "<<ses-smtp-username>>",
      pass: "<<ses-smtp-password>>",
    },
  });

  var mail = {
    from: "noreply@example.com",
    to: "recipient@gmail.com",
    subject: "test email with attachment",
    text: "mail body text with attachment",
    html: "<h1>mail body in html with attachment</h1>",
    // More options regarding attachment here: https://nodemailer.com/message/attachments/
    attachments: [
      {
        filename: "zipfile.zip",
        content: createSampleZip(),
      },
    ],
  };

  console.log("starting to send email");
  sender.sendMail(mail, function (error, info) {
    if (error) {
      console.log(error);
    } else {
      console.log("Email sent successfully: " + info.response);
    }
  });
};

sendEmail();
```
Online Learning: Scary but Cool
Tags: machinelearning, todayilearned
Published: 2022-09-04 19:16:30

`Online Learning??  You mean like Coursera?`
# What?
Online learning is a method of machine learning where data flows in over time rather than being available all at once.  

![What Netflix thinks Josh should watch](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q3l85pyuorc2cai0060l.png)

# Why?
Imagine this: it's been a month since you've ~binged~ watched Stranger Things at a healthy pace and you want to find your next show to watch (it's Breaking Bad).  In the dystopia without online learning, you'd have to wait a whole month* for Netflix engineers to train their ML Model based on your input data from the previous month before you they had an updated recommendation list for you.  

Online learning algorithms allow them dynamically provided updates over time based on your engagement with shows and movies on the platform.

*The timespan of a month was chosen arbitrarily, the point is that it would likely be slower.
Virtusa Neural Hack Season 6
Tags: cpp, stl, programming
Published: 2022-09-04 19:14:54

## Click on image...
[![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jy6kmxr228s91eh1c781.png)](https://www.youtube.com/watch?v=8mAGrlDafuY)

**Like and Subscribe** will be appreciated.
Introduction To Python for Data Engineering
Tags: python, beginners, codenewbie, architecture
Published: 2022-09-04 19:09:39

The rate at which data has continually been generated in the world is fast rising. Seagate UK has predicted that by 2025 there will be 175 zettabytes of data in the global data-sphere. From the rapid daily data growth, data engineering as a subdiscipline that focuses directly on transportation, transformation, and storage of data has steadily established itself in the technology realm.
Data Engineering has a deeper focus on the industrial process of data such as data pipelines and ETL (extract, transform, load) jobs. Data engineers are responsible for the provision of quality data for analysis and data-driven decision-making. For data engineers to successfully achieve their objectives, Python is primarily employed. Python Programming language is an interpreted general-purpose high-level programming language that emphasizes code readability and significant use of indentation
Why Python?
Over the years, other technologies or programming languages have been used in data handling and manipulation. However, python has since trampled over these technologies to become the most popular programming language worldwide. Its popularity and preference mainly stem from:
Ease of use: python is simple, its ease to learn and read syntax makes it easy to understand and helps one writes shortlines. Its ease of use enhances its user-friendliness hence garnering higher preference.
Learning Curve. Python provides a simple to grasp learning curve while also offering good standard libraries that have concise syntax. 
Wide applications. Providing a wide scope of libraries and packages, python enhances the possibility to complete many tasks across different domains efficiently and effectively.
Python for Data Engineers
Data Engineers are responsible for preparing and polishing the data so that it can be used for various tasks related to prediction, analytics, etc. python is used by data engineers for;
Data Acquisition. Sourcing data from APIs or through Web Crawlers involves the use of Python.  Moreover, scheduling and orchestrating ETL jobs using platforms such as Airflow, require Python skills.
Data Manipulation. Python libraries such as Pandas allow for the manipulation of small datasets. In addition to this, Python for Data Engineering provides a pySpark interface that allows the manipulation of large datasets using Spark clusters.
 Data Modelling. Python is used for running Machine Learning or Deep Learning jobs, using frameworks like Tensorflow/Keras, Scikit-learn, and Pytorch. So, Python for Data Engineering becomes a common language to effectively communicate between different teams.
Data Surfacing. Various data surface approaches exist, including the provision of data into a dashboard or conventional report, or the opening of data simply as a service. Python for Data Engineering is required for setting up APIs to surface the data or models, with frameworks such as Flask, and Django.
There are many use cases of Python in data engineering, and a language is an indispensable tool for any data engineer.
Codecademy CS102 Final Project: Find a Trail
Tags: beginners, python, programming
Published: 2022-09-04 19:09:14

For my final project in the Codecademy CS102 course I wrote a program to recommend local hiking trails.

##Project Requirements
The program must make recommendations based on input from the user using both search and sort algorithms.

##My Program
I read in data from local State Parks and use a merge sort to sort the trails by length.  
Users can choose to filter by State Park, trail length and/or trail difficulty. 

Recommendations are found by both binary and linear searches. 


The code can be found here [at GitHub.](https://github.com/acasagranda/Trail-Project)
Big O Notation
Tags: algorithms, beginners, javascript
Published: 2022-09-04 19:05:08



How bad are our code? 

Let's figure it out, learning a little bit about Big O Notation!

{% embed https://stackblitz.com/edit/js-3n3rxx?ctl=1&devToolsHeight=33&embed=1&file=index.js&hideExplorer=1&hideNavigation=1&theme=dark %}
Kotlin 基礎 Part 2 -- Exception(例外) の投げ方
Tags: kotlin, exception
Published: 2022-09-04 15:40:41

## why

例外についての知見が

> API にリクエストを投げて駄目だったときに備えて作っておくべきもの

程度しかなかったので

---

## Exception (例外) とは？

https://www.udemy.com/course/kotlinmasterclass/learn/lecture/16673664#overview

Udemy の Kotlin Master Class で学習した。

予想しないことが起こった時に出るもので
一度例外が出ると、そこからシステムは復帰できないらしい。

Stacktrace という Exception の前にどこの関数が動いたかの情報が出る.

---

## 普通に起こる Exception

```kotlin
    print("text".toInt())

java.lang.NumberFormatException: For input string: "text"
```

String を Int にすると NumberFormatException が出る。

```php
at com.example.springboot.PersonHandler.getPersons(Resource.kt:18) 
```

同時に Stacktrace が出る。
ここでは、 PersonHandler の getPersons ( Resource.kt の 18 行目 ) で起きたという情報が取れた。

---

## try/catch で Exception を握り潰して簡易エラーメッセージだけだしてアプリを続行する

```kotlin
    try {
      print("text"?.toInt())
    } catch (e: Exception) {
      println("Exception Occurred!")
      println(e.localizedMessage)
    }
```

先程の NumberFormatException を起こすコードを try の内部にいれて
Exception がでたら Exception の localizedMessage がでるようにした。

```kotlin
Exception Occurred!
For input string: "text"
```

localizedMessage だとこの最小限のエラーメッセージが出る。
また、通常 Exception がでたらアプリは終了する。
しかし今回は try で予測して Exception を catch している。
なのでアプリは終了せず、次の行が実行できた。

---

## Exception を握りつぶしながら詳細なスタックトレースも出す

```kotlin
catch (e: Exception) {
      println("Exception Occurred!")
      e.printStackTrace()
      println(e.localizedMessage)
    }
```

e.printStackTrace を catch の中にいれると
Exception を握りつぶしながら、詳細なスタックトレースも出せる。

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

再び見慣れたエラーの赤い文字が出るようになる

その後に finally を書くと、try がうまくいっても Error がでてもどのみち動く。初期化処理とかを書くのかな？

---

## 状況や引数不足で例外を投げるようにする

オリジナルの例外メッセージを投げられる。

```kotlin
    throw IllegalStateException("なんかちがう")
```

```php
java.lang.IllegalStateException: なんかちがう
```

https://programmer-life.work/java/illegalstateexception

IllegalStateException は不適切な状況の時に投げるべき Exception

https://kotlinlang.org/docs/exceptions.html#the-nothing-type

```kotlin
    val name = null
    name ?: throw IllegalArgumentException("Name required")
```

```php
java.lang.IllegalArgumentException: Name required
```

IllegalArgumentException は引数が不適切な時に投げる Exception

このように、その場にふさわしい名前の例外を投げよう！

---

## 条件に応じてオリジナルな例外を投げる

Runtime Exception を拡張して、HogeIdNotFoundException のようなカスタムエラーも作ることができる。要検証。

HogeId がない場合に throw HogeIdNotFoundException() をする。

---

## まとめ

String が Int に変換されたり、予想外のことが起こると
Kotlin は Exception を吐いてアプリが終了する。

しかし、予想外のことが起きそうな行を try の内部で書いて
catch で受け止めれば、アプリを終了せずに続行することができる。

一方、握りつぶしたところでその処理は行われない。データの不整合などが起きると困るので、catch の中には stacktrace を出すようにして後でログで確認できるようにしよう！

また、Usecase で条件に応じて IllegalStateException や IllegalArgumentException を throw すれば、まずいものが入る前にアプリを終了するようにできる。

さらに、Runtime Exception は拡張できるので、自分のオリジナルの Exception を作るとエラーログが追いやすくなるだろう。