teleren/devto huggingface dataset:
Improve your Django query with bulk_create 👋
Tags: django, python
Published: 2022-02-05 12:29:25

Assume you have a model called `Blog`:
```python
class Blog(models.Model):
    title = models.CharField(max_length=255)
    content = models.CharField(max_length=500)
```
and you want to insert 10 blogs in your database, so let's build our views:
```python
class BlogApi(APIView):

    def get(self, request):

        for _ in range(10):
            blog = Blog.objects.create(
                title = 'Blog Title',
                content = 'Blog Content'
                )
        return Response(status=status.HTTP_201_CREATED)
```

This will insert 10 times into the database with CPU time 268.63ms as you can see 👇
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9l1ul4phqiqjc7znsog8.png)
               
-> The debugging above from [django-debug-toolbar](https://github.com/jazzband/django-debug-toolbar)
  
Now let's use `bulk_create` to see the difference 😉
```python
class BlogApi(APIView):

    def get(self, request):

        blog_list = [] # Empty list to save blog object on
        for _ in range(10):
            blog = Blog(
                title = 'Blog Title',
                content = 'Blog Content'
                )
            blog_list.append(blog)

        Blog.objects.bulk_create(blog_list) # Use bulk_create to insert the list of blog objects

        return Response(status=status.HTTP_201_CREATED)
```

How much this will cost?
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3829xced7bl1cxgphdhc.png)

Only 2 queries in 1.35ms with CPU time 156.79ms !!

That's awesome 😅

