teleren/devto huggingface dataset:
Connect Ropes(code and explanation)
Tags: leetcode, algorithms, python, beginners
Published: 2022-02-13 16:04:28

**Yet another question on a mixture on Greedy approach utilizing heap data structure**
Problem Statement 
Given ‘N’ ropes with different lengths, we need to connect these ropes into one big rope with minimum cost. 
The cost of connecting two ropes is equal to the sum of their lengths.
Example 1:
Input: [1, 3, 11, 5]
Output: 33
Explanation: First connect 1+3(=4), then 4+5(=9), and then 9+11(=20). So the total cost is 33 (4+9+20)
Example 2:
Input: [3, 4, 5, 6]
Output: 36
Explanation: First connect 3+4(=7), then 5+6(=11), 7+11(=18). Total cost is 36 (7+11+18)
**SOLUTION**
This question is a perfect example of how heap data structure can be utilized in solving a question that requires greedy approach
In this case, everytime you have to add the smallest two numbers.You can even do this question using a auxillary array that will store all the prefix sums
but here we will be utilizing an heap to do so
**ALGORITHM**
1.Make a min heap
2.Push all the elements in the heap
3.Remove top two elements from the heap and store its sum in another variable
4.Push this sum again in the heap
5.Continue till heap is empty

```
from heapq import *
def connectRopes(ropeLengths):
    minHeap = []
    for length in ropeLengths: #push all the lengths in heap
        heappush(minHeap, length)
    
    finalLength = 0
    while len(minHeap) > 1:
        temp = heappop(minHeap) + heappop(minHeap) #pop the first two elements
        finalLength += temp #Calculate its sum and store in another variable 
        heappush(minHeap, temp) #Push the current sum again in heap for further calculations
    return finalLength
```
_Time Complexity_
Inserting all the elements inside a heap will take O(NlogN)
Removing top two elements and again push in heap will take a maximum of O(NlogN) time
So overall time complexity is O(NlogN)
_Space Complexity_
minHeap will require a space of O(N)
SUPER SEMAINE LIBÉCLUBIENNE - Programme
Tags: libeclub
Published: 2022-02-13 16:02:56


![Affiche Super Semaine Libéclubienne](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oee26iuuxh0t0ebv7mui.png)
Dès demain, la SSL (Super Semaine LIBÉCLUBIENNE) commence, alors voici un petit rappel concernant notre programme ! Mais avant de commencer, **N'OUBLIEZ PAS DE VOUS INSCRIRE DANS L'ONGLET "ÉVÉNEMENT" DU DISCORD POUR AVOIR ACCÈS AUX ACTIVITÉS**. C'est important de le faire, ça nous facilite la vie concernant l'organisation, ça évite les débordements (ex : en séance cinéma quelqu'un arrive et une discussion se forme sur un autre sujet alors qu'on regarde un fim). MERCI :)


![Affiche planning](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zatv6s9qdfjcuq8ru1v6.png)
· **14 février 2022 à 21h00 : Le Château Ambulant**
![Affiche Château Ambulant](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3a4q30b4vzw8hrtenu7m.png)Regardons tous ensemble le film "Le Château Ambulant"
> Sophie, une orpheline de 18 ans, travaille dur dans la boutique de chapelier que lui a laissée son père. Un jour, en ville, elle croise Hauru, un magicien très séduisant, mais faible de caractère. Une sorcière, se méprenant sur leurs sentiments, change Sophie en une vieille femme de 90 ans.

· **15 février à 21h00 : Soirée dessin**
![Affiche Soirée dessin](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/soy8yz9ac7mfiqvo4gx3.png)

· **16 février à 21h00 : Soul**
![Affiche Soul](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cjqgb1s906ef1mnvcxip.png)Regardons tous ensemble le film "Soul"
> Passionné de jazz et professeur de musique dans un collège, Joe Gardner a enfin l'opportunité de réaliser son rêve : jouer dans le meilleur club de jazz de New York. Mais un malencontreux faux pas le précipite dans le 'Grand Avant', un endroit fantastique où les nouvelles âmes acquièrent leur personnalité, leur caractère et leur spécificité avant d'être envoyées sur Terre. Bien décidé à retrouver sa vie, Joe fait équipe avec 22, une âme espiègle et pleine d'esprit.

· **17 février à 21h00 : Soirée Jeux**
![affiche soirée jeux](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t41pd3vz89yuf58e6x26.png)Nous allons jouer à plusieurs et s'affronter sur divers jeux tel que : **Wolfy(Loups-Garous), Among Us, Gartic Phone, KCulture, et peut-être plus encore...**

