teleren/devto huggingface dataset:
Throw a Custom Error in JavaScript
Tags: javascript, tutorial
Published: 2021-11-22 05:21:06

In a recent code review, a more senior colleague asked that I throw an error in an exported function so I wasn't just writing a `console.log` that might not have meaning. The custom error was needed because the value I was checking was an HTTP status considered an error (ex. 404) instead of an error that Node would throw.

I wasn't aware there was a way to do this in Node.js so I did some research and found that it was really pretty straightforward!

When you write the function that is performing the evaluation, ensure you use the `throw` keyword to return a string containing your custom message when your defined error condition is hit so that Node.js recognizes it as an error.

```Javascript
const anything = (item) => {
  if (item === "nothing") {
    throw "It's not anything"
  } else {
    return "It's something"
  }
}
```

In the function that is performing the evaluation, add a `try...catch` block to handle an error if it is returned.

```Javascript
const checkThingness = (item) => {
  try {
    console.log(anything(item))
  }
  catch(err) {
    console.log(err)
  }
}
```

When you call the main function, an error will be handled properly by the `catch` block.

```Javascript
checkThingness("something")
// > It's something
checkThingness("nothing")
// > It's not anything
```

Here is the full sample code block.

```Javascript
const anything = (item) => {
  if (item === "nothing") {
    throw "It's not anything"
  } else {
    return "It's something"
  }
}

const checkThingness = (item) => {
  try {
    console.log(anything(item))
  }
  catch(err) {
    console.log(err)
  }
}

checkThingness("something")
// > It's something
checkThingness("nothing")
// > It's not anything
```

While this is a very simple example, it makes plain how to start using custom errors via the `throw` keyword to handle your code more robustly with a good coding pattern. Further examples are included in the [MDN entry for the `throw` keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw).
¡Gasteroids! 👾 + ☄️
Tags: javascript, showdev, gamedev, programming
Published: 2021-11-22 05:10:16

Hi there! 👋🏼
This weekend I decided to take a break from coding... by coding a mini-game! Yeah I know that isn't exactly "taking a break", but it was actually pretty fun to make.

I originally wanted to make something similar to Galaga, but the work that would have required would have defeated the purpose of the whole activity, so I made asteroids as the "enemies" instead, hence the name of the game.

Here's the end result:
![game_gif](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o1o67op3bykimgyyc8n8.gif)

Both the code and the game itself are uploaded to **GitHub** so head over there if you want to take a look!

{% github DevTony101/gasteroids %}

Comment down below what your final score was! 
Can you beat mine of 6720? 😉

## Improvements
The game was made using **p5.js**, and the code isn't too complex (I hope), so if you are a beginner who is looking for some fun project to work with or you just have some hours to spare, here's a list of improvements you could make to this game:

- Make the spaceship explode when an asteroid hit it
- Give the spaceship some special super-power based on the score
- Give the spaceship an extra-live based on the score
- Give the spaceship some powerup by exploding an "special item"
- Add a bossfight (A big asteroid that requires a set number of hits maybe?)

You can clone the repo so you can add this features and, if you'd like your changes to be in the main game, you can make a pull request.

Thank you for reading! If you have comments and/or suggestions to make, please leave them down below.

See you next time 👋🏼
Free React Responisve Restaurant Website Design using Styled Components with ScrollReveal Animations🥗
Tags: react, webdev, javascript, angular
Published: 2021-11-22 04:06:51

## You can get the template from the link proivided in the description of the video.

### Technologies Used :-
+ React
+ Styled Components

### Libraries and Assets Used :- 
+ React Icons
+ Scroll Reveal

## To learn how to create this template watch the complete video. You can get the template for free from the link provided in the description of the video.

{% youtube eOV2tx1aJZA %}

## Please do like the video and subscribe to the channel. It helps and motivates me to create more content like this.
Tips when adding Tailwind to an existing project (Bootstrap, etc.)
Tags: tailwindcss
Published: 2021-11-22 03:46:54

## Opting out from tailwind reset (preflight)
Begin, by opting out of Tailwind reset called "preflight" to avoid conflict with existing CSS resets (i.e. mordern-normalize) by setting preflight to `false`
```js
tailwind.config.js


module.exports = {
  mode: 'jit',
  purge: [],
  darkMode: false,
  corePlugins: {
    preflight: false // set preflight to false
  }, 
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
}
``` 

## Namespacing all tailwind classes with a prefix
Prefixing all tailwind classnames with a prefix (e.g `tw-`) helps prevent clashes with existing classnames