Read more about `bulk_create()` & `bulk_update()`from the the [docs](https://docs.djangoproject.com/en/4.0/ref/models/querysets/#bulk-create)

Finally, thanks for reading and I hope you learned something new in Django ORM, have a lovely day 🌼
Interactive Resume
Tags: codepen, help, webdev, russia
Published: 2022-02-05 11:57:43

## 
Привет! 
Я совсем новичок в этом деле! Прошу не ~~ср@*ь~~ гневными сообщениями.😘 

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

**Подскажите пожалуйста, как сделать (обзор "фонарика") круглым, по сути любому совету буду признателен!**

<p>Played a little bit of hide and seek with my resume. Used the code for the flashlight effect from here:<a href="http://codepen.io/arroinua/pen/bBxgm" target="_blank">http://codepen.io/arroinua/pen/bBxgm</a></p>

{% codepen https://codepen.io/zvrhub/pen/KKygjgX %}
how to get list length
Published: 2022-02-05 11:26:20

| Get list length in Python 3    | Examples                                                                                                                                                                     |
|--------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| len() function                 | list = [10, 20, 30]<br>n = len(list)<br>print(“The length of list is: “, n)                                                                                                  |
| for loop                       | list = [‘Python’,’Java’,’Kotlin’,’Machine Learning’,’Keras’]<br>size = 0<br>print(“Length of the input string:”)<br>for x in list:<br>size+=1<br>print(size)                 |
| len() function for nested list | nestedList = [‘Krishna’, 20,’John’, [20, 40, 50, 65, 22], ‘Yung’, 11.98]<br>print(“Original List = “, nestedList)<br>print(“Length of a Nested List = “, len(nestedList[3])) |

[how to get list length in python](https://www.howtouselinux.com/post/get-the-length-of-a-python-list)
js❤️ - Destructuring + Spread Los restantes
Tags: javascript, es6, react, spanish
Published: 2022-02-05 11:08:30

## Destructuring + Spread → Los restantes

Al hacer _destructuring_ podemos utilizar también el operador _spread_ para almacenar en una variable un grupo de elementos. Por ejemplo:

Almacenar en un _array_ "el resto de argumentos" de una función

```js
function printLn(prefix, suffix, ...rest) {
  console.log(prefix, rest.join(" | "), suffix);
}
printLn("<line>", "</line>", "one", "two", "three");
// <line>one | two | three</line>
```

Guardar el primer elemento (o los primeros) y los restantes

```js
const [first, second, ...rest] = [4, 7, 2, 5];
// first = 4, second = 7, rest = [2, 5]
```

Guardar el último elemento (o los últimos) y los restantes

```js
const [ ...rest, prev, last ] = [9, 4, 7, 2];
// rest = [9, 4], prev = 7, last = 2
```

Y también con objetos:

Guardar un atributo (o varios) y los restantes

```js
const error = { level: "log", method: "fetch", error: 404 };
const { level, ...details } = error;
console[level](details);
// { method: "fetch", error: 404 }
```

## ¡A ponerlo en práctica!

Ahora te propongo un pequeño ejercicio para practicar lo que hemos aprendido.

[Ejercicio 1 en CodeSandbox](https://codesandbox.io/s/mutable-currying-co0lh?file=/src/Input.js )

{% spoiler ver solución %}
[Solución Ejercicio 1 en CodeSandbox](https://codesandbox.io/s/relaxed-tereshkova-mt2l7?file=/src/App.js)
{% endspoiler %}

[Siguiente - Funciones →](https://dev.to/jacarma/js-arrow-functions-y-funciones-de-primera-clase-cla)
Trying dev.to
Tags: json, firebug
Published: 2022-02-05 11:08:13

Today I happened to visit caniuse.com and type "JSON" input the search box.

Guess what?

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vlq4f62cfl2xel99m46l.png)
 
Even the Chrome did not support `JSON` in its first three major versions.

Can't believe how time flies.

I miss the days to debug JavaScript with `alert` and `fiddler`.

I miss the first day when I used Firebug and had a strong feeling that this stuff would save years of my life.
Use Siri Shortcut to Create Notion Pages
Tags: productivity
Published: 2022-02-05 10:50:44

[Video Introduction](https://www.youtube.com/watch?v=bQGCQhIyJKY)



[Shortcut Demo](https://www.icloud.com/shortcuts/6db2aa9fc3be4c4cb1abf6506fc13d3a)

| Note: `multi_select` is a list of objects
Revisiting Rock Paper Scissors from The Odin Project Section 12
Tags: javascript, html, tutorial, theodinproject
Published: 2022-02-05 10:50:31



# Revisting Rock Paper Scissors
 
My first JavaScript App. Revisiting Rock, Paper, Scissors App. Very proud of myself at this point I am going to start making a video a week to remind myself how I implemented the logic on each of my projects.

[Rock Paper Scissors](https://youtu.be/J8Fd8Pw_ht0) This is the first video I made it covers how how coded the first part of the rock paper scissors assignment from section 7 in The Odin Project.
[Revisiting Rock Paper Scissors](urhttps://youtu.be/Lvyyq6_hQbYl) This link will take you to a video that covers how I code section 12 In The Odin Project assignment Revisisting Rock Paper Scissors.
js❤️ - Spread Operator
Tags: javascript, react, es6, spanish
Published: 2022-02-05 10:33:42


## Spread Operator

Este operador permite "extender" los elementos de una colección en varios elementos o parámetros. Veamos algunos usos:

Añadir un elemento a un _array_ sin modificar el original

```js
const a = [1, 2];
const b = [...a, 5]; // [1, 2, 5]
const c = [9, ...a]; // [9, 1, 2]
```

Concatenar _arrays_ sin modificar los originales

```js
const a = [1, 2];
const b = [5, 9, 10];
const c = [...a, ...b]; // [1, 2, 5, 9, 10]
```

Clonar un objeto (solo el primer nivel)

```js
const a = { name: "Javi", num: 1 };
const b = { ...a }; // { name: "Javi", num: 1 }
const eq = (a === b); // false
```

Cambiar un atributo de un objeto sin modificar el original

```js
const a = { name: "Javi", num: 1 };
const b = { ...a, num: 2 }; // { name: "Javi", num: 2 }
```

Combinar objetos

```js
const a = { name: "Javi", num: 1 };
const jetpack = { altitude: 2000, speed: 850, num: 4 };
const b = { ...a, ...jetpack };
// { name: "Javi", num: 4, altitude: 2000, speed: 850 }
```

Pasar un _array_ como una lista de argumentos

```js
const tokens = [2022, 1, 3];
const date = new Date(...tokens); // Thu Feb 03 2022...
```

[Siguiente - Destructuring →](https://dev.to/jacarma/js-destructuring-3dd6)
Lead
Tags: discuss, personal, improvement, growth
Published: 2022-02-05 10:33:01

---
title: Lead
published: true
description: Show how it's done
tags: discuss, personal, improvement, growth
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2dy4hiisx0hgz6rpaxbx.jpg
---

_Originally published on [my blog](https://www.nikola-breznjak.com/blog/daily-thoughts/lead/)._

> Before you demand more from other people, show how 'more' looks like.

---

This is [why I write](https://www.nikola-breznjak.com/blog/daily-thoughts/why-do-i-write-these-daily-thoughts-posts/) these 'daily thoughts' posts.
Max Level Sum of A Binary Tree
Tags: python, computerscience, programming, beginners
Published: 2022-02-05 10:31:33

**Problem Statement:** 
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.

Return the smallest level x such that the sum of all the values of nodes at level x is maximal.

**Approach**

This was a problem which had some quite interesting solving... In this approach I used a BFS. I took one row at a time found its sum and compared it with the previous sum. If its greater than the previous one then I replaced the max Level with the current Level. Finally at the end of the looping I returned the max Level.

**Algo Images**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5i1e0jdo9lwjivk753el.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/45d1titpprexbfxsrkre.jpg)

**Code**
```
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def maxLevelSum(self, root: TreeNode) -> int:
        if root == None: return None

        currentLevel: int = 1
        maxLevel: int = None
        maxSum: int = None

        BFSQueue: list[TreeNode] = [root]

        while len(BFSQueue) > 0:
            currentLength: int = len(BFSQueue)
            currentSum: int = 0

            for i in range(currentLength):
                currentNode: TreeNode = BFSQueue.pop(0)
                currentSum += currentNode.val

                if currentNode.left != None: BFSQueue.append(currentNode.left)
                if currentNode.right != None: BFSQueue.append(currentNode.right)

            if (maxSum == None) or (maxSum < currentSum):
                maxSum = currentSum
                maxLevel = currentLevel
                
            currentLevel += 1

        return maxLevel
```

**Result Image**

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

_If you got to learn something from this post make sure you like the post and click on the follow button for more such content. 
Also if you have some suggestions and want to improve it make sure you comment down below..._
Day 6 of 100DaysOfCode
Tags: 100daysofcode, programming, challenge, python
Published: 2022-02-05 10:29:04

## Day 6 of 100 Days Of Code
_I was too tired for writing a post yesterday._

Here can you find what I learned (& published) yesterday.

### What I published / coded / updated yesterday?
* Started with improving the [simple-amari.py](https://pypi.org/simple-amari.py).

> **INFO**: simple-amari.py is a wrapper for the [AmariBot API](https://amaribot.com/). I write a post about the libary later.

* Ended with fixing some bugs in the [AntiScamBot backend](https://github.com/AntiScamBot/backend) Python rewrite. 

> **INFO**: The day should actually end with this post, was just too tired to make this.
Rearrange array in alternating positive & negative items with O(1) extra space 
Tags: programming, beginners, java, dsa
Published: 2022-02-05 10:27:32

Given an array of positive and negative numbers, arrange them in an alternate fashion such that every positive number is followed by negative and vice-versa maintaining the order of appearance. 
Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in the end of the array.

Examples : 

Input:  arr[] = {1, 2, 3, -4, -1, 4}
Output: arr[] = {-4, 1, -1, 2, 3, 4}

Input:  arr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8}
output: arr[] = {-5, 5, -2, 2, -8, 4, 7, 1, 8, 0}

Asked in **Amazon**

**At even position:** negative numbers
**At odd position:** positive numbers

`i`--> *It will find the negative element in the array*
`j`--> *It will find the positive element in the array*

**JAVA CODE**
```
import java.util.*;
public class RearrangeArrayInAlterPos {
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the size of the array:");
        int n=sc.nextInt();
        int[] arr=new int[n];
        System.out.println("Enter the elements of the array:");
        for(int i=0;i<n;i++)
        {
            arr[i]=sc.nextInt();
        }
        reArrange(arr, n);
    }
    //doing right rotate to shift the elements to the right
    //this is done to maintain the order of the elements
    public static void rotate(int arr[],int start,int end)
    {
        int temp=arr[end];
        for(int i=end-1;i>=start;i--)
        {
            arr[i+1]=arr[i];
        }
        arr[start]=temp;
    }
    public static void reArrange(int arr[],int n)
    {
        int i=0,j=0,k=0;
        while(i<n && j<n && k<n)
        {
            if(k%2==0)//if k is even
            {
                if(arr[k]>=0)
                {
                    i=k; j=k;
                    while(i<n && arr[i]>=0)
                       i++;
                    if(i>=n) break;
                    else
                       rotate(arr,j,i);
                }
            }
            else{
                if(arr[k]<0)
                {
                    i=k;
                    j=k;
                    while(j<n && arr[i]<0)
                       j++;
                    if(j>=n) break;
                    else
                    rotate(arr,i,j);
                }
            }
            k++;

        }
        for(int l=0;l<n;l++)
           System.out.print(arr[l]+" ");

    }
    
}
```
Failure
Tags: discuss, personal, improvement, growth
Published: 2022-02-05 10:22:26

---
title: Failure
published: true
description: Welcome failure in your life, but be wary of its two-edged blade
tags: discuss, personal, improvement, growth
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/erenkqkxubcsuqujp0eq.jpg
---

_Originally published on [my blog](https://www.nikola-breznjak.com/blog/daily-thoughts/failure/)._

> Welcome failure in your life, but be wary of its two-edged blade. Make sure you learn from it and grow, instead of falling into self-pity and never getting back up. Looking back at your life, you'll see that those local minima (math lingo alert! 🙂) were your defining moments.

---

This is [why I write](https://www.nikola-breznjak.com/blog/daily-thoughts/why-do-i-write-these-daily-thoughts-posts/) these 'daily thoughts' posts.
js❤️ - Introducción
Tags: javascript, es6, react, spanish
Published: 2022-02-05 10:20:26

JavaScript tiene sus peculiaridades y nos hemos divertido mucho con ellas ([ver WTFJS](https://github.com/denysdovhan/wtfjs)) pero lo cierto es que desde que en 2015 se estandarizó es6 el lenguaje ha evolucionado mucho y ahora es un lenguaje potente y productivo.

En esta serie de artículos vamos a repasar algunas de sus posibilidades y cómo se pueden utilizar para escribir un código más conciso y expresivo.

## Clases

Sí, JavaScript ya soporta definir classes sin hacer _hacks_.

Pero, en los últimos años la comunidad de programadoras de JavaScript ha ido alejándose más y más de la programación orientada a objetos y acercándose hacia la programación funcional (más o menos).

Por eso no vamos a hablar de clases en este artículo, en su lugar puedes echar un vistazo a algún artículo sobre programación funcional en js, por ejemplo [Pragmatic Functional Programming in JavaScript
](https://dev.to/sethcalebweeks/pragmatic-functional-programming-in-javascript-2lll)

De lo que sí vamos a hablar es de **inmutabilidad**.

## Inmutabilidad

Inmutabilidad es un concepto de programación funcional que indica que no cambiamos el valor de las variables.

Necesitamos abrazar este concepto si utilizamos **React** (o la mayoría de _frameworks_ actuales). React nos permite definir un árbol de componentes que representa nuestra UI. Los componentes reciben _props_ de sus padres y a veces tienen estado.

Cuando el componente que está en la raíz del árbol cambia su estado, todo el árbol debe renderizarse. Esto de normal ocurre muchas veces, incluso varias veces por segundo, por eso es importante que la renderización del árbol sea rápida.

Para ahorrar tiempo de renderizado, antes de pintar cada componente React comprueba si este tiene cambios o si por el contrario puede utilizar el estado anterior del componente. Y para eso comprueba si sus _props_ han cambiado o si su estado ha cambiado, más o menos de esta forma:

```js
// para cada prop
if (prop !== oldProp) changed = true; // strict equality comparison
...
```

Por eso el siguiente código es erróneo:

```js
const [users, setUsers] = useState([]);

return (
    <UserList onAdd={(user) => setUsers(users.push(user))}/> {/* ⛔️ */}
)
```

El método _push_ modifica el _array_ original. En el `setUsers` estamos volviendo a asignar el mismo objeto al estado y cuando React compruebe si `users === oldUsers` pensará que no hay cambios y no renderizará este componente.

En su lugar necesitamos buscar estrategias para generar nuevos valores sin modificar el objeto original. Muchas de las estrategias comunes las veremos en estos artículos, para otras más especiales te recomiendo echar un vistazo a [immer](https://github.com/immerjs/immer).

El ejemplo anterior podría arreglarse así:

```js
const [users, setUsers] = useState([]);

return <UserList onAdd={(user) => setUsers([...users, user])} />;
```

Gracias al uso de _spread operator_, del que hablaremos en el siguiente artículo.

[Siguiente - Spread Operator →](https://dev.to/jacarma/js-spread-operator-3kpb)
Enough
Tags: discuss, personal, improvement, growth
Published: 2022-02-05 10:12:48

---
title: Enough
published: true
description: Too much is never enough
tags: discuss, personal, improvement, growth
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hwkqhbkk70h1bv35t1py.jpg
---

_Originally published on [my blog](https://www.nikola-breznjak.com/blog/daily-thoughts/enough/)._

> Too much is never enough.
>
> On average, we have more than we need. When you've covered all of Maslow's needs, and you start to yearn for more, that's when usually problems start.
>
> There's nothing wrong with wanting and yearning and working towards more, but beware of the reason for doing that and make sure you're grateful for what you've got; because wanting more and never being happy with what you've got, will lead down the path of disappointment and depression.

---

This is [why I write](https://www.nikola-breznjak.com/blog/daily-thoughts/why-do-i-write-these-daily-thoughts-posts/) these 'daily thoughts' posts.
GitHub Socialify - 💞 Create GitHub Repo Card - Socialify your project. 🌐 #1
Tags: javascript, tutorial, github, productivity
Published: 2022-02-05 08:52:09

GitHub Socialify - 💞 Socialify your project. 🌐 Share with the world! #1

You can create your GitHub repositories card like this.

[![WebScrapperJS](https://socialify.git.ci/sh20raj/WebScrapperJS/image?description=1&font=Bitter&forks=1&issues=1&language=1&name=1&owner=1&pattern=Floating%20Cogs&pulls=1&stargazers=1&theme=Dark)](https://github.com/sh20raj/WebScrapperJS)


---

Here is the website URL :- https://socialify.git.ci/

You can also customize your repo card on their website. It's so easy to use and useful.

Copy the markdown or image URL from there place on your website and your card will be in front of world.

```Markdown
![WebScrapperJS](https://socialify.git.ci/sh20raj/WebScrapperJS/image?description=1&font=Bitter&forks=1&issues=1&language=1&name=1&owner=1&pattern=Floating%20Cogs&pulls=1&stargazers=1&theme=Dark)
```

![GitHub Socialify](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t7igsp24wrrd6q4352u1.PNG)


---

> ## Checkout their GitHub Repo :-

![socialify](https://socialify.git.ci/wei/socialify/image?description=1&font=Bitter&forks=1&issues=1&language=1&name=1&owner=1&pattern=Floating%20Cogs&pulls=1&stargazers=1&theme=Dark)

---

{% github https://github.com/wei/socialify %}
Day 91 of 100 Days of Code & Scrum: More SQL JOINs and Next.js Authentication
Tags: javascript, webdev, beginners, 100daysofcode
Published: 2022-02-05 08:45:42

Happy weekend, everyone!

I've done a lot of SQL learning today, and I'm almost done with [SQLZoo's SQL Tutorial](https://sqlzoo.net/wiki/SQL_Tutorial). Afterwards, I should be ready to move to MySQL, as I now have a decent grasp of SQL basics.

Anyway, let's move on to my daily report!

## Yesterday

I fixed some styling bugs that I overlooked for a while, and continued to learn more about Next.js, SQL, and scaled Scrum.

## Today

### Next.js

- learned about server-side authentication and access token authentication (JWTs) in Next.js.
- continued going through [Next.js & React by Maximilian Schwarzmüller](https://www.udemy.com/course/nextjs-react-the-complete-guide/).

### SQL

- learned about inner and outer JOINs.
- learned about chaining multiple JOINs to merge multiple tables.
- continued to go through [SQLZoo's SQL Tutorial](https://sqlzoo.net/wiki/SQL_Tutorial).

### Scrum

- continued reading the [Nexus guide](https://scrumorg-website-prod.s3.amazonaws.com/drupal/2021-01/NexusGuide%202021_0.pdf?nexus-file=https%3A%2F%2Fscrumorg-website-prod.s3.amazonaws.com%2Fdrupal%2F2021-01%2FNexusGuide%25202021_0.pdf) for scaling Scrum.

Thank you for reading! Have a good day!

![Rammina Thank You Banner](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x9ayfxxxaz2g2hfcqbsk.png)

## Resources/Recommended Readings

- [Next.js & React by Maximilian Schwarzmüller](https://www.udemy.com/course/nextjs-react-the-complete-guide/)
- [Next.js official documentation](https://nextjs.org/docs/getting-started)
- [SQLZoo's SQL Tutorial](https://sqlzoo.net/wiki/SQL_Tutorial)
- [The 2020 Scrum Guide](https://scrumguides.org/scrum-guide.html)
- [Nexus guide](https://scrumorg-website-prod.s3.amazonaws.com/drupal/2021-01/NexusGuide%202021_0.pdf?nexus-file=https%3A%2F%2Fscrumorg-website-prod.s3.amazonaws.com%2Fdrupal%2F2021-01%2FNexusGuide%25202021_0.pdf)

### Image Credits

- [Cover Image From Austin Smith](https://levelup.gitconnected.com/sql-joins-2cc89babb6f9)

## DISCLAIMER

**This is not a guide**, it is just me sharing my experiences and learnings. This post only expresses my thoughts and opinions (based on my limited knowledge) and is in no way a substitute for actual references. If I ever make a mistake or if you disagree, I would appreciate corrections in the comments!

<hr />

## Other Media

Feel free to reach out to me in other media!

<span><a target="_blank" href="https://www.rammina.com"><img src="https://res.cloudinary.com/rammina/image/upload/v1638444046/rammina-button-128_x9ginu.png" alt="Rammina Logo" width="128" height="50"/></a></span>

<span><a target="_blank" href="https://twitter.com/RamminaR"><img src="https://res.cloudinary.com/rammina/image/upload/v1636792959/twitter-logo_laoyfu_pdbagm.png" alt="Twitter logo" width="128" height="50"/></a></span>

<span><a target="_blank" href="https://github.com/Rammina"><img src="https://res.cloudinary.com/rammina/image/upload/v1636795051/GitHub-Emblem2_epcp8r.png" alt="Github logo" width="128" height="50"/></a></span>