teleren/devto huggingface dataset:
2244. Minimum Rounds to Complete All Tasks
Tags: java, programming, tutorial
Published: 2023-01-04 18:10:53

## Question
You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level.

Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.

 

Example 1:

Input: tasks = [2,2,3,3,2,4,4,4,4,4]
Output: 4
Explanation: To complete all the tasks, a possible plan is:
- In the first round, you complete 3 tasks of difficulty level 2. 
- In the second round, you complete 2 tasks of difficulty level 3. 
- In the third round, you complete 3 tasks of difficulty level 4. 
- In the fourth round, you complete 2 tasks of difficulty level 4.  
It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.
Example 2:

Input: tasks = [2,3,3]
Output: -1
Explanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.
 

Constraints:

1 <= tasks.length <= 105
1 <= tasks[i] <= 109

## Intuition
In each round, we can complete either 2 or 3 tasks with the same difficulty. We actually need to find the minimum number of rounds, so it's ideal to complete 3 tasks because it will reduce the number of rounds.
Example: say we have 6 x tasks. To get the minimum, it is always better to complete 3, 3 tasks than 2, 2, 2 tasks.

## Approach
So first of all we actually need to consider the count and a hashmap can be best used for this scenario. After taking the count and storing it in the hashmap, iterate through the hashmap and check whether the count is < 2. This is our base condition and we can return -1 right away.
Otherwise, just try to find how many 3 jobs + 3 jobs + …. + 2 jobs count.
This can be achieved by (currentCount + 2) / 3 and adding this result to the minimum round.

## Complexity
* Time complexity:
O(n) + O(n) because we are traversing through the array first and then through the hashmap which can have approx. n elements in the worst case.
* Space complexity:
We use an extra hashmap to store the count of each task; it can be n in the worst case.
So space complexity will be O(n).


## Code
```Java
class Solution {
    public int minimumRounds(int[] tasks) {
        int length = tasks.length;
        if (tasks == null || length == 0) {
            return 0;
        }
        int roundCount = 0;
        Map<Integer, Integer> taskCount = new HashMap<>();
        for (int task : tasks) {
            taskCount.put(task, taskCount.getOrDefault(task, 0) + 1);
        }
        for (Integer taskKey : taskCount.keySet()) {
            int currentKeyCount = taskCount.get(taskKey);
            if (currentKeyCount < 2) {
                return -1;
            }
            roundCount += (currentKeyCount + 2) / 3;
        }
        return roundCount;
    }
}
```

Please feel free to discuss about any different idea or different approach.
Data e Tempo em Python
Tags: python, beginners, tutorial, braziliandevs
Published: 2023-01-04 18:05:47

Podemos obter informações de data e tempo em Python usando o módulo `datetime`. Vamos importá-lo:

```py
import datetime
```

## Data

No módulo `datetime` podemos usar a classe `date`, que possui o método `today()` para carregar a data do dia atual:

```py
data = datetime.date.today()
print(data)
```

Exemplo de resultado:

```
2023-01-04
```

Também podemos obter cada informação da data de maneira separada:

```py
dia = datetime.date.today().day
mes = datetime.date.today().month
ano = datetime.date.today().year

print(dia)
print(mes)
print(ano)
```

Exemplo de resultado:

```
4
1
2023
```

## Tempo
Para obtermos o tempo, usaremos a classe `datetime` e seu método `now()`:

```py
agora = datetime.datetime.now()
print(agora)
```

Exemplo de resultado:

```
2023-01-04 14:28:19.041413
```

Observe que o horário do tempo está organizado em:

`hora:minuto:segundo.microsegundo`

## Formatação do tempo

Podemos alterar a maneira como o tempo está sendo exibido através do método `strftime()`. Por padrão, temos `%d` para dia, `%m` para mês, `%y` para ano, `%H` para hora, `%M` para minuto e `%S` para segundos.  Vamos usar novas variáveis para guardar esses valores formatados:

```py
formato1 = agora.strftime('%d/%m/%y')
print(formato1)

formato2 = agora.strftime('%d.%m.%Y %H:%M:%S')
print(formato2)
```

Exemplo de resultado:

```
04/01/23
04.01.2023 14:28:19
```

Observe que usando `%Y`, temos o ano exibido com 4 caracteres.
CSS unit is my name
Tags: css, html, webdev, beginners
Published: 2023-01-04 18:05:17

Hi 👋

**CSS Unit** is my name. I am the standard of measurement used in CSS to express the size of an element's property.

