teleren/devto huggingface dataset:
Find All K-Distant Indices in an Array
Tags: leetcode, dsa, theabbie
Published: 2022-06-12 14:30:41

You are given a **0-indexed** integer array `nums` and two integers `key` and `k`. A **k-distant index** is an index `i` of `nums` for which there exists at least one index `j` such that `|i - j| <= k` and `nums[j] == key`.

Return _a list of all k-distant indices sorted in **increasing order**_.

**Example 1:**

**Input:** nums = \[3,4,9,1,3,9,5\], key = 9, k = 1
**Output:** \[1,2,3,4,5,6\]
**Explanation:** Here, `nums[2] == key` and `nums[5] == key. - For index 0, |0 - 2| > k and |0 - 5| > k, so there is no j` where `|0 - j| <= k` and `nums[j] == key. Thus, 0 is not a k-distant index. - For index 1, |1 - 2| <= k and nums[2] == key, so 1 is a k-distant index. - For index 2, |2 - 2| <= k and nums[2] == key, so 2 is a k-distant index. - For index 3, |3 - 2| <= k and nums[2] == key, so 3 is a k-distant index. - For index 4, |4 - 5| <= k and nums[5] == key, so 4 is a k-distant index. - For index 5, |5 - 5| <= k and nums[5] == key, so 5 is a k-distant index. - For index 6, |6 - 5| <= k and nums[5] == key, so 6 is a k-distant index.`
Thus, we return \[1,2,3,4,5,6\] which is sorted in increasing order. 

**Example 2:**

**Input:** nums = \[2,2,2,2,2\], key = 2, k = 2
**Output:** \[0,1,2,3,4\]
**Explanation:** For all indices i in nums, there exists some index j such that |i - j| <= k and nums\[j\] == key, so every index is a k-distant index. 
Hence, we return \[0,1,2,3,4\].

**Constraints:**

*   `1 <= nums.length <= 1000`
*   `1 <= nums[i] <= 1000`
*   `key` is an integer from the array `nums`.
*   `1 <= k <= nums.length`

**SOLUTION:**

    class Solution:
        def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:
            n = len(nums)
            indices = set()
            for i, el in enumerate(nums):
                if el == key:
                    for j in range(max(i - k, 0), min(i + k + 1, n)):
                        indices.add(j)
            return sorted(indices)
great list of "cool" sites from hnews
Published: 2022-06-12 14:23:06

---
title: great list of "cool" sites from hnews
published: true
description: list of sites
tags: 
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

This thread is great https://news.ycombinator.com/item?id=31708366

Here is a list of some of the cool sites there are others:

https://geizhals.de/ - this is a german site but the UI is nice and you can find a lot of stuff.
https://www.gsmarena.com/search.php3? - a phone search site. When I was at https://crossbrowsertesting.com we used this site a lot
https://www.howacarworks.com/ - how a car works
https://www.mcmaster.com/ - the UI here is so nice. those illustrations
https://ciechanow.ski/mechanical-watch/ - how does a mechanical watch work?
https://ciechanow.ski/exposing-floating-point/ - floating point. all programmers should read this.
http://worrydream.com/
https://apolloinrealtime.org/ - this is amazing if you are a space nerd.

There is a lot more stuff on the thread
Largest Combination With Bitwise AND Greater Than Zero
Tags: leetcode, dsa, theabbie
Published: 2022-06-12 14:00:42

The **bitwise AND** of an array `nums` is the bitwise AND of all integers in `nums`.

*   For example, for `nums = [1, 5, 3]`, the bitwise AND is equal to `1 & 5 & 3 = 1`.
*   Also, for `nums = [7]`, the bitwise AND is `7`.

You are given an array of positive integers `candidates`. Evaluate the **bitwise AND** of every **combination** of numbers of `candidates`. Each number in `candidates` may only be used **once** in each combination.

Return _the size of the **largest** combination of_ `candidates` _with a bitwise AND **greater** than_ `0`.

