teleren/devto huggingface dataset:
AWS S3 -- CLI で bucket の中身を全て DL する
Tags: aws, s3
Published: 2022-06-12 16:34:22


## why

AWS S3 は Web コンソールの GUI だと、
ファイルを一つ一つ DL することしかできない。

サイトの CSS などが膨大な場合、すべて手動だと
かなり時間がかかってしまう。

なので一つのバケットをまとめて DL する方法を調べた。

---


## 前提

S3 のディレクトリと IAM ユーザーは作ってあるものとする

## アクセスキーの生成

https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html

この記事の通りに IAM の

左のリストメニューの Users
タブの一つの Security credentials
内部のボタンの Create access key

ここまで行くとモーダルが表示されるので

* Access Key ID
* Secret Access Key

これらを控える。

---

## CLI アプリの DL

https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html

この記事を参考にして

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

インストーラーを DL

起動してインストール

```php
which aws
/usr/local/bin/aws

aws --version
aws-cli/2.7.4 Python/3.9.11 Darwin/21.5.0 exe/x86_64 prompt/off
```

ターミナルで調べてみると、無事に入っていることが確認できた。

---

## AWS の認証情報を入力する

https://docs.aws.amazon.com/cli/latest/userguide/getting-started-quickstart.html

このクイックスタートの記事を参考にする

```php
aws configure
AWS Access Key ID [None]: 
```

aws configure コマンドを打つと
対話式で 

* アクセスキーID
* シークレット アクセスキー
* リージョン名
* フォーマット端子

これらを求められるので入力する

前者 2 つは先ほど生成して
後者 2 つの
リージョンは ap-northeast-1 
フォーマットは json 
にする。

設定ファイルから読み込むこともできるらしい。

---

## S3 のディレクトリを Clone する

https://blackbird-blog.com/aws-s3-cli-download

この blackbird-blog の記事を参考にする

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

S3 の bucket を選び、ディレクトリで Copy s3 URL ボタンをクリックすると

s3://bucketName/directoryName/

この構成で s3 URL がクリップボードにコピーされる

このバケット名まで使って

```php
aws s3 cp {s3_URL} . --recursive
```

これでバケットの中身を全て DL できる

```php
aws s3 cp s3://workspace.name/ . --recursive

download: s3://workspace.name/assets/css/main.css to assets/css/main.css
download: s3://workspace.name/assets/css/header.css to assets/css/header.css
....
```

このように、中身を全て DL できた！
How to add Bootstrap to your React app
Published: 2022-06-12 16:32:57


When I started building projects and wanted to make them look good, I soon learned Bootstrap was an efficient way to style them. It's also pretty intuitive (which is a godsend). 

Unfortunately, I got stuck at the first step: installing Bootstrap.
 
Hopefully this will save you from getting stuck at the installation too. 

1. run `$npm install bootstrap react-bootstrap` in your React app's directory.

2. Now, it's time to ask yourself specifically what you want to style: buttons, the navbar, do you want to add cards? Browse through what bootstrap has to offer here: https://react-bootstrap.github.io/components/alerts/

3. Once you've perused through all the components Bootstrap has, and some have caught your eye, navigate to the file where you want to use them. Here, you'll import the specific component at the top of the file by writing: `import { Component } from "react-bootstrap"` (include the name of the component you want)
Underneath that, include: `import "bootstrap/dist/css/bootstrap.min.css";`

4. Now you're free to include that component in your file. 
If you want to add different components, simply add them to the curly braces at the import at the top of the file: 

`import { Component1, Component2 } from "react-bootstrap"`

Congrats! You've installed Bootstrap and included components in your app. Now, you can focus on styling the components to your preference.

... how do you do that?  

The styling in Bootstrap is done primarily through the component's attributes. For example: 

`<Component variant="primary">`

... will give you the pre-styled "primary" version of this component.

You can find these attributes and examples of what styles they offer in the "components" section of the Bootstrap docs we looked at before: 
https://react-bootstrap.github.io/components/alerts/