For instance, the snippet below used me to define the size of the `div` element's `width`—wherein `px` is the unit, and `300` is the number of `px`s (pixels).

```css
div {
  width: 300px;
}
```

## About my children

My children's names are relative and absolute length units.

**Relative length unit** is a dynamic standard of measurement.

You will often see her as a percentage (`%`), element (`em`), root element (`rem`), or fraction (`fr`).

**Absolute length unit** is a fixed standard of measurement.

You will often see him as pixels (`px`), centimeters (`cm`), millimeters(`mm`), and inches (`in`).

Visit [CodeSweetly](https://codesweetly.com/css-unit) to find out more about us.
My 1st Opensrc Project: Tip
Tags: webdev, opensource, github, beginners
Published: 2023-01-04 17:59:01

## Happy New Year!

*Also, disclaimer this is about my first time __leading__ an open source project and all of thing things I have learned.*

### Make sure you hide private information

If I launch an app I usually did so on a private repo or a private hosting site, and often the .env variables were needed to run.
When starting an open source project make sure to add your private links, logins, or data to an .env file and add said file to .gitignore before pushing your repo. 

#### If you made the mistake already, you can always:

1. Roll back your commit and delete it there.
2. If it's only your first commit. Delete that repo and create a new one with the tip mentioned above.
3. Google/Stackoverflow another method

---

### Make a CONTRIBUTING.md

This may seem obvious but if it's open source then you must want people to contribute so, give them rules and instruction on how to do so. There are plenty of resources to outlining how to make a good one.

It is ok if it is less than perfect at the start just try to keep up with it as issues and improvements arise. Trust me it will make your life and the contributors lives easier.

---

### Add Security Checks / Protections 

Github has tons of pre-built checks for repos, use them. The last thing you want is for someone to be able to make changes to your repo without your or a mod's approval.

---

### Live and Learn

While not making mistakes is great and all. Making mistakes and learning from them is how you grow as both a person and a developer. There are a ton of other things I wish I knew better opening my repo to public but because of them I have learned a ton and improved a ton.

<br>

If you are looking for help there are tons of resources to get assistance you just have to look a little bit to find them.



-K. Richmond
Basic flow / working of k8s
Tags: kubernetes, devops, beginners, tutorial
Published: 2023-01-04 17:50:28

**Master Node **:
When a slave node needs some action to be performed it directly communicates with API server.
Now API server forwards the request of slave node to Controller Manager which then makes a check via API server to etcd Cluster of present scenario of requesting slave node.
Now after this, the Controller Manager checks if the present state is the same as the desired state or not.
If a match is not established, the Controller Manager instructs the Kube scheduler to do the needful. 

**Slave Node **:
First of all a container is created with the help of a container engine inside a POD. 
For creation of a POD kubelet makes a request to the API server and then the Master node plays its role.
After creation of POD, Kubeproxy assigns it IP address so that a POD can be uniquely identified.
How To Group Result By A Particular TimeFrame E.g Weeks Using PostgreSQL
Tags: webdev, postgres, programming, database
Published: 2023-01-04 17:49:37

We have a database of posts, comments and likes. The likes table has a field which states if the like is for a comment or for a post.

The task is to return the number of likes on comments and posts created in each week.

1. Let us create all 3 tables

```
create table likes(
	id serial primary key,
	post_id integer,
	comment_id integer,
	created_at timestamp
);

create table comments(
	id serial primary key,
	created_at timestamp,
	contents varchar(20)
);

create table posts(
	id serial primary key, 
	created_at timestamp,
	caption varchar(40)
)
```


2. Let us insert values into the 3 different tables


```
insert into likes(created_at,post_id, comment_id)
values('2015-09-11 07:38:03.774+01', 2, null),
('2013-07-29 23:15:00.764+01', null, 1),
('2016-05-24 04:06:32.237+01', 2, null),
('2016-11-30 11:17:04.954+01', 1, null),
('2015-04-18 18:48:01.439+01', null, 3);

insert into posts(created_at, caption)
values('2015-09-11 07:38:03.774+01', 'he'),
('2013-07-29 23:15:00.764+01', 'kie'),
('2016-05-24 04:06:32.237+01', 'foe'),
('2016-11-30 11:17:04.954+01', 'eijw'),
('2015-04-18 18:48:01.439+01', 'jne');

insert into comments(created_at, contents)
values('2015-09-11 07:38:03.774+01', 'ew'),
('2013-07-29 23:15:00.764+01', 'ie'),
('2016-02-24 04:06:32.237+01', 'eiw'),
('2016-07-30 11:17:04.954+01', '303'),
('2015-04-18 18:48:01.439+01', 'ij')

```


## Then we will go into the hard part

First of all, you will realize that whenever we have data in the comment_id column of the likes table, the post_id field will have a default data of null. This is also done vice versa.

1. We will join the posts table to the likes table using a left join. This is to ensure that no likes record is left behind

```
left join posts on posts.id = likes.post_id
```

2. We will also join the comments tables to the likes table using the left join. This is to ensure that no likes record is left behind.

```
left join comments on comments.id = likes.comment_id
```

3. Then we will group the joined table using the week constraint.

```
select date_trunc('week', coalesce(posts.created_at, comments.created_at))as week from likes

```
4. We will then count the number likes and comments for each week

```
select count(comments.created_at) as liked_comment, count(posts.created_at) as liked_posts from likes
```


There you have it, the final result.

```
select date_trunc('week', coalesce(posts.created_at, comments.created_at))as week, count(comments.created_at) as liked_comment, count(posts.created_at) as liked_posts from likes
left join posts on posts.id = likes.post_id
left join comments on comments.id = likes.comment_id
group by week
order by week desc
```


If you have any questions, feel free to leave a comment and I will respond as fast as possible.
Streamlining gcloud with a custom CLI for serverless JavaScript developers
Published: 2023-01-04 17:33:17

## Overview

In my [previous article](https://dev.to/subfuzion/getting-started-with-the-google-cloud-cli-interactive-shell-for-serverless-developers-45l), I walked through using the Google Cloud CLI interactive shell for deploying serverless apps to Cloud Run.

As noted, `gcloud` provides comprehensive commands, but using it involves fairly detailed knowledge of a somewhat daunting number of steps that must be followed to set up project resources and deploy an app.

To simplify the experience for JavaScript developers, I created a lightweight CLI, called `run`, that streamlines those steps using a simple configuration file (`run.yaml`) to handle all the details. When you deploy, `run` will prompt for any missing configuration settings and save them for subsequent deployments.

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

In addition, the `run` CLI can also generate starter projects and examples to help you get up and running even faster.

To create and deploy an application, you run the following commands:

```
run login
run new
run deploy
```

This what using `run` looks like:

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

I plan to add more templates, examples, and support for integrations with other Google Cloud services.

Keep in mind that `run` is not a replacement for everything that `gcloud` can do. It's primary goal is only to make it easier for JavaScript developers to get up and running on Cloud Run.

Install it from [npm](https://www.npmjs.com/package/@subfuzion/run):


```
npm install -g @subfuzion/run

# or

npx @subfuzion/run
```

See the [repo](https://github.com/subfuzion/run) for more details.

Give `run` a try and let me know what you think.
Pinte su camino hacia una experiencia inolvidable.
Published: 2023-01-04 17:28:29

Haz que tu evento especial sea memorable con nuestro [campo de paintball en Ruidera](https://www.animadoscb.com/paintball-en-lagunas-de-ruidera/).


Da rienda suelta a tu guerrero interior con el Paintball en Las Lagunas de Ruidera.
Celebre cualquier ocasión especial o simplemente diviértase con sus amigos en nuestro campo de paintball. Nuestro equipo de profesionales se asegurará de que tengas todo lo necesario para que tu experiencia sea inolvidable.
Celébralo con estilo.
Haz que tu evento especial sea inolvidable con un campo de paintball en Las Lagunas de Ruidera. Ya sea una comunión, un cumpleaños, una despedida o cualquier otra celebración, tú y tus invitados podréis pasarlo en grande jugando en el campo de paintball.
Celebre cualquier hito con paintball.
Haga que cualquier hito sea inolvidable en el Campo de Paintball de Las Lagunas de Ruidera. Ya sea un cumpleaños, un aniversario, una promoción o una reunión, usted y su grupo se lo pasarán en grande jugando al [paintball en Ciudad Real](https://www.animadoscb.com/campo-paintball-ciudad-real/) y creando recuerdos para toda la vida.

Celebre sus acontecimientos especiales de una forma única.
Haz que tus eventos especiales sean aún más memorables celebrándolos en el campo de Paintball de Las Lagunas de Ruidera. Diviértete y juega con tu familia y amigos mientras creas recuerdos imborrables.

Cree recuerdos que durarán toda la vida.
Pásalo en grande en el campo de paintball
Published: 2023-01-04 17:26:31

¡Celebra cumpleaños, despedidas de soltero y cualquier otro evento especial con las emociones del [campo de paintball en Ciudad Real ](https://www.animadoscb.com/campo-paintball-ciudad-real/)
Reserva ahora




Libera a tu guerrero interior
Únase a nosotros para vivir una experiencia única y emocionante en nuestro campo de paintball al aire libre. Perfecto para cualquier evento especial, ejercicio de formación de equipos o simplemente para divertirse. Nuestras instalaciones de última generación se encuentran en las hermosas Lagunas de Ruidera, requerirán un escenario ideal para su próxima aventura.
Celébralo con estilo.
Haz que tu evento sea inolvidable con un campo de paintball en Las Lagunas de Ruidera. Perfecto para comuniones, despedidas y otras ocasiones especiales, muestra a tus invitados una experiencia sin igual. ¡Prepárate para celebrarlo por todo lo alto!

CARACTERÍSTICA #2
Celebra cualquier evento con una batalla de paintball.
¡Haga que su día especial sea inolvidable con una batalla de paintball en Las Lagunas de Ruidera! Perfecto para cumpleaños, eventos corporativos o cualquier tipo de celebración, el campo ofrece una forma emocionante y única de crear recuerdos que durarán toda la vida.
Celébralo por todo lo alto con una experiencia de Paintball.
Haga que cualquier evento sea memorable con una experiencia de [Paintball en Las Lagunas de Ruidera](https://www.animadoscb.com/paintball-en-lagunas-de-ruidera/). Disfrute de la emoción del juego mientras pasa tiempo con amigos y familiares. Con nuestra gama de opciones, puede personalizar la experiencia para satisfacer las necesidades de todos.

¿A qué esperas? ¡Pintemos la ciudad de rojo!
A running sum
Tags: javascript, beginners, programming, tutorial
Published: 2023-01-04 17:21:46

Today I took a break from working with JS objects, and did a challenge involving an array instead. 



```js
/* Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).

Return the running sum of nums.

Example:

Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
*/
```

## Write the function that sums together array items
<br/>
```js
const runningSum = (array) => {
//loop through the array for the length of the array.
// sum together the previous item from the array to the current item of the array
//return the new array

};
```
<br/>
The start seems really easy, just apply a for loop to the array and the deed is done. Not so fast.
<br/>
```js
for(let i = 0; i<array.length; i++){
  
}
```
<br/>
When working with arrays, I usually start the index (`i`) at the value of `0`. Let's think about how this would work in this example.
<br/>

We need to put together the previous array item `[i-1]` and the current array item `[i]`. If we run the code as is, with `let i = 0`, then the beginning index is -1. That won't do. Javascript arrays are zero indexed and I needed to modify the value of `i`, so that `[i-1]` returns zero on the first loop. I just decided on changing the value to `1` and that solved the problem.

<br/>

```js
const runningSum = (array) => {
for(let i = 1; i<array.length; i++){

}

};
```
<br/>

After that it is just as easy as suming both values together, set the new value of the existing array to the said sum / new value and continue doing so until the end of the array. After that the new array is returned and that is it.

<br/>

```js
const runningSum = (array) => {
  for (let i = 1; i < array.length; i++) {
    let newValue = array[i - 1] + array[i];
    array[i] = newValue;
  }
  return array;
};
```
<br/>

I tried the code on a few different examples and got the wanted results. It looks like the code is working as intended.

```js
console.log(runningSum([1, 2, 3, 4]));
console.log(runningSum([1, 1, 1, 1, 1, 1]));
console.log(runningSum([1, 2, 3, 4, 5, 6]));
console.log(runningSum([1, 2, 3, 3, 2, 1]));

/* Results:
[ 1, 3, 6, 10 ]
[ 1, 2, 3, 4, 5, 6 ]
[ 1, 3, 6, 10, 15, 21 ]
[ 1, 3, 6, 9, 11, 12 ]
*/
```
<br/>

### Conclusion

That is it for today's challenge. It was nice short and simple, great for practicing things that I studied.
How to use ChatGPT in Visual Studio Code.
Tags: dev, openai, gpt3, vscode
Published: 2023-01-04 17:18:03

> Devs, are you tired of having to switch from Visual Studio Code to the browser to search for information or answers to your questions? **Try VS ChatGPT!**

## What is VS ChatGPT?

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

[VS ChatGPT](https://marketplace.visualstudio.com/items?itemName=0xFedev.vs-chatgpt) is an extension for Visual Studio that allows you to bring the power of OpenAI GPT-3 directly into the most popular and widely used editor.

Using the extension is very simple:

* Search for "VS ChatGPT" in the marketplace and install the extension;
* Register an account with OpenAI and generate a new API Secret Key;
* Set the API Key in the extension settings;
* Run the command `ChatGPT: Text completions` and start using the extension!

Enjoy!
CodeNewbie Podcast Season Finale (S22E9): Coding Bootcamps and Coding Journeys with Mark Thompson
Tags: podcast, codenewbie, bootcamp
Published: 2023-01-04 17:08:37

---
title: CodeNewbie Podcast Season Finale (S22E9): Coding Bootcamps and Coding Journeys with Mark Thompson
published: true
description: 
tags: podcast, codenewbie, bootcamp
cover_image: https://community.codenewbie.org/remoteimages/uploads/articles/dwqjlzwlpk0xsucgml6q.png
---

In this season finale (S22E9) of the CodeNewbie Podcast, @saronyitbarek talks about coding bootcamps and learning journeys with [Mark Thompson](https://twitter.com/marktechson), Senior Developer Relations Engineer at Google. 

{% embed https://community.codenewbie.org/codenewbiepodcast/s22e9-coding-bootcamps-coding-journeys-mark-thompson %}

Mark Thompson, [aka Mark Techson](www.marktechson.com), loves to teach and code. He is an award-winning university instructor and engineer with a passion for creating meaningful learning experiences.

- [Listen on Apple Podcasts](https://podcasts.apple.com/us/podcast/s22-e9-coding-bootcamps-coding-journeys-mark-thompson/id919219256?i=1000592322158)

- [Listen on Spotify](https://open.spotify.com/episode/1zhOKw5o3U6vFl9B7gEcBv?si=3e5545dd3fe44a7d)

Or, listen wherever you normally get your podcasts!

***

That's all for this season of the CodeNewbie podcast! We hope you enjoyed it. Word of mouth goes a long way in the worlds of tech and podcasting, so please share your favorite episodes with your friends! We'll see you next season 💜
Python Dictionaries - Update data, loop through 🐍
Tags: python, webdev, programming, tutorial
Published: 2023-01-04 17:07:29

Dictionaries are an interesting data structure in Python. In other programming languages like JavaScript, you can call it an object.

Getting back to our example, we can change the value of a dictionary key as shown below:

```
dict = {"name": "Nitin", "age": 34, "gender": "male"}

dict["name"] = "ABC"
dict["name"]
Result -> ABC
```
Pretty easy isn't it?

### Add a new key-value pair
Now let's look at how we can add a new key-value pair to a dictionary.
Python dictionary has an `update` method that gives you the freedom to add or update a new key-value pair.

```
dict = {"name": "Nitin", "age": 34, "gender": "male"}

dict.update({"city": "Pune"})
dict
Result -> {"name": "Nitin", "age": 34, "gender": "male", "city": "Pune"}
```

### Update a key-value pair
Updating a key-value pair is pretty simple.
```
dict = {"name": "Nitin", "age": 34, "gender": "male"}

dict.update({"city": "Delhi"})
dict
Result -> {"name": "Nitin", "age": 34, "gender": "male", "city": "Delhi"}
```

If you observe in the above example, the new key-value pair is added with the curly braces as an argument to the `update` method.
>If the key-value pair already exists in the dictionary then the value will be replaced and if the key-value pair does not exist then this method will create a new key-value pair.


### Loop over the dictionary
We can also loop over the dictionary data using the `for` iterator and it's quite easy.
```
dict = {"name": "Nitin", "age": 34, "gender": "male"}

for data in dict.keys():
    print(data)

Result ->
name
age
gender
```
Here we loop over the dictionary keys and as a result, the keys are getting printed.

We can also loop over the dictionary keys' values using the `for` iterator
```
dict = {"name": "Nitin", "age": 34, "gender": "male"}

for data in dict.values():
    print(data)

Result ->
Nitin
34
male
```

### Easy to understand? 💡

A dictionary contains

- Loop over the dictionary
- Add or update the dictionary data

>This would look similar to an object in JavaScript


## Conclusion 📗

There are more posts on the way related to the dictionaries...So keep reading.

Thanks in advance for reading this article...🚀

*I am more than happy to connect with you on*

- [@twitter](https://twitter.com/_nitinreddy3)
- [@LinkedIn](https://www.linkedin.com/in/nitinreddy3/)

*You can also find me on*

- [@Github](https://github.com/nitinreddy3)
- [@DEV](https://dev.to/nitinreddy3)
- [@Medium](https://medium.com/@nitinreddy3)