teleren/devto huggingface dataset:
Ruby Shortcut to Call a Method with Each Array Item as Parameter
Tags: ruby
Published: 2022-06-11 00:26:30

As a Ruby programmer, you probably know the `&:` shortcut to call a method on each item in an array. For example, this snippet will call the `to_s` method on `:foo` and `:bar`. 

```ruby
[:foo, :bar].each(&:to_s)
```

The above code is similar to:

```ruby
[:foo, :bar].each do |item|
  item.to_s
end
```

However, instead of calling a method on the array item, you want to **call a method and pass the array item to that method.** Is there a one-liner for that?

```ruby
[:foo, :bar].each do |item|
  puts(item)
end
```

It turns out, Ruby has a corresponding `&method` shortcut to accomplish precisely this. 

```ruby
[:foo, :bar].each(&method(:puts))
```

Two things are going on here.

First, the `method(:puts)` finds the method named `puts`. As per the documentation, you can access the instance variables and `self` method on whichever object you called `method` on. 

> [method(sym) -> method](https://ruby-doc.org/core-3.1.1/Object.html#method-i-method)
>
> Looks up the named method as a receiver in *obj*, returning a [`Method`](https://ruby-doc.org/core-3.1.1/Method.html) object (or raising [`NameError`](https://ruby-doc.org/core-3.1.1/NameError.html)). The [`Method`](https://ruby-doc.org/core-3.1.1/Method.html) object acts as a closure in *obj*'s object instance, so instance variables and the value of `self` remain available.

Second, the `Method` object returned by the `method` method (_wow, that's one too many methods_) implements the `to_proc` method, so you can use it after `&`, which is to say:

> If `foo` is an object with a `to_proc` method, then you can pass it to a method as `&foo`, which will call `foo.to_proc` and use that as the method's block.

```ruby
&method(:puts) # is equivalent to
{ |e| puts(e) }

&:name # is equivalent to
{ |e| e.name }
```

When you say `&method(:puts)`, it finds the `Method` object and calls `.to_proc` on it. 

```ruby
array.each(&method(:foo))
```

is equivalent to,

```ruby
array.each { |e| foo(e) }
```
---

## Is It Worth It?

Now, does that mean you go ahead and replace the explicit method calls in `each` loops with this one-liner? **Probably not.** 

Sometimes, that explicit method call is just what you need to keep the code readable and easier to understand. Not just for your colleagues, but for the future you. Using this one-liner adds an extra mental overhead for your brain to translate and understand what it's doing, which is not worth in many cases. 

However, sometimes this shortcut is precisely what you need to express what you meant. That's why I love Ruby. The freedom to choose, do, and say whatever you want, however you want, to **write software, well.** 

Anyway, hope that helps.
Update config location in kubectl Kubernetes in Linux
Published: 2022-06-11 00:02:37

Create file in ~/.bashrc.d/kubectl.config

```
export KUBECONFIG=YOUR_CUSTOM_LOCATION_CONFIG_PATH:${KUBECONFIG:-$HOME/.kube/config}
```

after create file like above, open terminal and input command

```
source ~/.bashrc
```
for check config is works you can use command

```
kubectl get pod
```
Check Completeness of a Binary Tree
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 00:00:43

Given the `root` of a binary tree, determine if it is a _complete binary tree_.

In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.

**Example 1:**

![](https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-1.png)

**Input:** root = \[1,2,3,4,5,6\]
**Output:** true
**Explanation:** Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.

**Example 2:**

![](https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-2.png)

**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** false
**Explanation:** The node with value 7 isn't as far left as possible.

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 100]`.
*   `1 <= Node.val <= 1000`

**SOLUTION:**

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def isCompleteTree(self, root: Optional[TreeNode]) -> bool:
            nodes = [(root, 0)]
            keys = {}
            while len(nodes) > 0:
                curr, l = nodes.pop()
                keys[l] = curr.val
                if curr.left:
                    nodes.append((curr.left, 2 * l + 1))
                if curr.right:
                    nodes.append((curr.right, 2 * l + 2))
            mkey = max(keys.keys())
            for l in range(mkey):
                if l not in keys:
                    return False
            return True
Day 571 : It ain't over
Tags: hiphop, code, coding, lifelongdev
Published: 2022-06-10 23:17:26

_liner notes_:
- Professional : Got a chance to reach out to the team about some upcoming features. Helped out with a community question. Read over a proposal for a new SDK. Finished up some tickets. I think I need to add some more updates to an example, so it ain't over. Pretty good way to go into the weekend.

- Personal : Last night, I went through a bunch of tracks for the radio show and went to sleep.

![A path through green hills of Vogtsburg, Germany](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ye31o9o92xq1fooe0mr.jpg)

Going to finish putting together the radio show, work on my new side project and watch the new episode of "The Boys".

Have a great night and weekend!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube aDyFmrmc_Rc %}
Day 63: Back to writing
Published: 2022-06-10 23:03:49

Hi!
so the task for this week are finished so I decided to get back to writing as it had been a while since I Posted a tutorial article. I realized that it would be better if I focused on writing more article through series so that I will be more motivated to write and also write simple articles that focuses thoroughly on a single topic therefore I will be looking into that starting from tomorrow where I plan to write about Heroku. 
Today I also got introduced to a new team that I will be joining for the upcoming days so more task should be expected in the next days including mockups designs so we will be looking into that too.
Let's enjoy the weekend for now
Signing off...
Clumsy Factorial
Tags: leetcode, dsa, theabbie
Published: 2022-06-10 23:00:43

The **factorial** of a positive integer `n` is the product of all positive integers less than or equal to `n`.

*   For example, `factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1`.

We make a **clumsy factorial** using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply `'*'`, divide `'/'`, add `'+'`, and subtract `'-'` in this order.

*   For example, `clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1`.

However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.

Additionally, the division that we use is floor division such that `10 * 9 / 8 = 90 / 8 = 11`.

Given an integer `n`, return _the clumsy factorial of_ `n`.

**Example 1:**

**Input:** n = 4
**Output:** 7
**Explanation:** 7 = 4 \* 3 / 2 + 1

**Example 2:**

**Input:** n = 10
**Output:** 12
**Explanation:** 12 = 10 \* 9 / 8 + 7 - 6 \* 5 / 4 + 3 - 2 \* 1

**Constraints:**

*   `1 <= n <= 104`

**SOLUTION:**

    class Solution:
        def clumsy(self, n: int) -> int:
            expr = ""
            opr = ["*", "//", "+", "-"]
            for i in range(n):
                expr += str(n - i)
                if i < n - 1:
                    expr += opr[i % 4]
            return eval(expr)
Hacks do Github - Mantendo a ordem
Tags: braziliandevs, github, beginners, programming
Published: 2022-06-10 22:30:43

![Order](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cjw4tzmqw8pycb1kyd52.png) 

O Github é cheio de funcionalidades e o mais utilizado isso vocês já sabem e vamos continuar a série de "hacks" da plataforma que vão otimizar e melhorar sua experiência.

⚠️ Importante: Os prints que serão exibidos para exemplificar podem estar diferentes da interface do seu GitHub, por que sou muito adepto a extensões que melhoram a usabilidade e que ajudam no meu dia a dia. Partindo desse ponto peço que dê uma olhada [nesse artigo](https://dev.to/jhonywalkeer/extensoes-para-navegador-turbinando-sua-experiencia-no-github-538) antes.

Quando criamos uma nova feature para um projeto **open source**, normalmente criamos uma branch nova, fazemos as alterações, fazemos o push para o repositório nessa nova branch e então envia um **pull request**.

Quando o pull request é aceito é feito o processo para [atualizar o repositório com o repositório forkado]() e tudo fica 100% como deveria! Mas, com o tempo, a lista de branchs no Github vai aumentando, mas não vamos precisar delas, pois seu pull request já foi aceito. Como limpar a sujeira e deixar somente as branchs que precisamos?

## Removendo branchs do Github

Para remover uma branch do Github, você pode usar o comando no seu terminal (sim, claro que vamos utilizar os comandos GIT você ainda tinha dúvida?)

```
git push origin nome_da_branch --delete
```
E com esse comando iremos deletar a branch do Github! Ou podemos utilizar este comando também:

```
git push origin :nome_da_branch
```
Com os dois pontos `: ` na frente do nome da branch, o resultado é o mesmo

## Removendo branchs localmente

Aproveitando o gancho, vou falar como você pode remover as branchs locais também cujo o comando é:

```
git branch -D nome_da_branch
```

Então é isso pessoal, sei que você provavelmente já conhecia esse comando (uns 98% de certeza), mas é sempre bom relembrar e utiliza-ló para organizar seus repositórios.

Fontes onde pesquisei esse conteúdo:

- https://docs.github.com/pt/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-branches
Thousand Separator
Tags: leetcode, dsa, theabbie
Published: 2022-06-10 22:30:39

Given an integer `n`, add a dot (".") as the thousands separator and return it in string format.

**Example 1:**

**Input:** n = 987
**Output:** "987"

**Example 2:**

**Input:** n = 1234
**Output:** "1.234"

**Constraints:**

*   `0 <= n <= 231 - 1`

**SOLUTION:**

    class Solution:
        def thousandSeparator(self, n: int) -> str:
            n = str(n)
            l = len(n)
            for i in range(1, l):
                if i % 3 == 0:
                   n = n[ : l - i] + '.' + n[l - i : ]
            return n
Eurosia Space System Sürecim
Published: 2022-06-10 22:21:02

Eylül 2021`de  Türkiyenin 5 farklı Üniversitesinden öğrencilerin bulunduğu ekip olan Eurasia Space Systems (ESS) takımına, KTU Uzay Kulübü olarak dahil olduk. Bu geniş takımın, aviyonik tarafından sorumlu olan ekibinin masaüstü yer istasyonunun, arayüzünü geliştirdim. Aynı zamanda şu anda ESS takımının sosyal medya ekibinde görev almaktayım. ESS takımı olarak Dünya genelinde teknik rapor yarışması olarak düzenlenen. Latin American Space Challenge (L.A.S.C.) yarışmasında "3 Km katı yakıtlı roket" kategorisinde The Future roketimiz, yarışmayı 2. olarak tamamlamıştır.
Maximum Difference Between Node and Ancestor
Tags: leetcode, dsa, theabbie
Published: 2022-06-10 22:00:45

Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`.

A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/11/09/tmp-tree.jpg)

**Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\]
**Output:** 7
**Explanation:** We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/11/09/tmp-tree-1.jpg)

**Input:** root = \[1,null,2,null,0,3\]
**Output:** 3

**Constraints:**

*   The number of nodes in the tree is in the range `[2, 5000]`.
*   `0 <= Node.val <= 105`

**SOLUTION:**

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:
            nodes = [(root, root.val, root.val)]
            mdiff = 0
            while len(nodes) > 0:
                curr, currmin, currmax = nodes.pop()
                mdiff = max(mdiff, currmax - currmin)
                if curr.left:
                    nodes.append((curr.left, min(currmin, curr.left.val), max(currmax, curr.left.val)))
                if curr.right:
                    nodes.append((curr.right, min(currmin, curr.right.val), max(currmax, curr.right.val)))
            return mdiff
How to fix "It is not possible to unreserve more products of ... than you have in stock." in Odoo
Tags: python, datascience, programming, tutorial
Published: 2022-06-10 21:44:35


# Have you been hit with the "It is not possible to unreserve more products of ... than you have in stock." bug? Run this script to solve your issues.


1. The issue has way to many variables to properly track down the issue at scale. If you search forums, you will find multiple DB's and instance types having the issue. 

2. No matter how your move/record got bugged, the bottom line is in Odoo's system there is simply not enough product to unreserve or cancel the move. 

3. This fix runs a brute force, solution and should only be done as a last resort. Back up your DB and run on a test instance before. 



The script will overwrite both the reserved and real quantity, so that the bugged moved can close. 

**Example***

Say you have a record for product x for a total of 100, that you can't cancel. The script would overwrite the product and location qty's to 100 (regardless of what it should be), so that we can cancel the move. 


Plug in your login info and product info. Note: Login should probably be env variables, as we are running locally I didn't bother sitting this up. 

Run the script and find stock.quant record to overwrite, after you overwrite it, go back to the move and you will no be able to cancel it. 


```
 rsv_qty = models.execute_kw(db, uid, password, 'stock.quant', 'write',
                            [room_id, {
                                'reserved_quantity': overwrite_number, 
                            }])
    print("Reserved Overwrite Successful")

    
    rsv_qty = models.execute_kw(db, uid, password, 'stock.quant', 'write',
                            [room_id, {
                                'quantity': overwrite_number, 
                            }])
    print("Real Overwrite Successful")
```


https://github.com/thetrebelcc/Odoo-Unable-to-Unreserve-Fix-Script


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ae1wsfbh330ufz6gx75g.png)
Migrating from Flask-Script to Flask-CLI
Tags: flask, python
Published: 2022-06-10 21:40:33

I am migrating from Flask-Script to Flask-CLI with the latest Flask version. Here are what my manage.py and migrate.py file look like.
I am getting this error#

```
app 
Traceback (most recent call last):
File "manage. py", line 19, in
<module>
cli()
File "/usr/local/lib/python3.7/site-packages/click/core. py", line 1130, in __call__
2022-06-10 20:01:34
app
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/flask/cli.py", line 579, in main
2022-06-10 20:01:34
app 
return super().main(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/click/core. py", line 1055, in main
2022-06-10 20:01:34
app
rv = self.invoke(ctx)
File "/usr/local/lib/python3.7/site-packages/click/core. py", line 1657, in invoke
```
Please help thanks!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n6joc0z4fkwaqikxsh2s.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bshueqg3o93raquaor22.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/leijw458let93e1pia2k.png)
Best Practices of choosing a system.
Published: 2022-06-10 21:32:21

 Preamble

The browsers only understand JavaScript, however with rise of stuff that we use on browsers e.g. Games, Virtual Reality, Augmented Reality, JavaScript hasn't been able to catch up due to its inherent interpreted nature despite its powerful engines like V8.

Suppose you have a cool game or software developed in a low-level programming language e.g. C/C++ or a high-level programming language e.g. Java/C#/Rust/Go. With WebAssembly you can run these apps on a browser. Wihout re-writing them in JavaScript.

Wait, what?
What is WebAssembly?

    WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable compilation target for programming languages, enabling deployment on the web for client and server applications.

    -https://webassembly.org/

    WebAssembly, or wasm, is the most significant new technology to come to the web platform in a decade. Technically speaking, it is a new, low-level, assembly-like language that runs efficiently on the existing web platform and is backward-compatible with its precursor, asm.js. Most people, however, will use the wasm format as a compiler target, translating their applications into web-ready modules that can run in modern web browsers at near-native speeds.

    -https://research.mozilla.org/webassembly

W A S M

Check out Milica Mihajlija's awesome blog to know more.
Blazor

Blazor is an open-source framework from Microsoft to develop Component based UIs using language you already know and love, C#. I'll be blunt and say:

    It's Microsoft's response to Angular and React.

Because why not?

But it's not why we're talking about Blazor here. The reason is, one of the hosting models of Blazor is WebAssembly.

Blazor's home page says:

    Blazor can run your client-side C# code directly in the browser, using WebAssembly. Because it's real .NET running on WebAssembly, you can re-use code and libraries from server-side parts of your application.
    -https://dotnet.microsoft.com/apps/aspnet/web-apps/blazor
Decode the Slanted Ciphertext
Tags: leetcode, dsa, theabbie
Published: 2022-06-10 21:30:39

A string `originalText` is encoded using a **slanted transposition cipher** to a string `encodedText` with the help of a matrix having a **fixed number of rows** `rows`.

`originalText` is placed first in a top-left to bottom-right manner.

![](https://assets.leetcode.com/uploads/2021/11/07/exa11.png)

The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of `originalText`. The arrow indicates the order in which the cells are filled. All empty cells are filled with `' '`. The number of columns is chosen such that the rightmost column will **not be empty** after filling in `originalText`.

`encodedText` is then formed by appending all characters of the matrix in a row-wise fashion.

![](https://assets.leetcode.com/uploads/2021/11/07/exa12.png)

The characters in the blue cells are appended first to `encodedText`, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed.

For example, if `originalText = "cipher"` and `rows = 3`, then we encode it in the following manner:

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

The blue arrows depict how `originalText` is placed in the matrix, and the red arrows denote the order in which `encodedText` is formed. In the above example, `encodedText = "ch ie pr"`.

Given the encoded string `encodedText` and number of rows `rows`, return _the original string_ `originalText`.

**Note:** `originalText` **does not** have any trailing spaces `' '`. The test cases are generated such that there is only one possible `originalText`.

**Example 1:**

**Input:** encodedText = "ch   ie   pr", rows = 3
**Output:** "cipher"
**Explanation:** This is the same example described in the problem description.

**Example 2:**

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

**Input:** encodedText = "iveo    eed   l te   olc", rows = 4
**Output:** "i love leetcode"
**Explanation:** The figure above denotes the matrix that was used to encode originalText. 
The blue arrows show how we can find originalText from encodedText.

**Example 3:**

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

**Input:** encodedText = "coding", rows = 1
**Output:** "coding"
**Explanation:** Since there is only 1 row, both originalText and encodedText are the same.

**Constraints:**

*   `0 <= encodedText.length <= 106`
*   `encodedText` consists of lowercase English letters and `' '` only.
*   `encodedText` is a valid encoding of some `originalText` that **does not** have trailing spaces.
*   `1 <= rows <= 1000`
*   The testcases are generated such that there is **only one** possible `originalText`.

**SOLUTION:**

    class Solution:
        def decodeCiphertext(self, encodedText: str, rows: int) -> str:
            m, n = rows, len(encodedText) // rows
            op = ""
            for i in range(n):
                for j in range(m):
                    if i + j < n:
                        op += encodedText[(n + 1) * j + i]
            return op.rstrip()
Make awesome Portfolio.
Published: 2022-06-10 21:27:18

Hi ✋😁
I would like to introduce my self,
my name is Maeri
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3nlh3d95cg2vvxu8wqxr.png) and I am a web developer.

I wrote this article to share my new portfolio.

I was searching for designs on google for a couple of days, and then I stumbled on a good design that I like. Its a design by Brittany Chiang.

I built my portfolio based on her design using Vue Js, and with the help of the plugin Vuetify. I tweaked my portfolio a little with the taste that I like.
Introduction to cyber threats.
Tags: security, productivity
Published: 2022-06-10 21:22:47

As we are going through unusual and challenging times, our daily habit has been affected in all sorts of ways. For those who are working from home, this is indeed a very difficult time. We are more open to cyber attacks due to the little to no cyber security we have in place while working from home.

Hackers are desperately trying to exploit the opportunity and up to some extent, it’s working. It’s mainly because many organizations and business tasks have gone from an internal network to the open internet without much preparation. This has exposed them to more potential threats.

Some of the common attacks are listed below.

    Email-Phishing
    SMS-Phishing
    Mobile Malware
    Malicious Software
    Ransomware Attacks

Cyber Security Best Practices For Remote Workers

In this rising time of cyber attacks, taking preventive action against these interventions is a necessity.

    Use antivirus and antispyware software on every computer used in your business and make sure they are frequently updated.
    Limit physical access to your computers and network components.
    Regularly change passwords and ensure that they’re not easy to predict

more detailed version published at https://beaglesecurity.com/blog/blogs/2020/04/13/Cyber-Security-Threats-and-Best-Practices-for-Remote-Workers.html