teleren/devto huggingface dataset:
Code Smell 67 - Middle Man
Tags: webdev, codenewbie, tutorial, oop
Published: 2021-04-12 03:08:38

*Let's break Demeter's Law.*

# Problems

- Unnecessary Indirection

- Empty Classes

- Readability

# Solutions

1. Remove Middle man.

# Sample Code

## Wrong

{% gist https://gist.github.com/mcsee/8f89b53d0be21a6779e4be53673edf5c %}

## Right

{% gist https://gist.github.com/mcsee/63674fe800fca77d3a7edc39bde428c8 %}

# Detection

Same as its [opposite smell](https://dev.to/mcsee/code-smell-08-long-chains-of-collaborations-30c3), We can detect this small using parsing trees.

# Tags

- Coupling

- Declarative

- Readability

# Conclusion

This is exactly the opposite to [Message Chain](https://dev.to/mcsee/code-smell-08-long-chains-of-collaborations-30c3). We make explicit the message chain. 

# Relations

{% post https://dev.to/mcsee/code-smell-08-long-chains-of-collaborations-30c3 %}

# More info

%[https://refactoring.guru/smells/middle-man]

%[https://refactoring.com/catalog/removeMiddleMan.html]

%[https://wiki.c2.com/?MiddleMan]

%[https://www.jetbrains.com/help/idea/remove-middleman.html#remove_middleman_example]

%[https://en.wikipedia.org/wiki/Law_of_Demeter]

# Credits

Photo by <a href="https://unsplash.com/@dancounsell">Dan Counsell</a> on <a href="https://unsplash.com/s/photos/robber">Unsplash</a>
  
* * *

> Whenever I have to think to understand what the code is doing, I ask myself if I can refactor the code to make that understanding more immediately apparent.

_Martin Fowler_

* * *
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

%[https://dev.to/mcsee/series/9470]
Modify request and response headers in Chrome
Tags: http, chrome, firefox, headers
Published: 2021-04-12 02:46:26

Having control over the headers in every request that passes through your browser can be a great power to have. You can test sites in production, delete referer headers to minimize online tracking, test the CSRF implementation on a target while pentesting and so on, the list is endless. With Requestly, you can do all this in a few simple steps.

1. Create a modify headers rule in requestly. Give it a suitable name and description.
![Requestly - Modify Headers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1xtqdzbz4rq36v239mtr.jpg)
2. Select if you want to modify the request header or the response header
![Change request or response headers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jzhglcjip6bl2qf8atso.jpg)
3. Select the action that you want to do. Do you want to add a new header, modify an existing one or delete a header from all matching requests/responses
![Apply operations to be performed on http headers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n52k82l7g12nm9oy5f1d.jpg)
4. Enter the header name and its value
5. Specify when this rule should be applied. You can match requests/responses based on URL, hostname, or path. You can also use regex if you want
![URL matching to modify headers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xbb82m706mfz47pbnsjm.jpg)

Now you know how to yield this power. But remember 
![Spiderman - with great power comes great responsibility](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nck6jpix3dopiv880o0f.jpeg)
Show npm/yarn current package version in repository on GitHub organization
Published: 2021-04-12 02:19:42

---
title: Show npm/yarn current package version in repository on GitHub organization
published: true
description: 
tags: 
---

[Show Ruby/Gem version in repository on GitHub organization - DEV Community 👩‍💻👨‍💻](https://dev.to/sanemat/show-ruby-gem-version-in-repository-on-github-organization-1h7d)

yarn
```
$ for dir in */; do (cd $dir; git grep -n -A1 -E '^jquery@' yarn.lock 2>/dev/null|perl -ne 'print if s/  version "(.*?)"/$1/'| tr -s '\n' '\0' | xargs -0 -I {} printf "$(basename $(pwd))/{}\n") done
```

npm
```
$ for dir in */; do (cd $dir; git grep -n -A1 -E '"jquery"' package-lock.json 2>/dev/null|perl -ne 'print if s/"version": "(.*?)"/$1/'| tr -s '\n' '\0' | xargs -0 -I {} printf "$(basename $(pwd))/{}\n") done
```
HELP! CRM inside Twilio, not Login-in.
Published: 2021-04-12 02:06:57

Hello Everyone, I'm working on setting up our twilio flex system with our CRM incorporated inside. Everything seems great, exept when I try to login into my crm through twilio flex nothing happens. When input the user and password then it like refreshes. This is done in react.

This is the code I'm using

flex.CRMContainer.defaultProps.uri = "https://samplewebsite.net/";


Now I think this can be a security issue of some sort. Is there someone here that has had a similar issue or can point me in the right direction?

Thank you!
I want to build a Python wrapper for an API, how should I approach it?
Tags: python, help, discuss
Published: 2021-04-12 02:01:45


I am planning to build a python wrapper around a rest API.

- I want to support friendly functions, with autocompletion in the editor.
- I want 100% test coverage
- I want the package to be modular, so that, any changes to API, can be easily reflected
- I want to support both async and normal methods
(the core will be implemented thru async, but there will be a wrapper for those who don't want to use async)

example:
```python
import asyncio
from library import Api

api = Api()

async def do_job():
    thing = await api.get_thing()
    print(thing)

asyncio.run(do_job())
```

or 

```python
from library.sync import Api

thing = api.get_thing()

print(thing)
```

the data that will be passed to the functions should be validated. planning to use pydantic.

planning to create a sub-package `library.models` to contain all the modules defining the models.

**how should I design the entire thing? how should I structure the project?**

**best practices? guides?**
LeetCode 1448. Count Good Nodes in Binary Tree
(javascript solution) | Microsoft question
Tags: algorithms, javascript
Published: 2021-04-12 01:57:04

###Description:
Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.

Return the number of good nodes in the binary tree.

###Solution:
Time Complexity : O(n)
Space Complexity: O(height of the tree)

```javascript
// DFS solution
var goodNodes = function(root, max = root.val) {
    let output = 0
    // Only add to output if we meet the condition
    if(root.val >= max) output++
    // Increase the max if we encounter a val greater than max
    max = Math.max(Math.max(root.val, max))
    // Traverse the tree to compare more nodes
    if(root.left) output += goodNodes(root.left, max)
    if(root.right) output += goodNodes(root.right, max)
    
    return output   
};
```
Make everything an experiment
Tags: productivity, experiment, practices
Published: 2021-04-15 09:09:54

---
title: Make everything an experiment
published: true
date: 2021-04-12 00:00:00 UTC
tags: productivity,experiment,practices
canonical_url: https://jhall.io/archive/2021/04/12/make-everything-an-experiment/
---

The best course of action isn’t always obvious. Should you use an RDBMS or NoSQL database? Should you use Scrum or Kanban?

Sometimes the best course of action may be obvious to you, but you can’t convince others on your team.

In either case, there’s a simple tactic that can help break the deadlock:

**Experiment!**

Conduct a short-term experiment, using one of your proposed solutions. After a short trial period (perhaps a week, perhaps a month), re-evaluate, and determine next steps. If your chosen database isn’t turning out as great as planned, it’s easy at this stage to change course, with minimal wasted effort.

To conduct a successful team experiment, follow these simple steps, taken from my video course, [_Ship better code faster_](https://jhall.io/sbcf):

1. **State the goal.** What is the reason for the experiment? Might be a technical improvement, streamlining of meetings, or any other team goal.
2. **Propose an action.** What action are you agreeing to do as an experiment? Remember: It’s not permanent. Nobody’s committing to staying this course forever.
3. **Agree to a timeline.** How long will this experiment run? 1 or 2 weeks is usually sufficient, although some changes may require more time to meaningfully evaluate. In other cases, an hour may be enough.
4. **Conduct the experiment.** Do the proposed action for the agreed duration. Try to stick to the plan, and not abort the experiment early, unless there’s a really good reason!
5. **Review the results.** Get the team together and discuss the experiment. What went well? What went poorly?
6. **Iterate.** What are the next steps? Was the experimental action successful? Should it continue? Should it cease? Will you try some other experiment?

* * *
If you enjoyed this message, [subscribe](https://jhall.io/daily) to _The Daily Commit_ to get future messages to your inbox.
Neglecting cyber-security
Tags: cybersecurity, startup, architecture, junior
Published: 2021-04-12 01:51:51

Let's imagine. As a new graduate software engineering student, you find your first job in a small startup. Where you are the only engineer.

You get assigned an internal project to improve the quality of life of the company. A project that involves handling all the customers’ data and notes from the company. All the critical data on your hands.

Then you apply what you learned at school and in tutorials, you create a front-end, a back-end, and quickly set up a database. You do a proof-of-concept (PoC). All the team is now super excited by your app. As a result, feature requests start to rain.

Time is money, so you build on top of your PoC. You add features one by one. You start to have a great product and getting adoption from the team.

Everything is great!

The next day, you arrive at the office. The app is down. That happens sometimes. Generally, a reboot of the back-end fixes it.

It does not work this time. You start digging into the issue. The team is calling you for support. But you are clueless.

Finally, you identify a problem with the database. You restart it. The app works now! But it’s empty. All data is gone! You check the database content to find a ransomware message asking you to pay X bitcoins to get back your data.

The next day you lose your job and your product gets abandoned.

Time is money, it’s true, and you may neglect cyber-security when there’s nothing at stake. But when there is, don’t treat cyber-security as if it was a virtual reality problem.

-----------------------------------

Photo by <a href="https://unsplash.com/@maxlarochelle?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Max LaRochelle</a> on <a href="https://unsplash.com/s/photos/clouds?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
JavaScript Scope
Tags: javascript, scope
Published: 2021-04-12 01:45:18

Scope in a programming language controls the visibility and lifetime of variables and parameters.  

Another way of thinking about scope: The part of the program where a particular identifier is visible or accessible such as a variable or function name.

Why am I ranting about scope, well..., it's because of the following reasons:

1. Security. Variables can only be accessed from a certain area of the program.

2. Reduces naming collision. We can use the same variable name in different scopes.

3. Bugs. We all love bugs or do we? Getting to know a little bit more about scope will help you understand variable values or issues.

Before I get in to examples, we have to know what types of scope exist:

1. Global
2. Function
3. Block

**Global**
Any variable that is not inside a function or block ( a pair of curly braces ) is inside the global scope.

**Function**
Any variable that is declared inside a function can only be accessed within that function, that means you cannot access them from outside it.

**Block**
ES6 introduced let and const variables, unlike var, they can be scoped to the nearest pair of curly braces. That means they can't be accessed outside that pair.

Finally, how does JavaScript find the variable value.

1. Check current scope
2. Check outer scope
3. Check global scope

If it's still not able to find the variable, it will either implicitly declare the variable in the global scope or return an error. 
 
Time for examples:

**Global**
```
var meow = 'Meow';

function cat () {
 return meow
}

// value returned by cat is 'Meow'
cat()

console.log(meow) // Prints 'Meow'
```

In this case, the variable meow will not return an error since it is in the global scope and is accessible everywhere since it is not function scoped or block scoped.

**Function**
```
function cat () {
  var meow = 'Meow';
  return meow
}

// value returned by cat is 'Meow'
cat()

console.log(meow) // Uncaught ReferenceError: meow is not defined
```

If we try to access meow outside of cat it will return a `Uncaught ReferenceError: meow is not defined` since meow is only accessible or visible in the function cat.

**Block**
```
if(true) {
  const cat = 'meow';
  var meow = 'Meowwwww!!!!';
  console.log(cat); // Prints 'meow'
}

console.log(cat); // Uncaught ReferenceError: cat is not defined

console.log(meow); // Prints 'Meowwwww!!!!'
```

So, what is going on here, the variable cat is bound to the if statement because of the curly braces or block scope. 

In this case the variable cat if accessed outside the if statement will return an error as defined above but since meow is not block scoped it will return the expected value. Remember const and let variables are block scoped.

**Summary**
* A scope is an area where a variable is visible and accessible. 
* Just like functions, scopes in JavaScript can be nested and the JavaScript engine traverses the scope chain ( how JavaScript looks for the variable ) to find the variables used in the program.
First Attempt at Intersection Observer
Tags: javascript, css, ui, intersectionobserver
Published: 2021-04-12 01:15:16

Thanks to Pedro, I learned a cool API this week and applied it in our favorite project [telescope](https://github.com/Seneca-CDOT/telescope).

I was assigned an issue to accomplish the new banner design, which is to [make the navbar appear only when the user scroll to the timeline](https://github.com/Seneca-CDOT/telescope/issues/2041). In other word, the navbar should not be showed in the banner, but, it should be showed when the first post is at the top of the screen.

To accomplish this feature, I need to track the element in the current screen. The API that Pedro introduced to me is [Intersection Observer](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API). The basic idea of this API is to **observe** the element in the viewport. The function `isIntersecting()` tells you if the element that you're observing is still in the viewport. It doesn't have to 100% in the screen or 100% out of the screen, the observed percentage can be configured as well.

Therefore, since our goal is to show the navbar when the user scrolls to the timeline, and the first post is at the top of the screen. In other word, the navbar should be showed when the banner is totally gone. We put the observer to our banner.

In [this PR](https://github.com/Seneca-CDOT/telescope/pull/2094), I move `<navbar>` into `<main>`, so that I can separate it from the `<Banner>`. Moreover, to add props for `<Banner>` and `<navbar>` in order to share the result of intersection observer. After moving the position of navbar, I also need to add navbar to about page and search page, because all pages used to share the navbar when it was in the banner header. The other changes that needed to make is the CSS styling of navbar in about page. In about page, `<a>` uses a certain color from our palettes. Once we move navbar to about page, the navbar will be applied with these color because navbar icons all have `<a>` in their links. By adding another styling setting to `<svg>`, the color can be overridden. I'm still thinking if there is a better way to do so, since the original styling for navbar should not be overridden, and the solution should not be overridden to correct.

It was an amazing experience to work with something new. Thanks to Pedro and Dave's help and suggestion in this PR! The initial thought was actually using React context. However, it *is* too complicated to use, and since we only need to share the state with one component, we can do it without using context. But, I'm definitely gonna check out more practices of React context.
How accurate can IP Geolocation get?
Published: 2021-04-12 01:01:58

Since I started working at an IP geolocation startup company, I have come to realise just how misunderstood IP geolocation technology is. In my previous startup, we use to derive location data of a website using an IP address with freely available databases. We would often get inaccurate data which we would ignore as an outlier in the data.

Even now many developers use a free database or an API to detect the IP address of a website visitor and redirect them to different web pages. If you have developed an eCommerce site using WordPress + woo-commerce plugins, it is likely that you are using an IP address to detect the location and change the currency format and other content of your website.

I was talking to one of my developer friend about IP geolocation APIs and he simply stated that it was nothing but a simple database lookup on whois database and it isn’t that accurate. However, it is more complex than a simple data lookup.

I am curious to understand what the dev community think about IP geolocation technology and how do you go about implementing an API or a process to identify a user’s location with an IP address.
What are Data Classes in Python?
Tags: python, beginners
Published: 2021-04-12 00:59:33

Data classes is a new feature introduced in Python 3.7. This feature aims to reduce boilerplate code sucs as `__init__()` and `__eq()__` methods in user-defined Python classes. By using the `dataclasses` module’s decorators and functions, one can create concise Python classes. Let’s review the use of the data classes feature with an example.

Employee class could be declared concisely like shown below with the data classes decorator.
```python
from dataclasses import dataclass, field

@dataclass
class Employee:
    id: int
    first_name: str
    last_name: str
    email: str
    base_pay: float
    tax_rate: float = field(default=0.01, init=False)
    hobbies: list = field(default_factory=list())
    
    def calculate_pay(self):
        net_pay = self.base_pay - (self.base_pay * self.tax_rate)
        return net_pay
    
   
emp1 = Employee(1, 'John', 'Doe', 'john.doe@example.com', 10000, ['Fishing', 'Soccer'])
print(emp1)    #Employee(id=1, first_name='John', last_name='Doe', email='john.doe@example.com', base_pay=10000, tax_rate=0.01, hobbies=['Fishing', 'Soccer']) 
print(emp1.calculate_pay())  #9900.0
```
* `@dataclass` decorator above generates `init`, `repr` and `eq` methods by default. `@dataclass` generator without any parameters like declared above is equivalent to the below declaration:
```python
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
```
* If `order` parameter is set to true, it will generate boilerplate methods  `lt`, `gt`, `le`, and `ge`. Also, true value supplied to the `unsafe_hash` parameter would generate `hash` method. 
* Dataclasses use the `typing` module to define the data type of the declared class fields. However, if one wishes to not specify the field data types, they can use `typing.Any` for all of their fields in the class.
* By default, all fields of the class are included in the generated methods. But this can be customizable using field declaration. For example, `tax_rate` field in the example is excluded from the `init` method.
```python
tax_rate: float = field(default=0.01, init=False)
```
* Also, we can use the `default_factory` parameter to initialize complex data types such as list.
* Dataclasses module has several convenience functions. For example, `dataclasses.fields` function provides a list of fields in the form of tuple. Also, `dataclasses.asdict` returns a dictionary representation of the supplied object.

<strong>Dataclasses</strong> is one of the powerful features introduced in the recent versions of Python. Here is the <a href=" https://docs.python.org/3/library/dataclasses.html">link</a> for learning more about it's capabilities so you can start using this feature in your projects.
How to become a software engineer without a CS Degree
Tags: javascript, career
Published: 2021-04-12 00:37:06

Recently, I started creating content for developers.

In this video, I explain how I got into software engineering and I explain some tips I wish I knew starting my job search.

TLDR; No you don't not need a CS degree to become a developer

Let me know if you have any questions

I hope you enjoy it :)

LINK TO VIDEO https://www.youtube.com/watch?v=kb5ct9Zage0

For more free content follow me on Twitter: https://twitter.com/GetTeknikal

Scott
Migrate Magento code to another server
Published: 2021-04-12 00:24:51


SSH to both servers old one (server A) and a new one (server B)

you need to Copy the files legacy server **A**  :

Archive it first  
```
tar -czvf magento.tar.gz app/code/
```
move to the public dir server **A**:
```
 mv magento.tar.gz pub/
```
Go to new server **B** web dir. for example :
```
cd /var/www/html/
```
Download files to the new server **B**: 
```
wget https://www.{domain}.com/magento.tar.gz
```
Untar files on a new serve **B**:
```
tar -xzvf magento.tar.gz -C magento
```
remove a file on the old server **B**:
```
rm pub/magento.tar.gz 
```
In the next step, you will need to dump Magento DB. See my other posts.
LeetCode 1304. Find N Unique Integers Sum up to Zero (javascript solution) | Microsoft Question 
Tags: algorithms, javascript
Published: 2021-04-12 00:23:14

###Description:
Given an integer n, return any array containing n unique integers such that they add up to 0.

###Solution:
Time Complexity : O(n)
Space Complexity: O(n)

```javascript
var sumZero = function(n) {
    // Initalize output array with all 0s
    let output = Array(n).fill(0);
    // Increase i by 2 to add each number and it's negative value to output on each loop so that the total sum of the entire array will always be 0
    for (let i = 0; i < n - 1; i += 2) {
        // Use i + 1 because we already initialized 0 to be in the array
        // If n is an odd number the last number in output will be zero (because we increase i by 2, we will aways stop at an even number,leaving one space at the end that will stay 0) and every other number in output will be paired with its negative value to keep the sum of output to be 0
        // If n is even then all numbers in output will cancel each other out and the sum will be 0
        output[i] = i + 1;
        output[i + 1] = -(i + 1);
    }
    return output;
};
```