teleren/devto huggingface dataset:
Use fake static classes to protect your namespace (js/ts)
Tags: typescript, javascript, namespace, encapsulation
Published: 2022-06-22 21:22:16

We all know that modules let you hide a symbol in a file so other files don't collide with it.

And we're all enlightened post-OOP folks who do this

```ts
type Point = [x: number, y: number]
function magnitude(p: Point) {
    return Math.sqrt(p[0] * p[0] + p[1] * p[1])
}
```

instead of doing this

```ts
class Point {
    constructor(public x: number, public y: number) {}
    magnitude() {
        return Math.sqrt(this.x * this.x + this.y * this.y)
    }
}
```

The types & interfaces & functions approach prevents weird inheritance patterns, serializes well for database/filesystem/networking purposes, and typically lets you write more concise code because you don't have to tear apart and re-instantiate these classes all the time:

```ts
// nice
function add(p: Point, q: Point): Point {
    return [p[0] + q[0], p[1] + q[1]]
}
// annoying constructor; less symetric
class Point {
    // ...
    add(q) {
        return new Point(this.x + q.x, this.y + q.y)
    }
}
```

**But something has been lost in this transition. The _project_ namespace becomes massive.** In any large project, there are going to be some common operations that you want to do with different types of data. ECMAScript modules allow you to use a short, appropriate names. The project ends up looking like this:

```ts
// accounts.ts
function transfer(accountId: string, amount: number) {}

// item-management.ts
function transfer(from: User, to: User, itemId: string) {}

// array-helpers.ts
function transfer<T>(from: T[], to: T[], val: T) {}

// ...
```

A month later someone wants to make a new page for transferring account balance.

-   They try jumping to `transfer` in the codebase and there are five exported definitions.
-   Auto-import suggests junk from unrelated parts of the project.
-   **There is no easy way to find all the methods on User** because there are tons of short functions scattered throughout the project.

## Solution

**Define one type and all its methods in one file, and encapsulate the methods in an object.**

```ts
// Point.ts
export type Point = [x: number, y: number]
export const Point = {
    mag: (p: Point) => Math.sqrt(p[0] * p[0] + p[1] * p[1]),
    add: (p: Point, q: Point) => [p[0] + q[0], p[1] + q[1]],
    mul: (p: Point, factor: number) => [p[0] * factor, p[1] * factor],
} as const

// some-application-code.ts
import { Point } from './Point'

function whatever() {
    const p: Point = [5, 6]
    const q: Point = [10, 11]
    return Point.add(p, q)
}
```

This will

-   stop the project vocabulary from becoming too large,
-   allow you to see all the ~~methods~~ functions available on a ~~class instance~~ value when using it,
-   give you a clear place to write code when you want to expand a type, and
-   avoid huge import statement blocks,
-   allow you to search in project for a specific function (`Point.add` is unique but `add` would have lots of false positives),
-   allow you to use shorter function names without ambiguity.
Forming, Storming, Norming, and Performing
Tags: agileteam, leadership
Published: 2022-06-22 20:34:57

###### I am always posting provoking post on my Linkedin, and I have decided to replicate those here. [Let's socialize!](https://www.linkedin.com/in/alexsandro-souza-dev)

Building a new team?

You can't expect a new team to perform well when it first comes together.

The Psychologist Bruce Tuckman has created a model that describes the path that most teams follow on their way to high performance. He identified 4 stages: Forming, Storming, Norming, and Performing.

When you understand what typically happens in the different phases, you can help your new team become effective more quickly

<img src="https://media-exp1.licdn.com/dms/image/C4E22AQHZvgKMe-yGvw/feedshare-shrink_1280/0/1591307633254?e=1658966400&v=beta&t=6s4hx4sUuLsFWA-zZmvb87CZk2pb4nRvEKeLygav1Z8">

## Forming
Using either a top-down or bottom-up approach, a team comes together to address a problem and propose solutions. Each member of the team orients themselves to the project task. They begin to establish relationships within the group. It’s typically a time of great positivity.

## Storming
This is the most dangerous phase in terms of team success. Team leaders establish roles for each team member. This often brings out many negative aspects of group behavior. For example, it can lead to interpersonal conflict and “turf wars” as people stake out the parts of the project they want to control. It can lead to members of the team not appreciating the perspective of others. Some people may even resist joining the team at all. This is a point where the team is most likely to fall apart.