· **18 février à 21h00 : Soirée PowerPoint**
![affiche soirée powerpoint](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wuyebtj74cb02bds31ml.png)Avec le logiciel de votre choix, créez un diaporama/exposé sur un thème libre en environ 1h30. Vous le présenterez ensuite 
INSCRIPTION OBLIGATOIRE

Merci de m'avoir lu, n'oubliez pas de vous inscrire!
Introduction to modern python: Getting started with python
Tags: python, luxtechacademy, datascience, programming
Published: 2022-02-13 15:13:57




As a code newbie, when someone talks about python the first thing that comes to mind is probably the animal lol well it's not.
Python is a computer programming language that enables users to build websites, analyze data and visualize data.
It was originally created by Guido van Rossum in 1991 and further developed by the python Software Foundation. Guido wanted to create a programming language that was that used simple syntax and had code lines that were easy to read. he named python python because he wanted a name that was unique and kind of mysterious.

_**So why should you want to learn how to code using python**_
_There are many reasons why you want to learn python_

 

* It's highly versatile: Python can be used to carry out several functions across many industries. Functions such as analyzing data etc.
*  It uses simple syntax: This makes coding easy to understand and learn. It is said that if you can write 'hello world' that you can write any line of code. Believe me this is very true.
 ```
 print ("hello world")
  ```
*  Python has a large and very supportive community where you can ask any confusing question and get answers. Communities like stack overflow etc.
  
*  Python is one of the most used programming languages in the world. Many big companies use this language, companies like google, facebook, amazon, netflix to mention but a few.

* The demand for python and skilled python users is on the increase. The career opportunities and salary is also increasing, it is used in fields like data science, app development, web development, machine learning etc.
![From the image we can see that python is topping the list of programming languages with about 29.72%](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hj825cvztut1y6frcjst.jpg)
_**
So where can you learn python from**_
  You can learn python from 
*Bootcamps
*Online courses: Courses from udemy, coursera, codecademy, udacity, sololearn etc.
*Youtube
One of the most amazing things is that most these sites offer free courses.
You can also read blog post on medium, hashnode, dev.to etc, they will help a lot.

Incase you are confused on any syntax, you can google it, websites like stack overflow, geek for geeks, w3schools will help out.
Remember google is your friend.

Thanks for reading!
Manage CodeCommit and CodePipeline in Multiple AWS Accounts
Published: 2022-02-13 15:09:10

This video demonstrate how to setup AWS Codepipelines in multiple AWS accounts with single CodeComit as a Single Source Of Truth.

https://youtu.be/bB3vwAUgsBk

Use this repo to access the IAM policy materials used in this demo.
https://github.com/awsfanboy/aws-codecommit-with-crossaccount-codepipeline
Install PHP AMQP Extension on Mac
Tags: php, pecl, macos, homebrew
Published: 2022-02-13 14:37:20

I spent several hours trying to set up **PHP** **amqp** extension on mac. When I finally got it to work, I created this post as a reference for myself in the future, and also to assist anyone trying to install it.


First, follow the usual steps to install rabbitmq from the URL: 
https://rabbitmq.com/install-homebrew.html

After installing rabbitmq and adding it to your path, you can then follow these steps found in this URL:
https://blog.karatos.in/a?ID=00850-2e534416-7a8d-4bce-b77c-ea946f63e10c

The steps below are similar to the ones in the above URL, however, I had to modify it to make it work in my case.

Download the latest version of AMQP or any version of your choice from this URL: https://pecl.php.net/package/amqp

Extract the zipped file and visit it on your terminal.

```
$ cd/Users/***/Downloads/amqp-<VERSION>/amqp-<VERSION>
```

```
$ phpize
```

```
$ ./configure -with-php-config=/opt/homebrew/bin/php-config --with-amqp --with-librabbitmq-dir=/opt/homebrew/Cellar/rabbitmq-c/<VERSION>
```

In my case, I ran the previous command with version 0.11.0 as seen below:
./configure -with-php-config=/opt/homebrew/bin/php-config --with-amqp --with-librabbitmq-dir=/opt/homebrew/Cellar/rabbitmq-c/0.11.0

**Run the following commands**:

```
$ make
```

```
$ make test
```

```
$ make install
```

That's it. amqp should be installed by now. Next, you have to add the extension to your PHP configuration.

Open the php.ini file at **/opt/homebrew/etc/php/8.1/php.ini**, if the extension have been added (extension="amqp.so"), remove it and create ext-amqp.ini in the folder /opt/homebrew/etc/php/8.1/conf.d and add the following content:

