teleren/devto huggingface dataset:
Как не быть мудаком, и польза дискуссии
Published: 2022-06-09 06:31:56

Пришёл на работу поработал часок поставил компилировать приложении, налил напиток и готов писать.
Сегодня закончил слушать книгу **Не работайте с мудаками**, и я понял, что книга написана обо мне, ведь я тоже  в предыдущих работах  встречал таких людей, и к сожалению пришлось поработать с ними, они конечно вынесут вам мозг по полной, я полностью согласен с автором книги Робертом  Саттоном и  как он описывает их  “мудаки”. Самый опасный момент наступает тогда, когда такие люди получают должность повыше и топчет  своих подчиненных. Такие люди не дадут компании развиваться, потому что все в окружении такого начальника будут замкнуты и не будут проявлять инициативы и выдвигать свои новые идеи к публике. Ещё есть интересный пример в этой книге: 

> «соучредитель и бывший CEO Intel Энди Гроув, который, как мне кажется, очень упрямый человек, любитель поспорить. Но Гроув знаменит тем, что всегда придерживается фактов и готов пригласить любого – начиная от новичков-программистов и стэнфордских студентов, которых он учит бизнес-стратегии, и заканчивая топ-менеджерами своей компании, – чтобы оспорить свои новые идеи. Для Гроува целью является поиск истины, а не желание «поставить работника на место»


А теперь барабанная дробь, я так же ввиду дела своей хоть и маленькой фирмы дела, я с семью так же веду дискуссию, там где мне кажется что нужно что то оспорить, я спорю, привожу примеры, если нужно звоню, уточняю, зову людей для решения задач, но всегда стараюсь вести дискуссию в любой момент, когда или я или мои родные нуждаемся в дискуссии чтобы добить вопрос. Мне важна сам ответ, истина, почему мои взгляды или то, что я считаю абсолютно правильным, для моего отца или для моих родных кажутся неверным решением, что привело их к этому выводу, спорю и пытаюсь всегда держать планку, не повышать голос, не перебивать собеседника и дать ему понять, что я веду дружескую дискуссию а не хочу поставить его на место и показать свою правоту. 

И каждый раз убеждаюсь, что дискуссия если она не переходит в личности и не перегибать палку, то даёт обеим сторонам только большие плюсы. Я люблю спорить с отцом, потому что он прожил больше меня и каждый раз я получаю от него разные жизненные истории и понимаю, что если я сделаю так же то получится вот так, оказывается вот так нельзя делать. 

Раньше, я думал в большинстве случаев, моя точка зрения верна, потому что : что # видел мой собеседник, который стоит передо мной?  :и что видел я. Да, кажись, я тоже был мудаком, работая с ними адаптировался так сказать)). Но стоило мне поменять формулировку от: да что он знает? на: а может он знает истину? ведь не зря спорит. И  я начал узнавать людей с других сторон и начал замечать таких людей все больше и больше.

**Всем добра и продуктивного дня**, и желаю, чтобы мы сами и окружающие наши люди не были мудаками, а наши дискуссии приносили только положительные плюсы.
Restore IP Addresses
Tags: leetcode, dsa, theabbie
Published: 2022-06-09 06:30:40

A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros.

*   For example, `"0.1.2.201"` and `"192.168.1.1"` are **valid** IP addresses, but `"0.011.255.245"`, `"192.168.1.312"` and `"192.168@1.1"` are **invalid** IP addresses.

Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order.

**Example 1:**

**Input:** s = "25525511135"
**Output:** \["255.255.11.135","255.255.111.35"\]

**Example 2:**

**Input:** s = "0000"
**Output:** \["0.0.0.0"\]

**Example 3:**

**Input:** s = "101023"
**Output:** \["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"\]

**Constraints:**

*   `1 <= s.length <= 20`
*   `s` consists of digits only.