## Norming
A corner is turned. Team members buy into the process and begin to work together effectively. They develop trust with each other. The team achieves better cohesion as people find ways to work together, despite their differences.

## Performing
The team begins to excel. Having put the needs of the group ahead of personal needs, the team begins to focus on a shared goal and find ways to solve any problems that come up. Typically, this means that the structure of the team is fixed, but the roles of each member are flexible.
DORA metrics: a Google open source tool for tracking them
Tags: dora, gcp, devops
Published: 2022-06-22 20:29:46

**DORA** stands for DevOps Research and Assessment and is a research group acquired by Google in 2018. Their goal is to help organizations achieve high DevOps and organizational performance with data-driven insights. In their 2018 book, Accelerate, they identified a set of metrics (4) that could help organizations measure their team's software delivery performance, to improve them. Improving the delivery performance will have an impact on the business


These four key metrics are:

1. **Deployment Frequency**: how often an organization successfully releases to production. This metric doesn't say if you are releasing valuable software or not, but if you don't release frequently there's nothing to measure
2. **Lead Time for Changes**: the amount of time it takes a commit to get into production. This metric should be very useful for improving the release process: if it's too long maybe the process needs some changes.
3. **Time to Restore Services**: how long it takes an organization to recover from a failure in production. 
4. **Change Failure Rate**: the percentage of deployments causing a failure in production. From a business point of view, it’s essentially an indication of the business risk of making changes.

The first two are velocity metrics, the last two are stability metrics.