**Example 1:**

**Input:** candidates = \[16,17,71,62,12,24,14\]
**Output:** 4
**Explanation:** The combination \[16,17,62,24\] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0.
The size of the combination is 4.
It can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0.
Note that more than one combination may have the largest size.
For example, the combination \[62,12,24,14\] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0.

**Example 2:**

**Input:** candidates = \[8,8\]
**Output:** 2
**Explanation:** The largest combination \[8,8\] has a bitwise AND of 8 & 8 = 8 > 0.
The size of the combination is 2, so we return 2.

**Constraints:**

*   `1 <= candidates.length <= 105`
*   `1 <= candidates[i] <= 107`

**SOLUTION:**

    class Solution:
        def largestCombination(self, candidates: List[int]) -> int:
            res = 0
            for i in range(32):
                l = 0
                for c in candidates:
                    if c & (1 << i):
                        l += 1
                res = max(res, l)
            return res
note about conda envs
Tags: python, conda
Published: 2022-06-12 13:59:42

---
title: note about conda envs
published: true
description: note about conda envs
tags: python, conda
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

I can never remember this for some reason ...

The command to list environments you have on disk
```
conda env list
```

The command to activate an environment
```
activate <envname>
```

I always set the PATH variable myself so those will only work if the anaconda directory and the anconda\Scripts directory on are on your PATH.
Day 15 - Units
Tags: 100daysofcode, solidity, web3, blockchain
Published: 2022-06-12 13:34:00

