teleren/devto huggingface dataset:
Python global name 'self' is not defined
Published: 2022-12-16 16:07:11



self is the self-reference in a Class. Your code is not in a class, you only have functions defined. You have to wrap your methods in a class, like below. To use the method main(), you first have to instantiate an object of your class and call the function on the object.

Further, your function setavalue should be in __init___, the method called when instantiating an object. The next step you probably should look at is supplying the name as an argument to init, so you can create arbitrarily named objects of the Name class ;)

class Name:
    def __init__(self):
        self.myname = "harry"

    def printaname(self):
        print "Name", self.myname     

    def main(self):
        self.printaname()

if __name__ == "__main__":
    objName = Name()
    objName.main() 

Have a look at the Classes chapter of the Python tutorial an at Dive into Python for further references.
Who's not Afraid of Z-index?
Tags: webdev, css, html, programming
Published: 2022-12-16 19:34:30

Z-index is a CSS property that we use to alter the standard order of the HTML layers. The standard behavior of the browser is to render the next element in front of the last one.

Here at Labcodes we’ve had some interesting experiences with this, that’s why in this post we’ll show you good and bad practices with Z-Index and help you understand the logic behind it --- > https://lab.codes/who-isnot-afraid-zindexdt
How can we effectively explain large codebases?
Published: 2022-12-17 11:55:30

Hello DEV!

After starting to wrap up on NextSketch 2, we decided to write on the issue NextSketch 2 is planning to solve; How do we efficiently explain huge projects?

## The Problem

Often times when trying to understand the way a huge codebase works, we turn to documentation, which is sometimes not the best way to get started. People experienced with the Project aren't always available to query (especially if they're in a different time zone), and not everyone is the best at explaining. Language can also be a huge barrier to getting up to speed.

Often, the context of the explanation can get lost in our language semantics. We think that Diagrams are a much more universally understood way of explaining how the project works from a 10,000ft high perspective. Using diagrams in this case (compared to text-based docs), are much easier to parse, and preserve more context.

## How can NextSketch 2 help?

This is why we started working on NextSketch 2. 

For those who don't know, NextSketch 2 is an IntelliJ-Platform Plugin for designing diagrams explaining how your project architecture to others. It provides a fast editor experience, the ability to create multiple levels of diagrams, attach source files, and store diagrams right inside the project, making it self-documenting. Being a Plugin, it also makes the overhead of using an additional tool as slim as possible. 

To be clear, NextSketch 2 is not a tool to generate diagrams automatically from code. Diagrams such as these often have questionable utility as there is not much insight to be gained from looking at the code-graph instead of just reading the code itself.

We're hoping to release in January of 2023 if everything goes well! Also, let us know below how you get started on large codebases in the comments!

