teleren/devto huggingface dataset:
DRY (within a project) != (across multiple apps)
Tags: webdev, javascript, html, css
Published: 2020-05-26 10:25:51

# Don't repeat your self in different scopes

I won't explain basics here, we all know how important it is not to repeat our selves. However, how do you decide the scope of re-usability? Should everything be a component? Or, maybe there are cases where having reusable pieces of UI that are aware of the app state is desirable.

Personally, I feel the word "component" is overused by big players like React. Why such a strong statement? - Well, I think there is much more to name something a component than a piece of UI which receives props. 

A component supposed to be self-contained, it shouldn't be aware of the hosting app. It should be usable across multiple projects, and the number of its props and their variations shouldn't intimidate a developer.

At [GlueCodes](https://www.glue.codes), when designing the architecture of code to be spitted by our platform we took a few aspects into consideration:

- we need proper components to be reusable across apps and they should be easy to plug-n-play.
- we need some sort of partials which aren't likely to be shared across multiple apps but they repeat among multiple pages e.g. sections, blocks etc.
- we need to be open to third-party libraries and use npm/yarn.

### Reusable slots

![Reusable slots](https://solid-js.s3.eu-west-2.amazonaws.com/reusable-slot.gif "Reusable slots")

Every web app consists of elements which are shared across multiple pages. These can be header, footer, cookie consent notice or anything limited only by your imagination. In your pages, you can use any pre-added reusable UI slots or just add a new one by simply using it in the page HTML.


### Components

![Components](https://solid-js.s3.eu-west-2.amazonaws.com/use-component.gif "Components")

Imagine you just click install and the component gets injected with its testing props, example app actions it may expect etc. - that's how we imagine an easy plug-n-play. Will too many components slow the page down? No, our component building process strips out unnecessary code including rendering layer and commonly used utility libraries. All components are versioned to make sure your project never falls apart. If you want to develop a component yourself, good news! - we have a proper dev process in place which lets you use standard stuff (more on it in the next post). 


### Third-party libraries

![Third-party libraries](https://solid-js.s3.eu-west-2.amazonaws.com/third-party.gif "Third-party libraries")

Many valuable libraries have already been written. [GlueCodes](https://www.glue.codes) is an IDE for professionals and it wouldn’t be complete without a full access to NPM Registry. You can use your favourite open source libraries as you like.


So just don't f**king repeat your self and read more about  [GlueCodes Platform](https://www.glue.codes). :wink:

repo: https://github.com/gluecodes/gluecodes-framework

*We're running a [Kickstarter](https://www.kickstarter.com/projects/gluecodes/gluecodes-platform) campaign to be able to finish off the IDE and web components. Any pledge is much appreciated.*
Remove unwanted properties from Javascript Objects using ES6 destructuring
Published: 2020-05-26 09:59:46

lets say we received an object  from an api response which contains some sensitive data

```jsx

const userData = {
  name:"Rick Sanchez",
  email:"ricksanchez@getSchwifty.com"
  address :" Dimension C-137",
  sensitiveInfo:"wubba lubaa dub dub",
  secretportalkey:"ABCDEF"
}
```

Now we want to pass it to some third party api but we dont want to pass the sensitiveInfo and secretPortal key to the Api

So, How do we remove that from the Object ?

Simple, just use the power of destructuring  

```jsx
const {sensitiveInfo,secretportalkey,...notSoSensitiveData} = userData

/* Now our notSoSensitiveData will contain all the properties except the ones which
 are destructured
*/

console.log(notSoSensitiveData)

/* {
  name:"Rick Sanchez",
  email:"ricksanchez@getSchwifty.com"
  address :" Dimension C-137",
}
*/
```
Demystifying [[environment]] in JavaScript Closure 
Tags: javascript, interview, closure, beginners
Published: 2020-05-26 09:58:21

Hi all, For those who don't me I'm Divakar, Passionate developer with 5 years of experience in web and mobile development. I learned software development the hard way, following lots of confusing tutorials, failing to understand core concepts and finally having no idea how things work. So I wanted to help the community to
understand it in a better way without any hassle.

Before getting know about the closure i will start with couple of questions

> **<h3><strong>Can you make a function to run only once ?</strong></h3>**

> **<h3><strong>Can you make a function to memorize ?</strong></h3>**

By end of this article you will be able to answer those questions.

**<h3><strong>Closure:</strong></h3>**

Every function in JavaScript is bound to have a [[ environment ]] or [[ scope ]] hidden property ,that have reference to the current lexical environment of their creation.

> Do remember that lexical environment is theoretical and no one can get this object in console and manipulate it directly

 Closure is a function that also have this hidden property along with it ,which stores the state of the current lexical environment, by which it can have access to outer variables. This makes closure in JavaScript as one of the most powerful concept. 

Usually, a lexical environment gets removed from memory along with all the variables after the function calls finishes . But this is not the case in CLOSURE, it gets tied to the memory even after the function call finishes.


From now on i will be calling this hidden [[ scope ]] or [[ environment ]] property as a backpack.
 

<img src="https://dev-to-uploads.s3.amazonaws.com/i/qtm8pxl69mlv3c0n8l7f.png" width="4096" />

In the above function , when getCounter() function call gets executed it runs in the execution context ,

Step 1: It searches for counter variable in the local memory of the execution context

Step 2: JS Engine cannot find the counter variable in the local memory of the execution context, now it looks into the backpack - Voila ! we found the counter variable and it picks up

Step 3: It increments the counter and the value gets modified in the backpack ( persistent memory ) as well. So if the getCounter() is called again , then the counter variable value will be incremented to one.

<img src="https://dev-to-uploads.s3.amazonaws.com/i/mf824bc9am75zsl4fp3g.png" width="2048"/>

In the above code you could see that each time you initalize a variable with makeNewCounter , there will be independent backpacks available to getCounter and anotherCounter.


Great ! 🎉🎉 Now the next time you use closure , you have clear idea what is happening behind the scenes.


Since now you know about the closure and its actual working behind the scenes try to answer my first 2 questions 

> **<h3><strong>Can you make a function to run only once ?</strong></h3>**

> **<h3><strong>Can you make a function to memorize ?</strong></h3>**
Bite-Size Python: Dictionaries basic
Tags: python
Published: 2020-05-15 16:10:23

---
title: Bite-Size Python: Dictionaries basic
published: true
description: Basic usage of dictionaries data type in Python
tags: python
---

As the name imply, dictionary consists of keys and values mapping so that we can lookup for the `value` using the `key` the same way we lookup for the meaning of the word.

This post will show some basic operation on dictionaries like dictionary creation, modification and so on.

Let's start!


Dictionary creation 
```python
# create empty list
>>> a_dict = {}
# or
>>> a_dict = dict()

# create with some value
# key's in the dictionary can be mix with some other types
>>> a_dict = {"key1": "value1", 2: "two", "three": 3} 
>>> a_dict
{'key1': 'value1', 2: 'two', 'three': 3}

# or using dict() with sequence of key-value pairs
# like list of a pair of tuple
>>> a_dict = dict([("key1", "value1"), (2, "two"), ("three", 3)])
>>> a_dict
{'key1': 'value1', 2: 'two', 'three': 3}
```


Accessing dictionary value

```python
# using the same manner of accessing list element 
# but use the key instead of index number
>>> a_dict["key1"]
'value1'
# or using get()
>>> a_dict.get(2)
'two'
# the main difference between these two is 
# get() will return None if the key is not found 
# in the dictionary but the other will raise the KeyError exception
# so, your program will break if the error's raise, so be careful
>>> a_dict.get("python")
>>> # noting happen

>>> a_dict["python"]
KeyError: 'python'

# you can check whether the key is available 
# in the dictionary or not using `in` syntax
>>> "key1" in a_dict
True
>>> "python" in a_dict
False

```


Dictionary modification

```python
# modify the existing value
>>> a_dict["key1"] = "one"
>>> a_dict
{'key1': 'one', 2: 'two', 'three': 3}

# adding new key-value pair
>>> a_dict["python"] = "snake"
>>> a_dict
{'key1': 'one', 2: 'two', 'three': 3, 'python': 'snake'}

# delete using `del`
>>> del a_dict[2]
>>> a_dict
{'key1': 'one', 'three': 3, 'python': 'snake'}
```

Iterating over dictionary
```python
# we can iterate over dictionary using looping statement like `for-loop` with items() to get both key and value pair for each member
>>> for k, v in a_dict.items():
        print(k,":",v)
key1 : one
three : 3
python : snake

# getting keys only using keys()
>>> a_dict.keys() 
dict_keys(['key1', 2, 'three'])

# as you expect, we can get only values too!
>>> a_dict.values()
dict_values(['one', 3, 'snake'])
```

I hope this can help you to getting start using dictionary in Python.

Thanks for reading! :)
Countdown number game solver
Tags: challenge
Published: 2020-05-26 09:11:58

---
title: Countdown number game solver
published: true
tags: challenge
---

In the UK there is a game show called [Countdown](https://www.channel4.com/programmes/countdown). It has two main components, rearranging letters and doing arithmetic.

This challenge is concerned with the arithmetic, or number game, part.

In the number game the contestants are given six numbers between (and including) 1 and 100. No number repeats. A target number less than 1000 is then generated. The contestants have to use the numbers they are given to create a sum that equals the target. They can use addition, subtraction, multiplication and division. Each number can be used up to once, unless you make that number out of the other numbers.

For example, say the numbers are 1, 2, 6, 12, 14 and 5 and the target is 144. 12 &times; 12 is not a solution because 12 can only be used once. However 6 &times; 2 &times; 12 is a solution. (14 - 2) &times; 12 is also a solution.

The challenge is to create a programme or function that takes a list of numbers and a target and then generates solutions that use those numbers to create that target.

## Tests

```
numberGame([7, 12, 4, 5, 25, 50], 615)
# possible output
# (((((7*12)+4)+25)*5)+50) = 615

numberGame([7 11 1 2 25 75], 367)
# possible output
# (((((1+75)-7)*11)-25)/2) = 367
```

It's not necessary to show all possible solutions, just at least one that works.
Vanilla JS FadeIn/Out 
Tags: vanillajs, javascript
Published: 2020-05-26 09:08:52

It looks like JQuery is slowly starting to be "a thing of the past".. so i recently migrated <a href="https://github.com/BMSVieira/BVSelect-VanillaJS">my project</a> from JQuery to Vanilla.. and the result is quite satisfying.

First, you can be sure that if you made it with JQuery, you will make it with Vanilla aswell, but keep in mind that may required a few more lines of code.

One of the things that i used to use alot with JQuery was FadeIn/FadeOut... now the question was: how to do it in Vanilla?

Well... quite easy actually.
Hope it helps someone.

```javascript
        // ** FADE OUT FUNCTION **
        function fadeOut(el) {
            el.style.opacity = 1;
            (function fade() {
                if ((el.style.opacity -= .1) < 0) {
                    el.style.display = "none";
                } else {
                    requestAnimationFrame(fade);
                }
            })();
        };
        
        // ** FADE IN FUNCTION **
        function fadeIn(el, display) {
            el.style.opacity = 0;
            el.style.display = display || "block";
            (function fade() {
                var val = parseFloat(el.style.opacity);
                if (!((val += .1) > 1)) {
                    el.style.opacity = val;
                    requestAnimationFrame(fade);
                }
            })();
        };
```
It works really well and it gives your project a little personality :P
Azure SSL Certificate! WebApp!! WAF!!!
Tags: azure, security, sslcertificate, azurewebapplicationfirewall
Published: 2020-05-26 09:06:57

---
title: Azure SSL Certificate! WebApp!! WAF!!!
published: true
description: 
tags: Azure, Security, SSL Certificate, Azure Web Application Firewall
---

Recently happen to come across a scenario where the SSL certificate (in Azure) was auto-renewed and Azure Web Application Firewall (WAF) SSL offloading went kaput! 

The setup!
Internet --> Azure WAF --> Azure WebApp

Auto-renewed Cert is in KeyVault (KV). Though the KV gives you an option to export the certificate you will end up getting the "Password for the certificate is wrong" error/notification 

Following is what I managed to do get the certificate successfully imported into WAF listener 

<b>Login to Azure and set the subscription</b> 
Login-AzureRmAccount
Set-AzureRmContext -SubscriptionId xxxxx-xxxxx 

<b>Download Certificate stored as PFX as Secret</b> 
$vaultName  = "<i>yourvaultname</i>"
$keyVaultSecretName = "<i>secretname</i>"
$secret = Get-AzureKeyVaultSecret -VaultName $VaultName -Name $keyVaultSecretName

<b>Create PFX Object from the Secret we received</b>
$pfxCertObject = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @([Convert]::FromBase64String($secret.SecretValueText),"", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)

<b>Create a Password to associate with the PFX </b>
$pfxPassword = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 50 | % {[char]$_})

<b>Notedown the pfx password by checking</b>  <i>(you will need this to import the certificate in the WAF")</i>
$pfxPassword
![](https://dev-to-uploads.s3.amazonaws.com/i/2eo788yh1cf0r3k9znrn.jpg)


<b>Write the PFX Object to file System and add a password to it </b>
$currentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath

[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath

[io.file]::WriteAllBytes("C:\tmp\appservicecertificate.pfx",$pfxCertObject.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $pfxPassword))

You should be able export the certificate from your local drive
![](https://dev-to-uploads.s3.amazonaws.com/i/cn6e2qxrshtzwd1ggk7n.jpg)

<b> Time to Import the SSL Certificate in WAF!</b>
(Az Portal) Home -> Applciation Gateway -> Listeners -> <i> Your Listener Name </i> -> Certificate -> Select "Renew or edit selected certificate" and follow the onscreen instructions to import the renewed certificate..
Managed vps hosting by Scala Hosting
Published: 2020-05-26 08:59:03

Managed VPS means improved security The shared hosting model is not safe. When a website on a shared server is compromised the hacker uses it to attack and compromise the other websites on the server. It is 100’s of times easier to compromise a website with local access to the server. By moving your website on its own <a href="https://www.scalahosting.com/cloud-servers.html">secured managed vps hosting</a> you improve its security 100’s of times and help the Internet become a safer place.
Gatsby blog with Web Monetization and custom components
Tags: gftwhackathon, react, gatsby, webmonetization
Published: 2020-05-26 08:30:18

## What I built
I have created a [Gatsby blog](https://gftw-hackathon.netlify.app/) experimenting with various usages of web monetization, namely: 
* enabling exclusive content
* removing ads
* micropayment counter
* revenue sharing
* starting and stopping monetization

### Submission Category: 
Creative Catalyst

## Demo
Please visit [my website](https://gftw-hackathon.netlify.app/).
### Screenshot of home page
![screenshot](https://github.com/petr7555/gftw-hackathon/blob/master/screenshot.PNG?raw=true)

## Link to Code
{% github petr7555/gftw-hackathon%}

## How I built it
I created a gatsby-personal-starter-blog and then created custom React components.
My journey is documented as posts on the [blog](https://gftw-hackathon.netlify.app/blog/).
Recreating Lodash: _.pull()
Tags: lodash, programming, javascript
Published: 2020-05-26 08:19:42

I want to start a series where I'll look at various lodash functions and recreate them to the best of my knowledge using plain ol' Javascript.

I did look around for this on DEV, but couldn't find any articles related to this, so saw an opportunity to make one (or maybe I'm just really bad at searching).

I'm starting out with the [`_.pull()`](https://lodash.com/docs/4.17.15#pull) function cause that's one I know how to recreate easily, but feel free to suggest functions in the comments below and I'll consider them for the next edition of the series.

## What does it do?

The _.pull() method simply takes an array and a variable number of values after it and modifies the array with the values removed.

```js
let array = ['a', 'b', 'c', 'a', 'b', 'c'];
_.pull(array, 'a', 'c');
console.log(array);
// => ['b', 'b']
```

# How can we make it better?

Now, if there's one thing I do not like, it's functions mutating my original array. I'd much rather have it return a new array thus not modifying the original data.

Another change I'll be making is instead of working on variable arguments, to make this tutorial simple, I'll just pass another array with all the values, so the finished function would look like this:

```js
array = ['a', 'b', 'c', 'a', 'b', 'c'];
result = pull(array, ['a', 'c']);
console.log(result);
// => ['b', 'b']
```

This is similar to another function in lodash, [`_.difference()`](https://lodash.com/docs/4.17.15#difference), so we're essentially rebuilding that.

# How do we build it?

Right off the bat, we'll be using the [`Array.prototype.filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) method for this.

Let's write our function definition first.

```js
let pull = (array, values) => {
  // insert magic here
};
```

Let's call the filter method on the array.

```js
let pull = (array, values) => {
  return array.filter(item => {
    // insert more magic here
  })
};
```

Now, we're going to check if the item inside the values array exists inside the array. We can do this by using the [`Array.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) function.

If the value exists, we would get a non-zero value, so we can return false to remove it from the array, otherwise we can return true to keep it in the array.

```js
let pull = (arr, values) => {
  return arr.filter((item) => {
    return values.indexOf(item) < 0;
  });
};
```

This is going to churn out our expected output.

## Does this really work?

Here's a CodePen to play around with and see the code in action.

{% codepen https://codepen.io/AmruthPillai/pen/BaoEvpE default-tab=js,result %}

## Conclusion

Of course, in reality, lodash does a lot more in terms of type checking and it's well built out, but it would pay to know how it works under the hood :)

Do let me know if you find this interesting with a reaction, and if you want to see other functions, mention them in the comments!

Thank you so much for reading! :)
How To Start a Blog In 2020 From Scratch
Tags: startup, blog
Published: 2020-05-26 05:53:13

Blogging is no wonder a great career & you can earn a handsome amount if you put great effort and that too with dedication. If you want to learn <a href="https://onehostingcenter.com/how-to-start-a-blog-in-2020-from-scratch/">how to start a blog in 2020</a> so that you can grow an audience and make a good amount, you’ve come to the right place.

We’ll walk you through the step-by-step process so that you can easily start your blog in 2020. Here we have also covered the answer to some common blogging questions, and BONUS – show you some free tools and resources that definitely going to help you in the blogging journey. 

You just need to follow simple steps in order to create your own blog and start padding your wallet. 

<b>Step 1 - Pick the Right Blog Topic</b>

Always remember before starting – Do you enjoy the topic? Is it fun? These 2 questions are very important when you have planned to start your blogging journey. But yes, if you’re looking to start a blog to generate passive income… then you need to choose a viable blog topic that has great chance to succeed. 

<b>Step 2 - Choose the Right Blogging Platform</b>

There are several free blogging platforms out there. In fact, we’ve witnessed many bloggers starting with a free Medium.com account. here you can test out your  ideas and make sure they’re viable before creating a full-fledged blog. 

Remember, once you’re ready to build an audience and make money online, there’s only one blogging platform that you must consider and that’s WORDPRESS

<b>Step 3 - Choose a Domain Name</b>

Names are not clever, but they greatly help you decide to stay or just go by clearly articulating who they are helping. That’s simply what a good domain name does & so having a good domain is a bless. 

<b>Step 4 - Purchase a Web Hosting Plan</b>

There are number of <a href="https://onehostingcenter.com/top-web-hosting-providers-2020/">web host providers</a> for WordPress but we always recommend “SiteGround” to our readers because it’s quite affordable & offers great features at low costs. 

<b>Step 5 - Install WordPress</b>

When you login into SiteGround user panel for the very first time, the Account Setup Wizard will appear. Click the Start a new website option and then after select WordPress as the software. Next, you’ll create the login details for your WordPress account.

Now, Go to your WordPress login URL by appending /wp-admin (or /admin or /login or /wp-login) to the end of your domain name.

<b>Step 6 - Choosing a WordPress Theme</b>

Install wordpress theme of your choice >> Install >> Activate!

<b>Step 7 - Install WordPress Plugins</b>

The 5 Types of WordPress Plugins You Need to Install

Performance Plugins (Our Pick: WP Super Cache)
SEO Plugins (Our Pick: Yoast SEO)
Backup Plugins (Our Pick: UpdraftPlus)
Security Plugins (Our Pick: iThemes Security)
Social Sharing Plugins (Our Pick: Social Warfare)

<b>Step 8 - Write Your First Blog Post!</b>
I'm Making Great Progress on my Side Project and I'm Freaking Ecstatic
Tags: devjournal, codenewbie, womenintech
Published: 2020-05-26 08:11:38

_This post was originally published on May 26, 2020 on [my blog] (https://alexlsalt.github.io/blog)._

Wow, happy Tuesday - I'm on a freaking roll since last night. Allow me to explain...

So, yesterday I finally implemented a timing feature for my Wellbean app. Essentially, after a given number of hours (depending on the frequency set i.e. Daily, Weekly, etc), each list item will either stay white (default, timer hasn't expired) or turn red (expired, timer has run out).

When the list item/contact turns red, it means the user should consider contacting that particular contact, based on their pre-set contact suggestion frequency.

![Screenshot of Wellbean UI](https://dev-to-uploads.s3.amazonaws.com/i/zkkbhbnswnza3kwzn77j.png)

Ah! I'm so freaking excited about it. It's crazy how it's all coming together, both in the code and in my mind! I'm so proud of it all.

I'm going to focus today's work on learning how to implement Firebase rules for the database so that I can publicly release it while keeping the data private.

Then, after today, I'm going to wrap it all up, record a demo on Loom, craft up a big readME for the GitHub repo, and shout from the rooftops! Cheers.