{% embed https://github.com/Envoy-VC/30-Days-of-Solidity noreadme %}

This is Day `15` of `30` in Solidity Series
Today I Learned About Units in Solidity.

In solidity we can use wei, gwei  or ether as a suffix to a literal to be used to convert various ether based denominations. Lowest unit is wei and 1e12 represents 1 x 10^12.

Similar to currency, Solidity has time units where lowest unit is second and we can use seconds, minutes, hours, days and weeks as suffix to denote time.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract MyUnits {
    // 1 wei == 1
    // 1 gwei == 1e9
    // 1 ether == 1e18
    uint256 costOfNFT = 12.5 ether;
    uint256 gasLimit = 3000 wei;

    //1 == 1 seconds
    //1 minutes == 60 seconds
    //1 hours == 60 minutes
    //1 days == 24 hours
    //1 weeks == 7 days

    uint256 durationOfMint = 7 days;
}
```

---
Search in Rotated Sorted Array
Tags: leetcode, dsa, theabbie
Published: 2022-06-12 13:30:37

There is an integer array `nums` sorted in ascending order (with **distinct** values).

Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`.

Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`.

You must write an algorithm with `O(log n)` runtime complexity.

**Example 1:**

**Input:** nums = \[4,5,6,7,0,1,2\], target = 0
**Output:** 4

**Example 2:**

**Input:** nums = \[4,5,6,7,0,1,2\], target = 3
**Output:** -1

**Example 3:**

**Input:** nums = \[1\], target = 0
**Output:** -1

**Constraints:**

*   `1 <= nums.length <= 5000`
*   `-104 <= nums[i] <= 104`
*   All values of `nums` are **unique**.
*   `nums` is an ascending array that is possibly rotated.
*   `-104 <= target <= 104`

**SOLUTION:**

    class Solution:
        def getPivot(self, nums):
            n = len(nums)
            beg = 0
            end = n
            while beg <= end:
                mid = (beg + end) // 2
                if mid < n - 1 and nums[mid] > nums[mid + 1]:
                    return mid + 1
                if beg >= end - 1:
                    return 0
                elif nums[mid] > nums[0]:
                    beg = mid
                else:
                    end = mid
                    
        def binarySearch(self, nums, beg, end, target):
            while beg <= end:
                mid = (beg + end) // 2
                if mid >= end:
                    break
                elif nums[mid] == target:
                    return mid
                elif beg == end:
                    break
                elif nums[mid] > target:
                    end = mid
                else:
                    beg = mid + 1
            return -1
        
        def search(self, nums: List[int], target: int) -> int:
            n = len(nums)
            k = self.getPivot(nums)
            left = self.binarySearch(nums, 0, k, target)
            if left != -1:
                return left
            right = self.binarySearch(nums, k, n, target)
            if right != -1:
                return right
            return -1
Tips for New Programmers. 1. Read Documentation (Add yours)
Tags: beginners, programming, codenewbie, discuss
Published: 2022-06-12 13:28:56


![Doc](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6hhom911qw57495e9266.gif)

**Yes! Read the Docs**

It might looks pretty boring but you'll be saving yourself a lot of heartache.☺️

- What's your Tip for a Coding Newbie?

- What have you learnt that you've been doing wrong?

- What would you change if you were starting afresh?

Please leave a **comment**.🤭🤭
Count the Hidden Sequences
Tags: leetcode, dsa, theabbie
Published: 2022-06-12 13:00:42

You are given a **0-indexed** array of `n` integers `differences`, which describes the **differences** between each pair of **consecutive** integers of a **hidden** sequence of length `(n + 1)`. More formally, call the hidden sequence `hidden`, then we have that `differences[i] = hidden[i + 1] - hidden[i]`.

You are further given two integers `lower` and `upper` that describe the **inclusive** range of values `[lower, upper]` that the hidden sequence can contain.

*   For example, given `differences = [1, -3, 4]`, `lower = 1`, `upper = 6`, the hidden sequence is a sequence of length `4` whose elements are in between `1` and `6` (**inclusive**).
    *   `[3, 4, 1, 5]` and `[4, 5, 2, 6]` are possible hidden sequences.
    *   `[5, 6, 3, 7]` is not possible since it contains an element greater than `6`.
    *   `[1, 2, 3, 4]` is not possible since the differences are not correct.

Return _the number of **possible** hidden sequences there are._ If there are no possible sequences, return `0`.

**Example 1:**

**Input:** differences = \[1,-3,4\], lower = 1, upper = 6
**Output:** 2
**Explanation:** The possible hidden sequences are:
- \[3, 4, 1, 5\]
- \[4, 5, 2, 6\]
Thus, we return 2.

**Example 2:**

**Input:** differences = \[3,-4,5,1,-2\], lower = -4, upper = 5
**Output:** 4
**Explanation:** The possible hidden sequences are:
- \[-3, 0, -4, 1, 2, 0\]
- \[-2, 1, -3, 2, 3, 1\]
- \[-1, 2, -2, 3, 4, 2\]
- \[0, 3, -1, 4, 5, 3\]
Thus, we return 4.

**Example 3:**

**Input:** differences = \[4,-7,2\], lower = 3, upper = 6
**Output:** 0
**Explanation:** There are no possible hidden sequences. Thus, we return 0.

**Constraints:**

*   `n == differences.length`
*   `1 <= n <= 105`
*   `-105 <= differences[i] <= 105`
*   `-105 <= lower <= upper <= 105`

**SOLUTION:**

    class Solution:
        def numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int:
            pos = [0]
            for d in differences:
                pos.append(pos[-1] + d)
            least = min(pos)
            pos = [p + lower - least for p in pos]
            return max(upper - max(pos) + 1, 0)
Gray Code
Tags: leetcode, dsa, theabbie
Published: 2022-06-12 12:30:40

An **n-bit gray code sequence** is a sequence of `2n` integers where:

*   Every integer is in the **inclusive** range `[0, 2n - 1]`,
*   The first integer is `0`,
*   An integer appears **no more than once** in the sequence,
*   The binary representation of every pair of **adjacent** integers differs by **exactly one bit**, and
*   The binary representation of the **first** and **last** integers differs by **exactly one bit**.

Given an integer `n`, return _any valid **n-bit gray code sequence**_.

**Example 1:**

**Input:** n = 2
**Output:** \[0,1,3,2\]
**Explanation:**
The binary representation of \[0,1,3,2\] is \[00,01,11,10\].
- 00 and 01 differ by one bit
- 01 and 11 differ by one bit
- 11 and 10 differ by one bit
- 10 and 00 differ by one bit
\[0,2,3,1\] is also a valid gray code sequence, whose binary representation is \[00,10,11,01\].
- 00 and 10 differ by one bit
- 10 and 11 differ by one bit
- 11 and 01 differ by one bit
- 01 and 00 differ by one bit

**Example 2:**

**Input:** n = 1
**Output:** \[0,1\]

**Constraints:**

*   `1 <= n <= 16`

**SOLUTION:**

    class Solution:
        def grayCode(self, n: int) -> List[int]:
            if n == 1:
                return [0, 1]
            prev = self.grayCode(n - 1)
            k = 1 << (n - 1)
            return prev + [prev[i] + k for i in range(k - 1, -1, -1)]
UI\UX Developer / HTML / UI / Frontend Developer | Remote Links are given in comment.
Tags: javascript, programming, html, css
Published: 2022-06-12 12:27:17



**SR NO - 0024 UI\UX Developer - Analyst Role.**
Skill : Proficiency in HTML5, CSS3, JavaScript, jQuery, and Angular for rapid prototyping and UI screen development.
Location : Bangalore
Experience : 2 Year

**SR NO - 0025 Frontend Developer - HTML / CSS / Bootstrap / JS / CodeIgnitor**
Skill : Build responsive website UI optimized for different screen sizes
Experience : 3 Year
Location : Bangalore

**SR NO - 0026 UI/UX Developer**
Skill :  HTML CSS Bootstrap Photoshop , Photoshop (psd) to HTML Conversion 
Location : Chennai
Experience : 2 Year

**SR NO - 0027 HTML Developer**
Skill :  Proficient understanding of web markup, including HTML5 and CSS3
Location : Bangalore
Experience : 1 Year

**SR NO - 0028 HTML Developer**
Skill :  Proficient understanding of web markup, including HTML5 and CSS3, Basic understanding of server-side CSS pre-processing platforms, such as LESS and SASS
Experience : 1 Year
Location : Baner, Pune, Maharashtra

**SR NO - 0029 Ui / Ux Developer**
Skill :  Html/Css/Javascript/Jquery
Experience : 1 Year
Location : Bangalore

**SR NO - 0030 UI/UX Developer**
Skill :  Good Knowledge of HTML5, CSS3,Bootstrap,Photoshop, Adobe XD, PrimeNg, JavaScript, TypeScript, Angular
Experience : 1 Year
Location : Vijayawada

**SR NO - 0031 UI/UX Developer**
Skill :  We’re looking for a UI/UX developer who will take a key role on our team. Our UX developer will be responsible for conducting user research, creating wireframes and designs, and ultimately aligning user behavior to actions that drive results.
Experience : 1 Year
Location : Kolkata, India, Asia/Pacific

**SR NO - 0032 Web Designer**
Skill :  Create quality HTML5, CSS3, JS UI, ensuring high-quality graphic standards and brand consistency.
Experience : 3 Year
Location : Kānpur

**SR NO - 0033 Frontend Developer**
Skill :  Java Script, OOPS Concept, HTML, CSS, AngularJS, 
Experience : 1-2 years
Location : Remote



**Note :** 
1. We are not associated with any company , consultancy , recruitment firm. Just sharing vacancies to help to get job for Web Developers.
2. Check comments for details.
[a newbie on its journey to learn about web 3] notes about web 3.0
Tags: web3, braziliandevs
Published: 2022-06-12 12:05:30

---
title: [a newbie on its journey to learn about web 3] notes about web 3.0
published: true
description: Notes about web3
tags: web3, braziliandevs
---

Web 3 is an idea, an ideia of a decentralized web, where it’s users are no longer clients - clients of the “big techs” (facebook, google, youtube etc) - but owners of their own data. This goes in the extreme opposite of how we know the web today, a place where we sell our data to gain access to platforms.

The idea of web 3 is to use blockchain - blocks of information encrypted in a chain - to deliver this proposal, where our data is not centralized on a server but is stored on several computers, where no one has access other than the “owner” and whoever it authorizes., making unwanted manipulation of this content impossible. This can be applied in a variety of ways - from blogging platforms to payments.

The way the web would work would be very different from what we have today, a plataform like twitter, for example, could be a DAO (decentralized autonomous organization), where decisions would be made in "community" and by votes and their definitions are guaranteed by what we call smart contracts, which are contracts used to automatically carry out transactions or anything suitable for trading without the need for an intermediary.

--------------------------------------------

**Versão em pt-br**

A web 3 nada mais é que uma ideia, uma ideia de uma web descentralizada, onde seus usuários não são mais clientes - clientes, no caso, das conhecidas “big techs” - facebook, google, youtube etc - e sim donos do seus dados. Isso vai ao extremo contrário de como conhecemos a web hoje, um lugar que vendemos nossos dados para ter acesso a plataformas.


A ideia da web 3 é utilizar o blockchain - blocos de informação criptografados numa corrente - para entregar essa proposta, onde nossos dados não ficam centralizados em um servidor e sim em vários computadores, onde ninguém tem acesso além do “dono” e quem ele autorizar, tornando impossível a manipulação indesejada desse conteúdo, isso pode ser aplicado de várias formas - desde plataformas de blog até pagamentos.


O modo que a web funcionaria seria muito diferente do que temos hoje, uma plataforma como o twitter, por exemplo, poderia ser umas DAO (organização autônoma descentralizada), onde as decisões seriam feitas em “comunidade” e por votos e suas definições são garantidas pelo que chamamos de smart contracts, que são contratos utilizados para realizar transações automaticamente ou qualquer coisa apropriada para negociação sem a necessidade de um intermediário.
(Parte 1) Padrões JavaScript: Dicas rápidas
Tags: javascript, braziliandevs
Published: 2022-06-12 12:04:12

---
title: (Parte 1) Padrões JavaScript: Dicas rápidas
published: true
description: Dicas de padrões javascript tiradas do livro do Stoyan Stefanov
tags: javascript, braziliandevs
---

# 

Olá galera! Tudo bem com vocês? Depois de muuito tempo, resolvi voltar a escrever aqui no blog. 

Como podem adivinhar pelo título, a ideia dessa série é mostrar alguns padrões/dicas que achei interessante do [livro "Padrões JavaScript", do Stoyan Stefanov](https://www.amazon.com.br/Padr%C3%B5es-Javascript-Stoyan-Stefanov/dp/857522266X),
inclusive não poderia indicar mais! Se está procurando entender melhor sobre design patterns, coding patterns & antipatterns, esse livro é perfeito, 
estou adorando o conteúdo! Bom, vamos lá! :p 

## Padrão objeto de configuração

Sabe quando sua função recebe muitos parâmetros e isso acaba dificultando a leitura? Por exemplo:

```js
function registerUser (email, password, name, lastname, birthdate, country, city, subscribeNewsletter) {}
```

Você pode passar um objeto como parâmetro da função nesses casos, ou passar por exemplo, as informações "obrigatórias" como parâmetro
e passar um "objeto de configuração" com os campos opcionais. Alguns exemplos:

```js
function registerUser (email, password, userConfig) {}
...

const userConfig = { 
   name: "Karoline",
   lastname: "Alencar",
   birthdate: "66/66/6666",
   country: "Brazil",
   city: "São Paulo",
   subscribeNewsletter: false
}
registerUser("email@email.com", "password", userConfig)

```

```js
function registerUser (userConfig) {}
...

const userConfig = { 
   email: "email@email.com",
   password: "password",
   name: "Karoline",
   lastname: "Alencar",
   birthdate: "66/66/6666",
   country: "Brazil",
   city: "São Paulo",
   subscribeNewsletter: false
}
registerUser(userConfig)

```

## Utilizando funções imediatas em objetos 

Imagine que, ao iniciar uma aplicação, você precisa enviar uma mensagem baseado na localização do usuário e isso requer uma série de validações, uma alternativa é criar um objeto que faça a validação imediatamente e retorne a mensagem:

```js
const userLocationMessage = {
 message: (function () {
   ...
   return 'hoi'
 })(),
 getMessage: function () {
    return this.message;
 }
}

// usando
userLocationMessage.getMessage() // "hoi"
```
Nesse caso, o valor de `message` é "hoi".


Por hoje é isso! xoxo <3

![Alt Text](https://media.giphy.com/media/GB0lKzzxIv1te/giphy.gif)
Transpose Matrix
Tags: leetcode, dsa, theabbie
Published: 2022-06-12 12:00:41

Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`.

The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.

![](https://assets.leetcode.com/uploads/2021/02/10/hint_transpose.png)

**Example 1:**

**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\]

**Example 2:**

**Input:** matrix = \[\[1,2,3\],\[4,5,6\]\]
**Output:** \[\[1,4\],\[2,5\],\[3,6\]\]

**Constraints:**

*   `m == matrix.length`
*   `n == matrix[i].length`
*   `1 <= m, n <= 1000`
*   `1 <= m * n <= 105`
*   `-109 <= matrix[i][j] <= 109`

**SOLUTION:**

    class Solution:
        def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
            m = len(matrix)
            n = len(matrix[0])
            op = [[-1 for i in range(m)] for j in range(n)]
            for i in range(m):
                for j in range(n):
                    op[j][i] = matrix[i][j]
            return op
Little React productivity boost by 'curried' function
Tags: react, javascript, functional, webdev
Published: 2022-06-12 11:56:15

Assalom alaykum!

React da ko'pincha ushbu holatdagi _**event handler**_ larni ishlatilishini guvohi bo'lamiz ya'ni odatda `implicit` bo'lgan dastlabki **_event_** argumentimizga  qo'shimcha tarzda 2 - argumentni ham funksiyamizga yuborishga to'g'ri keladi:

```typescript
const handleChange = (e: Event, type: string) => {
  // input event va type bilan bog'liq kodimiz
}

return (
  <>
    <!-- ... -->
    <input onChange={(e) => handleChange(e, 'line')} />
    <!-- ... -->
    <input onChange={(e) => handleChange(e, 'point')} />
    <!-- ... -->
    <input onChange={(e) => handleChange(e, 'polygon')} />
    <!-- ... -->
  </>
)
```

Ushbu kod albatta xatosiz ishlaydi lekin bu yerda muammo `onChange` event handler funksiyamizni yoyishga to'g'ri keladi ya'ni:

> `onChange={handleChange} => onChange={(e, arg1) => handleChange(e)}`

Bundan tashqari kodimiz unchalik ham `clean` emas. Balki bu usulni bitta joyda ishlatsak uncha bilinmas lekin bu kodimiz bir nechta joyida qayta-qayta ishlatilsa ayniqsa refactor qilishda muammo yaqqol ko'rinadi.

**Sodda yechim**: `curried` funksiya bilan kodimizni quyidagi _**elegant & clean**_ ko'rinishga olib kelishimiz mumkin:


```typescript
const handleChange = (type: string) => (e: Event) => {
  // input event va type bilan bog'liq kodimiz
}

return (
  <>
    <!-- ... -->
    <input onChange={handleChange('point')} />
    <!-- ... -->
    <input onChange={handleChange('line')} />
    <!-- ... -->
    <input onChange={handleChange('polygon')} />
    <!-- ... -->
  </>
)
```

Ya'ni funksiya qaytaradigan funksiyani event handler sifatida ishlatamiz.


> Curried funksiyalar haqida ushbu linkdan batafsil ma'lumot olishingiz mumkin: https://javascript.info/currying-partials