**SOLUTION:**

    class Solution:
        def isValidChunk(self, s):
            if len(s) > 1 and s[0] == "0":
                return False
            if int(s) < 0 or int(s) > 255:
                return False
            return True
        
        def getAddress(self, s, curr, i, n):
            op = []
            if len(curr) == 4 and i == n:
                return [curr]
            for j in range(i + 1, n + 1):
                chunk = s[i:j]
                if self.isValidChunk(chunk):
                    val = self.getAddress(s, curr + [chunk], j, n)
                    op.extend(val)
            return op
        
        def restoreIpAddresses(self, s: str) -> List[str]:
            val = self.getAddress(s, [], 0, len(s))
            return [".".join(v) for v in val]
Web App - EDU
Tags: codepen
Published: 2022-06-09 06:01:34

{% codepen https://codepen.io/mazdevelop100/pen/PoZrRBx %}

Hello friends,
I selected a sketch of the https://dribbble.com site and implemented it in a completely responsive way with HTML, SCSS, JS. I want to ask for your opinion about my performance.
Overview of the Plan :
 https://lnkd.in/d82VdKs 
Thanks for the very good design Outcrowd. Design Agency
Demo Codepen:
 https://lnkd.in/dRQ-pYw  
Github:
 https://lnkd.in/dcJazrR
Relative Sort Array
Tags: leetcode, dsa, theabbie
Published: 2022-06-09 06:00:48

Given two arrays `arr1` and `arr2`, the elements of `arr2` are distinct, and all elements in `arr2` are also in `arr1`.

Sort the elements of `arr1` such that the relative ordering of items in `arr1` are the same as in `arr2`. Elements that do not appear in `arr2` should be placed at the end of `arr1` in **ascending** order.

**Example 1:**

**Input:** arr1 = \[2,3,1,3,2,4,6,7,9,2,19\], arr2 = \[2,1,4,3,9,6\]
**Output:** \[2,2,2,1,4,3,3,9,6,7,19\]

**Example 2:**

**Input:** arr1 = \[28,6,22,8,44,17\], arr2 = \[22,28,8,6\]
**Output:** \[22,28,8,6,17,44\]

**Constraints:**

*   `1 <= arr1.length, arr2.length <= 1000`
*   `0 <= arr1[i], arr2[i] <= 1000`
*   All the elements of `arr2` are **distinct**.
*   Each `arr2[i]` is in `arr1`.

**SOLUTION:**

    class Solution:
        def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
            arr2index = {}
            for i, a in enumerate(arr2):
                arr2index[a] = i
            return sorted(arr1, key = lambda x: (arr2index[x], arr2index[x]) if x in arr2index else (float('inf'), x))
How to redirect traffic from a domain to sub subdomain using AWS S3 and Route 53.
Published: 2022-06-09 05:53:57

---
title: How to redirect traffic from a domain to sub subdomain using AWS S3 and Route 53.
published: true
description: 
tags: 
//cover_image: https://direct_url_to_image.jpg
---
**Scenario :**

You want to redirect traffic from your main domain to a subdomain.
From the  [AWS documentation](https://aws.amazon.com/premiumsupport/knowledge-center/route-53-redirect-to-another-domain/), its:
Apex domain (example.com) to subdomain (www.anydomain.com), including www.example.com.

In my case I want to redirect traffic from getkinetic.co to subdomain schools.getkinetic.co.

schools.getkinetic.co points to a landing page with HTTPS protocol. 

**Prerequisites :**
Your Domain Name Service is Route 53 with a hosted zone 
You already have an SSL certificate from ACM or any other certificate authority 


**Steps :**

1.Create an s3 bucket with a globally unique name.Once created go to properties as shown:
Scenario :
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uvtwbktm18nietl0zzcq.png)
Note that the region is North Virginia 
2.Scroll to the bottom where it  is written static web hosting  as shown : 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hx3q8coh24qph6fdieqb.png)
3.Click edit and you will see Static website hosting disabled by default. Click enable.
4.You will now see a new section: Hosting type with two options: *1.Host a static website* 
         *2.Redirect requests for an object.* 

5.Choose the redirect requests for an object. This is because we are not hosting a new website but redirecting traffic to another domain. 
6.Once you have chosen the redirect requests for an object, enter in the host name the target domain as shown :
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rovjq9j57lc0pnvj4smy.png)
 