Hope this helped. For a great tutorial on how to use basic Bootstrap components: https://www.youtube.com/watch?v=8pKjULHzs0s
Same Tree
Tags: leetcode, dsa, theabbie
Published: 2022-06-12 16:30:39

Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg)

**Input:** p = \[1,2,3\], q = \[1,2,3\]
**Output:** true

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg)

**Input:** p = \[1,2\], q = \[1,null,2\]
**Output:** false

**Example 3:**

![](https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg)

**Input:** p = \[1,2,1\], q = \[1,1,2\]
**Output:** false

**Constraints:**

*   The number of nodes in both trees is in the range `[0, 100]`.
*   `-104 <= Node.val <= 104`

**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 isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
            if not p or not q:
                if p or q:
                    return False
                return True
            if p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right):
                return True
Hi, Welcome to melbite, 👋
Tags: webdev, melbite, tutorial, productivity
Published: 2022-06-12 16:16:31

Hello dev.to writers and learners,

Would you like to try this new blogging platform?

https://melbite.com

Melbite is a blogging platform for sharing all kinds of content from software development, farming, fashion, poetry, business ideas and all meaningful content.

Try it out.
https://melbite.com
Array Reduce Method in JavaScript
Tags: javascript, beginners, programming, tutorial
Published: 2022-06-12 16:13:44

Hello everyone! Today i wanted to write an article about a method that gave me a lot of trouble back in the day. That method is the **Array.prototype.reduce** method.

I'll first show the method to you using an example, then explain everything after.

Check the example below:

```javascript
const numbersToAdd = [0, 1, 2, 3, 4, 5];

const initialValue = 0;
const sum = numbersToAdd.reduce((previousValue, currentValue) => previousValue + currentValue, initialValue);

console.log(sum);
```

In the example above, we had an array that we wanted the sum of, so we used the reduce method to "reduce" the whole array into one number. That's what this method does, it **reduces** the array into one particular thing.

The reduce method takes one callback function, and optionally one other parameter that states the initial value that we're going to reduce the array to. This can be an object, a number, a string, anything basically.

Note that if you don't specify an initialValue, the reduce method will use the first element of the array as the initialValue.

And inside the callback, the callback function takes 2 parameters and it can take 2 other optional ones, the first two are **previousValue** and **currentValue** respectively. What that means is, reduce method effectively loops over the array, taking the returned value of the callback function, as the **previousValue** of the next loop. And uses that to execute the callback again with the **currentValue**, and so on so forth.

The other two parameters this method can take are **currentIndex** and **array**. As those two suggest by their name, **currentIndex** is just the current index of the **currentValue** in that array, and **array** of course, being the array itself that is being looped upon.

Here is another example, this time with all the optional parameters used:

```javascript
const peopleData = [["Khan", 23], ["James", 30], ["Molly", 43]];

const initialValue = {};
const peopleObj = peopleData.reduce((previousValue, currentValue, currentIndex, array) => {
  const [name, age] = currentValue;
  previousValue[currentIndex] = {
    name,
    age,
  };

  return previousValue
}, initialValue);

console.log(peopleObj);
```

OK i kinda lied with the "all" optional parameters being used part but i think you get what it means :D

And there you go, the Array Reduce method of JavaScript! I don't know why this gave me trouble before but i hope i cleared any confusion you might've had as well!


### CONCLUSION

Array reduce method is a method used to reduce an array into one specific thing. Like getting the sum of an array of numbers or making an object out of an information array.

And as always, if there's any error in my code or the information i've given you, please comment so i can see and fix it immediately! Feedback is very important, and i'm always looking out for it.

Have a great day! :)
Create a Simple Static Website on AWS S3 bucket using Terraform.
Tags: terraform, aws, s3, devops
Published: 2022-06-12 16:13:08

You can use Amazon S3 to host a static website. This is a simple way for you to host your portfolio online or for you to serve static content to your users. 

