teleren/devto huggingface dataset:
Pathfinding with Javascript: The A* Algorithm
Tags: javascript, algorithms, tutorial, programming
Published: 2022-06-03 13:02:49

There has been no shortage of academic research into finding efficient ways to find paths. Its use in games, logistics, and mapping makes it an important topic for any aspiring programmer to try their hand in.

One of the most famous algorithms for computing the quickest route between two points is the A* algorithm. In this article, we’ll go over how A* works and even do a quick implementation of the algorithm in Javascript.

---

###What is the A* algorithm?

A* is an improved version of Dijkstra’s search algorithm that was developed at the Stanford Research Institute. It makes use of heuristics(educated guesses that help reduce the time taken to compute the result) to increase its performance and efficiency. Unlike Dijkstra, this algorithm is specific i.e. it only finds the shortest path from one point to another instead of all possible end-points. It is used in online maps, video games,  artificial intelligence, and other similar applications.

---

###Implementation
In our Javascript implementation, we will use arrays to track our path over a grid but we can use other data structures like a heap or a graph to improve the overall performance of our code. You can find the complete code below:

{% embed https://gist.github.com/RanjanSushant/4dd689b7c95cb7ccf56c41dcfc8db22e %}

A* works by considering all the adjacent points around our starting point and computing a cost function(Which you can think of as time or distance) for each of the adjacent points. Since our goal in pathfinding is to find the path that requires the least cost, we will then explore the option that has the least cost, and repeat this process until we reach our end point.

The cost value of a point is computed by adding the distance from that point to our starting point, to the distance from that point to the ending point. Note that since we are working over a grid, we are using what’s called the [taxicab norm](https://en.wikipedia.org/wiki/Taxicab_geometry) to measure distance(The sum of horizontal and vertical differences between the points). The way you choose to measure distance is going to depend on the problem you are working on. For example, if your agent is able to move diagonally on the grid, you probably would use the [euclidean norm](https://en.wikipedia.org/wiki/Euclidean_distance).

---

There you have it! We just implemented a basic version of the A* search algorithm in JavaScript. You can take this to the next level by adding obstacles, allowing diagonals, etc. You can even create an animation that shows the path being traced from the starting point to the end.

No matter what you’re developing, you don’t want to be bogged down by your computer’s infrastructure. At [Codesphere](https://link.codesphere.com/MM), we’re building an all-in-one development platform that lets you develop with the full power of the cloud behind you.

Let us know in the comments how you plan to use this algorithm.
Happy coding!
Convert Sorted Array to Binary Search Tree
Tags: leetcode, dsa, theabbie
Published: 2022-06-03 13:00:47

Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a **height-balanced** binary search tree_.

A **height-balanced** binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg)

**Input:** nums = \[-10,-3,0,5,9\]
**Output:** \[0,-3,9,-10,null,5\]
**Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted:
![](https://assets.leetcode.com/uploads/2021/02/18/btree2.jpg)

**Example 2:**

![](https://assets.leetcode.com/uploads/2021/02/18/btree.jpg)

**Input:** nums = \[1,3\]
**Output:** \[3,1\]
**Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs.

**Constraints:**

*   `1 <= nums.length <= 104`
*   `-104 <= nums[i] <= 104`
*   `nums` is sorted in a **strictly increasing** order.

**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 sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
            n = len(nums)
            if n > 1:
                root = TreeNode(nums[n // 2])
                root.left = self.sortedArrayToBST(nums[:n//2])
                root.right = self.sortedArrayToBST(nums[1 + (n//2) :])
                return root
            elif n == 1:
                return TreeNode(val = nums[0])
            else:
                return None
How to vertically center an element without Flex
Tags: css, html, webdev, jetthoughts
Published: 2022-06-03 12:58:50

How vertically center with Flex you can view [Vertical align with a full screen across Tailwind CSS](https://jtway.co/vertical-align-with-a-full-screen-across-tailwind-css-5c6ad91c3e4f)
```html
<div class="outer">
  <div class="inner">Centered</div>
</div>
```

## Transform Translate
It’s possible to center it by nudging it up half of it’s height after bumping it down halfway:

```css
.outer {
  position: relative;
  height: 100vh;
}
.inner {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
```

## Display: Table-Cell
Outer element to be displayed as a `table` and the inner element to be displayed as a `table-cell` which can then be vertically centered.

```css
.outer {
  display: table;
  height: 100vh;
}
.inner {
  display: table-cell;
  vertical-align: middle;
}
```

## Fixed Height
Set `margin-top: -yy` where `yy` is half the height of the inner container to offset the item up.
```css
.outer {
  position: relative;
  height: 100vh;
}
.inner {
  position: absolute;
  height: 100px;
  margin-top: -50px;
  top: 50%;
}
```
Do one thing at a time - prefering composition over branching logic
Published: 2022-06-03 12:56:21

---
title: Do one thing at a time - prefering composition over branching logic
published: true
description: Software code grows in complexity, a good rule of thumb is assuring your code is doing one thing at a time.
tags: 
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

A simple yet powerful yea - do one thing at a time. Over time you will notice we apply that idea to many patterns in coding.

Pattern to use: prefer extracting and composing differences over using boolean flags:

Simple example is a setter function that uses a different key based on a boolean:


```javascript
async function setData(data, isLoggedIn) {
  // ...ignore
  const storeKey = isLoggedIn ? 'logged_in_key' : 'logged_out_key';
  await setStoreData(storeKey, data);
  return true;
}
```

It's best instead to extract storeKey as an argument

```javascript
async function setData(data, storeKey) {
  // ...ignore
  await setStoreData(storeKey, data);
  return true;
}
```

While the above example is simple in projects we see many make this mistake. 

Classes are typically catch-all places of branching logic. 

Tip: everytime you see a branching logic question yourself if it won't benefit from composition. 


_ps: This is a post zero of a series on writing better code, follow me for more_
I started creating SwiftUI tutorials
Tags: ios, swift, beginners, discuss
Published: 2022-06-03 12:56:04

Recently, I have planned to record every other day in attempts to create as many useful SwiftUI tutorials as possible and set them to an upload schedule. So far it's going to plan and I am enjoying it! I was a bit nervous at first but I am starting to feel more comfortable sat behind a mic. 

If you are interested in Swift, Apple development or just want to support me please feel free to check out my channel:
[Hayd iOS Channel](https://www.youtube.com/channel/UCAEeGczWvlS1Y-fPFHu5Cow)

Here is my recent video:
[Sleek Task Manager App UI using Swift](https://www.youtube.com/watch?v=VmshStMKllo)

Feedback is welcomed and I hope you all have a lovely weekend.

Happy coding!!
tryna make dev.to, with dev.to
Tags: javascript, svelte, webdev, programming
Published: 2022-06-03 12:32:48

so i came across the dev.to api

and i thought it might be fun to make dev.to like website which, basically, takes articles from the dev.to api...

the api: [https://developers.forem.com/api](https://developers.forem.com/api)

i used svelte spa(single page application) to achieve the task since its is minimal and takes a ton of load out.

the application can be used to view posts(ofc), user profiles and user posts, see posts by tags and post comments.

here's the web app: [https://dev--to.vercel.app/](https://dev--to.vercel.app/)
here's the repo: [atordvairn/dev--to](https://github.com/atordvairn/dev--to)


that's it. have a nice day
Additive Number
Tags: leetcode, dsa, theabbie
Published: 2022-06-03 12:30:41

An **additive number** is a string whose digits can form an **additive sequence**.

A valid **additive sequence** should contain **at least** three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.

Given a string containing only digits, return `true` if it is an **additive number** or `false` otherwise.

**Note:** Numbers in the additive sequence **cannot** have leading zeros, so sequence `1, 2, 03` or `1, 02, 3` is invalid.

**Example 1:**

**Input:** "112358"
**Output:** true
**Explanation:** 
The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. 
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8

**Example 2:**

**Input:** "199100199"
**Output:** true
**Explanation:** 
The additive sequence is: 1, 99, 100, 199. 
1 + 99 = 100, 99 + 100 = 199

**Constraints:**

*   `1 <= num.length <= 35`
*   `num` consists only of digits.

**Follow up:** How would you handle overflow for very large input integers?

**SOLUTION:**

    class Solution:
        def getSeq(self, num, i, n, a, b, ctr):
            if i >= n:
                return ctr >= 3
            for j in range(i + 1, n + 1):
                curr = int(num[i:j])
                if a == None or b == None or curr == a + b:
                    if self.getSeq(num, j, n, b, curr, ctr + 1):
                        return True
                if num[i] == "0":
                    break
            return False
        
        def isAdditiveNumber(self, num: str) -> bool:
            return self.getSeq(num, 0, len(num), None, None, 0)
JavaScript Hoisting and Function Types
Tags: javascript, programming, tutorial, beginners
Published: 2022-06-03 12:26:59

Declarations, Expressions and Statements

{% embed https://www.youtube.com/embed/HKD13OvGddE %}
_See this and many other articles at [lucaspaganini.com](lucaspaganini.com)_

We have two ways of defining functions in JavaScript:

1. Functions declarations (AKA functions statements)

```ts
function add(a, b) {
  return a + b;
}
```

1. Function expressions

```ts
const add = function (a, b) {
  return a + b;
};
```

Their differences lie not only in the syntax but also in the order that they're loaded.

## Hoisting

Function declarations are loaded before the code execution, that process is called _hoisting_.

```markdown
1 - Code execution
1.1 - Function declarations
1.2 - Function expressions
```

```markdown
Hoisting

1 - Function declarations
2 - Code execution
2.1 - Function expressions
```

That's why we can use them before their declarations.

```ts
add(1, 2);
//=> 3

function add(a, b) {
  return a + b;
}

add(1, 2);
//=> 3
```

Functions _expressions_, on the other hand, are treated as regular JavaScript values, just like a `number`, `string` or `boolean`. You can assign them to a variable, but they're **not** hoisted, you need to declare them before usage.

```ts
add(1, 2);
//=> TypeError: add is not a function

const add = function (a, b) {
  return a + b;
};

add(1, 2);
//=> 3
```

## Arrow Functions

Another difference is that you can't have arrow function declarations. All arrow functions are expressions.

```ts
add(1, 2);
//=> TypeError: add is not a function

const add = (a, b) => a + b;

add(1, 2);
//=> 3
```

## Conclusion

References are below.

<p>If you enjoyed the content, you know what to do. <app-newsletter-modal-trigger>Subscribe</app-newsletter-modal-trigger> if you want to know more about JavaScript and web development in general.</p>

Have a great day and see you soon.

## References

1. [Function expressions on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function)
2. [Function declarations on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)
3. [Arrow function expressions on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)
How to build, test, and automate iOS app deployment
Tags: ios, mobile, tutorial, cicd
Published: 2022-06-03 12:25:00

As developers, we spend so much time on repetitive tasks like preparing builds, running tests, and pushing them to Stores. Secretly we all wish the process to be easier.

In this article, we are going to see how can we build, test and deploy our iOS app on AppStore automatically without using Fastlane. The build will be pushed to TestFlight after merging PR in the master branch of the git repository.

To make navigation easier, I have divided the article into 3 separate sections. We will explore scripts to —

- Automate build
- Automate tests
- Automate deployment

We will set up CI in such a way that every commit will run tests and build process but only master commits will push builds to TestFlight.

I have used GitLab CI for example but you can take script commands and fit them into any other CI like Jenkins and Github Actions easily.

Note — I have assumed you all have the basic idea about app deployment on ITC (AppStore Connect) and you already have created your app to the AppStore console.

To read full version of the article, visit [Canopas Blog.](https://blog.canopas.com/a-complete-guide-to-ios-app-auto-deployment-with-ci-cd-b5dc516ba41d)
Course Schedule II
Tags: leetcode, dsa, theabbie
Published: 2022-06-03 12:00:47

There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.

*   For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.

Return _the ordering of courses you should take to finish all courses_. If there are many valid answers, return **any** of them. If it is impossible to finish all courses, return **an empty array**.

**Example 1:**

**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** \[0,1\]
**Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is \[0,1\].

**Example 2:**

**Input:** numCourses = 4, prerequisites = \[\[1,0\],\[2,0\],\[3,1\],\[3,2\]\]
**Output:** \[0,2,1,3\]
**Explanation:** There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is \[0,1,2,3\]. Another correct ordering is \[0,2,1,3\].

**Example 3:**

**Input:** numCourses = 1, prerequisites = \[\]
**Output:** \[0\]

**Constraints:**

*   `1 <= numCourses <= 2000`
*   `0 <= prerequisites.length <= numCourses * (numCourses - 1)`
*   `prerequisites[i].length == 2`
*   `0 <= ai, bi < numCourses`
*   `ai != bi`
*   All the pairs `[ai, bi]` are **distinct**.

**SOLUTION:**

    class Solution:
        def topologicalSort(self, graph, node, visited):
            visited.add(node)
            for j in graph.get(node, []):
                if j not in visited:
                    self.topologicalSort(graph, j, visited)
            self.sorted.append(node)
        
        def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
            graph = {}
            for a, b in prerequisites:
                graph[b] = graph.get(b, []) + [a]
            self.sorted = []
            visited = set()
            for node in range(numCourses):
                if node not in visited:
                    self.topologicalSort(graph, node, visited)
            self.sorted.reverse()
            pos = {}
            for i, node in enumerate(self.sorted):
                pos[node] = i
            for i in graph:
                for j in graph[i]:
                    if pos[i] > pos[j]:
                        return []
            return self.sorted
Book Club: "Test Driven Development: By Example" #11
Tags: books, tdd, discuss
Published: 2022-06-03 11:01:07

---
title: Book Club: "Test Driven Development: By Example" #11
published: true
description: A chapter by chapter discussion of "Test Driven Development By Example" by Kent Beck
tags: books, tdd, discussion
series: Book club TDD By Example
---

## Chapter 11: The Root of All Evil

I felt some uneasiness at this chapter. Here we finish removing the duplication between `Dollar` and `Franc`, but recognising those classes have served their purpose, we can get rid of them.

Having completed this chapter a while after removing the duplicated methods within those classes, this felt a bit strange. Essentially these classes had no responsibility other than their constructor, which is not sufficient purpose. These classes mapped to my understanding of real _money_, so I was sad to see them go. But, we still have the concept of `currency` which `Money` is taking care of.

If we need a Dollar or Franc class some day, we can write one, no sweat.

In addition we removed some duplication in the tests, which made me very happy! Tests are much easier to name when they don't step on another tests' toes.


🔎 View my code-along repo at https://github.com/ruthmoog/test-driven-development-by-example 

-----

![Book cover](https://learning.oreilly.com/library/cover/0321146530/250w/ ) Kent Beck's "[Test Driven Development: By Example](https://www.oreilly.com/library/view/test-driven-development/0321146530/)" was released in 2002. The book aims to explain how to use TDD to write quality code that works.
100 Days of Code: The Complete Python Pro Bootcamp for 2022 - Day 19 (Turtle Race Game)
Published: 2022-06-03 11:31:24

- 19.1 Make an etch a sketch app
````python
import turtle
from turtle import Turtle, Screen


tim = Turtle()
screen = Screen()
turtle.listen()


def move_forward():
    tim.forward(10)


def move_backwards():
    tim.back(10)


def counter_clockwise():
    tim.left(15)


def clockwise():
    tim.right(15)


def reset_screen():
    tim.screen.reset()


screen.onkey(move_forward, "w")
screen.onkey(move_backwards, "s")
screen.onkey(counter_clockwise, "a")
screen.onkey(clockwise, "d")
screen.onkey(reset_screen, "c")
screen.exitonclick()
```
- Turtle Race Game
````python
"""Import Statements"""
from turtle import Turtle, Screen
import random

"""Variables"""
colors = ["purple", "blue", "green", "yellow", "orange", "red"]
y_position = [-140, -80, -20, 40, 100, 150, ]
is_race_on = True
all_turtles = []

"""Screen setup"""
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Pick a color (purple, blue,"
                                                          "green, yellow, orange, red)")

"""Objects"""
for turtle_index in range(0, 6):
    new_turtle = Turtle(shape="turtle")
    new_turtle.color(colors[turtle_index])
    new_turtle.penup()
    new_turtle.goto(x=-225, y=y_position[turtle_index])
    all_turtles.append(new_turtle)

if user_bet:
    is_race_on = True

while is_race_on:

    for turtle in all_turtles:
        if turtle.xcor() > 217:
            is_race_on = False
            winning_color = turtle.pencolor()
            if winning_color == user_bet:
                print(f"Congratulations, your turtle {winning_color} has won")
            else:
                print(f"The winning turtle is {winning_color}, better luck next time")
        rand_distance = random.randint(0, 10)
        turtle.forward(rand_distance)

"""Keep screen open until clicked"""
screen.exitonclick()
```
Maximum Number of Words You Can Type
Tags: leetcode, dsa, theabbie
Published: 2022-06-03 11:30:38

There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.

Given a string `text` of words separated by a single space (no leading or trailing spaces) and a string `brokenLetters` of all **distinct** letter keys that are broken, return _the **number of words** in_ `text` _you can fully type using this keyboard_.

**Example 1:**

**Input:** text = "hello world", brokenLetters = "ad"
**Output:** 1
**Explanation:** We cannot type "world" because the 'd' key is broken.

**Example 2:**

**Input:** text = "leet code", brokenLetters = "lt"
**Output:** 1
**Explanation:** We cannot type "leet" because the 'l' and 't' keys are broken.

**Example 3:**

**Input:** text = "leet code", brokenLetters = "e"
**Output:** 0
**Explanation:** We cannot type either word because the 'e' key is broken.

**Constraints:**

*   `1 <= text.length <= 104`
*   `0 <= brokenLetters.length <= 26`
*   `text` consists of words separated by a single space without any leading or trailing spaces.
*   Each word only consists of lowercase English letters.
*   `brokenLetters` consists of **distinct** lowercase English letters.

**SOLUTION:**

    class Solution:
        def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
            broken = set(brokenLetters)
            return len([True for w in text.split() if len(set.intersection(set(w), broken)) == 0])
Is Subsequence
Tags: leetcode, dsa, theabbie
Published: 2022-06-03 11:00:46

Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_.

A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace"` is a subsequence of `"abcde"` while `"aec"` is not).

**Example 1:**

**Input:** s = "abc", t = "ahbgdc"
**Output:** true

**Example 2:**

**Input:** s = "axc", t = "ahbgdc"
**Output:** false

**Constraints:**

*   `0 <= s.length <= 100`
*   `0 <= t.length <= 104`
*   `s` and `t` consist only of lowercase English letters.

**Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?**SOLUTION:**

    class Solution:
        def isSubsequence(self, s: str, t: str) -> bool:
            i = 0
            j = 0
            while i < len(s) and j < len(t):
                if s[i] == t[j]:
                    i += 1
                    j += 1
                else:
                    j += 1
            return i == len(s)
TWITTER BOT WITH PYTHON
Tags: c4rl3, python, bot, twitter
Published: 2022-06-03 11:28:27

salut les gars... dans mes heures perdues j'ai pensé à mettre sur pied un bot pour la communauté de dev du Cameroun🇨🇲 sur Twitter.

pratiquement le bot doit retweeter , liker , commenter et follow les dev avec le tag #CmrDev.🕺🏽

*le bot est fonctionnel mais ce qui me fait défaut c'est que mon niveau d'accès sur Twitter n'est pas élevé pour faire ses opérations..si quelqu'un peut aider je lui serais infiniment reconnaissant * 🧎🏾‍♂️

[https://github.com/carleii/Twitter-Bot-retweet--like--follow-and-comment-for--CmrDev](https://github.com/carleii/Twitter-Bot-retweet--like--follow-and-comment-for--CmrDev)