teleren/devto huggingface dataset:
BFE.dev #55. highlight keywords in HTML string
Tags: javascript
Published: 2020-11-06 15:05:41

> [BFE.dev](https://bigfrontend.dev) is like a LeetCode for Front End developers. I’m using it to practice my skills.

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


This article is about the coding problem [BFE.dev#55. highlight keywords in HTML string](https://bigfrontend.dev/problem/highlight-keywords-in-HTML-string)

## Analysis

The goal is to wrap keywords with `<em>`.

```js
highlightKeywords(
  'Hello FrontEnd Lovers', 
  ['Hello', 'Front', 'JavaScript']
)
// '<em>Hello</em> <em>Front</em>End Lovers'
```

Looks easy, just search for the keywords and replace them. But it is trickier when there are overlapping keywords

```js
highlightKeywords(
  'Hello FrontEnd Lovers', 
  ['Front', 'FrontEnd', 'JavaScript']
)
// 'Hello <em>FrontEnd</em> Lovers'
```

The idea I came up is like this.

1. when we find a keyword, say `'Front'` in above example, we keep track of the `start` and `end`.
2. we loop through the letters between them, and check if there is new word matched. If matched we extend the `end` if needed, this is in case there are some keywords like `ontE`. 
3. stop when `end` is met. The substring between `start` and `end` should be highlighted.

Above logic handles overlapping, what about adjacent case ? 

```js
highlightKeywords(
  'Hello FrontEnd Lovers', 
  ['Front', 'End', 'JavaScript']
)
// 'Hello <em>FrontEnd</em> Lovers'
```

For this case, we could actually repeatedly search for the intervals from above logic, and group them up.

## Show me the code

First we solve a sub problem:

> Given a start index, return the end index of highlighting substring.
> If not found, return -1.

We could follow the steps explained above to get the following code.

```js
const keywordSet = new Set(keywords)

// return -1 if non-existing
const getEndForEm = (start) => {
  let isEmFound = false
  let end = start

  // extend end if new keywords are matched.
  while (start <= end) {
    for (let word of keywordSet) {
      const length = word.length
      if (html.slice(start, start + length) === word) {
        isEmFound = true
        end = Math.max(end, start + length - 1)
      }
    }

    start += 1
  }

  return isEmFound ? end : -1
}
```

Now things become easier, we could just loop through all the indexes, and repeatedly call above function to get the `real` end index to highlight.

```js
let result = ''

for (let i = 0; i < html.length;) {
  let endForEm = getEndForEm(i)
  
  // check if there is adjacent keyword 
  while (endForEm > -1) {
    const nextEndForEm = getEndForEm(endForEm + 1)
    if (nextEndForEm === -1) {
      break
    }
    endForEm = nextEndForEm
  }
  
  if (endForEm > -1) {
    result += '<em>' + html.slice(i, endForEm + 1) + '</em>'
    i = endForEm + 1
  } else {
    result += html[i]
    i += 1
  }
}

return result
```

## Passed

This is an interesting problem.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/z0wt2867f4anb5g026oj.gif)

Hope it helps, you can have a try at [here](https://bigfrontend.dev/problem/highlight-keywords-in-HTML-string)
🐳 Limit docker logs size
Tags: docker, monitoring, tips, todayilearned
Published: 2020-11-06 14:49:29

Hello! The other day I got an alert on one server. The disk space was almost full, even though there is just a simple app controlled by a docker-compose.

It turned out one of the application was ElasticSearch, and the log file size of this container was... 10G.

So I had to find a way to remove and rotate the logs of this container.

Adding this part to the `docker-compose.yml`:

```yml
version: '3'
services:
    app:
        ...
        logging:
            driver: "json-file"
            options:
                max-size: "100m"
                max-file: "10"
```

You can control how docker will deal with the logs: choose a log driver, the max size of the log file, and the number of files. Pretty convenient!

The official documentation here: https://docs.docker.com/compose/compose-file/#/logging


**Note:** You can directly configure the logs at the docker daemon level. Checkout out here: https://docs.docker.com/config/containers/logging/configure/#configure-the-default-logging-driver


### To get further

Limit the log size on the system is great, but the best is to send the logs to a logs aggregator such as Loki or Elasticsearch!
Ethical Debt, we all have it. Now what?
Tags: debt, ethical, development, startup
Published: 2020-11-06 14:39:35

---
title: Ethical Debt, we all have it. Now what?
published: true
description: Ethical debt is also building up in our tech companies.
tags: debt, ethical, development, startup 
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/lybc1xskqp3zace3gh2n.png
---
As this election season ends like a very awkward date with that kid you had a crush on in High School, there will be many retrospectives. Twitter and Facebook both handled this final hour very differently. What does that mean for the future of the platforms and democracy? These are questions we all should be asking on repeat.

But the reality is tech culture itself encourages ethical debt by reinforcing the grind and grow mentality. While also supporting the power structures implemented by the founding fathers of this country.

Just like now, the 1700s were years of knowledge-sharing and fast growth. Ethical questions regarding diversity are brought up frequently at the beginning of this era's democratic beginning. Questions set aside in the wake of ambitious men, white men like George Washington and Thomas Jefferson. They ultimately kept their resource theft side-gig. Landowners whose decisions kept slavery and inequality around by controlling the founding of this country. Decisions we are still paying for in black lives and tight elections with the racist landowners of our season.

**But Ethical debt is just like Technical debt or laundry; nobody wants to acknowledge and face the pile in the corner.** 

It's more fun and exciting to build and reap the reward than to review or remove things from the stack. It's hard to accept the cycle of creation and death in any endeavor.

But the truth is that the virtual realm is just getting more significant in daily life. These problems, like angles just a few degrees apart, only grow with time and influence.

Suppose you are a startup just getting started. Be aware that someday you may pay the price for your teams' lack of diversity and pay equity. Either directly with the individuals, you harm. Or more likely, through what is hiding in your code, ready pounce and cause a public relations nightmare.

Diversity is a lens that opens up the world. It's like that bigger screen with smaller pixels. You don't see the problems that will take your company down because you refuse to see the people you are harming. *But if you accept the cycle and both diversify your team and your process.* You become part of the solution and put yourself ahead of the field.

The outcry for tech companies to deal with ethical debt is only going to grow from here. **What story will the future say about you and the choices you made today?**

<span>Photo by <a href="https://unsplash.com/@dylandgillis?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Dylan Gillis</a> on <a href="https://unsplash.com/s/photos/debt?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>
Pomodoro
Tags: learning, notes, aprendendo, anotacoes
Published: 2020-11-06 14:36:29

---
title: Pomodoro
published: true
description: Com o objetivo de reter mais conhecimento e informação sobre o que estou estudando, estou criando o hábito de fazer anotações e, pretendo compartilhar por aqui os tópicos que eu anotar.
tags: #learning, #notes, #aprendendo, #anotacoes
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/lw6lchup0hxx1ht3ure4.jpeg
---

A Técnica Pomodoro é um método de gerenciamento de tempo. 

Foi desenvolvida por Francesco Cirillo por volta de 1980.

### Explicação

E técnica consiste em focar totalmente em algum objetivo durante um determinado período de tempo (25 minutos) e, fazer uma pausa estratégica para descanso (5 minutos).

A ideia é recompensar o esforço do cérebro pelo período de foco exercido pelo tempo estipulado, bem como, planejar um período específico de pausa, evitando a procrastinação.

### Exemplo de uso:

**Planejamento:**

Faça uma lista com as tarefas que você precisa fazer durante o dia.

**Definição de tempo e descanso:**

1. Definir um tempo de trabalho focado (recomenda-se 25 minutos);
2. Definir um tempo de descanso (recomenda-se de 3 a 5 minutos);

**Começar:**

1. Ativar o cronômetro;
2. Trabalhar totalmente focado na primeira tarefa da lista, até o alarme tocar;
3. Quando o alarme tocar, fazer a pausa;
4. Depois da pausa, repetir o processo;

Importante dizer que, nem sempre (ou quase nunca) uma atividade vai ser iniciada e finalizada dentro do período exato de 25 minutos. A ideia é repetir o processo até terminar toda a atividade.

Outro ponto importante, é fazer uma pausa um pouco mais longa (10 a 30 minutos), depois de repetir o processo por umas 4 vezes. Nesse período maior de descanso, o cérebro pode assimilar o que foi feito durante o período de foco.

### Interrupções

Durante o período de foco, é possível que surjam interrupções e até mesmo pensamentos e ideias que possam te distrair e/ou atrapalhar o foco na atividade  atual. 

Para esses momentos, a ideia é ter um bloco de notas, onde toda e qualquer distração possa ser anotada. Com isso, você pode voltar o quanto antes para a resolução da atividade atual e, pode verificar o motivo das interrupções em um momento posterior.


#### Objetivo desse post

_Com o objetivo de reter mais conhecimento e informação sobre o que estou estudando, estou criando o hábito de fazer anotações e, pretendo compartilhar por aqui os tópicos que eu anotar._
Sử dụng console trong JS
Tags: javascript
Published: 2020-11-06 14:26:05

## console.log()

## console.error()

Dùng để in lỗi ra trình duyệt. Mặc định nó sẽ được highlight (tô màu đỏ)

## console.warn()

Có thể dùng để test code. Mặc định nó cũng được highlight như console.error. Tuy nhiên nó sẽ tô màu vàng.

## console.clear()

Xóa console và xuất ra message `Console was cleared`

## console.time() và console.timeEnd()

Được dùng kết hợp để đo thời gian. ví dụ

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/5sdlqvr6ytxthl9kg46c.png)

## console.table()

Dùng để in dữ liệu ra trình duyệt dưới dạng table.

## console.count()

Có thể dùng trong vòng lặp để kiểm tra xem 1 giá trị cụ thể được thực thi bao nhiêu lần

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

## console.group()

Được dùng để nhóm các nội dung trong 1 block (khối). Có thể mở rộng và thu gọn nhóm

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dkp6y7mv6u86w6o5u0h3.png)
Unresolved domain names while docker build
Tags: personaltips
Published: 2020-11-06 14:09:08

