teleren/devto huggingface dataset:
Eleventy - Shortcode for Embedding Codepen
Tags: webdev, javascript, beginners, eleventy
Published: 2022-06-08 05:40:08

> Don't know what eleventy is? Before you read further, check out this amazing [series of articles](https://www.tatianamac.com/posts/beginner-eleventy-tutorial-parti/)  by [Tatiana Mac](https://www.twitter.com/TatianaTMac) to know more about [eleventy](https://11ty.dev) and static site generators in general.

Eleventy makes embedding content in your templates fairly simple with the help of shortcodes.

Shortcodes are used to invoke a particular function which returns some html or any other data based on the information that is passed. They are mainly used to reuse html templates which require some preprocessing.

While writing blogs, I came across the need to embed codepens in my articles for a quick code demo.

Initially, I used to copy and paste the embed code provided by the codepen website. That's not at all feasible.

It wasn't the case that I didn't knew about shortcodes at all because I used them on DEV, but I wasn't sure if something like that existed in eleventy too. So, I buckled up and went on to explore shortcodes in eleventy!

## Tutorial

As per eleventy's [official documentation](https://www.11ty.dev/docs/), the default templating engine for markdown files is `liquid`, so here I have used a `liquid` shortcode as an example. You can [create a shortcode for other templating engines](https://www.11ty.dev/docs/shortcodes/) also.

Inside `.eleventy.js`, write the following code:

```js
eleventyConfig.addLiquidShortcode("codepen", function (url) {

    const url_array = url.split("/");

    const profile_url_array = url_array.filter((string, index) => {
        return (index < (url_array.length - 2)) ? true : false
    })

    const username = profile_url_array[profile_url_array.length - 1];
    const user_profile = profile_url_array.join("/");
    const data_slug_hash = url_array[url_array.length - 1];

    return `<p class="codepen" data-height="600" data-default-tab="result" data-slug-hash="${data_slug_hash}" data-user="${username}" style="height: 571px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;">
    <span><a href="${url}">See the pen</a> (<a href="${user_profile}">@${username}</a>) on <a href="https://codepen.io">CodePen</a>.</span>
    </p>
    <script async src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>`;
});
```

> Shortcode: `{% codepen 'url' %}`

Pass a codepen `url` to the shortcode function. Split the `url` using `/` as a separator.

You will get an array from which you can filter out the slug after the `profile` url. Convert the filtered array into a string using `join("")`. What you get is the `profile url` of a codepen user.

Similarly, you can extract the `username` as well as the `codepen id`.

Copy the `embed` code from codepen and edit it to make it dynamic. The function returns the dynamic `embed` code.

Signing off.