7.For protocol choose HTTPS.
8.Click save changes.
9.Next got to your hosted zone on Route 53 and click a create record 
10. To configure the record :
      *Record name - leave the text box empty as we want to      
      redirect to the apex domain.*
      *Record type is Type A : 
      Route traffic to: enable alias and choose Alias to S3 
      website endpoint, choose the region where your s3  
      bucket is situated*, mine was in US East (N. Virginia) 
      us-east-1, on the next drop-down you will find the 
      bucket you created. See screen shot below:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k53xi1dt4aynvaba91g0.png)
 11.Click save and you are all set!
How to debug errors in Javascript as a newbie
Tags: webdev, beginners, javascript, codenewbie
Published: 2022-06-09 05:35:11

I spent hours debugging my javascript code yesterday and I wanted to share with you what to do so you do not spend the same amount of time for a very simple problem.


1. **Using your browser** -  When debugging for frontend app use the console tab on your browser inspect option, to get here you can right click on an open page in your browser, click on inspect and then look for console, then refresh the tab open and see what errors it drops. 

2. **Look for the red line** - Don't take the error exactly for what it says or the line it tells you the error is coming from, read the code and look for the line where the error is coming from. Sometimes error messages are misleading and would lead you to going to google and trying what might not be the solution to your error, Make sure you know the line of code the error is coming from. 


I hope this guide can help when you are trying to find bugs in your Javascript code next time, Thank you for reading this.
Dungeon Game
Tags: leetcode, dsa, theabbie
Published: 2022-06-09 05:30:37

The demons had captured the princess and imprisoned her in **the bottom-right corner** of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in **the top-left room** and must fight his way through `dungeon` to rescue the princess.

The knight has an initial health point represented by a positive integer. If at any point his health point drops to `0` or below, he dies immediately.

Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).

To reach the princess as quickly as possible, the knight decides to move only **rightward** or **downward** in each step.

Return _the knight's minimum initial health so that he can rescue the princess_.

**Note** that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/03/13/dungeon-grid-1.jpg)

**Input:** dungeon = \[\[-2,-3,3\],\[-5,-10,1\],\[10,30,-5\]\]
**Output:** 7
**Explanation:** The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.

**Example 2:**

**Input:** dungeon = \[\[0\]\]
**Output:** 1

**Constraints:**

*   `m == dungeon.length`
*   `n == dungeon[i].length`
*   `1 <= m, n <= 200`
*   `-1000 <= dungeon[i][j] <= 1000`

**SOLUTION:**

    class Solution:
        def calcMin(self, dungeon, x, y, m, n):
            if (x, y) in self.cache:
                return self.cache[(x, y)]
            if (x, y) == (m - 1, n - 1):
                self.cache[(x, y)] = max(1, 1 - dungeon[m - 1][n - 1])
                return self.cache[(x, y)]
            right = float('inf')
            bottom = float('inf')
            if y < n - 1:
                right = self.calcMin(dungeon, x, y + 1, m, n)
            if x < m - 1:
                bottom = self.calcMin(dungeon, x + 1, y, m, n)
            currMin = min(right, bottom)
            self.cache[(x, y)] = max(1, currMin - dungeon[x][y])
            return self.cache[(x, y)]
        
        def calculateMinimumHP(self, dungeon):
            self.cache = {}
            return self.calcMin(dungeon, 0, 0, len(dungeon), len(dungeon[0]))
LocalStorage wrapper service in Angular
Tags: webdev, typescript, angular, tutorial
Published: 2022-06-09 05:22:05