[ampq]
extension="amqp.so"

Save the file and restart php.

```
$ brew services restart php
```

Next, check if it amqp is installed successfully:

```
$ php -i|grep amqp
```

Happy hacking 🚀


**References**

- https://stackoverflow.com/questions/51818515/installing-amqp-on-mac-with-brew/69653679#69653679

- http://kasanova.nl/posts/enable-amqp-in-php

- https://rabbitmq.com/install-homebrew.html

- https://blog.karatos.in/a?ID=00850-2e534416-7a8d-4bce-b77c-ea946f63e10c

- https://pecl.php.net/package/amqp
How to create staging environment on Cloudflare Pages
Tags: cloudflare, cloudflarepages
Published: 2022-02-13 14:29:30

---
title: How to create staging environment on Cloudflare Pages
published: true
tags: Cloudflare,CloudflarePages
---

As far as I know, Cloudflare does not officially provide documents to set up staging environments on Cloudflare Pages.
I raised a feature request to allow us creating staging environments, and then I got an advise how to create staging environments.

## Premises

When you push or merge changes to the `staging` branch on GitHub, the content of the `staging` branch will be deployed and the deployment can be accessible from stg.example.com.
The deployment of the `main` branch can be accessible from example.com as well.

- Project name of Cloudflare Pages: example-prj
- Name of the Git branch corresponding to the staging environment: `staging`
- Domain name for staging environment: stg.example.com (You can also associate different apex domain like example-stg.com.)
- Name of the Git branch for production environment: `main`
- Domain name for production environment: example.com

## 1. Create `staging` branch on GitHub

Create it as usual.

## 2. Add stg.example.com to Custom Domains of Cloudflare Pages

You can see Custom Domains tab on the Cloudflare Pages dashboard.
Add stg.example.com from the tab.

## 3. Fix DNS so that stg.example.com points the deployment for `staging` branch

By adding the custom domain to Cloudflare Pages, the new CNAME record stg.example.com which points example-prj.pages.dev is automatically added to your DNS.

Modify the DNS record value so that it points staging.example-prj.pages.dev.

Note that you need to enable Cloudflare CDN (orange-cloud) for stg.example.com. If you disable Cloudflare CDN (gray-cloud), stg.example.com does not point staging deployment properly.

(Therefore, I guess you cannot associate domain with staging deployment if you use a DNS provider other than Cloudflare. See next section for possible workaround.)

## Why this works?

Actually, each deployments of the non-production branches are accessible with BRANCH_NAME.example-prj.pages.dev. We just associated the custom domain with it.

As I mentioned, if you use a DNS other than Cloudflare, I guess you cannot associate custom domain with the staging deployment. You can use staging.example-prj.pages.dev as the staging environment.
Specificity Matters in Media Queries
Tags: webdev, html, css, tutorial
Published: 2022-02-13 14:22:41

A few weeks ago, I was working on a website page's responsive design and was fiddling with the media queries. For some reason, the `grid-template-areas` property wouldn't adjust when the *viewport width* hits the indicated size but there were no problems with the other properties that were being changed alongside it.

---

##Consider the Code below (written using sass):
```
#Initial Properties
.container .contact .contact-form {
    display: grid;
    column-gap: 2rem;
    row-gap: 2.4rem;
    grid-template-areas:
        "name email"
        "subject subject"
        "message message"
        "send send";
}
```
(NOTE: The `.container` is nested inside a *body* and *main* tag)

