teleren/devto huggingface dataset:
Build and SSR react on the fly
Tags: react, gatsby, serverless, nextjs
Published: 2020-04-09 18:23:10

Here's a story -> 🤠

You have a blog website like dev.to and you want users to write articles when they log in. They write their article in the form of markdown and then publish it. The published article goes to an s3-bucket which triggers an s3 create Object event. The event launches a lambda function(Serverless). 

Now, the lambda function has to convert that markdown into a static HTML using react, by fetching and parsing the markdown into the components as props. Then the static HTML is passed to another s3-bucket which acts as a static web server.

##Why this approach?
 Its cheaper, faster and more scalable than running your own web-server. (ec2)

##Methods already tried !!!!!
1. NextJs:- It's good, it's great but not for this use case.
 Possible approaches:-
 1. Spinning up a custom express server
 -> Caveats :
   Its least documented and doesn't work 99% of the time. [See](https://dev.to/adnanrahic/a-crash-course-on-serverless-side-rendering-with-reactjs-nextjs-and-aws-lambda-13ed?signin=true)

 2. Using get ServerSideProps 
 -> Caveats :
   It doesn't work 99% of the time. 
 [See](https://stackoverflow.com/questions/61027992/cannot-pass-array-from-getstaticprops-in-next-js)

2. Gatsby:- Best static builder, does everything, has plugin support and node APIs so I can fetch the s3 object easily.
 1. The ONLY ISSUE: It DoEsN'T allow us to change the ExPoRt directory.😵😡
[See](https://github.com/gatsbyjs/gatsby/issues/12817) while lambda limits us to write to one and only /temp directory.

###Methods which work (Sort offfff) !!!!!!
#####The Great Gatsby !!
1. Exporting Gatsby using plugins and [node APIs](https://www.gatsbyjs.org/docs/node-apis/#createPages) and then using [this approach](https://flaviocopes.com/react-server-side-rendering/) to render it. Looks good and works, but it clashes with babel and webpack. Gatsby/Router doesn't work at all.

# FireJSX to the rescue

[FireJSX](https://github.com/eAdded/FireJSX) is a zero config, highly customizable, progressive react static site generator with blazingly fast SSR. Built for fast on the fly builds and SSR.
Comment three facts you learned after some time in the software industry
Tags: career, discuss
Published: 2020-04-09 18:22:01

---
title: Comment three facts you learned after some time in the software industry
published: true
description: 
tags: career, discuss
---
1. More programmers don't really mean faster deliveries.
2. It's ok to not code at all after work hours.
3. You are not defined by any programming language.
Software Architecture (introduction)
Tags: architecture, developers
Published: 2020-04-09 18:21:36

In this series, we will talk about software architecture and what should the developer know, the article will be sample and basic knowledge.
there will be more upcoming parts related to different Software Architecture

The output from this series should let you have the basic knowledge of software architecture.

**Note**: the article is boring for the developer as there will be no code 😃


#What is architecture?
According to [Wikipedia](https://en.wikipedia.org/wiki/Architecture) Architecture is both the process and the product of planning, designing, and constructing buildings or any other structures, in our case what is the software architecture?
it's the same actually but instead of planning and designing for building, you are designing for software.
- Software architecture is the shape of the system.
- The higher level of the code we write.
- It deals with the structure of the code and how things are organized.
- How internal and external components will communicate with each other.


> The first concern of the architect is to make sure that the house is usable, it is not to ensure that the house is made of bricks
> -- <cite>uncle bob</cite>

And this means is to specify what is essential and what is details.

For example, we want to build a house, then we need to think about:
- The space inside the house is essential because if there is no space then there will no place to put your things or to move inside the house.
- The usability of the house if your house contains no rooms then it's useless to live inside it and you will need it to replace it with another house.
- The building material of the house is a detail, as you can build a house using bricks, woods, stone, ...etc.


The essential here means is to support the primary needs of the house or in our case will be the domain everything else is just implementation of details.

When we build software:
- The domain is essential.
- The use cases are essential.
- Presentation is a detail as you can build your application using ASP, JSP, angular, react, ...etc.
- Data persistence is also a detail, you can use SQL or no-SQL to store your data.

When architecting software you need to think about the business and the problem it will solve.

###What is the Domain?
The domain is the business or the subject your project or software will serve, for example, you need to build a software for banking of financial services, so you need first to understand what is banking and the domain here will be the banking.


In the next part, we will talk about,
Database Centric vs Domain Centric architecture.
Here’s a reason why your website is not secure
Tags: security, javascript, html, clickjacking
Published: 2020-04-09 18:18:51

If you are a website developer, you have most probably protected yourself from common attacks such as XSS, SQL, CSRF, etc.

**_But are you safe from a Clickjacking attack?_**

* * *

_Try this:_

_1) Create a blank html file_

_2) Add the following code:_

```html
<style>body { margin:0; }</style>

<iframe src=”http://your-site.com" width=”100%” height=”100%” style=”border: 0"></iframe>
```

Then open the html file in your browser. If your browser loads your website, congratulations (_pun_)! You’re susceptible to _clickjacking attacks_ :)

But if your browser displays the following error (or similar) in your console:

```
Refused to display ‘https://your-site.com' in a frame because it set ‘X-Frame-Options’ to ‘sameorigin’.
```

then you are _\[relatively\]_ safe.

* * *

**_What is Clickjacking?_**

> Clickjacking is an attack where an attacker uses an iframe to load your site and tricks a user to click on a button/link. The attacker then hijacks the clicks meant for the original server.

The above code opens your website in such a way that no one can tell the difference between your real website and the iframed version, especially if an attacker uses a \[false\] url _similar_ to your domain name, e.g. _faceebook.com_

> Most sites like Facebook, Github, Whatsapp, etc have blocked iframes page loading, i.e. you cannot load any of these pages via an iframe. YouTube only allows embedded videos.

* * *

Whether you are using Nginx, Apache server, etc., you should disable the loading of your website in an iframe by setting the `x-frame-options` header in your config files to DENY, e.g.

```
x-frame-options: DENY
```

Protect yourself from Clickjacking attacks today.

You can learn more here:

[https://keycdn.com/blog/x-frame-options](https://keycdn.com/blog/x-frame-options)
mvnx - The npx of the JVM world.
Tags: showdev, java, kotlin
Published: 2020-04-09 18:15:40

From one-off command execution to daily use, command-line tools are indispensable parts of the software engineer's toolbelt. Every popular programming language has a framework for at least argument parsing, but most also offer components for more complex requirements such as prompting or colored output. However, deployment of CLIs is where language ecosystems differ.

## The Problem with JVM CLIs

Want to write a CLI in JavaScript? Easy! Just pick some libraries, translate your idea to code, upload to npm (or any other package registry), and you're all set. Anyone can now deploy and use your CLI with the help of npx.

Now, what about the JVM? You pick some libraries, write the code, and upload the artifact to a maven registry. If you were writing a JavaScript library, you'd be out counting the downloads on npmjs.com. Not in the case of a JVM CLI, though. There's no standard tool for downloading and executing runnable JARs residing in maven repositories. Thus, despite the general availability of your artifact, it takes quite a bit of effort to obtain and execute your CLI. 

## Enter mvnx

Having written a few Kotlin CLIs in the past months, I decided to take on this situation. I created mvnx, which boldly claims to address the execution of JARs available in maven repositories:

  > https://github.com/mvnx/mvnx

Inspired by npx, mvnx takes the maven coordinates of an artifact and handles the rest. Watch:

![Cowsay on the JVM](https://dev-to-uploads.s3.amazonaws.com/i/knqpo05960wnxpg1xf3i.png)

If you don't want to enforce a specific version, then you may omit the version coordinate altogether! In this case, mvnx will obtain the latest version.

~~~~
$ mvnx -q com.github.ricksbrown:cowsay "Hello, World"
~~~~

By default, mvnx will query the Central Repository. You can alter this behavior by specifying a custom repository URL with support for HTTP Basic authentication credentials and aliases.

Pro tip: mvnx loves GitHub Packages!

## Wrapping Up

The JVM ecosystem offers a plethora of excellent libraries, along with stable dependency management solutions. Building upon these foundations, CLIs were easy to write and distribute, but hard to get and execute. mvnx aims to be the missing link between CLI authors and consumers.
Deploying WhiteNoise - Building SaaS #35
Tags: python, django, saas, whitenoise
Published: 2020-04-09 18:03:37

{% youtube fHTJYlpxjvo %}

In this episode, we updated Continuous Integration, Nginx, and the Ansible deployment tasks to use WhiteNoise.  With all the changes in place, we tested things out to verify that WhiteNoise served up the CSS, JS, and image files.

We started with Circle CI.  First, I fixed the JS assets cache because the cache key never changed and Circle did not save fresh assets each build.

After completing the assets cache, I created a new cache that stored all the static files after running `collectstatic`.  This new cache was necessary for the package step.

Since we were condensing two build artifacts (one for the static files and one for the Python code) into one, the package script needed all the static files at packaging time.  Because Circle splits everything between jobs, this meant that we had to cache all the static files.

Once we fixed up Circle CI and pushed up the changes, we ran an Ansible deploy to the staging site.

From some inspection of the Circle CI build and the Shiv app on the staging server, I confirmed that the Circle CI changes did what we wanted.

The next major step in the process was Nginx configuration changes.  In this new model, the Django application will serve the static assets.  That means that Nginx should stop serving those files.  This change was a quick removal in the Nginx configuration file of this section:

```nginx
    location /static/ {
        alias /var/www/conductor/;
        expires max;
        add_header Cache-Control public;
    }
```

By removing this `location` block, Nginx passes all `/static/` requests to the Django application.  We did another deploy and confirmed that the Django application served the assets.  Ultimately, I confirmed this by observing that static files used Brotli compression.  This was one of the new features that WhiteNoise brought to the table.

The remainder of the stream was a cleanup of Circle CI and Ansible.  I realized that the Circle CI pipeline had an extra job that we didn't need.  We removed the extra job, then turned our attention to Ansible.

I removed Ansible tasks that touched anything related to separate static directories.  This cleaned out `static_root` and `static_url` in Ansible so that only Django has to care about those things.

On the next stream, we're going to dig into a new tool to manage settings and split settings and configuration apart cleanly.

This article first appeared on [mattlayman.com](https://www.mattlayman.com/building-saas/deploying-whitenoise/).
How to properly catch Express-Validator errors returned by Axios
Tags: expressvalidator, axios
Published: 2020-04-09 17:54:41

Many Express.js based API's extensively uses **[express-validator](https://express-validator.github.io/)** to validate their POST/ GET / PATCH requests and when we test it via postman, it normally returns proper error messages with status code. But when we call the endpoints via **Axios** in our client applications (Angular, React, Vue.js), it doesn't return the proper error messages as we expected.
To solve that issue we need to handle the error object returned by the Axios more precisely like below-

    /*
     * Handling Errors using async/await
     * Has to be used inside an async function
     */
    try {
        const response = await axios.post('http://your.site/api/signup', formData);

        // Success 🎉
        console.log(response);
    } catch (error) {
        // Error 😨
        if (error.response) {
            /*
             * The request was made and the server responded with a
             * status code that falls out of the range of 2xx
             */
            console.log(error.response.data);
            console.log(error.response.status);
            console.log(error.response.headers);
        } else if (error.request) {
            /*
             * The request was made but no response was received, `error.request`
             * is an instance of XMLHttpRequest in the browser and an instance
             * of http.ClientRequest in Node.js
             */
            console.log(error.request);
        } else {
            // Something happened in setting up the request and triggered an Error
            console.log('Error', error.message);
        }
        console.log(error);
    }
Putting Foot in Recursion 
Tags: recursion, datastructure
Published: 2020-04-09 17:15:40

---
title: Putting Foot in Recursion 
published: true
description: Baseline of recursion 
tags: recursion , data structure
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/rgj4ee478805ty11hs1f.jpeg
---
## BaseLine of Recursion

| Rules        | 
| ------------- |
| Base Condition    | 
| Recurrence Relation | 
| Draw Stack to Debug  :innocent:| 



Let's take a question to understand the above baseline:-

##### Reverse the char [] array Using ``Recursion``

* Input: ["H","a","n","n","a","h"]
* Output: ["h","a","n","n","a","H"]

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


##### Swap Node Using ``Recursion``

* Input: [1,2,3,4]
* Output: [2,1,4,3]

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

##### :wink:Debugging

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

<i>Its a stack</i> 

<b>Green indicate pop operation from stack</b>

<a>https://codereview.stackexchange.com/questions/240216/reverse-string-recursion</a>

I have put code on <b>Code Review Stack Exchange.</b>

Disclaimer: Code Review Stack Exchange is a good opportunity for you to review code and follow the best code pattern/design.

Discuss memory optimization.

Hint: 1. see how you can u avoid creating an object and use the static method.

Hint: 2. Why I have used end
*mid = start + (end - start)/2
and why not * mid = (start + end)/2

Share your thoughts over <b>Code Review Stack Exchange.</b>; I would love to hear that.

Soon I will create a video over it :sweat_smile:
Is grid on body container is not best idea on css ?
Tags: css, html, grid, help
Published: 2020-04-09 16:56:12

---
title: Is grid on body container is not best idea on css ?
published: true
description: I could see in most of the website, every section uses grid.There is no single website which uses grid on body. Does it impact performance of website. ? In one of the blog of #css-trick has suggested to avoid to use grid in body.
tags: #css #html #grid #help
---
100daysofcode Flutter
Tags: 100daysofcode, flutter
Published: 2020-04-09 16:22:39

day 31/100 of #100daysofcode #Flutter
Learning Flutter , courses Udemy from
@maxedapps

 Today learning new widget dismisible, practicing provider
https://github.com/triyono777/100-days-of-code/blob/master/log.md
Find Public APIs on the Internet
Tags: public, api, website, free
Published: 2020-04-09 16:15:39

---
title: Find Public APIs on the Internet
published: true
description: List of the websites where you can find the public APIs for your developments.
tags: public,APIs,website,free
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/rm9kw59kuofm8ipil872.png
---

If you are looking for the public APIs to integrate into your projects or want's build something interesting. Then check out my website called [public-apis.io](https://publicapis.io) and explore interesting APIs.

Currently, I curated this APIs list from the internet and give a nice interface with Advanced search. So, you can easily find APIs with your keywords. We have around 700+ APIs into 40+ categories.

[Geocoding APIs](https://publicapis.io/category/geocoding)
[Development APIs](https://publicapis.io/category/development)
[Data Access APIs](https://publicapis.io/category/data-access)
[Cloud Storage APIs](https://publicapis.io/category/cloud-storage-and-file-sharing)
[Anime APIs](https://publicapis.io/category/anime)
[Weather APIs](https://publicapis.io/category/weather)
[Open Data](https://publicapis.io/category/open-data)
[Music APIs](https://publicapis.io/category/music)
[👉View All APIs](https://publicapis.io)

![Public APIs](https://dev-to-uploads.s3.amazonaws.com/i/rm9kw59kuofm8ipil872.png)


That's it. Let me know your thoughts in the comments.

And if you like my work then you can buy me coffee 👉 [buymeacoffee.com/mddanishyusuf](https://www.buymeacoffee.com/mddanishyusuf)

Mohd Danish
Website: [mohddanish.me](https://mohddanish.me)
Twitter: [@mddanishyusuf](https://twitter.com/mddanishyusuf)
A rap song about over engineering
Tags: showdev, culture, programming
Published: 2020-04-09 16:12:28

---
title: A rap song about over engineering
published: true
description: https://www.youtube.com/watch?v=dQdsFpvTKU4
tags: #showdev, #culture, #programming
---

Song url: https://www.youtube.com/watch?v=dQdsFpvTKU4

Quick background on the project: I'm a full time programmer and I love making rap music. I see a lot of humor in the profession/industry, and thought it would be fun to combine the two.
Ergonomics of desk-setups
Tags: ergonomics, homeoffice, workstations, discuss
Published: 2020-04-09 16:11:38

Hi everybody,

I wondered, how many of you are aware of ergonomic rules on how to create an ergonomic workspace. Specially in the homeoffice. When you browse for example the hashtag desksetup on instagram you will find that most desks are placed against a wall, so you can place rgb strip or a picture frame and simply make a good picture.

But that is actually quite bad for your eyes, if you can't focus on a different distance for the whole day. I tend to put my desks on a right angle from the wall so a can look into the room.

What are your toughts on that? I would like to see your desk setups, that have an ergonomic purpose.

Stay home, stay save.
About Ruby Hash#<= (Subset)
Tags: ruby, hash, documentation
Published: 2020-04-09 16:10:28

---
title: About Ruby Hash#<= (Subset)
published: true
description: 
tags: ruby, hash, documentation
---

Get more information and more examples at my AboutRuby project:
* [AboutRuby project](https://github.com/BurdetteLamar/AboutRuby/blob/master/core/Hash/api/markdown.md#-subset)

Here's the write-up over at the Ruby project:
* [Ruby project](https://ruby-doc.org/core-2.7.0/Hash.html#method-i-3C-3D)

My main page is [here](https://github.com/BurdetteLamar/AboutRuby#about-ruby).

TL;DR

I've been working on enhancements to the documentation for the Ruby project.  Getting these enhancements posted to the Ruby project has been very slow.  They're not actually meeting resistance;  I know because my many PRs for enhancing class ENV were accepted (though not rapidly).  It's just that everyone is busy.

Anyhow, I'm stashing all this stuff on in my own project, called AboutRuby.  The piecemeal migration from there to the Ruby project is not going to be completed in my lifetime (I'm 77 years old).

So:  I'm going to blow my own horn here on DEV, to encourage you to use the enhanced documentation.
Maximum Sum Subarray of Size K, Applying Sliding Window pattern
Tags: javascript, interview, career, algorithms
Published: 2020-04-09 15:57:40

Question: Given an array of integers and a number k, find the maximum sum of a subarray of size k.

Eg: For given array A[] = {10,30,20,50,60,40,40} of size k = 2
The maximum sum subarray would be 
sum =  50 + 60 = 100.

<strong>Brute Force: O(N*K)</strong> N = Size of Array.

Brute force solution would be to generate all possible subarray of size K and find the maximum among those subarrays.

```javascript
var maxSubarray = function(arr,k){
  let max = 0;
  for(let i=0;i<arr.length-k+1;i++){
    let tempMax = 0;
    for(let j=i;j<i+k;j++){
      tempMax += arr[j];
    }
    if(tempMax > max){
      max = tempMax;
    }
  }
  return max;
};
```

Now let's think about optimizing it. Let's observe what are we actually doing at each step.
<img src="https://media.giphy.com/media/jJA5fhjTuIOqc/giphy.gif" />

```javascript
Let
A[] = [10,20,10,40,50,10,60]
K = 3

for index 0 : sum = 10 + 20 + 10 or index 0 + index 1 + index 2
for index 1 : sum = 20 + 10 + 40 or           index 1 + index 2 + index 3
for index 2 : sum = 10 + 40 + 50 or                     index 2 + index 3 + index 4
for index 3 : sum = 40 + 50 + 10 or                               index 3 + index 4 + index 5      

and so on..
```

From this, we can see that at each iteration, we sum up add the elements between index(i,i+k). But also observe that at each step we're repeating the same steps.

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

So as you can see we're repeating same steps, so now let's think about how can we avoid duplicate steps, this leads to our another observation that 

for a given index i, sum = A[i] + A[i+1] + A[i+2] + ... + A[i+k];
for index i+1        sum =        A[i+1] + A[i+2] + ... + A[i+k] + A[i+k+1];

so at each iteration <strong>i+1</strong>, we are subtracting A[i] and we're adding A[i+k+1].

And this, Ladies and Gentlemen is called a <strong>sliding window</strong> where at each step we add the next element and remove the previous element.

<img src="https://media.giphy.com/media/3orieUe6ejxSFxYCXe/giphy.gif" />

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

Let's code it ! 
```javascript 
var maxSubarray = function(arr,k){
  let max = 0;
  let windowSum = 0;
  let windowStart=0;
  for(let windowEnd=0;windowEnd<arr.length;windowEnd++){
      windowSum+=arr[windowEnd];
      if(windowEnd>=k-1){
        max = Math.max(windowSum,max);
        windowSum -= arr[windowStart];
        windowStart++;
      }
      console.log(windowSum,max);
  }
  return max;
};
```
That's it ! Now you know how to see the patterns and solve most commonly asked interview question. Your interview will be like : 

<img src="https://media.giphy.com/media/OwQn9LCHFcQ5G/giphy.gif" />

Hope you understood and liked my explanation!

github:https://github.com/AKHILP96/Data-Structures-and-Algorithms/blob/master/problems/MaximumSubarraySum.js