Thanks for Reading!
Last week top 5 posts tagged(#github)
Tags: github, c4r4x35
Published: 2022-12-18 16:30:41

##Code brushes for GitHub Copilot
GitHub Copilot is incredible, and if you check what's happening in the preview released as the Copilot Labs extension it will only get more amazing.

Check this out:

Let's start with a basic...
{% link https://dev.to/codepo8/code-brushes-for-github-copilot-4hij %}
##Automated Frontend Workflow
In a world where robots have not yet taken our place, we still have to deal with repetitive tasks. We are constantly trying to find the easiest and laziest way to accomplish something, some people...
{% link https://dev.to/helmuthdu/automated-frontend-workflow-4665 %}
##Preparing to move away from Twitter
I opened my Twitter account more than 13 years ago, in August 2009. For 12 years, I kept focusing on professional-related content: Java, the JVM, programming, etc. I built my audience, trying to...
{% link https://dev.to/nfrankel/preparing-to-move-away-from-twitter-3fm2 %}
##20 Git Commands you (probably) didn't know about 🧙‍♂️
If you've ever browsed the git manual (or run man git), then you'll have noticed there's a whole lot more to git than what most of us use on a daily basis. A lot of these commands are incredibly...
{% link https://dev.to/lissy93/20-git-commands-you-probably-didnt-know-about-4j4o %}
##The Power of GitHub Actions for Streamlining DevOps Workflows
Introduction

GitHub Actions is a powerful tool for automating development workflows, and it has quickly become a staple in the DevOps world. With its ability to integrate with various tools and...
{% link https://dev.to/pramit_marattha/the-power-of-github-actions-for-streamlining-devops-workflows-1h91 %}
SQL 基礎 Part 03 -- docker-compose で立てたコンテナで立ち上げ時に DB と全権力ユーザーを作成して、外部からログインする
Tags: sql, docker
Published: 2022-12-18 16:41:30


## why

Spring で実際につなぐために、接続情報があり、テーブルが自動生成される PostgreSQL サーバーを Docker で立てたくなった。

---

## Docker Compose で ログイン情報を書いて SQL ファイルでテーブル作成を試す

https://zenn.dev/msksgm/articles/20220603-kotlin-jdbc-postgresql#db

この記事を参考に、docker-compose.yml に 

* DB の名前
* ユーザー名
* パスワード

これらを書いて

読み込まれる SQL でテーブルの作成を擦るように書いてみた。

しかし、これだと DB と USER が作られていないので
DB にログインしてテーブルができているか確認することができなかった。

---

## SQL でユーザーと DB の作成を行い、DB の権限をユーザーに渡す

https://amateur-engineer.com/docker-compose-postgresql/

この記事を参考に 

```yml
version: '3.2'
                                                                                                                                          
services:
  #
  # PostgreSQL
  #
  person-db:
    image: postgres:14-bullseye
    container_name: person-db
    ports:
      - 5444:5432
    volumes:
      - ./postgresql/init:/docker-entrypoint-initdb.d
    environment:
      POSTGRES_USER: kaede
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: person-db
      POSTGRES_INIT_DB_ARGS: --encoding=UTF-8

```

init を初期位置の *.sql として

00-init.sql を作り(名前はなんでもOK)

```kotlin
CREATE USER kaede;                                                                                                                    
CREATE DATABASE person-db;
 
GRANT ALL PRIVILEGES ON DATABASE person-db TO kaede;
```

user と db と権限作ったら

```kotlin
dc up
WARNING: Found orphan containers (psql_pgadmin_1, postgres_dc, psql_postgres_1, sample-pg) for this project. If you removed or renamed this service in your compose file, you can run this command with the --remove-orphans flag to clean it up.
Starting person-db ... done
Attaching to person-db
person-db    | 
person-db    | PostgreSQL Database directory appears to contain a database; Skipping initialization
person-db    | 
person-db    | 2022-12-18 16:36:57.296 UTC [1] LOG:  starting PostgreSQL 14.6 (Debian 14.6-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
person-db    | 2022-12-18 16:36:57.296 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
person-db    | 2022-12-18 16:36:57.296 UTC [1] LOG:  listening on IPv6 address "::", port 5432
person-db    | 2022-12-18 16:36:57.298 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
person-db    | 2022-12-18 16:36:57.303 UTC [26] LOG:  database system was shut down at 2022-12-18 16:36:14 UTC
person-db    | 2022-12-18 16:36:57.309 UTC [1] LOG:  database system is ready to accept connections

```

ちゃんと起動して DB が作られて

```php
psql -h localhost -p 5444 -U kaede -d person-db
Password for user kaede: 
psql (12.12 (Ubuntu 12.12-0ubuntu0.20.04.1), server 14.6 (Debian 14.6-1.pgdg110+1))
WARNING: psql major version 12, server major version 14.
         Some psql features might not work.
Type "help" for help.

person-db=#
```

user kaede
db person-db

これで接続することができた。
How to create Prefabs in Unity3D?
Tags: unity3d, csharp, gamedev, tutorial
Published: 2022-12-19 12:14:07

This short article explains what Unity's Prefabs are and what they are useful for.

**Motivation**

Let's imagine that we want to make a Tower Defence game in Unity. At first we would create a Tower GameObject, that would look something like this in the Hierarchy:

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

When the player starts the game, usually there are no Towers in the scene yet. What we need is a way to save our Tower GameObjects somewhere and then load them into the Hierarchy again as soon as the player wants to build a tower.

This is what Prefabs are for.

**Creating a Prefab**
Let's create a Prefab. It's very easy, all we have to do is drag our GameObject from the Hierarchy into the Project area like this:

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

Afterwards we can see the Prefab in our Project area:

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

Now we can delete the GameObject from our Hierarchy so it's not in the game world anymore. But since it's in the Project area, we don't lose it completely.

**Loading a Prefab**
If we want to load a prefab, we have two options. We can either do it manually by dragging it from the Project area into the Hierarchy area, or by using a script that calls Instantiate.

Here is an example script that loads a Prefab as soon as the game starts:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {
    public GameObject prefab = null;
               
    void Start () {
        // instantiate the prefab
        // -> transform.position means that it will be
        //    instantiated at the position of *this*
        //    gameobject
        // -> quaternion.identity means that it will
        //    have the default rotation, hence its not
        //    rotated in any weird way
        Instantiate(prefab,
                    transform.position,
                    Quaternion.identity);
    }
}

Now all we have to do is add the Test script to a GameObject in the scene, take a look at the Inspector and then set the public prefab variable to any Prefab from our Project area like this:

After pressing start, it immediately loads our Tower Prefab into the scene.

Simple as that!
Collecting info for the development of a community mobile app shielding SDK (freeRASP React Native flavor)
Tags: reactnative, security, freerasp, mobile
Published: 2022-12-19 13:39:33

Based on experience with freeRASP for Android/iOS/Flutter/Cordova, there should be a demand for a shielding SDK for RN-based apps, right? I worked on the development of previous freeRASP flavors, and I would like to support React Native apps also. However, this will be quite a new experience as I am not well-versed in the RN ecosystem yet. That's why I would highly appreciate any tips regarding package management, nuances of hybrid development in the RN world, etc. I target iOS and Android platforms.

Is there anything specific you would like to see in the implementation?

Anything to watch out for?

Goals

Easy to use SDK that satisfies needs of app security and mobile OWASP MAS compliance

Available on GitHub and also as a npm package

Configurable (~ same as Flutter version) - configuration as a single object

Lightweight

It will be able to detect reverse engineering, debugger, simulator, repackaging or cloning attempts, running the app in an unsafe OS environment (e.g., root or jailbreak), hooking frameworks, and installing the application through unofficial stores.
⚛️Componentes Funcionais e de Classe em React⚛️
Tags: javascript, reactnative, webdev, react
Published: 2022-12-19 22:52:38

## ![react components](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nkegoz2r0fb9x4yihqav.png)
_**👇Um artigo objetivo sobre componentes em React👇**_
<br>
**⚛️O que são _React Components_?**
![Estrutura de pastas em react](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xf56nr2y1owy9vf5j0mn.png)
- _Components_ são considerados os principais blocos de construção de um aplicativo em React;
- Embora todos os componentes estejam no mesmo local da estrutura de pastas, eles operam de forma independente uns dos outros e se combinam em um componente pai para formar a interface final para o usuário.
<br>
**⚛️Que problema resolveu?**

- Anteriormente, a criação de uma página web simples requeria que os devs escrevessem centenas de linhas de código;
- Na estrutura tradicional de DOM, simples mudanças podiam ser bastante desafiadoras;
- Para resolver esses problemas, uma abordagem baseada em componentes **independentes e reutilizáveis** foi introduzida.
<br>
**⚛️Como um componente se parece?**

- Considere toda a interface do usuário (UI) como uma árvore;
![react-tree](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/18j7s0ytpvmtsy7n7ai8.png)
- Aqui, a raiz é o componente inicial e cada uma das outras peças se torna um ramo, os quais são subdivididos em sub-ramos.
<br>
**⚛️Quais são os tipos de componentes?**

**📲Componentes Funcionais:**

- É o primeiro tipo de componente e também o mais recomendado;
- Um _functional component_ é uma função em JavaScript/ES6 que retorna um elemento do React (JSX);
- Ele sempre começa com uma letra maiúscula (convenção de nomes);
- Se necessário, aceita props como parâmetro;
- Por exemplo, você pode criar um componente funcional com sua definição por _arrow function_ 👇
```
const Welcome = (props) => { 
  return <h1>Hello, {props.name}</h1>; 
}
```
> "Essa função é um componente do React válido, pois ele aceita um único argumento de objeto 'props' com dados e retorna um elemento do React." (reactjs.org)

- Para utilizar um componente mais tarde, você precisa exportá-lo para, então, importá-lo em outro lugar.
<br>
**🔃Componentes de Classe:**

- _Class Component_ é uma classe do ES6 que será um componente quando fizer o ‘extend’ de um componente (comportamento ou valor) do React;
- Aceita props (no construtor), se necessário;
- Deve ter um método de render() para retornar o JSX;
- Abaixo vemos a mesma função Welcome anterior, porém retornada como um componente de classe:

```
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
```
<br>
**⚛️Conclusão**

- Componentes são a melhor maneira de organizar seu aplicativo React e ajudam a escrever um código mais bem gerenciado;
- Ambos são bons, porém prefiro _Funcional Components_ a _Class Components._
Obrigado se você acompanhou até aqui e espero que esse artigo o ajude na trajetória como dev.

---
_Autor: Marcelo Schäffer Petry_
https://linkedin.com/in/m-petry/
https://marcelopetry.com/
My first npm, state management
Published: 2022-12-20 04:59:32

[https://github.com/vyquocvu/anystate
](https://github.com/vyquocvu/anystate
)

Features:
Lightweight object state management
Open Source Project
Small App Size (~2Kb)
Easy to use with nay framework, just a callback on change

About:
AnyState is an open source programs built using Typescript (for a more secure environment).
Troubleshooting: compiled against a different Node version
Tags: node, troubleshooting
Published: 2022-12-20 11:20:43

## Symptom

Running a node project with the dependency on Better Sqlite3 got the following error message:

```
Error: The module '... /node_modules/better-sqlite3/build/Release/better_sqlite3.node'
  was compiled against a different Node.js version using
  NODE_MODULE_VERSION 83. This version of Node.js requires
  NODE_MODULE_VERSION 93. Please try re-compiling or re-installing
  the module (for instance, using `npm rebuild` or `npm install`).

  ' the module (for instance, using `npm rebuild` or `npm install`).
  ' bindings (node_modules/bindings/bindings.js:112:48)

```

## Cause

The error message itself contains enough details, also shows the cause and solution. 

In short: the node version used to compile the installed `better_sqlite3` is not the same as the node version currently used, so it asks to recompile it with the current version.

## Solution

- `npm i -D electron-rebuild`. 
- Delete the `node_modules` directory.
- In `package.json` add `scripts` to.

   ```
    "rebuild": "electron-rebuild -f -w better-sqlit3",
   ```

- `npm i`
- `npm rebuild`

Reference link:

- https://github.com/WiseLibs/better-sqlite3/issues/549
- https://github.com/WiseLibs/better-sqlite3/issues/545
Creating Your Own Personalized Avatars with AI
Tags: ai, machinelearning, tutorial, deeplearning
Published: 2023-01-02 08:03:40


![Stable Diffusion generated Avatars](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/myo05zfsl6utq8w11hx4.png)

Have you ever wanted to create your own personalized avatars from photos, but found the process to be difficult or expensive? With the advent of artificial intelligence, it has become easier than ever to create unique and striking images using your own photos as a reference.

I have created a Google Colab tool that allows you to do just that, and it's completely free to use with just a Google account. This tool is based on the latest AI technology and allows you to train an AI text-to-image generator called Stable Diffusion.

To get started, simply upload your photos and follow the prompts to begin training the model. You can adjust the settings to fine-tune the model's performance and improve the accuracy of the generated images. Once you are satisfied with the results, you can save the model to your Google Drive and use it to generate images anytime.

This is a great opportunity to explore the capabilities of AI and see how it can be used to create novel and striking images. Give it a try and see what you can create!

Link to Google Colab below 👇🏼

https://colab.research.google.com/github/geocine/sd-easy-mode/blob/main/EasyMode_Stable_Diffusion.ipynb
Scanning for open ports
Tags: linux, bash
Published: 2023-01-04 12:13:47

## lsof
list of open files
```bash
lsof -i -P -n | grep LISTEN
```

## netstat
Print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships
```bash
netstat -tulpn | grep LISTEN
```

## ss
utility to investigate sockets
```bash
ss -tulpn | grep LISTEN
```

## nmap
network exploration tool, port scanner

```bash
nmap -open 192.168.3.34
```

## scanning open ports on remote IP address
```bash
nc -zv 192.168.3.34 2>&1 1-1024 | grep -v refused
```
this scans open ports in the range of 1 to 1024 on the above IP address.
redirects the error output to standard outoput and matches all lines except refused

## scanning all open ports on the subnet using nmap
```bash
nmap -n 192.168.3.0/24
```

## Sources

- **Linux for Networking Professionals** by Rob VandenBrink
- https://www.cyberciti.biz/faq/unix-linux-check-if-port-is-in-use-command/
- man pages
The Everyday Life of an HNG Intern; Isaac Ojerumu’s Story
Tags: beginners, programming, tutorial, career
Published: 2023-01-04 13:11:08

**Task 8**
Interns that made it to stage 8 were requested to submit every work they've done thus far in the internship, using links, to **Mark Essien**, the chief organizer of the HNG internship. He was to intensively review the work done by each intern so far in the internship.
Interns were served forms that they were to fill out individually. This was the medium through which they submitted their works. Slots that were to be filled included;

- Name
- Email
- Slack ID
- Team
- Link to PR(Poll Request) on Github: This contained the links to every task done by an inter; codes, endpoints, etc.

Interns, by whose work the chief organizer was impressed were promoted to the final stage; stage 9.

Dear reader, thank you for yet another read. I hope that this episode and the series as a whole have been insightful, educative, and inspiring. See you on the next page.
Please, let's get in touch on Medium; **Zini Zada**, and Twitter; **Zada_Zini**

Link to next episode:
https://dev.to/zadazini/the-everyday-life-of-an-hng-intern-isaac-ojerumus-story-50l7
How do I find the last version of a deleted file in Git
Tags: git, bash, programming, github
Published: 2023-01-05 00:43:50

A few months ago, I deleted a file.

Today, I realized that actually, I need it! I picked a random commit 6 months ago and found the file… but hm, what if it changed after that point?

How do I find the *final* version of that file?

Here's the Git command I used:

```sh
$ git log --full-history -- src/path/to/file.js
```

This finds the commit that deleted the file. So, I checked out that commit, and then backed up one more:

```sh
$ git checkout HEAD~1
```

This loads the file right before it was deleted! 🎉

Git is such a powerful tool.

H﻿appy hacking!

Originally posted here: https://blog.luispa.dev/posts/how-do-i-find-the-last-version-of-a-deleted-file-in-git
YOLO Section - GitJump A Simple Tool for Navigating Git Repositories in Go.
Published: 2023-01-09 17:07:21

---
title: YOLO Section - GitJump A Simple Tool for Navigating Git Repositories in Go.
published: true
description: 
tags: 
cover_image: https://upload.wikimedia.org/wikipedia/commons/thumb/f/f4/Git_session.svg/2880px-Git_session.svg.png
# Use a ratio of 100:42 for best results.
# published_at: 2022-12-22 01:20 +0000
---

Hey everyone,

A few months ago, I started to use GitHub more frequently as a learning tool, exploring repositories and projects I was interested in to understand better how they were developed and how teams approached challenges. I was looking for a tool that would allow me to easily move between commits to trace the history of a project, but I couldn't find anything that fit the bill "maybe I didn't search very well". So, I decided to create my own!

It is an ULTRA-SIMPLE app for navigating through the commits of a repository using a simple syntax. It's been an enormous help in my learning process, and I hope it can also be of use to others. If you're interested in checking out my repo, you can find it here: https://github.com/douglasmakey/gitjump

## Why?

Did you know that you can use git as a powerful tool for learning? By browsing the commit history of a repository, you can gain insight into a project's development process and evolution. This method can be handy when learning about a new topic or trying to understand how a team tackled challenges along the way. Give it a try and see how exploring commit history can enhance your learning experience!

In addition to providing a detailed history of a project's development, exploring commit history can also help you learn about best practices and coding styles. By seeing how other developers structure their code and commit messages, you can pick up valuable tips and techniques you can apply to your work. And if you're working on a team, analyzing commit history can help you understand how your colleagues approach problems and communicate their solutions. So next time you want to learn something new, check out the commit history of relevant repositories - you might be surprised at what you can discover!