```
@media (max-width: 700px) {
.contact .contact-form {
    background: yellow;
    grid-template-areas:
        "name name"
        "email email"
        "subject subject"
        "message message"
        "send send";
    }
}
```
(NOTE: The `background-color` change was only used to show that it's working on the indicated viewport width(700px), but the `grid-template-areas` does not)
###The Result
![Initial Result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9oxr40h7nnc30wq5otzz.png) As you can see, the `background-color` changed as expected but not the `grid-template-areas` result which should presumably have all the input blocks occupy the entire width of the form.

---

##How I solved this is by adding another parent tag when targeting the `.contact-form` , namely the `.container` parent.
```
#Media Query REVISED
@media (max-width: 700px) {
.container .contact .contact-form {
    background: yellow;
    grid-template-areas:
        "name name"
        "email email"
        "subject subject"
        "message message"
        "send send";
    }
}
```
![Final Result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6xcxa7nsxd62hwo8tpyq.png)Adding the `.container` class allowed the `grid-template-areas` changes to go through. It doesn't end here though. Oddly enough, even if I don't use the `.container` class but instead used its parents in its place, namely the `<main>` or `<body>` tag, the changes will still go through:

```
@media (max-width: 700px) {
    main .contact .contact-form {
    }
}

AND

@media (max-width: 700px) {
    body .contact .contact-form {
    }
}
```
*will work, but*
```
@media (max-width: 700px) {
    .contact .contact-form {
    }
}
```
*does not.*

---

##Conclusion
I tried recreating this using CSS and SCSS, with the same tags, classes, and nesting (just the very bare minimum) but the same problem didn't present itself. I don't know what was wrong with my previous code but I just concluded that I should be VERY SPECIFIC when using media queries.
.
.
.
(Just my thoughts and experience, Not a tutorial)
Setting up absolute paths in Parcel and TypeScript
Tags: typescript, parcel, beginners
Published: 2022-02-13 14:09:56

## Motivation

Absolute paths are very useful. Instead of importing modules using relative paths, first descending to the root level and then going up again, when we use absolute paths we just need the "going up" part because we start from the root directory already.

One of the main advantages of absolute paths over relative ones is the independence of file location within the project; that is, you can move the file to a new location without having to edit its contents.

As an example, let's imagine that we have the following directory structure:

![An example of directory structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4vhig74hkakl5go6wjar.png)

Using relative path, to import something from `lib.ts` into `fool.ts` I would have to write:
```javascript
// first I "go down" and then "go up" again
import { Example } from  "../../../lib/lib";
```

Using absolute path, importing the same module is simpler:
```javascript
// I start from the "root" directory
import { Example } from "lib/lib";
```

The "problem" here is that absolute paths do not work in TypeScript or Parcel by default.

## Absolute paths in TypeScript

To be able to use absolute paths in TypeScript we can set the `baseUrl` property in the `tsconfig.json` file. With this, we define `src` as our root directory (for module resolution).

```json
// tsconfig.json
{
  ...
  "baseUrl": "./src"
  ...
}
```

According to TypeScript [documentation(1)](https://www.typescriptlang.org/docs/handbook/module-resolution.html#base-url):
> Setting baseUrl informs the compiler where to find modules. All module imports with non-relative names are assumed to be relative to the baseUrl.

## Absolute paths in Parcel
Although Parcel works very well with TypeScript, it does not use the `baseUrl` property of `tsconfig.json` to resolve module paths. For it to be able to find the files, there is a proper configuration - using [aliases(2)](https://parceljs.org/features/dependency-resolution/#aliases) - to be added to `package.json`

```json
// package.json
{
  ...
  "alias": {
    "lib": "./src/lib"
  }
  ...
}
```

That's it! Now our code `import { Example } from "lib/lib";` works as expected and modules paths are resolved accordingly. 🙂

## Links

1. https://www.typescriptlang.org/docs/handbook/module-resolution.html#base-url
2. https://parceljs.org/features/dependency-resolution/#aliases
3. https://www.typescriptlang.org/tsconfig#baseUrl
JavaScript 101: Ultimate JavaScript Guide
Tags: javascript, beginners, webdev, luxacademy
Published: 2022-02-13 14:02:31

## Introduction
JavaScript is one of the most popular programming languages on the planet. It can both be used as a client-side or server-side language. On the client-side, it is used with HTML(Hypertext Markup Language) and CSS(Cascading Style Sheets) to enhance a web page’s functionality such as: validating forms, creating interactive maps, and displaying animated charts. JavaScript can also be run on servers; a popular server side environment is Node.js. Here, it's used to access databases and file systems.

## Getting Started
Because of its wide range of applications, you can run JavaScript in several ways:
* Using console tab of web browsers
* Using [Node.js](https://nodejs.org/en/download/)
* Using code editors e.g. [Visual Studio Code](https://code.visualstudio.com/)
* By creating web pages

All the popular web browsers have built-in JavaScript engines hence you can run JavaScript on a browser. In this JavaScript guide we'll be using the [google chrome](https://www.google.com/chrome/?brand=BNSD&gclid=CjwKCAiA9aKQBhBREiwAyGP5lfxrytDR24JQsIDmsCI39aV_o2_Qy8fj9QurSeA6b_Dppon_-Yn3lxoCnugQAvD_BwE&gclsrc=aw.ds) console tab to run our first JavaScript program. 


Exciting, innit?
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pvgx9ccr2ho0duw6zast.gif)

The first step is to open google chrome, followed by opening the console tab by pressing `Ctrl+Shift+i` if you're on windows. You can use the console tab to run any JavaScript program.

In JavaScript, users can declare a variable using 3 keywords: var, let and const. **var** is global scoped, **let** is block scoped while **const** is also block scoped but can't be updated once it's declared.

Our first JavaScript program will simply be outputting a message on the console. Let's first declare a string variable x as shown below.
`var x = "Hello world!";`

The next step is to output the string on the console using the command below.
`console.log(x);`

The output of this program is shown below.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/852rofxhwid7vcadd9e0.jpg)


That wasn't hard, was it?
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ya8n0x689l0yn7qa20o.gif)

## What Next?
If you wish to continue learning JavaScript in depth, here are some **free** resources that may be helpful:
* [Free code camp](https://www.freecodecamp.org/news/learn-javascript-full-course/)
* [The Net Ninja](https://www.youtube.com/watch?v=iWOYAxlnaww&list=PL4cUxeGkcC9haFPT7J25Q9GRB_ZkFrQAc&ab_channel=TheNetNinja)
* [Traversy Media](https://www.youtube.com/watch?v=hdI2bqOjy3c&t=12s&ab_channel=TraversyMedia)

I hope you found this article useful and I'd like to urge you to do as many projects as possible in order to improve your skills. Bonne chance!
Quick start with Kafka
Tags: kafka, beginners, macos, streaming
Published: 2022-02-13 13:52:40

Just a **quick introduction about Kafka**. Apache Kafka is a framework implementation of a software bus using stream-processing. It is an open-source software platform developed by the Apache Software Foundation written in Scala and Java. The project aims to provide a unified, high-throughput, low-latency platform for handling real-time data feeds. Wikipedia

So you can use Kafka for streaming real time data, message or for a ETl application and many more types eg. Netflix heavily use Kafka.

**Kafka general concept**:
Producer -> kafka borker -> topic -> consumer

So producer can create stream of messages for a specific topic. And that topic can be send almost real time to consumer which subscribed to that topic.

**How to install and start Kafka**:
As kafka is depends on zookeeper [Apache ZooKeeper is an open-source server for highly reliable distributed coordination of cloud applications. It is a project of the Apache Software Foundation. Wikipedia]. So need to install zookeeper as well.
But first we need to install Java. I am installaing in mac, almost similar process for other operating system as well.

`brew install java`
`brew install kafka`
It will install kafka along with all dependencies including zookeeper.

Then we need to run zookeeper in one tab of terminal by running the following command `zookeeper-server-start /usr/local/etc/kafka/zookeeper.properties`

Open another tab and run kafka by running the following command `kafka-server-start /usr/local/etc/kafka/server.properties`

Open another tab and create a topic on which we can test the both producer and consumer activity.
`kafka-topics --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1 --topic test`
Then run producer to send message `kafka-console-producer --broker-list localhost:9092 --topic test`
It will open for you to send messages. Wait and open another tab.
Run consumer `kafka-console-consumer --bootstrap-server localhost:9092 --topic test --from-beginning` 

And then go back to producer and send some message and see them immediately in consumer tab.
567. Permutation in String
Tags: cpp, programming, algorithms
Published: 2022-02-13 13:50:23



# Description

Given two strings `s1` and `s2`, return `true` *if* `s2` *contains a permutation of* `s1`*, or* `false` *otherwise*.

In other words, return `true` if one of `s1`'s permutations is the substring of `s2`.

## Example 1:

```
Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").
```

## Example 2:

```
Input: s1 = "ab", s2 = "eidboaoo"
Output: false
```

## Constraints:

- `1 <= s1.length, s2.length <= 104`
- `s1` and `s2` consist of lowercase English letters.

---

# Solutions

## Solution 1

### Intuition

### Code

```java
class Solution {
public:
    unordered_map<char, int> map1, map2;
    bool check(char& c) {
        if (map1.count(c) && map1[c] == map2[c]) {
            return true;
        }
        return false;
    }
    bool checkInclusion(string s1, string s2) {
        for (char& c : s1) {
            map1[c]++;
        }
        for (int i = 0, j = 0, cnt = 0; i < s2.size(); i++) {
            if (check(s2[i])) cnt--;
            map2[s2[i]]++;
            if (check(s2[i])) cnt++;
            if (i - j == s1.size()) {
                if (check(s2[j])) cnt--;
                map2[s2[j]]--;
                if (check(s2[j])) cnt++;
                j++;
            }
            if (cnt == map1.size()) return true;
        }
        return false;
    }
};
```

### Complexity

- Time: O(n)
- Space: O(n)

---