> *This post was originally published in [Syntackle](https://syntackle.live/blog/eleventy-shortcode-for-embedding-codepen-ZyslIPzCHpJo3kkPwu2U/)*
Valid Perfect Square
Tags: leetcode, dsa, theabbie
Published: 2022-06-08 05:30:37

Given a **positive** integer _num_, write a function which returns True if _num_ is a perfect square else False.

**Follow up:** **Do not** use any built-in library function such as `sqrt`.

**Example 1:**

**Input:** num = 16
**Output:** true

**Example 2:**

**Input:** num = 14
**Output:** false

**Constraints:**

*   `1 <= num <= 2^31 - 1`

**SOLUTION:**

    class Solution:
        def isPerfectSquare(self, num: int) -> bool:
            beg = 0
            end = num
            while beg <= end:
                mid = (beg + end) // 2
                if mid * mid == num:
                    return True
                elif beg == end:
                    break
                elif mid * mid > num:
                    end = mid
                else:
                    beg = mid + 1
            return False
How to create a Blogging Website with Express, NodeJs and MongoDB
Tags: node, mongodb, javascript, discuss
Published: 2022-06-08 05:14:21

Hello Developers,
<hr>
<center>
[Fork My github Repo And Give a Star](https://github.com/Yashkapure06/Blogging-Website.git)

If You want to make any awesome changes do fork and push in the repo.


</center>
* 1st you have to Fork the project
* Use your git Bash and 
``` git clone <url of repo> ```
* Next, You have to install all the necessary packages. So for that, just type 👇 and press enter 
```npm install```
* If you want to understand the code Open your favourite Code editor. I have explained each and every function in detailed manner in comment.
* To run the project You just have to write the following command <br>
```nodemon server.js```
* Server.js Contains
``` process.env.CONNECTION_URL ```
This  **CONNECTION_URL** contains the mongoDB Localhost url you can find it in mongoDB compass
* For the above  **CONNECTION_URL**  You need to create a `**.env**` file and  Add the following
CONNECTION_URL=localhosturl  (**NOTE❗: Do not use single or double quotes for adding url **)

<hr>
 I have created a **Blogging Website** with Node Js as backend, express and mongoDB as  a database.
This Blogging Website performs **CRUD** operations.

![New Post](https://user-images.githubusercontent.com/61585443/172445375-1885ff45-5bf7-4ef6-b3fb-1c38c8c51b63.png)

* Here You will just have to click on New Post to create a new Post from scratch.
<hr>

![Redirecting to New Post Page](https://user-images.githubusercontent.com/61585443/172445643-a6c31703-bc73-4fbf-8081-2d4464b50ced.png)

* Here You will get redirected to the new post page.
<hr>

![Here you can see the created post. You can further delete or edit this post](https://user-images.githubusercontent.com/61585443/172446528-8196c5f2-37ed-448b-8ed8-cd8bc62461f5.png)

* Here you can see the created post. You can further delete or edit this post.
<hr>


* This is **MongoDB Compass** Where you can see the data stored
![MongoDB Compass](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8jjf90t0gx5qyuyuyulz.png)


**Thank You For giving your Time**
django.db.utils.ProgrammingError: column <name> of relation "app_name__table" already exists
Tags: django, rest, solution, python
Published: 2022-06-08 05:10:43

Sometime we messed up with django migration and migrate process. Deleting migration file and run python manage.py makemigrations and python manage.py migrate solve the issue by undo previous migration or we can say that it takes us to previous migration state. But I faced one kind of situation where already a column created by a migrations and I saved some data in this column which was already created. And if i want to delete a migration file and want to go back previous situation django make sure that it doesn't happened because column is already created and I want to add this column again. And in this situation django will throw a error something like that 👇
![error message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2jgsdmnuak6qm6xlhhyn.png)
 
And I can't delete all my data and make migrations from zero. Because I'm in now production mode and have some data in my database. So I run this command and it's help me to overcome from this situation. And the magical command is 🧞- 
```bash 
python manage.py migrate --fake <put your app name>
```
Create website with vite
Tags: vite
Published: 2022-06-08 05:08:02

Hellow!!

I want to create portfolio site of Super mario brothers, so I want to use [this project](https://github.com/itsMapleLeaf/super-mario-typescript).
But this project is used builder called poi, and then it is deprecated... ...

I decided that I use vite on this project.

When I create website with vite, I could refer project which created with `yarn create vite`, and selectd vanilla.
Partition Array Into Three Parts With Equal Sum
Tags: leetcode, dsa, theabbie
Published: 2022-06-08 05:00:48

Given an array of integers `arr`, return `true` if we can partition the array into three **non-empty** parts with equal sums.

Formally, we can partition the array if we can find indexes `i + 1 < j` with `(arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])`

**Example 1:**

**Input:** arr = \[0,2,1,-6,6,-7,9,1,2,0,1\]
**Output:** true
**Explanation:** 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1

**Example 2:**

**Input:** arr = \[0,2,1,-6,6,7,9,-1,2,0,1\]
**Output:** false

**Example 3:**

**Input:** arr = \[3,3,6,5,-2,2,5,1,-9,4\]
**Output:** true
**Explanation:** 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4

**Constraints:**

*   `3 <= arr.length <= 5 * 104`
*   `-104 <= arr[i] <= 104`

**SOLUTION:**

    class Solution:
        def canThreePartsEqualSum(self, arr: List[int]) -> bool:
            n = len(arr)
            total = sum(arr)
            curr = 0
            f = -1
            s = -1
            for i in range(n):
                curr += arr[i]
                if f < 0 and curr * 3 == total:
                    f = i
                if curr * 3 == 2 * total:
                    s = i
                if f >= 0 and s >= 0 and f < s and s < n - 1:
                    return True
            return False
Getting Started with the Angular DateTimePicker Component
Tags: webdev, angular
Published: 2022-06-08 04:35:44

Learn how easily you can create and configure the Syncfusion [Angular DateTimePicker](https://www.syncfusion.com/angular-ui-components/angular-datetime-picker) using the Angular CLI command. This video also explains how to configure a few of the control’s basic features like setting specific date and time values, formats, and range restrictions for date selection. You will also learn how to enable the mask support in Angular DateTimePicker. 

**Product Overview**: https://www.syncfusion.com/angular-ui-components/angular-datetime-picker

**Download an example from GitHub**: https://github.com/SyncfusionExamples/getting-started-with-the-angular-datetimepicker-component

**Refer to the following documentation**: https://ej2.syncfusion.com/angular/documentation/datetimepicker/getting-started/

{% youtube XQnvxI77QVk %}
Design Add and Search Words Data Structure
Tags: leetcode, dsa, theabbie
Published: 2022-06-08 04:30:39

Design a data structure that supports adding new words and finding if a string matches any previously added string.

Implement the `WordDictionary` class:

*   `WordDictionary()` Initializes the object.
*   `void addWord(word)` Adds `word` to the data structure, it can be matched later.
*   `bool search(word)` Returns `true` if there is any string in the data structure that matches `word` or `false` otherwise. `word` may contain dots `'.'` where dots can be matched with any letter.

**Example:**

**Input**
\["WordDictionary","addWord","addWord","addWord","search","search","search","search"\]
\[\[\],\["bad"\],\["dad"\],\["mad"\],\["pad"\],\["bad"\],\[".ad"\],\["b.."\]\]
**Output**
\[null,null,null,null,false,true,true,true\]

**Explanation**
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True

**Constraints:**

*   `1 <= word.length <= 25`
*   `word` in `addWord` consists of lowercase English letters.
*   `word` in `search` consist of `'.'` or lowercase English letters.
*   There will be at most `3` dots in `word` for `search` queries.
*   At most `104` calls will be made to `addWord` and `search`.

**SOLUTION:**

    class Node:
        def __init__(self, val=None, children=[], end=False):
            self.val = val
            self.children = children
            self.end = end
    
    class WordDictionary:
    
        def __init__(self):
            self.root = Node(val=None, children=[])
    
        def addWord(self, word: str) -> None:
            n = len(word)
            curr = self.root
            for i, c in enumerate(word):
                found = False
                for node in curr.children:
                    if node.val == c:
                        curr = node
                        found = True
                        break
                if not found:
                    newcurr = Node(val=c, children=[])
                    curr.children.append(newcurr)
                    curr = newcurr
            curr.end = True
    
        def search(self, word: str) -> bool:
            n = len(word)
            paths = [(self.root, 0)]
            while len(paths) > 0:
                curr, i = paths.pop()
                if i == n and curr.end:
                    return True
                if curr.children and i < n:
                    for c in curr.children:
                        if word[i] == "." or c.val == word[i]:
                            paths.append((c, i + 1))
            return False
    
    # Your WordDictionary object will be instantiated and called as such:
    # obj = WordDictionary()
    # obj.addWord(word)
    # param_2 = obj.search(word)
Generate API key in JavaScript, Ruby and Python
Tags: webdev, api, javascript, python
Published: 2022-06-08 03:56:07

To access any application service sometimes we need an API key which is used to identify that only authorized users can access the service this API key could be in any format like hexadecimal and digits.

when a developer build an application (like a weather application) they have to generate a unique API key for all user who wants to access the service.

#### So How we can generate the API key?

It is quite easy to generate an API key in javascript, ruby, python or any other programming language we will use some library to generate random number strings.

#### Generate API key in Ruby

```ruby

require 'securerandom'

SecureRandom.urlsafe_base64(size_of_string)

SecureRandom.urlsafe_base64(30)

#7o4ZvEldmQbdNTA7uPpVZL6YuPKn6HDk1uRL--dP

``` 

#### Generate API key in JavaScript

To generate a random key in javascript there is two way

**@supercharge/strings package**

Install the npm package 

```javascript
npm i @supercharge/strings 
```

```javascript
const Str = require('@supercharge/strings')

const random = Str.random()  

const random_WithFiftySymbols = Str.random(50)  

console.log(random);

//kpHWxNZgrm7MbvrrHuLDY

console.log(random_WithFiftySymbols);

//QQh0eGOvxI16cZIXzIyZ2rsNfOk0AjclxYRLYxhZhzL5ZH_7gi
```

**By Node.js Crypto**

To generate a random string by Node.js Crypto you don't need to download any additional package this module is come with node.js by default.

```javascript
const Crypto = require('crypto')

function randomString(size = 30) {  
  return Crypto
    .randomBytes(size)
    .toString('base64')
    .slice(0, size)
}

console.log(randomString());

//UmjfVpC+d+6B2wZclWuz7BPePR6J9K
```


#### Generate API key in Python

By using random and string module we can generate random key with latter and digits. 

```python
import random
import string

print(''.join(random.choices(string.ascii_letters + string.digits, k=30)))

#vPDLFZ6NPozGW5LhEJIirm4aPHHKmC
```


Save this post ✅

Do like 😊

Share it 👨‍👨‍👦‍👦
need ncli routes Ukrain,Ecuador,ALGERIA,Haiti,Cuba,Laos,Thailand
Tags: voip
Published: 2022-06-08 03:47:49

need ncli routes Ukrain,Ecuador,ALGERIA,Haiti,Cuba,Laos,Thailand

Aaron
Maize Communication Co.,Limited
Skype: aaron-maizecomm
Whatsapp:8618571698930
Telegram:@aaron8812
Node.js | How to solve: Route.POST() requires callback functions but got a [object Undefined]
Published: 2022-06-08 03:38:22

## Hi, devs!

Every day we need to solve the errors and bugs and usually they appears just all the time.

Let's observe examples of error messages in this context:

`Error: Route.get() requires a callback function but got a [object Object]`

`Error: Route.POST() requires callback functions but got a [object Undefined]`

---

**What you need to do to solve?**

_First thing: debug your code!_

**If you are using VSCode, use the debug tool at the left (a play button with a bug on it)**

![Debut tool VS Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4t8xs58ysqzx0o42mid0.png)

If the message is coming with something _undefined_ or _object_ you need to looking for root cause.

**List of verifications to this error:**

1 - You use the _exports_ to permit other file to use you function?
2 - That function you call exists on its file?
3 - When you use module.exports take care to use correctly, remember if you use with `module.exports = { functionExported }` you need to use with a require in other file like `const example = require('./example')` and do `example.functionExported` to use.
4 - When you use _routes_ and _controllers_ to make yours _endpoints_, take care to exports the necessaries functions.

---

**Do you have more tips and tricks to solve this error? Post on comments.**

**Contacts**
Email: luizcalaca@gmail.com
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca
Maximum Subarray
Tags: leetcode, dsa, theabbie
Published: 2022-06-08 03:30:41

Given an integer array `nums`, find the contiguous subarray (containing at least one number) which has the largest sum and return _its sum_.

A **subarray** is a **contiguous** part of an array.

**Example 1:**

**Input:** nums = \[-2,1,-3,4,-1,2,1,-5,4\]
**Output:** 6
**Explanation:** \[4,-1,2,1\] has the largest sum = 6.

**Example 2:**

**Input:** nums = \[1\]
**Output:** 1

**Example 3:**

**Input:** nums = \[5,4,-1,7,8\]
**Output:** 23

**Constraints:**

*   `1 <= nums.length <= 105`
*   `-104 <= nums[i] <= 104`

**Follow up:** If you have figured out the `O(n)` solution, try coding another solution using the **divide and conquer** approach, which is more subtle.

**SOLUTION:**

    class Solution:
        def maxSubArray(self, nums: List[int]) -> int:
            n = len(nums)
            maxSoFar = float('-inf')
            maxEndingHere = 0
            for i in range(n):
                maxEndingHere += nums[i]
                maxSoFar = max(maxSoFar, maxEndingHere)
                maxEndingHere = max(maxEndingHere, 0)
            return maxSoFar
VyHow - the most trusted how-to site on the internet
Tags: vyhow, howto, how
Published: 2022-06-08 03:08:11

Welcome to VyHow, the most trusted how-to site on the internet. Our goal is to teach people how to do anything. With our help, billions of people have learned how to deal with large and small problems. [vyhow.com](https://vyhow.com/) creates the most reliable, comprehensive and delightful how-to content on the Internet. You can easily find what you're looking for with just one search, for example: how to screenshot on mac, how to train your dragon: the hidden world, how long to boil eggs, how to tie a tie, etc.

VyHow is a basic web-based program that makes learning how to do things a lot simpler and less stressful. It's the internet's most dependable how-to resource.
How reliable is the information provided by VyHow?
Because we thoroughly analyze each result, the odds of receiving spam or erroneous information are quite low. You'll obtain the right info in 95% of the time.

If you have any feedback for us, please don't hesitate to contact us here: 
Website: [https://vyhow.com/](https://vyhow.com/) 
Address: 3833 Main St, Suite 108, Springfield, Oregon, VA, 97478, USA
Phone: 18042078117
Mail: vyhowdotcom@gmail.com
Social media: 
Facebook: [https://www.facebook.com/vyhowdotcom](https://www.facebook.com/vyhowdotcom)
Twitter: [https://twitter.com/vyhowdotcom](https://twitter.com/vyhowdotcom)
Pinterest: [https://www.pinterest.com/vyhow/](https://www.pinterest.com/vyhow/)
Maximize Distance to Closest Person
Tags: leetcode, dsa, theabbie
Published: 2022-06-08 03:00:47

You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**.

There is at least one empty seat, and at least one person sitting.

Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. 

Return _that maximum distance to the closest person_.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/09/10/distance.jpg)

**Input:** seats = \[1,0,0,0,1,0,1\]
**Output:** 2
**Explanation:** 
If Alex sits in the second open seat (i.e. seats\[2\]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.

**Example 2:**

**Input:** seats = \[1,0,0,0\]
**Output:** 3
**Explanation:** 
If Alex sits in the last seat (i.e. seats\[3\]), the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.

**Example 3:**

**Input:** seats = \[0,1\]
**Output:** 1

**Constraints:**

*   `2 <= seats.length <= 2 * 104`
*   `seats[i]` is `0` or `1`.
*   At least one seat is **empty**.
*   At least one seat is **occupied**.

**SOLUTION:**

    class Solution:
        def maxDistToClosest(self, seats: List[int]) -> int:
            n = len(seats)
            i = 0
            firstGap = None
            lastGap = None
            curr = 0
            while i < n:
                ctr = 1
                while i < n -1 and seats[i] == seats[i + 1]:
                    ctr += 1
                    i += 1
                i += 1
                if seats[i - 1] == 0:
                    if not firstGap:
                        firstGap = ctr
                    lastGap = ctr
                    curr = max(curr, (ctr + 1) // 2)
            if seats[0] == 0:
                curr = max(curr, firstGap)
            if seats[-1] == 0:
                curr = max(curr, lastGap)
            return curr
Memorization in Javascript
Tags: memorisation, javascript, beginners, programming
Published: 2022-06-08 02:50:23

Memoization is a programming technique that attempts to increase a function’s performance by caching its previously computed results. 

Each time a memoized function is called, its parameters are used to index the cache.

 If the data is present, then it can be returned, without executing the entire function. Otherwise, the function is executed

Code for Memorization:
`const memoizeAddition = () => {
  let cache = {};
  return (value) => {
    if (value in cache) {
      console.log("Fetching from cache");
      return cache[value]; //Here, cache.value cannot be used as property name starts with the number which is not a                
                        //valid JavaScript identifier. Hence, can only be accessed using the square bracket notation.
    } else {
      console.log("Calculating result");
      let result = value + 20;
      cache[value] = result;
      return result;
    }
  };
};

// returned function from memoizAddition
const addition = memoizeAddition();
console.log(addition(20)); //output: 40 calculated
console.log(addition(20)); //output: 40 cached `