## Getting Started
Before we begin, you will need to have an AWS account and have terraform installed on your local machine. You can get started on AWS with a free tier. 
## Setting Up 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jzaw6dvf5v5iw68ff42o.png)
Our main.tf
{% embed https://gist.github.com/philcz16/cd905969487e95ceb337da421fcd252f.js %}

Variables.tf
{% embed https://gist.github.com/philcz16/7cfd037f59177174428352b3d805fe69.js %}

index.html
{% embed https://gist.github.com/philcz16/77dd9d81dbeeb0f194d9370c3107376b.js %}

error.html
{% embed https://gist.github.com/philcz16/3337797dd67d526c8490ed30836e5df7.js %}

##Putting it together
After installing AWS CLI run the command below to config your AWS environment so we can run terraform.

`aws configure`

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

`Terraform init`
The terraform init command is used to initialize a working directory containing Terraform configuration files

`Terraform fmt`
The terraform fmt command is used to rewrite Terraform configuration files to a canonical format and style (My favourite terraform command)

`Terraform validate`
The terraform validate command validates the configuration files in a directory

`Terraform plan`
The terraform plan command evaluates a Terraform configuration to determine the desired state of all the resources it declares, then compares that desired state to the real infrastructure objects being managed with the current working directory and workspace.

`terraform apply`
The terraform apply command executes the actions proposed in a Terraform plan to create, update, or destroy infrastructure.

Enter the bucket name and yes to create the bucket.

Once the bucket is created you can upload the index.html and error.html files or use 
`aws s3 sync $DESTINATION s3://$BUCKET_NAME`
I achieved this by placing the index.html and error.html in a $DESTINATION directory.

Click on your bucket, go to `properties` and scroll to the end.
Click on `Bucket website endpoint` to see your static website.
Positions of Large Groups
Tags: leetcode, dsa, theabbie
Published: 2022-06-12 16:00:43

In a string `s` of lowercase letters, these letters form consecutive groups of the same character.

For example, a string like `s = "abbxxxxzyy"` has the groups `"a"`, `"bb"`, `"xxxx"`, `"z"`, and `"yy"`.

A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx"` has the interval `[3,6]`.

A group is considered **large** if it has 3 or more characters.

Return _the intervals of every **large** group sorted in **increasing order by start index**_.

**Example 1:**

**Input:** s = "abbxxxxzzy"
**Output:** \[\[3,6\]\]
**Explanation:** `"xxxx" is the only` large group with start index 3 and end index 6.

**Example 2:**

**Input:** s = "abc"
**Output:** \[\]
**Explanation:** We have groups "a", "b", and "c", none of which are large groups.

**Example 3:**

**Input:** s = "abcdddeeeeaabbbcd"
**Output:** \[\[3,5\],\[6,9\],\[12,14\]\]
**Explanation:** The large groups are "ddd", "eeee", and "bbb".

**Constraints:**

*   `1 <= s.length <= 1000`
*   `s` contains lowercase English letters only.

**SOLUTION:**

    class Solution:
        def largeGroupPositions(self, s: str) -> List[List[int]]:
            n = len(s)
            i = 0
            op = []
            while i < n:
                ctr = 1
                while i < n - 1 and s[i] == s[i + 1]:
                    ctr += 1
                    i += 1
                i += 1
                if ctr >= 3:
                    op.append([i - ctr, i - 1])
            return op
iterate , iterate, iterate
Tags: functional, javascript
Published: 2022-06-11 17:55:36

Lets cut to the chase and look at what we are trying to do here. We need to write a function that can spit an array of any given size, such that every element is obtained by applying a function on the previous element.

Let us consider an initial element `x` and a function `f`, what we need is an array which looks something like this :
```javascript
[x, f(x), f(f(x)), ...]
```
Well, the simplest application of such a function would be to create a series of numbers like , squares of 2 : 1 ,2, 4, 8 ..

Now lets look at how we can write such a function 
```javascript
function iterate(fn, ele, n) {
  if (n === 0) return [];
  return [ele, ...iterate(fn, fn(ele), n - 1)];
}
```
Our function `iterate`, returns a list of repeated applications of `fn` to `ele`, repeated `n` number of times:
Lets try out some examples 
{% runkit
function iterate(fn, ele, iterationCount) {
  if (iterationCount === 0) return [];
  return [ele, ...iterate(fn, fn(ele), iterationCount - 1)];
}
%}
const multiply = (x) => (y) => x * y;
console.log(iterate(multiply(2), 1, 5));
{% endrunkit %}

The initial item and the function you apply can be anything that you can think of. You could easily create a list of dummy products take a look at the example: 
{% runkit
function iterate(fn, ele, iterationCount) {
  if (iterationCount === 0) return [];
  return [ele, ...iterate(fn, fn(ele), iterationCount - 1)];
}
%}
```
const initialProduct = { id: 100, slug: `prd${100}`, name: `Product-${100}` };

const createNextProduct = (product) => {
  const nextProductId = product.id + 1;
  return {
    id: nextProductId,
    slug: `prd${nextProductId}`,
    name: `Product-${nextProductId}`,
  };
};
console.log(iterate(createNextProduct, initialProduct, 5));
```
{% endrunkit %}
Python | OOP | Classes
Tags: python, guide, beginners
Published: 2022-06-12 15:55:29

Recently, I have realised that it is really hard for the beginners to follow the official documentations and most importantly, make sense out of it.

Since Python is one of the easy to use language and a lot of people want to get started with it, I think it is a good idea to share the knowledge in plain English.

For this reason, I am starting this blog post series to explain Python's object oriented model.

Python's object oriented model has the following basic characteristics:

- It is a mixture of the class mechanisms found in [C++](https://en.wikipedia.org/wiki/C%2B%2B) and [Modula-3](https://en.wikipedia.org/wiki/Modula-3).
- Classes themselves are objects. This helps for importing and renaming.
- Class members are public (Methods and Data Members both).
```python
class Example:
	classAttribute = 12345

example = Example()

print(example.i)
```

- Every class method needs to have `self` as the first argument, which is provided implicitly by the call.
```python
class Example:
	classAttribute = 12345

example = Example()

print(example.i)
```
- Aliasing: Objects have singularity, and multiple names can be bound to the same object. This is known as aliasing in other languages. Simply speaking, if you pass on object to a function as a argument and change the object inside that function, it will be changed in the main function as well.
```python
from typing import Type

class Counter:
    count = 0

def changeCount(counter: Type[Counter]):
    counter.count = 5

counter = Counter()

print(counter.count)
# 0

changeCount(counter)

print(counter.count)
# 5
```
- Most namespaces are currently implemented as Python dictionaries.
Binary Tree Pruning
Tags: leetcode, dsa, theabbie
Published: 2022-06-12 15:30:37

Given the `root` of a binary tree, return _the same tree where every subtree (of the given tree) not containing a_ `1` _has been removed_.

A subtree of a node `node` is `node` plus every node that is a descendant of `node`.

**Example 1:**

![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_2.png)

**Input:** root = \[1,null,0,0,1\]
**Output:** \[1,null,0,null,1\]
**Explanation:** 
Only the red nodes satisfy the property "every subtree not containing a 1".
The diagram on the right represents the answer.

**Example 2:**

![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_1.png)

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

**Example 3:**

![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/05/1028.png)

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

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 200]`.
*   `Node.val` is either `0` or `1`.

**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 hasOne(self, root):
            if root:
                if root.val == 1:
                    return True
                if self.hasOne(root.left) or self.hasOne(root.right):
                    return True
            return False
        
        def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
            if not self.hasOne(root):
                return None
            root.left = self.pruneTree(root.left)
            root.right = self.pruneTree(root.right)
            return root
Gradient Color Generator
Tags: html, css, javascript, webdev
Published: 2022-06-12 15:26:01

Hello World🌍, 
Welcome to my new article. Today, we are going a **beautiful Gradient Color Generator** using HTML, CSS, Javascript and also use a bit of bootstrap for styling.
Let's get to work!
- Out Boiler Plate

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <!-- Bootstrap cdn -->
  <link rel="stylesheet" href="style.css"> <!-- Our css-->
  <title>Gradient Color Generator</title>
<!-- Our main section will go here -->
<script src="script.js"></script> <!-- our js -->
</body>
</html>
```

- Our main section

```html
<main>
    <div class="container">
      <div id="hex-colors">
        <h1>Generate Beautiful Gradient Colors</h1>
        <h2>background: linear-gradient(to right, #<span id="hexcode1">ffffff</span>, #<span id="hexcode2">ffffff</span>);
        </h2>
        <button id="submit" class="btn btn-light">Click Me</button>
      </div>
    </div>
  </main>
```
We have some bootstrap classes in our main section.
But, we have to give it some basic style.
So, here goes:

- Our CSS (style.css)

```css
.container{
  width: 95%;
  margin: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

#hex-colors{
  width: 100%;
  text-align: center;
}

#hex-colors h1, h2{
  font-size: 2rem;
  text-transform: uppercase;
}

#hex-colors h2{
  margin-top: 15%;
  text-transform: lowercase;
}
```

- Our js (script.js)

```javascript
document.querySelector("#submit").addEventListener("click", () => {
    var hex_numbers = ["0","1","2","3","4","5","6","7","8","9","A", "B", "C", "D", "E", "F"];
    var hexcode1 = "";
    var hexcode2 = "";
    var random_index = 0;
    
    for(let i = 0; i < 6;i++){
      random_index = Math.floor(Math.random() * hex_numbers.length);
      hexcode1 += hex_numbers[random_index];
      random_index = Math.floor(Math.random() * hex_numbers.length);
        hexcode2 += hex_numbers[random_index];
    }
  
    document.body.style.background = `linear-gradient(to right, #${hexcode1}, #${hexcode2})`;
    document.querySelector("#hexcode1").textContent = hexcode1;
    document.querySelector("#hexcode2").textContent = hexcode2;
  });
```

See the example below:

{% codepen https://codepen.io/coding_dev_/pen/dydwGyP %}

What to do after this:
1.You can add more styling
2.You can also make a copy button(that copies the background code)

Did you find it useful? 
Comment down your thoughts! Don't forget to give it a heart and follow for more.
See you soon
Bye...
Kth Smallest Element in a Sorted Matrix
Tags: leetcode, dsa, theabbie
Published: 2022-06-12 15:00:45

Given an `n x n` `matrix` where each of the rows and columns is sorted in ascending order, return _the_ `kth` _smallest element in the matrix_.

Note that it is the `kth` smallest element **in the sorted order**, not the `kth` **distinct** element.

You must find a solution with a memory complexity better than `O(n2)`.

**Example 1:**

**Input:** matrix = \[\[1,5,9\],\[10,11,13\],\[12,13,15\]\], k = 8
**Output:** 13
**Explanation:** The elements in the matrix are \[1,5,9,10,11,12,13,**13**,15\], and the 8th smallest number is 13

**Example 2:**

**Input:** matrix = \[\[-5\]\], k = 1
**Output:** -5

**Constraints:**

*   `n == matrix.length == matrix[i].length`
*   `1 <= n <= 300`
*   `-109 <= matrix[i][j] <= 109`
*   All the rows and columns of `matrix` are **guaranteed** to be sorted in **non-decreasing order**.
*   `1 <= k <= n2`

**Follow up:**

*   Could you solve the problem with a constant memory (i.e., `O(1)` memory complexity)?
*   Could you solve the problem in `O(n)` time complexity? The solution may be too advanced for an interview but you may find reading [this paper](http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf) fun.

**SOLUTION:**

    import heapq
    
    class Solution:
        def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
            n = len(matrix)
            heap = []
            for i in range(n):
                for j in range(n):
                    heapq.heappush(heap, -matrix[i][j])
                    if len(heap) > k:
                        heapq.heappop(heap)
            return -heap[0]
Sites where you can get free hosting
Tags: html, css, hosting, beginners
Published: 2022-06-12 14:47:36

🎇Netlify.com
🎇Firebase
🎇Vercel.com
🎇GitHubPages
🎇Surge.sh
🎇Render.com
🎇Amazone Web hosting
🎇Google cloud hosting
🎇Glitch.com
🎇Fleek.co
🎇Begin.com
🎇Cloudaccess.net
🎇Infinityfree.net