<sub><span>Photo by <a href="https://unsplash.com/@kylejglenn">Kyle Glenn</a> on <a href="https://unsplash.com/s/photos/note">Unsplash</a></span></sub>

What to do when you have *github.com or chocolatey.org cannot be resolved* when you try to do **docker build**.


Multiple possible course of action:

- use [--add-host](https://docs.docker.com/engine/reference/commandline/build/#add-entries-to-container-hosts-file---add-host) argument in the build to give resolution

- use  **--network "Default Switch"** argument, to specify to RUN commands which network to use

- add in dockerfile, for example:
```yaml
RUN echo 104.20.73.28 chocolatey.org >> "C:\Windows\System32\drivers\etc\hosts"
```
- set [DNS for IPv6](https://stackoverflow.com/questions/25022704/set-ipv6-dns-address-to-local-host-using-powershell)

Hope this helps !
My first lines of code in html and css
Tags: codenewbie, womenintech, 100daysofcode, css
Published: 2020-11-06 14:07:55

As a web designer, it is often frustrating not to build your projects and depend on a third party to bring your designs to life. The best way to remedy this was to learn how to code!

That's how I discovered the joy of syntax, spending hours trying to figure out why it doesn't work and realizing that the culprit was a typo !

More seriously, like any beginner developer, I started by learning html and css.

I found html quite simple to learn The lines of code, so impressive for a neophyte, become familiar quickly enough, once the syntax is acquired. In my opinion, the biggest challenge when writing html is to group the different elements together, not only to get the page organization we wanted, but also to ensure these groupings make sense and optimize our code, especially for css.

Depending on the needs, `<div>` will be used to group elements spatially, `<section>` for content sharing the same theme, `<article>` for standalone content, `<nav>` for the navigation bar, etc. We will then choose to assign these tags an "id" if they are unique, a "class" if they are recurrent. 

If html seems quite understandable, it can sometimes become a bit redundant and it only allows to display raw content, without layout. So we can't wait, especially as a designer, to have fun with CSS and make it all look nice and it's a cold shower!

Some aspects of css are quite obvious. I want to change my font: `font-family`, my background color: `background-color`, center my text: `text-align` and so on. But the difficulties started with flexbox. 

In theory, it looks pretty simple, but in real life, since a child's positioning also depends on his parent's, I spent a lot of time positioning my different elements (and I had big headaches too!). I got into fights with z-indexes and "absolute" positions. And all this little world had to keep on behaving well with the different screen sizes. For my landing page project, I didn't want to give up and stick to my design, I was pretty proud when I got there!

And finally, one of the most important, how to transmit information and documents between designers and developers so that designs are respected and developers don't waste time? I used to annotate my screens with pixels and rem to define the spaces and provide the list of typos and colors. 
I'm glad I now have the basis to realize how much work my design requires and I'm thinking about using more code terms. For example, indicate that this title is an `h1`, that it must be centered and have a margin of x rem at the top and bottom.

It's not the fun part for me to rigorously organize my designs, but it's really essential for the collaboration to go well and there's no frustration on either side.

I also discovered the world of web development and I find it a very stimulating environment: there is an incredible number of resources, articles, forums, networks. It's really a chance to evolve in such a dynamic environment!

And now, let's go to Javascript!

P.S: You can see my work [here](https://codepen.io/your-work)
❎❓Quiz: Web Performance #6
Tags: challenge, webperf, webdev, quiz
Published: 2020-11-06 14:04:09

As often, abbreviations are also used in Web Performance.

What does the abbreviation WPO stand for?

- World People Organization
- Web Performance Optimization
- Web Performance Organization
- Web Presidents Organization

---
<center>[Answer the question](https://marcradziwill.com/web-performance-quiz/what-does-the-abbreviation-wpo-stand-for/)</center>
---
❎❓Quiz: Web Performance #5
Tags: challenge, webperf, webdev, quiz
Published: 2020-11-06 14:04:03

What means "instant" to the user? Check out the quiz challenge for today.

In which range, does the user feels that the responses to his actions are instant?

- 0 – 300 ms
- 300 - 1000 ms
- 1000 ms
- 10s +

---
<center>[Answer the question](https://marcradziwill.com/web-performance-quiz/in-which-range-does-the-user-feels-that-the-responses-to-his-actions-are-instant/)</center>
---
❎❓Quiz: Web Performance #4
Tags: challenge, webperf, webdev, quiz
Published: 2020-11-06 14:02:57

Web Performance correlates with other topics. What is the answer to the question today?

- User experience and business success
- Number of coffees drunk and choice of milk
- Body weight and BMI

---
<center>[Answer the question](https://marcradziwill.com/web-performance-quiz/what-has-a-direct-correlation-with-web-performance/)</center>
---
❎❓Quiz: Web Performance #3
Tags: challenge, webperf, webdev, quiz
Published: 2020-11-06 14:02:46

Quiz time! How much faster should your site, in general, be compared to your fastest competitor?

- 40%
- 10%
- 20%
- 1%

---
<center>[Answer the question](https://marcradziwill.com/web-performance-quiz/how-much-faster-should-your-site-in-general-be-compared-to-your-fastest-competitor/)</center>
---
❎❓Quiz: Web Performance #2
Tags: challenge, webperf, webdev, quiz
Published: 2020-11-06 14:02:32

Did you have the correct result yesterday? Check out the question today:

What does web performance stand for?

- Ranking of key pages
- Load times, interaction timing, etc.
- Conversion rates of the website

---
<center>[Answer the question](https://marcradziwill.com/web-performance-quiz/what-does-web-performance-stand-for/)</center>
---
❎❓Quiz: Web Performance #1
Tags: challenge, webperf, webdev, quiz
Published: 2020-11-06 14:02:21

Today we start the web performance quiz with a simple but important question.

Who is solely responsible for web performance?

- Developers
- Anybody who ships. Developers, DevOps, SEO-Experts, Marketeers
- Product Owner
- Project Manager

---
<center>[Answer the question](https://marcradziwill.com/web-performance-quiz/who-is-solely-responsible-for-web-performance/)</center>
---
Neuron JS - BYE BYE EXPRESS!
Tags: javascript, node, express, neuronjs
Published: 2020-11-06 14:00:37

I recently made this small, open source framework called Neuron JS which is heavily inspired by Express, but just much much better. Neuron JS is much faster and much more lightweight than Express.js being only 5kb in size. It supports 4 different request methods, GET, POST, PUT and DELETE. For CRUD functionality and APIs you would only need these methods. I mean, come on who really uses HEAD and COPY and LINK. Neuron JS also supports all Express middlewares, which means that existing libraries and modules will work just fine. Neuron is also under development for Deno.js since Express is not made for Deno yet. Neuron comes with in-built template engine support. And last but not the least, it is MVC-based. Right now, I am also working on integrating native MongoDB just like Django has integrated SQLite support.

[Go to NPM](https://www.npmjs.com/package/@yummyweb/neuronjs) to install Neuron.
[Go to Neuron Docs](https://neuron-docs.vercel.app/) to see how to work with it.
[Go to Neuron JS GitHub](https://github.com/antriksh123/neuron-js) to check out the source code and file issues.
PMP certification exam is assumed to be difficult. 
Published: 2020-11-06 13:59:32

PMP is one of the more difficult projects management exams. However, it is also one of the most worthwhile and lucrative certifications IT pros looking to advance their careers can obtain. Comparing the PMP to other exams helps you get a better idea of just how difficult it is. We’ll start by comparing the PMP to three other project management exams: CAPM (Certified Associate in Project Management). CAPM is another project management certification from PMI. The CAPM is an associate-level certification and therefore is a little less difficult than the PMP exam. Any exam which is difficult to crack requires clarity of concepts given in the study materials and also by doing smart work. SPOTO will definitely be the best choice, I found tutor highly qualified and experts, and by studying their <a href="https://www.spoto.info/">PMP certification</a> test papers I felt confident about passing the exam.
My non-dev side project got me 700 subscribers & 4000+ traffic
Tags: sideprojects, lessons
Published: 2020-11-06 13:56:28

---
title: My non-dev side project got me 700 subscribers & 4000+ traffic
published: true
description: What I learnt from my side-project launch. Some things which I seemed to have done right that helped me get 700 subscribers and 4000+ traffic.
tags: sideproject, lessons
//cover_image: https://direct_url_to_image.jpg
---

Hey everyone,

As a non-techie turned techie turned entrepreneur, I like to write about my experiences. When I started sharing them with my friends, they seemed to like it (surprisingly :P).

##My effort
So, I started to do this more regularly and also in a more structured fashion. I put together a [quick website](https://2.flexiple.com/build-a-startup-in-6-months) and named these reports: "No-VC Reports".

Then, I wrote:
📃 An article
⏲️ Each week
🗓️ For 6 months

##The launch
After all that hard work, I launched it on Product Hunt, which got me:
📈 700+ new subscribers
👑 #5 Product of the day on @ProductHunt
🚦 ~4000 new users to the website

##Lessons
I am sure a lot of you work on side-projects. I just wanted to share what I learnt so that you can maybe imbibe it into your project launches too!

So, I have summarised it in my tweet thread. Do let me know in case of any question! Happy to answer them :).

{% twitter 1324696984456818689 %}
Fun Project for getting started with AI: Rekognition DetectText
Tags: aws, beginners, ai, machinelearning
Published: 2020-11-06 13:53:41


AWS offers a comprehensive set of services and APIs for Artificial Intelligence and Machine Learning.
What's awesome about this is that this set of services caters for both customers without ML skills and those looking for advanced functions.

I recently created an application that uses the [Rekognition](https://aws.amazon.com/rekognition/?blog-cards.sort-by=item.additionalFields.createdDate&blog-cards.sort-order=desc) *DetectText API*.
Rekognition offers Image and Video APIs. **The following Image APIs are available:**

    - Labels
    - Custom Labels
    - Content Moderation
    - Face Detection and Analysis
    - Face search and verification
    - Celebrity Recognition
    - Personal Protective Equipment (PPE) detection
    - Text detection 

I recently created what would be a back-end of an application that receives images which contain text. The back-end (Python) calls the Rekognition DetectText API which extracts the text, receives the extracted text and concatenates this text into a string. The string is then published to an SNS topic as a message where all those subscribed will receive this message.

***The Architecture Design of the solution***

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/9772apuhynvm8ihm8fuf.png)

> **SNS Topic:** Create a topic accordingly, with the relevant subscriptions

> **S3 Bucket:** Create an S3 bucket and grant the necessary  permission. 
> *If there needs to be public access, allow this through 
> the access control lists (ACLs), bucket policies, access point  policies, etc.*
> ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/bib0mdv9wwde13yl3kbt.png)

> **Lambda Function:** modify the Basic Lambda Execution role to  include the following policies *(in addition to the default policy assigned at role creation)*:
> ***AmazonRekognitionReadOnlyAccess***
  ***AmazonS3ReadOnlyAccess***
  ***AmazonSNSFullAccess***

> ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/eg9maomba2nstl517091.png)

> Lastly, include the following [resource-based policy](https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html), so that S3 can trigger the Lambda on *PutObject* of the image:

> ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gngyuig5at0ol7ppxvoc.png)


**The complete code** is available in [my github repository](https://github.com/veliswaan/rekognition-detect-text/tree/master) and the sample is as below:

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

***Conclusion***

I hope this gets you started on AWS AI if you haven't already - and that you find your own use cases that will have you build even more fun (or useful :)) AI applications.