I looked a lot for a tool that could help my team track these metrics. I knew that Jira, Gitlab, and some other tools implement these features but I was looking for something with a high level of customization, and not so coupled to a specific product (we use different systems for deployment, change, and incident) and one day I incidentally discovered [FourKeys](https://github.com/GoogleCloudPlatform/fourkeys). 

FourKeys is an open-source project developed by Google, it consists of a generalized ETL Pipeline that can be extended to process inputs from a wide variety of sources. The pipeline ingests the data into Bigquery and then they should be displayed in a Grafana dashboard. 

The Github repo contains all the instructions to set up and run the project, here instead we can focus on the architecture. 


![HLD](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f590tjtds8wkdr6lqdxo.png)

1. The events are generated by your development environment, or better to say, by the tools you use in your dev environment. Gitlab, Github, Tekton, and Circle-CI are supported out of the box, and you can easily extend the supported set of tools.

2. The handler is a Cloud Run endpoint, it collects the event and pushes them into the appropriate Pub/Sub topic.

3. Another instance of Cloud Run consumes the events, makes some transformations and then inputs the data into BigQuery. At first, the data are sent into a raw events table (it's your operation log). From there, some scheduled query read from the log table and write to three different tables: Incidents, Changes and Deployments.

4. These tables are used to calculate the metrics and show them inside a dashboard.
Monkey Stone Js
Tags: webdev, javascript, beginners, programming
Published: 2022-06-22 19:47:06


# Monkey JS
[github](https://github.com/toutpuissantged/monkey-stone)
## What is a monkey js ?
  

 monkey js is a javascript library that allows you to create a reactive custom component 


# How to use monkey js ?

- import the monkey js library in your project
```js
import  monkey  from 'monkey-js';
```
- create a new component
```js
class Custom extends Monkey.Component {}
```
- use State in your component
```js
class Custom extends Monkey.Component {
  state = {
    value: '',
  }
  render() {
    const div = document.createElement('div');
    div.innerHTML = this.state.value;
    div.addEventListener('click', () => {
      this.setState({
        value: 'clicked',
      });
    });
    return div;
  }
}
```
- register your component outside the library
```js
customElements.define('custom', Custom);
```

# API 
list of all api 
  - ## ComponentDidMount
    this  methodes is called when component will be added to dom 
    - ### usage 
      ```js
      componentDidMount(){
        console.log('componentDidMount')
      }
      ```

  - ## ComponentWillUnmount
    this  methodes is called when component will be removed from dom 
    - ### usage 
      ```js
      componentWillUnmount(){
        console.log('componentWillUnmount')
      }
      ```

  - ## componentDidUpdate
    this  methodes is called when component will be updated
    - ### usage 
      ```js
      componentDidUpdate(){
        console.log('componentDidUpdate')
      }
      ```

  - ## setState
    this  methodes is used to update the state of the component
    - ### usage 
      ```js
      this.setState({
        text : 'new text',
      })
      ```

  - ## render
    this  methodes is used to render the component ui 
    each time when state is updated the render methode is automaticaly called also to rebuild the component ui with the new value 
    - ### usage
      ```js
      render(){
        return document.createElement('div');
      }
      ```
    
  - ## envent Emiter 
    this  methodes is used to emit an event
    - ### usage 
      ```js
      this.emitEvent('eventName', {
        data: 'data',
      })
      ```

  - ## state 
    this property is used to store the component state
    to updated the state use the setState methodes 
    ! warning : the state is not immutable , dont try to change the state directly , use the setState methodes
    - ### usage 
      ```js
      state = {
        text : 'text',
      }
      ```
    
# upcoming features

  - ## props 
    this property is used to store the component props
  
  - ## componentWillReceiveProps
    this methodes is called when component will receive new props
    

# License

  [![License](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

# Developer
  [![GitHub](https://img.shields.io/github/followers/toutpuissantged?style=social)](https://github.com/toutpuissantged)
Conditional Wrap in React
Tags: react, webdev, beginners
Published: 2022-06-22 19:39:46

If you ever played around with React, you probably found a situation where you'd need to conditionally wrap a component. If it matches some condition, it should be rendered inside a given tag, if not, leave it as is. Here's a small snippet for that:

```tsx
import { FC, ReactNode, createElement } from 'react';

interface WrapProps {
	if?: boolean;
	with: typeof createElement.arguments[0];
	wrapperProps: typeof createElement.arguments[1];
	children: NonNullable<ReactNode>;
}

const Wrap: FC<WrapProps> = ({
	if: condition,
	with: wrapper,
	wrapperProps,
	children,
}) =>
	condition ? createElement(wrapper, wrapperProps, [children]) : <>{children}</>;

export default Wrap;
```

Usage:
```tsx
const condition = useMemo(() => index % 2 === 0, [index]);

<Wrap if={condition} with="a" wrapperProps={{ 'data-testid': 'wrapper' }}>
	<p>Wrapped text</p>
</Wrap>
```

This component uses `React.createElement` because it allows dynamic component creation. It means that, instead of providing a function like `(children) => <p>{children}</p>` for Wrap, it is possible to pass a React Component instance or a HTML node name.
Here's my TOP Landing Page Project
Tags: beginners, programming, javascript, discuss
Published: 2022-06-22 19:34:50

## I finally completed The Odin Project landing page [project.](https://taepal467.github.io/landingPage/). 

I actually had fun working on this project. I did have some challenges along the way such as: 

- Working on Mobile First Workflow
According to the instructions, you don't have to worry about MFW. So I mainly focused on the Desktop design. But at the last minute, I decided to practice working on MFW. So on some devices it will look great. On others not so much

- Making the slideshows. This was a challenge for me since this is the first time I've used a slideshow on a project. I also wanted to practice using JavaScript. 

But other than that, so far I'm actually enjoying The Odin Project. This week I'll be working on the last two sections of the Foundations Curriculum which are JavaScript Basics and Back-End.
Best way to learn Closure in JavaScript ?
Tags: webdev, javascript, programming, beginners
Published: 2022-06-22 19:14:11

There are tons of resources out on the web which explain what closure is...

I will cut the crap of giving this:
> a function inside a function bla bla... is closure.

Instead what I will do is to give you a `1 minute` snippet that you need to **scan** and **understand** the output of the below 👇 code will be (without running on compiler or looking into the answer).

Once done we can check the answer and learn the concept of it.
Please feel free to comment, would love to respond and learn together.

---


```js
let cachedFunc = null

function log(message) {
  if (!cachedFunc) {
    // creates a function that closes over `message`
    // keep in mind `message` inside `log` is different
    // on each call
    cachedFunc = () => console.log(message)
  }
  cachedFunc();
}

log("hello")
log("goodbye")
```

---

#### Check the answer below compare:

{% collapsible Click to expand the Answer %} 

### Step by step execution:
1. `cachedFunc` is declared with `null`, and a function `log`.

2. On calling `log("hello")`, the context of calling `log` function is same as the `cachedFunc` declared, so it will find it's value to `null` as declared in outer scope.

3. Inside the `if condition` it will update the `cachedFunc` to a inline function which prints argument `message` to console.

4. Then it calls `cachedFunc` method which results in the message "hello".

5. On the second call `log("goodbye")` will not initialize the method again.
> So it will call the method that was in previous scope, in which the value of `message` is "hello" and that's why it will print the same "hello" again.

---

### Further explanation related to `Reactjs`:

Under the hood, `useCallback` works in a very similar way. On the first render, React saves the function you pass to `useCallback` somewhere and will always return that function.

Every other render will have your saved function, and will "remember" the scope it was created in, including the old value.

Without `useCallback` or adding dependencies to it, a new function would be created on each render or change in the dependencies, which means it would be able to refer to new with an up-to-date value.
{% endcollapsible %}

---

Here is the link to [codepen](https://codepen.io/m-nathani/pen/YzeoyZZ?editors=1112) to further play with it :)


Regards.

{% link https://dev.to/mnathani/how-to-cache-bust-frontend-app-132l %}
How the software we build is used maliciously and abusively 🎙
Tags: podcast, inclusion, security, mobile
Published: 2022-06-22 19:04:10

This is an episode of DevDiscuss where we are joined by experts in technology abuse to get into how the software we develop is used for abusive purposes in a variety of interpersonal contexts.

In the show, we talk about how you can be aware as a developer, but also for yourself and those around you. This is a topic that applies to all of us one way or another.

## Listen on Apple Podcasts

{% embed https://podcasts.apple.com/us/podcast/s9-e7-how-technology-is-used-as-a-tool-for-abuse/id1513053883?i=1000567362586 %}

## Listen on Spotify

{% embed https://open.spotify.com/episode/0AkVagAzpv8mPn9K8tf37P?si=HjqYW6EoSRi9O9dAjoBihw %}

## [Or listen right here on DEV](https://dev.to/devdiscuss/s9e7-how-technology-is-used-as-a-tool-for-abusecoercive-control)

***

Give it a listen, and let us know your thoughts.
What does * { box-sizing: border-box; } do? What are its advantages?
Tags: webdev, css, html, beginners
Published: 2022-06-22 18:36:09

The rule:

```
* {
    box-sizing: border-box;
  }
```
uses the universal selector to activate the Alternative Box Model for all elements in a document. In this box model, the width and height of an element is set to extend to the border edges of the box.

The default box model applied is the Basic Box Model, with `box-sizing: content-box;`. We have to use the `*` universal selector to change the default box sizing of all elements to `border-box`.

The Alternative Box Model implemented with `box-sizing: border-box` extends the height and width of an element to the border edges. So, any padding and border added are contained within the height and width and the content area shrinks to accommodate space for `padding` and `border` values.

**Advantages**
The advantages of using border-box are:
- Setting the height and weight to the border edges reflects the actual space being occupied and displayed on the screen.
- This makes design calculations and logic easier for developers.
- It helps make the box model and hence the layout more consistent in terms of interaction with other elements.
- Layouts are more predictable and easier to visualize.


---
References

1. [The alternative CSS box model](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model#the_alternative_css_box_model)
Longest Common Substring
Tags: cpp, algorithms, 100daysofcode, programming
Published: 2022-06-22 18:35:48

https://binarysearch.com/problems/Longest-Common-Substring

```cpp
int solve(string s0, string s1) {
    int m = s0.size(), n = s1.size(), res = 0;
    vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (s0[i] == s1[j]) dp[i + 1][j + 1] = dp[i][j] + 1;
            res = max(res, dp[i + 1][j + 1]);
        }
    }
    return res;
}
```
C++ program to print alphabet pyramid.
Tags: programming, tutorial, cpp, community
Published: 2022-06-22 18:29:15

Here in the following I've shared the Code for printing alphabet pyramid.


`#include <iostream>
using namespace std;
int main() {    
    int i,j,n,ch=64;
    cout<<"Enter Value For Patten : ";
    cin>>n;
    for(i=1;i<=n;i++)
    {
        ch=64;
        for(j=1;j<=i;j++)
        {
            ch+=1;
            cout<<(char)ch;
        }   
        cout<<"\n";
    }
    return 0;
}`


**Output:**

Enter Value For Patten : 6
A
AB
ABC
ABCD
ABCDE
ABCDEF
Day 25 - Fallback and receive Functions
Tags: 100daysofcode, solidity, web3, blockchain
Published: 2022-06-22 18:02:00

{% embed https://github.com/Envoy-VC/30-Days-of-Solidity noreadme %}

This is Day `25` of `30` in Solidity Series
Today I Learned About fallback and receive Functions in Solidity.


The solidity fallback function is executed if none of the other functions match the function identifier or no data was provided with the function call. Only one unnamed function can be assigned to a contract and it is executed whenever the contract receives plain Ether without any data. To receive Ether and add it to the total balance of the contract, the fallback function must be marked payable. If no such function exists, the contract cannot receive Ether through regular transactions and will throw an exception.

Properties of a fallback function:

- Has no name or arguments.
- If it is not marked payable, the contract will throw an exception if it receives plain ether without data.
- Can not return anything.
- Can be defined once per contract.
- It is also executed if the caller meant to call a function that is not available
- It is mandatory to mark it external.
- It is limited to 2300 gas when called by another function. It is so for as to make this function call as cheap as possible.


```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract Receiver{
    mapping(address => uint) public addressToAmount;

    receive() external payable {
        addressToAmount[msg.sender] += msg.value;
    }
}

contract Sender {
    uint amount = 1 ether;
    address payable _receiver = payable(0xcD6a42782d230D7c13A74ddec5dD140e55499Df9);
    function sendEther() public payable {
        _receiver.transfer(amount);
    }
}
```

**fallback()**

This function is called for all messages sent to this contract, except plain Ether transfers (there is no other function except the receive function). Any call with non-empty calldata to this contract will execute

**receive()**

This function is called for plain Ether transfers, i.e. for every call with empty calldata.

---
The Five-Point Framework for Saying No
Tags: programming, personaldevelopment, softwaredevelopment
Published: 2022-08-03 14:38:27

---
title: The Five-Point Framework for Saying No
published: true
date: 2022-06-22 17:52:53 UTC
tags: programming,personaldevelopment,softwaredevelopment
canonical_url: https://newsletter.engstuff.xyz/p/shorty-the-five-point-framework-for
cover_image: https://cdn-images-1.medium.com/max/889/0*s8Aije95e17nIUb0.png
---

#### Learn how to identify the signals that it’s time to say no

The fun part of working as engineers is that we get to solve challenges. We are expected to deliver high-quality solutions on time, which puts us under pressure. As a result, many engineers (primarily juniors) become silent when they need to say no.

But how do you know when to say no? What signals that it’s time to stop?

Here is an **oversimplified** framework that is easy to remember and use for requests, feedback, bugs, and tasks.

### The five-point framework

- **Product**  — What are the pain points or opportunities we are addressing? Do I know who will benefit from these changes and how?
- **Impact**  — Will the efforts make a difference to the company? Will this be the most valuable thing we can do right now?
- **Coding**  — Is it more challenging than it seems? How many “workaround” will I have to make?
- **Quality**  — Will the final results compromise any existing functionality? Does the final result meet our standards?
- **Results**  — Given the requirements, will the project be completed on time?

> The list can be expanded based on your needs, but I strongly urge keeping it short and straightforward.

### How to use it

1. Ask yourself these questions, and if you cannot answer one of them or do not feel confident about your answer, then say no until it is resolved.
2. You can also say stop in the middle of a task

_Originally published at_ [_https://newsletter.engstuff.xyz_](https://newsletter.engstuff.xyz/p/shorty-the-five-point-framework-for) _on June 22, 2022._
How to play video in flutter even during a call?
Tags: flutter, beginners
Published: 2022-06-22 17:27:29

Hello fellow developers and learners,

I'm trying to create a custom video player app that lets you play video even when you're in a phone call. As of now when you're in a call the video playback pauses. This feature is enabled in other players like VLC and MX player. I would like to know how to enable this feature. 

Thanks everyone for the help.