Browser [Storage](https://developer.mozilla.org/en-US/docs/Web/API/Storage) is accessible in browser platform only, and it is just one way to cache in browser. Thus we should avoid accessing it directly in code, wrapping it with internal service, allows us to control it, or even replace it. In this post, let us create a Storage Service in Angular, and organize it to better control what goes into localStorage.

The benefits we want to cover:

- Protect direct access to a web class, that could change in the future
- Allow different implementations. Here is a short read about [Browser storage limits and eviction criteria](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria), to get you dreaming about other solutions
- Allow different server platform implementation
- Unify naming for better debugging
- Control expiration and force reset of cache

### The service

The basic service is a wrapper of the window localStorage, looks too innocent, but we will build on top of it as we go along.

Continue reading on [Sekrab Garage](https://garage.sekrab.com/posts/localstorage-wrapper-service-in-angular).

{% embed https://garage.sekrab.com/posts/localstorage-wrapper-service-in-angular %}

### RESOURCES
-   [Browser storage limits and eviction criteria](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria)
-   [StackBlitz project](https://stackblitz.com/edit/angular-localstroage)
-   [Balance User Experience and Security to Retain Customers](https://auth0.com/blog/balance-user-experience-and-security-to-retain-customers/)

### RELATED POSTS

-   [Loading external configurations in Angular Universal](https://garage.sekrab.com/posts/loading-external-configurations-in-angular-universal)

-   [Catching and handling errors in Angular](https://garage.sekrab.com/posts/catching-and-handling-errors-in-angular)
Docker series (Part 6): Docker Networking Basics
Tags: docker
Published: 2022-06-09 05:06:30

Actually, containers need to use bridge which generally has a different IP address . These containers go through these bridge and then passes the firewall to the port.

when we create a container, we publish the container using -p

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uwxes5y1rdjujx91b6wu.png)
SO, if you check your devices IP address & this containers IP address, you will see that they are not same. Because the container is passing through a bridge which has its own IP address.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dll1t7i2ud1zcs9ckreo.png)
SO, this is the IP address of the bridge . The bridge is a medium through your devices firewall.

For this container, this is how it might look 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c80ze79c2k8c1cssweie.png)
Any traffic coming from port 80 passes through this IP and then go to the container.

Also, if you set another container with the same bridge, the containers then can contact each other.


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

So, that was it!

<img src="https://c.tenor.com/Tvd3VKwtse0AAAAC/cat-cute.gif">
Smooth Scroll on Mobile
Tags: webdev, performance
Published: 2022-06-09 01:37:33

## The Problem

Smooth scrolling on mobile devices is key to good user experience, though I think we all have experienced delayed or blocked scrolling behaviors.  

## The Cause

Event handlers may call `preventDefault()` to cancel default behaviours. In our case, the browser does not know if `preventDefault()` will be called before the touch handler finishes executing. So **it waits for the handler to finish** before triggering the scroll which is why we experience the delay.
 
## The Solution

Fortunately this can be avoided by setting the **passive** option of relevant event listeners to **true** like this:

```js
document.addEventListener(“touchstart”, handler, {passive: true})
```


To solve the problem, we need to tell the browser beforehand that the scroll will not be cancelled so that **it does not wait for the handler to finish running**. And this is exactly what `passive: true` does.

## Notes

### Default Value

According to [mdn](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#parameters),

> If not specified, defaults to false – except that in browsers other than Safari and Internet Explorer, defaults to true for the wheel, mousewheel, touchstart and touchmove events.

There are two takeaways here:

- On modern browsers like Chrome (version 56 or later), 
```js
document.addEventListener(“touchstart”, handler)
```
is equal to
```js
document.addEventListener(“touchstart”, handler, {passive: true})
```
- `passive: true` is only applied to handlers for these events: `wheel`, `mousewheel`, `touchstart` and `touchmove`.

### Prevent Scrolling

In some cases where we DO want to prevent scrolling (e.g. Google Map or other interactive iframes), we can easily cancel it by setting the following in CSS:

```
touch-action: none;
```

---

### References

- [https://developer.chrome.com/blog/scrolling-intervention/](https://developer.chrome.com/blog/scrolling-intervention/)
- [https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#parameters](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#parameters)
Dissertation Help
Tags: dissertationhelp, assignmenthelp
Published: 2022-06-09 04:46:32

**[Dissertation Help](https://www.instantassignmenthelp.com/dissertation-help)** in UK catered by Instant Assignment Help gives students the perfect support in preparing well-documented, formatted, and researched dissertations that are perfect for scoring exceptional grades while leaving an excellent impression upon professors. Plus, these dissertation writing services are available at a pocket-friendly price.
Detect your leaking API endpoints
Published: 2022-06-09 04:42:29

The purpose of this article is to show AppSec/developers how to get started with API security scanning tool EthicalCheck and detect your leaking APIs.
Why API leaks are a common problem. Most web and mobile are security tested at some point but APIs hardly get any attention. This means you may have leaking APIs that are live and in production.
Detecting your leaking API endpoints is very simple if you’re using the free tool. All you need is your API OpenAPI Specification/Swagger URL and get instant report.
EthicalCheck - Visit the GitHub page to run your free scan: https://apisec-inc.github.io/pentest/
Nested To HTML Entities
Tags: laravel, php, helper
Published: 2022-06-09 04:31:06

A quick one:

```php
<?php 

if(! function_exists('to_htmlentities'))
{
    function to_htmlentities(array $data)
    {
        return collect($data)
            ->map(function($value) {
                if(is_string($value)) {
                    return htmlentities($value);
                }

                if(is_array($value)) {
                    return to_htmlentities($value);
                }

                return $value;
            })
            ->toArray();
    }
}
```

Usage:

```php
$data = [
    "<script>alert('hi')</script>",
    [
        "<script>alert('hello')</script>",
    ]
];

$data = to_htmlentities($data);
```

This piece of code simply handle all text in array, including the nested one.
How to Sort an Array of 0s, 1s, and 2s in Java
Tags: array, java, algorithms
Published: 2022-06-09 04:03:14

Given an array A[] of 0s, 1s, and 2s of size N, the task is to write a function that can sort an array of 0s, 1s, and 2s in ascending order such that 0s are in the beginning followed by all 1s and then 2s at the end, and without using any internal or inbuilt sorting function or library.

## Examples
`Input: {0, 1, 2, 0, 1, 2}
Output: {0, 0, 1, 1, 2, 2}
Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}
Output: {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2}`

Well, there is no denying that that might be many approaches through which we can sort an array of 0s, 1s, and 2s, but in this blog, we will only see 3 approaches that we think were the best and the easiest among all other approaches.

Let’s start…

## Index

1. The Brute Force Approach
2. The Counting Approach
3. The Three Pointer Approach — Dutch National Flag Approach

## The Brute Force Approach
In this approach, we are going to compare each number of the array with the one next to it while traversing the array from left to right. We can do this by using a nested loop system in which the outer loop will keep a track of the number and the inner loop will compare it with the rest of the elements of the array.

## Algorithm

1. Use two loops for i and j=i+1 elements
2. Compare them to see if the ith element is bigger than the jth element
3. If yes, swap their position so that the smaller element comes first as we have to arrange the elements in ascending order.
4. Print the array

## Pseudo Code
```
for(i=0 -> N)
{
   for(j=i+1 -> N)
   {
      if(A[i] > A[j])
      {
         Swap(A[i], A[j])
      }
   }
}
Print A
```

```
package com.Tekolio.Arrays;
  
import java.util.Arrays;
  
public class Sort_0s_1s_2s {
    public static void main(String[] args) {
        int[] A = {0, 1, 2, 0, 1, 2};
        int n = A.length;
        for(int i=0; i<n; i++) {
            for(int j=i+1; j<n; j++) {
                if(A[i] > A[j]) {
                    int temp = A[i];
                    A[i] = A[j];
                    A[j] = temp;
                }
            }
        }
        System.out.print(Arrays.toString(A));
    }
}
```

## Output
A[] = [0, 0, 1, 1, 2, 2]

**Time Complexity** — O(N²) **Space Complexity**— O(1)

We all know the [time complexity](https://tekolio.com/time-complexity-of-algorithms-explained-with-examples/) of a sorting algorithm in N log N, but the above approach is taking the time complexity of N² which is even higher. Let’s see how we can optimize it to O)N).

[Continue Reading](https://tekolio.com/how-to-sort-an-array-of-0s-1s-and-2s/).