teleren/devto huggingface dataset:
Submit HTML Forms to JSON APIs easily
Tags: html, javascript, json, form
Published: 2020-09-06 00:06:15

# Motivation
Sometimes, you have an old school HTML form, but your front end interacts with an API. Submitting the form this way can be tricky. In this blog post, we will explore a clean way to do so.

# Code
The source code can be [found here](https://github.com/glorious73/submitformtojsonapi).

# Approach
The following approach will enable the developer to submit any HTML form to a "POST" API endpoint. Following are the steps:
1. Create the form with its inputs and submit input/button as you would normally do.
2. Give the form a unique Id.
3. Add a submit event listener to the form and pass the event object with it.
4. Build the request body in JSON format using the FormData class.
5. Add any headers, if needed.
6. Call the API using fetch or Axios (or any tool of your preference).
7. Change the window's location upon a successful response or show a notification if there are any errors.

## Step 1: The form
We will create a simple form that will be submitted to [JSON PlaceHolder](https://jsonplaceholder.typicode.com/) as an example.
![Simple Form](https://dev-to-uploads.s3.amazonaws.com/i/lg9itux9wemltcplsehd.PNG)
## Step 2: The form Id and the event listener
We will add an Id to the form and we will register an event listener to it, like so:
![Form Id](https://dev-to-uploads.s3.amazonaws.com/i/gp4avaopc6wdwei4v84a.PNG)
![Event Listener](https://dev-to-uploads.s3.amazonaws.com/i/iyl9u0vs5xgqztuzbf5c.PNG)
## Step 3: The function
The function will build the JSON body, build the request headers, and use the fetch service to POST the request by the submitted the form. This is how it looks like:
![Function](https://dev-to-uploads.s3.amazonaws.com/i/obxfyzm4b3nj4zmvtmn7.PNG)
## Step 4: Building the body
As you might have noticed, we called the function **buildJsonFormData**. It simply uses the object [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) to construct a set of key-value pairs in JSON format. It does that by looping over all inputs in the form and appending each key value pair to the JSON object, like so:
![Json Form Function](https://dev-to-uploads.s3.amazonaws.com/i/eby12p4jjr1e14oq28y3.PNG)
## Step 5: Adding Headers
Typically, you'd add headers to your request. You can checkout the sample function in **app.js** in the source to see one way to do it.
## Step 6: Submitting a request using Fetch
Now, the Fetch Service is what we built to submit any request and get the response so that we don't have to keep rewriting its logic. Since the code is self-explanatory, take a look:
![POST Request Function](https://dev-to-uploads.s3.amazonaws.com/i/h4l1zatw44e4nmqczppx.PNG)
## Step 7: Done. Informing the user or changing the page
Finally, we will navigate to the page that says "Success" and, for simplicity, show response data in the URL.
![Success](https://dev-to-uploads.s3.amazonaws.com/i/x289ov9masyxux4lpgum.png)

# Conclusion
In this blog post, we explored an effective and reusable way of submitting HTML forms to JSON APIs. 
[Cover Image credit](https://www.netclipart.com/isee/iTwmTRh_php-js-html-css/).
Day 96 : #100DaysofCode - Completed FreeCodeCamps CSS Grid and CSS Flexbox
Tags: 100daysofcode
Published: 2020-09-06 00:05:08

I completed the CSS Grid and CSS Flexbox sections on FreeCodeCamp. I learned a lot and hope to implement everything I learned into an application that I am building. I have heard many people say that as long as you know CSS Flexbox and Grid you can make very nice websites. I like bootstrap and other front-end libraries but there is something about building something on your own that makes you feel great. 

This time, I completed the freecodecamp sections but I also took notes for each in codepen to reference in the future, feel free to check them out. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/sanc8xgk2ey69zjnt2rd.png)

{% codepen https://codepen.io/SincerelyBrittany/pen/oNxpLye %}


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2utwchyy95es2zfid83n.png)

{% codepen https://codepen.io/SincerelyBrittany/pen/wvGPxrR %}


As always, thanks for reading. 

Sincerely, 
Brittany

Song of the Day:
{% youtube ObvvP1B1Wuw %}
The 3 Roles of a Freelance Developer
Tags: freelancing, career
Published: 2020-09-06 13:10:59

---
title: The 3 Roles of a Freelance Developer
published: true
cover_image: https://www.kartikey.dev/assets/brahma-vishnu-mahesh.jpeg
date: 2020-09-06 00:00:00 UTC
tags: freelancing, career
canonical_url: https://www.kartikey.dev/2020/09/06/the-3-roles-of-a-freelance-developer.html
---

According to Hindu mythology, the three cosmic functions of creation, sustaining, and transformation/destruction of the universe are performed by Lord Brahma, Lord Vishnu, and Lord Shiva, respectively. Similarly, to stand apart from others, we have to perform these three Godlike functions in our human profession! Let’s look into it from a freelance developer’s point of view.

### Being Brahma: the creator

Creating need not necessarily refer to just building web apps. There are many other tasks that you have to look into, like:

- Building a remarkable online presence to get new clients
- Creating a network of clients
- Drafting proposals
- Coming up with creative ideas to improve the products.
- A strategy to follow throughout the project.

### Being Vishnu: the sustainer

Once new projects start rolling, there is quite an amount of maintenance required, viz.:

- Maintaining a healthy relationship with the clients, including the previous ones.
- Stick to the strategy decided and maintain the pace of the project.
- Updating documentation, fixing bugs, upgrading dependencies, keeping an eye on the performance.
- Managing your finances and maintaining good health. (Do not underestimate this!)

### Being Shiva: the transformer/destroyer

Update to improvise!

- Transform and upgrade your work-style and strategy if needed.
- Troubleshooting technical challenges
- Refactor the code and get rid of the clutter.

There might be various other things apart from the above that a freelance developer is required to do, but, interestingly, all of it falls under these three categories.  
If you are a freelance developer, its a good idea to regularly introspect which of these three categories you expertise at and which you need to work upon.
How to add class names to a DOM element using JavaScript?
Tags: javascript
Published: 2020-09-06 00:00:00

---
  title: How to add class names to a DOM element using JavaScript?
  published: true
  tags: JavaScript
  date: Sun Sep 06 2020 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/add-classnames-element-dom-javascript
  cover_image: https://melvingeorge.me/_next/static/images/main-59a686e67d0f372c1b2198cd2f2137e9.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/add-classnames-element-dom-javascript)
  
## Add class names to a DOM element

To add a class name to a DOM element, you can use the `add()` method in the [`classList`](https://melvingeorge.me/blog/get-all-classnames-of-element-dom-javascript) property in an element using JavaScript.

Let's say you want to add a class name called `red` to an `h1` element.

```javascript
// first get the reference to the h1 element
const h1 = document.querySelector("h1");

// add red class name to h1 element
h1.classList.add("red");
```

- The method accepts valid class names as arguments.

If you want to add multiple classes at the same time, you can pass those class names to the `add()` method by passing them as arguments like this,

```javascript
// first get the reference to the h1 element
const h1 = document.querySelector("h1");

// add red, border-red, bg-yellow classnames
// to the h1 element at the same time
h1.classList.add("red", "border-red", "bg-yellow");
```

See this live example in [JSBin](https://jsbin.com/namabuyugi/2/edit?html,css,js,output).

### Feel free to share if you found this useful 😃.

---
Battle Nation Live
Tags: mrpowerscripts
Published: 2020-09-08 21:02:26

---
title: Battle Nation Live
published: true
date: 2020-09-06 00:00:00 UTC
tags: mrpowerscripts
canonical_url: https://mrpowerscripts.com/battle-nation-live/
---

Battle Nation Live is a discord variety show bot that I wrote a few years ago. It was the first real discord bot that I built. I was using Discord.js, and the code is atrocious. But it still works! And I’ve set it up to run on the MrPowerScripts discord server so that people can try it out any time.

## Battle Nation Live Overview

You can get the quickest overview of how it works by checking out [https://bnl.mrpowerscripts.com/](https://bnl.mrpowerscripts.com/), the original website.

## How does Battle Nation Live work

So how does the bot work? Join “The Show” voice channel and then run the`!signup` command, which adds you to the queue for the show. Once it is your turn, you will automatically get the “Live” discord role, which allows you to use the mic.

Everyone else remains muted, and it’s your turn to shine! Except there’s one catch. Everyone else gets to vote on whether you get to keep the mic or not using emoji during the performance. If you lose the vote at the end of the round, it goes to the next person! Rounds last 15 seconds, so you need to keep everyone entertained if you want to keep the mic.

And this whole process of users signing up, changing the role of who can use the mic, rotating people through the queue., and doing the emoji vote counts are managed by the bot. It’s pretty neat. I like to think of it as American Idol for discord, or some other singing or variety contest. Americas Got Talent for discord? I don’t know I never really watched those shows. But it’s possible to have these kinds of contests on discord as well!

## Battle Nation Live source code

The code is super terrible. I was learning a lot of stuff about node and js at the time, as I still am. But I’m going to share it anyway. [https://github.com/MrPowerScripts/battle-nation-live-discord-bot](https://github.com/MrPowerScripts/battle-nation-live-discord-bot)

And if you want to test your skills, joins the MrPowerScripts Discord server ([https://bit.ly/mrps-discord](https://bit.ly/mrps-discord)) where the bot is running 24/7. You can always hop on the mic at the Battle Nation Live show. lol I should never be allowed to name things.
How to remote debugging Odoo Docker images (Python based framework)
Tags: python, odoo, docker, vscode
Published: 2020-09-05 23:10:08

In order to understand how `remote debugging` works for all python services or apps which based on it such as Odoo, Flask, Django, Web2py or whatever. you have to understand three different concepts the docker container, the debugger, the python app server (in our case it's Odoo). so in many cases, when running Odoo from docker it is like the following image:
[![enter image description here][1]][1]


and what you really need to be able to debug would be like the following image:
[![enter image description here][2]][2]

please note the difference:

 - without debugging you have two ports, one internal the other is external which will pass http requests from the browser to Odoo & vice versa. however after debugging you have 4 ports, 2 of them for the http request & the other 2 for debugging information (which is based on json in our case) from Vscode to `debugpy` & vice versa (you could also use 2 ports by the way).
 - without debugging your entrypoint would be whats defined in the `Dockerfile`. with debugging, you modify the entrypoint to be `debugpy`. which will be responsible for running Odoo

so to debug Odoo you will be doing as following:

 1. Edit your `docker.dev` file & insert `RUN pip3 install -U debugpy`. this will install a python package `debugpy` instead of the deprecated one `ptvsd` because your vscode (local) will be communicating with debugpy (remote) server of your docker image using it.

  2. Start your container. you will be starting the python package that you just installed `debugpy`. it could be as next command from your shell.
```bash
docker-compose run --rm -p 8888:8888 -p 8869:8069 {DOCKER IMAGE[:TAG|@DIGEST]} /usr/bin/python3 -m debugpy --listen 0.0.0.0:8888 /usr/bin/odoo --db_user=odoo --db_host=db --db_password=odoo
```

  3. Prepare your launcher file as following. please note that `port` will be related to odoo server. `debugServer` will be the port for the debug server

```json
{
    "name": "Odoo: Attach",
    "type": "python",
    "request": "attach",
    "port": 8869,
    "debugServer": 8888,
    "host": "localhost",
    "pathMappings": [
        {
            "localRoot": "${workspaceFolder}",
            "remoteRoot": "/mnt/extra-addons",
        }
    ],
    "logToFile": true
}
```

  [1]: https://i.stack.imgur.com/xbA1K.png
  [2]: https://i.stack.imgur.com/cQ9AR.png
Day 95: #100DaysofCode - Practicing Collaborating Virtually.
Published: 2020-09-05 22:46:28

Today I did a few labs for my bootcamp and participated in a few collaborative meetings. I have had many opportunities in my career to collaborate in person and I enjoy team projects. I enjoy it today too, but collaborating virtually is very . . .different. When collaborating virtually we all have to remember to be patient. There are things that can go wrong such as computer issues or the losing service. Sometimes our computers just want to move slower than molasses and we have to sit there awkwardly waiting for the screen to load. It is times like this where you think to yourself, "I miss the days where I could see everyones face and just show them on paper what I think". 

In addition to technical difficulties, having etiquette while working virtually is hard too. There are times where you are lost and you do not want to interrupt someone else's thought. Sometimes you may have a better idea or way of doing something but you do not want to take away someone else's shine. 

Learning to code has its own challenges but I think virtual learning and collaborating makes the challenges even more difficult. Still in all, I learn so much from everyone every single time I have the opportunity to meet on zoom/other platforms and I am so grateful to have the opportunity. 

As always thanks for reading!

Sincerely, 
Brittany

Song of the day:

{% soundcloud https://soundcloud.com/bbrrandonn/elastic %}
The easiest way to achieve dark mode in tailwindcss
Tags: tailwindcss, darkmode, easy, css
Published: 2020-09-05 21:38:29

Here's a quickest way I've found to achieve dark and light mode theming in tailwindcss. 

### In tailwind.config.js
In this file, add the following **screens** to **extend**. i.e
```
module.exports = {
  future: {
    removeDeprecatedGapUtilities: true,
  },
  purge: ['./components/**/*.{js,ts,jsx,tsx}', './pages/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {
      colors: {},
      screens: {
        'light': { raw: '(prefers-color-scheme: light)' },
        'dark': { raw: '(prefers-color-scheme: dark)' }
      }
    },
  },
  variants: {
    backgroundColor: ['responsive', 'hover', 'focus', 'checked'],
  },
  plugins: [],
}

```
Now, we can do something like `dark:bg-red-700`.

To test, open your Google dev tools console, click the 3 dots icon, click **more tools** then select **rendering**.

Under **rendering**, scroll down to **Emulate CSS media feature prefers-color-scheme**. In the dropdown, select **prefers-color-scheme: dark**

You should see our `dark:bg-red-700` now take effect.
Sparse Arrays Code Challenge Solved
Tags: codechallenge, hackerrank
Published: 2020-09-05 21:34:14

---
title: Sparse Arrays Code Challenge Solved
published: true
description: Complete the function matchingStrings in the editor below. The function must return an array of integers representing the frequency of occurrence of each query string in strings.
tags: codechallenge, hackerrank
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/f0ilm8dz9il51sw8mi63.jpg
---
Ok! That's a simple problem with a simple solution written in Python 3, but to not lose the habit, I am publicly exposing my solution here.

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings.

Complete the function matchingStrings in the editor below. The function must return an array of integers representing the frequency of occurrence of each query string in strings.

**matchingStrings** has the following parameters:
- strings - an array of strings to search
- queries - an array of query strings

# Solution

```
def matchingStrings(strings, queries):
    return [strings.count(query) for query in queries]
```

That is it. With one single line, we are returning an array that counts how many _queries_ appears in _strings_.
Arrays: Left Rotation Code Challenge Solved
Tags: codechallenge, hackerrank
Published: 2020-09-05 21:32:16

---
title: Arrays: Left Rotation Code Challenge Solved
published: true
description: Given an array a of n integers and a number d, perform d left rotations on the array. Return the updated array to be printed as a single line of space-separated integers.
tags: codechallenge, hackerrank
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/qwkkxaqtmi7nglphaaju.png
---
A left rotation operation on an array shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1, 2, 3, 4, 5], then the array would become [3, 4, 5, 1, 2].

Given an array a of n integers and a number d, perform d left rotations on the array. Return the updated array to be printed as a single line of space-separated integers.

**Function Description**
Complete the function rotLeft in the editor below. It should return the resulting array of integers.

rotLeft has the following parameter(s):
- An array of integers a
- An integer d, the number of rotations.

**Input Format**
The first line contains two space-separated integers n and d, the size of a and the number of left rotations you must perform.
The second line contains n space-separated integers a[i].

**Constraints**
1 <= n <= 10^5
1 <= d <= n
1 <= a[i] <= 10^6

**Output Format**
Print a single line of n space-separated integers denoting the final state of the array after performing d left rotations.

**Sample Input**
```
4
1 2 3 4 5
```

**Sample Output**
```
5 1 2 3 4
```

**Explanation**
When we perform  left rotations, the array undergoes the following sequence of changes:

```
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 1]
[3, 4, 5, 1, 2]
[4, 5, 1, 2, 3]
[5, 1, 2, 3, 4]
```

## Solution
```
function rotLeft($a, $d) {
    $i = 0;
    $m = $d;
    if ($d > sizeof($a)) {
        $m = ($d % sizeof($a));
    }
    while ($i < $m) { 
        $a[] = $a[$i];
        $i++;
    }
    array_splice($a, 0, $m);
    return implode(' ', $a);
}
```
2D Array - DS Code Challenge Solved
Tags: codechallenge, hackerrank
Published: 2020-09-05 21:29:51

---
title: 2D Array - DS Code Challenge Solved
published: true
description: Complete the function hourglassSum in the editor below. It should return an integer, the maximum hourglass sum in the array.
tags: codechallenge, hackerrank
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/yhsr47pdurg0yksdgwyu.jpeg
---
Given a 6 x 6 array, arr:
```
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
```
We define an hourglass in A to be a subset of values with indices falling in this pattern in arr's graphical representation:
```
a b c
  d
e f g
```
There are 16 hourglasses in arr, and an hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in arr, then print the maximum hourglass sum.

For example, given the 2D array:
```
-9 -9 -9  1 1 1 
 0 -9  0  4 3 2
-9 -9 -9  1 2 3
 0  0  8  6 6 0
 0  0  0 -2 0 0
 0  0  1  2 4 0
```
We calculate the following 16 hourglass values:
```
-63, -34, -9, 12, 
-10, 0, 28, 23, 
-27, -11, -2, 10, 
9, 17, 25, 18
```
Our highest hourglass value is 28 from the hourglass:
```
0 4 3
  1
8 6 6
```
**Function Description**
Complete the function hourglassSum in the editor below. It should return an integer, the maximum hourglass sum in the array.

hourglassSum has the following parameter(s):
- arr: an array of integers 

**Input Format**
Each of the 6 lines of inputs arr[i] contains 6 space-separated integers arr[i][j].

**Constraints**
-9 <= arr[i][j] <= 9
0 <= i, j <= 5

**Output Format**
int the largest (maximum) hourglass sum found in arr.

## Solution
```
function hourglassSum($arr)
{
    $sum = -72;
    $sum_arr = array();
    for ($line = 0; $line < 4; $line++) {
        for ($col = 0; $col < 4; $col++) {
            $top = $arr[$line][$col] + $arr[$line][$col + 1] + $arr[$line][$col + 2];
            $middle = $arr[$line + 1][$col + 1];
            $bottom = $arr[$line + 2][$col] + $arr[$line + 2][$col + 1] + $arr[$line + 2][$col + 2];   
            if (($top + $middle + $bottom) > $sum) {
                $sum = $top + $middle + $bottom;
            }
        }
    }
    return $sum;
}
```
Repeated String Code Challenge Solved
Tags: codechallenge, hackerrank
Published: 2020-09-05 21:23:45

---
title: Repeated String Code Challenge Solved
published: true
description: Given an integer 'n' find and print the number of letters 'a's in the first letters of Lilah's infinite string.
tags: codechallenge, hackerrank
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/ecid35eg5ps67zbk7g1s.jpg
---
Lilah has a string, s, of lowercase English letters that she repeated infinitely many times.

Given an integer 'n' find and print the number of letters 'a's in the first letters of Lilah's infinite string.

For example, if the string s = 'abcac' and n = 10, the substring we consider is abcacabcac, the first 10 characters of her infinite string. There are 4  occurrences of 'a' in the substring.

**Function Description**
Complete the repeatedString function in the editor below. It should return an integer representing the number of occurrences of 'a' in the prefix of length in the infinitely repeating string.

repeatedString has the following parameter(s):
- s: a string to repeat
- n: the number of characters to consider 

**Input Format**
The first line contains a single string, s. The second line contains an integer, n.

**Output Format**
Print a single integer denoting the number of the letter a's in the first letters of the infinite string created by repeating infinitely many times.

**Sample input**
aba
10

**Sample output**
7

**Explanation**
The first letters of the infinite string are 'abaabaabaa'. Because there are a's, we print on a new line.

## Solution
```
function repeatedString($s, $n) {
    // check the number of occurrences of letter 'a' on given string $s
    $a_occurrences_in_s = substr_count($s, 'a');
    
    // check how many occurrences of string $s belongs to an repeated string $s of length of $n
    $s_occurrences_qty = floor($n / strlen($s));
    
    // get the $s occurrences left
    $s_occurrences_left = $n - ($s_occurrences_qty * strlen($s));
    
    // left string
    $s_left = substr($s, 0, $s_occurrences_left);
    
    // 'a' occurrences in left string
    $a_occurrences_in_s_left = substr_count($s_left, 'a');
    
    // occurrencies of 'a' on the entire repeated string of $s with a length of $n
    return ($a_occurrences_in_s * $s_occurrences_qty) + $a_occurrences_in_s_left;
}