```js
tailwind.config.js


module.exports = {
  mode: 'jit',
  purge: [],
  darkMode: false,
  corePlugins: {
    preflight: false
  },
  prefix: 'tw-', // set prefix to 'tw-'
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
}
```

**Example**
```html
<div class="bg-blue-500 h-40 w-40">
  ...
<div>
```
becomes
```html
<div class="tw-bg-blue-500 tw-h-40 tw-w-40">
  ...
<div>
```

## Increasing the specificity of tailwind classes
By nature tailwind classnames are low in specificity, so the chances of underlying CSS overriding it is very high. We are going to give more weight to our utilities by flagging them as `!important` in our config file.
**Note !** Using `!important` is bad practice, but its important to know when to use it

``` js
tailwind.config.js


module.exports = {
  mode: 'jit',
  purge: [],
  darkMode: false,
  corePlugins: {
    preflight: false
  },
  prefix: 'tw-',
  important: true, // set important to true
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
}
```

## Refrences
* [Adding Tailwind CSS to an Existing Project](https://www.youtube.com/watch?v=oG6XPy1t1KA&ab_channel=TailwindLabs)
Construção do recipiente da ração automática.
Tags: tutorial, diy, automacao, pet
Published: 2021-11-22 03:41:21

## O que foi utilizado:
<br>

<li> Placa de alumínio para:<ul> 
<li> Encaixe do cano no alimentador
<li> Hastes de suporte para o cano
</ul>
<li> Alimentador <ul>
<li> Motor
<li> Eixo de rosca helicoidal
<li> Caixa de aço inoxidável
</ul>
<li> Cano de 1,20 metro aproximadamente
<br>
<br>

## Especificações do Motor:
<br>

O motor utilizado foi um de 12V com um rotação de 90 RPM, que é também usado em vidros de carro. Tendo uma capacidade de ate 50Kg. 
<br>

![Image motor do carro](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gzhf9mbsdc8xeiwy2y3j.jpg)
<br>

## Funcionamento da comedouro:
<br>

O recipiente tem um motor que em seu eixo há uma rosca helicoidal, com seu giro faz que a ração caia no pote de ração.
<br>

![Image parte de cima do comedouro](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f0at3daqi4v7dy2bs4in.jpeg)
<br>

![Image parte de baixo do comedouro](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/flkvspqsnxhlf6dul3fc.jpeg)
<br>

## Preparação do encaixe:
<br>

Primeiramente cortei uma placa de alumínio aproximadamente 17.5cm X 15.0cm, para encaixar na parte superior do comedouro fiz alguns furos em sua superfície para facilitar o corte.
<br>

![Image placa com os furos](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9zl49z0lql2uk59u1iw6.jpeg)
<br>

Depois de fazer o corte utilizando um serrinha, ela ficou dessa maneira, para a passagem da ração.
<br>

![Image placa furada](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2z5e4f5g4ayornzgskbq.jpeg)
<br>
Utilizando o mesmo material da placa de aço, fiz as hastes de suporte para o cano, dobrando, cortando e furando para o encaixe dos parafusos.
<br>

![Image suporte do cano](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1dfffceii0xdxwuuhbc8.jpeg)
<br>

![Image suporte parafusado na placa](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b7z9yi8zjpgbq9sirmry.jpeg)
<br>

Ficando desta maneira o encaixe do cano com a placa e o suporte.
<br>

![Image cano na placa com o suporte](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9xphr65e4ze2iz2uq85d.jpeg)
<br>

Você pode ver o funcionamento do alimentador nesse <a href="https://twitter.com/BrosHenrique/status/1455671146049847298/video/1">link do vídeo</a> no meu twitter.
How to solve 'authentication failed' in Paramiko
Tags: python, programming, beginners, networkautomation
Published: 2021-11-22 03:38:51

I got an error when running automation script for network device like this:

```yml
~python-Automation/ $ python3 multivendor.py 

Traceback (most recent call last):
  File "multivendor.py", line 23, in <module>
paramiko.ssh_exception.AuthenticationException: Authentication failed.

```
so when you have entered the correct password and username but still get an error like that, you need to add this parameter in your automation script
```yml
look_for_keys=False
```
finally, **the parameter will disable search for discoverable private key files in ~/.ssh/**.

so you will see my script like this

```yml
import paramiko
import time

devices = [
    {
        'ip_address' : '172.16.1.1',
        'vendor' : 'mikrotik',
        'username' : 'router1',
        'password' : 'tes'
    },
    {
        'ip_address' : '172.16.1.2',
        'vendor' : 'cisco',
        'username' : 'cisco',
        'password' : 'cisco'
    }
]

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

for device in devices:
    ssh_client.connect(hostname=device['ip_address'],
                                username=device['username'],
                                password=device['password'],
                                look_for_keys=False)
                      
    print("success login to {}".format(device['ip_address']))

    if device['vendor'] == 'cisco':
        conn = ssh_client.invoke_shell()

        # conn.send("enable\n")
        conn.send("conf t\n")
        conn.send("int lo99\n")
        conn.send("ip add 10.1.99.1 255.255.255.255\n")
        time.sleep(2)

        # output = conn.recv(65535)
        # print(output.decode())
    else:
        ssh_client.exec_command('interface bridge add name=loopback3\n')
        ssh_client.exec_command('ip add add address=10.2.99.2/32 interface=loopback3')

ssh_client.close

```
Good luck :smile:
I want to use Linux but I can't...
Tags: linux, ubuntu
Published: 2021-11-22 03:28:45

I bet that everyone here has heard about Linux. However, only a few can use it because their hardware doesn't work with Linux.

In my case, I want to use Ubuntu 21.10 on my laptop, Acer Swift 5 - SF514-52T, but I can't because there's no sound coming out of the HDMI port. I have filed this issue [here](https://bugzilla.kernel.org/show_bug.cgi?id=214923).

I also can't connect my Bluetooth headset, Sony WH-CH710N, at all. The headset paired successfully but it just won't connect. I believe that this could be solved using the method provided [here](https://askubuntu.com/questions/1369458/bluetooth-headphones-stopped-working-after-updating-to-21-10) but I didn't have a chance to try it yet.

In fact, I had tried to run Linux on this laptop since Ubuntu 19.04 came out but fail because the integrated mic didn't work at all. Fortunately, [this issue is fixed](https://bugzilla.kernel.org/show_bug.cgi?id=201251) on Ubuntu 21.10.

Nevertheless, the sound system on Linux is a mess...

Linux will not succeed in the desktop market unless it works on most laptops considering that [laptops already sell nearly 3 times more than PCs](https://www.statista.com/statistics/272595/global-shipments-forecast-for-tablets-laptops-and-desktop-pcs/).

Hey, Linux, see you again in Ubuntu 22.04 LTS, KDE neon, or [SteamOS 3.0](https://9to5linux.com/valve-says-steamos-3-0-will-be-available-for-everyone-to-download-and-install)!
code every day with me
Tags: javascript, programming, 100daysofcode, algorithms
Published: 2021-11-22 03:01:20

##--DAY 25--
Hi, I am going to make #100DaysOfCode Challenge. Everyday I will try solve 1 problem from leetcode or hackerrank. Hope you can go with me until end.
**Now let's solve problem today:**
Problem: Isomorphic Strings
Detail: [here](https://leetcode.com/problems/isomorphic-strings/)
Idea: Use hashmap to store value of each string then compare them
My solution (javascript):
```js
var isIsomorphic = function(s, t) {
    let map1 = new Map(), map2 = new Map();
    if (s.length != t.length) return false;
    for (let i = 0; i < s.length; i++) {
        if((map1.has(s[i])&&map1.get(s[i])!=t[i])||
           (map2.has(t[i])&&map2.get(t[i])!=s[i])
          ) return false;
        map1.set(s[i],t[i]);
        map2.set(t[i],s[i]);
    }
    return true;
};
```
-->*If you have better solution or any question, please comment below. I will appreciate.*
New Application
Tags: beginners, help, ai, challenge
Published: 2021-11-22 02:00:16

Hi Devs,
I am going to work with an AI algorithm company to develop a photo editing app. Here are some features display.Could you plz give me some advice and suggestions? Appreciate!
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6svehhe6ep5kcjgkm6w7.jpeg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/43fb4b6rl1h5kkcqa6pa.jpeg)
如何在 Jupyter Notebook 跑 Python 異步程式
Tags: python, jupyter, async
Published: 2021-11-22 01:49:12

異步是 Python 3.4 起引入的重大變革，透過 asyncio 模組與新的 `async`、`await` 語法達到與 JavaScript 類似的異步執行效果。

一個最簡單的異步程式例子：

```Python
import asyncio

async def do_something():
    await asyncio.sleep(1)

loop = asyncio.get_event_loop()
loop.run_until_complete(do_something())
```

在上面的例子內有幾個 Python 異步程式的特徵：

- 由 `async` 關鍵字定義 `do_something()` 為異步函式。
- 函式內有 `await` 關鍵字的敘述句表示該敘述可為異步執行。
- `await` 後呼叫的函式 `asyncio.sleep()` 為一個具有 awaitable 的函式，對 `await` 關鍵字來說，後面呼叫的函式有 awaitable 屬性是必須的，否則會引發錯誤。
- 取得一個 event loop 物件，並令此 event loop 物件去執行 `do_something()`。

Event loop 物件可以接受一系列的 async 函式，並互相調度，在上面的例子中，因為只有單個任務，所以用異步顯得脫褲子放屁，在真實的場景中，event loop 接受多個 async 函式後，當遇到第一個函式的 `await`，異步機制就會開始作用，讓第一個函式的 `await` 繼續跑，並開始讓下一個函式也跑起來，以此類推直到所有 event loop 內的異步函式都跑完。

## 當在 Jupyter Notebook 裡跑異步程式

在 Jupyter Notebook 內可以直接使用 `await` 語法呼叫異步函式：

```Python
import asyncio

await asyncio.sleep(1)
```

就這麼簡單。
Day 16 of #100daysofcode: Material UI
Tags: 100daysofcode, react, python, beginners
Published: 2021-11-22 01:34:42

I decided to spend time today learning about Material UI. In a previous post, I mentioned that I wanted to figure out what the difference between Material UI and Material.io was. It turns out, Material UI is just a React library which was created using the Material.io philosophy. 

## Material UI Compared to React-bootstrap
After playing around with Material UI for a while, I really like it. It feels like it has much more features than React-bootstrap, which makes sense since it was originally created for React while React-bootstrap originally started as a CSS stylesheet/library.

I am going to be replacing React-bootstrap with Material UI moving forward. I personally like the look of the out-of-the-box Material UI components more than React-bootstrap's components. It also feels a little easier to get information about Material UI.

## Flutter
I have recently started to looking into mobile development a little more; partly out of curiosity and partly because I want to find a way to port my app to mobile as well as web. I ran across Flutter as a useful system to run my app on both mobile and web. I will be looking more into Flutter in the coming days.

## Today
* Completed the ES6 FreeCodeCamp tutorials -- The next FreeCodeCamp tutorial section for JS is Regular Expression. In the past, regex has been my least favorite thing to work with, so I'm not looking forward to it!
* Took a break from Django, decided to learn about Material UI
* Spent some more time deliberating about how I want to move forward with my Study Aid app


## Upcoming
* Iron out details regarding the Study Aid app (I really need to name this thing)
  * Flask vs Django
  * Flutter?
  * Should I change how I deploy? Should Docker get in the picture?
  * Are there any other systems I should think about using as a part of this project?
* Learn more about Material UI, I will probably use Material UI a little bit in my (ongoing) school project. 
* Start the Study Aid app!


### Resources
[JS Course - FreeCodeCamp](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/)
[Material UI](https://mui.com)
[Django Tutorial](https://docs.djangoproject.com/en/3.2/intro/tutorial01/)
Solution to Problems that Beginners Encounter ~CSS~
Tags: beginners, css
Published: 2021-11-22 00:59:29

Here are some problems I encountered while I was working on my project, and the solutions to them I got from my instructor and found through searching.


< How To Adjust Image Size >
When we want to align images in a row with the same height (and width), we use "object-fit: cover". But sometimes it won't work only by using it. 
Here is the solution:
Set the width and the height of the images to 100%.
     width: 100%;
     height: 100%;
     object-fit: cover;


<Darken Background Image>
I found several ways to darken the background images.
Here are some:
(1) Using ":before"
.hero {
  width: 100%;
  height: 100vh;
  background: url("..(image url)..") no-repeat center center;
  background-size: cover;
  position: relative;
  background-attachment: fixed;
}
.hero:before {
  content: "";
  background: rgba(0, 0, 0, 0.2);
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

(2) Using "Linear-gradient"
.container {
  background-image: linear-gradient(to bottom, 
  rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.5))
}


<Align Texts Without Using Table>
When I wanted to align data vertically, I could only think of using "table" or "&nbsp;". We can use "grid" not only for images, but texts.
.data {
    display: grid;
    grid-template-columns: 2fr 1fr;
}


These problems might seem too trivial, but actually they are not to beginners like me and it takes so long to find the solutions.
So, I hope this would help someone who's also struggling with the same problems.
TypeScript Dynamic Module Import
Tags: javascript, typescript, architecture, node
Published: 2021-11-22 00:43:00

Can you tell the difference between these two import statements?

```ts
import Button from "@kenaz/button";
```
VS
```ts
const buttonModule = await import("@kenaz/button");
const Button = buttonModule.default;
```

Simple right? - The first imports the module statically at `build-time`, whereas the second imports the module dynamically at `run-time`. 

With the first code snippet, most ES bundler will include the button component in our final bundle. Whereas with the second snippet, our button could be split into a separate chunk. This could be an advantage when your page gets super duper complex with 1000 states, but the button is only needed in 1 of those states.

Now, can you tell the difference between these twos?

```ts
async function loadButton() {
  const buttonModule = await import("@kenaz/button");
  return buttonModule.default;
}
```

VS

```ts
async function loadComponent(name = "@kenaz/button") {
  const module = await import(name);
  return module.default;
}
```

Disregard the context and the use case supplied via the naming of those functions, these two dynamic import statements do not seem to differ that much. At least, that's what I thought when I was using these two interchangeably while developing locally with a dev server that was transpiling these code on-the-fly. 

However, the difference came to light when I created a production bundle while trying to import a local module using the 2nd snippet:

```ts
const Button = await loadComponent("./button")
```

It threw this error:

```
Cannot find module './button'
Require stack:

/app/dist/index.js Error: Cannot find module './button'
```

> I filed an [issue](https://github.com/vercel/ncc/issues/793) for the `ncc` bundler regarding a similar behavior

It turned out that when passing a local path to `import`, the code becomes unanalyzable by the TypeScript compiler. Thus, the compiler does not bundle the local import code, leaving us with the error above.

> The more I think of this, the more I realized this behavior is reasonable. I.e, if the module name is arbitrary, how could the compiler know which module would be imported? Should it just compile every possible combination of file in the project then? That's probably not a good solution...

My conclusion: for local module (owned by my project such as `"./button"`), statically analyzable dynamic import is required for most bundler to find and compile those module correctly. On the other hand, if the module is in a separate module (a dependency such as `@org/some-module`), the node runtime can crawl the `node_packages` directory for them.
Building a Docker container for kiterunner
Tags: docker, fuzzing, api, linux
Published: 2021-11-22 00:29:00

---
title: Building a Docker container for kiterunner
published: true
description: How I built my own Docker container to run the kiterunner API scanner
tags: docker, fuzzing, apis, linux
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ai7qswpjkx276xq49v4t.jpeg
---

In the last few weeks, I've finally wrangled my head around Docker a bit. 

As a demo, I've built a docker container for [kiterunner](https://github.com/assetnote/kiterunner).

Kiterunner is an API-fuzzing tool, very useful for bug bounty hunters and pen-testers. Shoutouts to [@insiderphd](https://twitter.com/insiderphd) for introducing me to the tool. I should have watched that video sooner!

Like any good tool, it requires some installation stuff beforehand.

I realized this is a good opportunity to begin integrating Docker into my workflow in a potentially useful way.

-----

To quickly get Docker installed on debian or ubuntu:

```
# Install Docker
sudo apt-get install \
    ca-certificates \
    curl \
    gnupg \
    lsb-release
curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian \
  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
```

-----

If you have Docker installed, you can simply:

```
docker run darkmagex6/kiterunner <params>
```

I set it up so that you can pass parameters directly to the container.
Now, I have not yet dealt with an easy way to write output directly from the container to the local filesystem, but you can use `docker cp` for that.

```
docker cp darkmagex6/kiterunner:<filename> <destination>
```

-----

The Dockerfile for my kiterunner setup:
edit: swapped from debian to alpine and reduced number of RUN commands

```
FROM    alpine:latest
RUN     wget https://github.com/assetnote/kiterunner/releases/download/v1.0.2/kiterunner_1.0.2_linux_amd64.tar.gz && \
     tar -xvzf kiterunner_1.0.2_linux_amd64.tar.gz && \
     wget https://wordlists-cdn.assetnote.io/data/kiterunner/routes-small.kite.tar.gz && \
     wget https://wordlists-cdn.assetnote.io/data/kiterunner/routes-large.kite.tar.gz && \
     tar -xvzf routes-small.kite.tar.gz && \
     tar -xvzf routes-large.kite.tar.gz && \
     rm -rf kiterunner_1.0.2_linux_amd64.tar.gz routes-small.kite.tar.gz routes-large.kite.tar.gz
ENTRYPOINT ["./kr"]
```

There's probably a better way to do this, but it is working.

-----

If you enjoy this content or found it helpful in any way and want to show me some support, please check out my Twitch streams at [https://twitch.tv/darkmage666](https://twitch.tv/darkmage666).

Also check out my homepage: [https://evildojo.com](https://evildojo.com)

You can support me on Patreon at: [https://patreon.com/darkmage](https://patreon.com/darkmage)