teleren/devto huggingface dataset:
simply run segment anything on single image
Tags: datascience, machinelearning
Published: 2023-04-13 23:58:58

segmentation anything model is popular lately.
to try it's interacte usage, i made simple matplotlib script.

Below script use webagg backend, so after you run script new brower tab will open.
you can draw bounding box with mouse dragging, after you release mouse, automatically sam model will run on it


## installation
```bash
conda create --name sam pip python=3.10
conda activate sam
conda install -y pytorch torchvision torchaudio -c pytorch
pip install transformers
pip install git+https://github.com/facebookresearch/segment-anything.git
pip install datasets
pip install matplotlib
pip install tornado
pip install jupyter
pip install notebook
```



## load library


```python
import matplotlib
import numpy as np
from datasets import load_dataset

matplotlib.use('WebAgg')
import random

import cv2
import datasets
import matplotlib.pyplot as plt
import numpy as np
import torch
from matplotlib.widgets import RectangleSelector
from PIL import Image
from segment_anything import SamPredictor, sam_model_registry
```

## download weight
```bash
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth
```


## load model


```python
#  %% load model
sam_checkpoint = "sam_vit_b_01ec64.pth"

# for m1 mac
model_type = "vit_b"
device = "mps"

# # use linux with gpu
# model_type = "vit_h"
# device = "cuda"

sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)
sam.to(device=device)
predictor = SamPredictor(sam)


```

## load image


```python
ds = datasets.load_dataset("ydshieh/coco_dataset_script", "2017", data_dir="./dummy_data/", split='train[:10]')
example = ds[0]
img = Image.open(example['image_path'])
image = np.array(img)
img



```

## run single image


```python

predictor.set_image(image)

# %% select function
def on_select(eclick, erelease):
    x1, y1 = eclick.xdata, eclick.ydata
    x2, y2 = erelease.xdata, erelease.ydata
    print(f"Rectangle selected from ({x1}, {y1}) to ({x2}, {y2})")

    input_box = np.array([x1,y1,x2,y2])
    masks, scores, logits = predictor.predict(
        point_coords=None,
        point_labels=None,
        box=input_box[None, :],
        multimask_output=False,
    )
    mask = masks[0]
    color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
    h, w = mask.shape[-2:]
    mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
    ax = plt.gca()
    ax.imshow(mask_image)


plt.close('all')
fig, ax = plt.subplots()
ax.imshow(image)
rect_selector = RectangleSelector(ax, on_select, useblit=True, button=[1], minspanx=5, minspany=5, spancoords='pixels', interactive=True, 
)
plt.show()


```


```python

```
👥 How to clone a website into a Chrome Extension.
Tags: javascript, webdev, tutorial, chrome
Published: 2023-04-13 23:41:47

This is a simple tutorial to how clone a website into a chrome extension . 

Full repo : https://github.com/bolodissenoura/chrome-extension



Actually is not a real clone, we will reproduce the hole website if a iframe tag and show it on a google extension.

There are some reasons to you do it. But today i will clone a real open-source project called Phived.

Phived is a dead-simple, anti-procrastination to-do list. you can have up to 5 tasks at a time. to add more tasks, complete some of your ongoing ones. no login, no cookies, no images and no ads.

Phived website: https://www.phived.com/


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



## Let's start

#### Step 1# - Create a folder
> mkdir my-extension

#### Step 2# - Create a `128.png` file as your logo

> Create a 128p by 128p logo for your app.
> In the app folder, save the file as 128.png.

#### Step 3# - Create a `Popup.html` file

> At the src you should put your website.

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Phived</title>
  </head>
  <body>
    <iframe
      src="https://www.phived.com/"
      style="
        overflow: auto;
        height: 500px;
        width: 500px;
      "
      title="W3Schools Free Online Web Tutorials"></iframe>
  </body>
</html>
Ï
```


#### Step 4# - Create a `manifest.json` file

```json

{
  "manifest_version": 2,
  "name": "phived",
  "version": "1.0.0",
  "icons": {
    "128": "128.png"
  },
  "description": "Anti-procrastination to-do list. you can have up to 5 tasks at a time. to add more tasks, complete some of your ongoing ones. no login, no cookies, no images and no ads.",
  "content_scripts": [{ "matches": ["<all_urls>"], "js": ["Content.js"] }],
  "browser_action": {
    "default_popup": "Popup.html",
    "default_title": "phived"
  }
}


```

#### Step 5# - Run and test

- Save the app or extension folder on your test device.
- Go to chrome://extensions/.
- At the top right, turn on Developer mode.
- Click Load unpacked.
- Find and select the app or extension folder.
- Open a new tab in Chromeand thenclick Appsand thenclick the app or extension. Make sure it loads and works correctly.
If needed, make changes in the manifest.json file, host the app folder, and retest it. Repeat until the app or extension works correctly.


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


If every things runs ok, you should see your extension like that:


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


</hr>

Hope this post can be helpful!
For some feedback or more content, follow me on [twitter](https://twitter.com/daniellimae) or [github](https://github.com/bolodissenoura)
The Importance of Python in Software Engineering: A Versatile and Efficient Tool
Tags: softwareengineering, python
Published: 2023-04-13 23:36:38

Python is a general-purpose programming language that has gained immense popularity over the years. It is a powerful tool for software engineering and has become an essential language for developers in various fields, from web development to scientific computing. Python’s popularity in software engineering is due to its simple and readable syntax, easy-to-learn nature, and extensive range of libraries and frameworks. In this blog post, we will discuss the importance of Python in software engineering.

Easy to learn and use
Python is an easy-to-learn language, making it an excellent language for beginners to learn. The syntax of Python is simple and readable, making it easy for developers to understand and write code. This makes it an ideal language for rapid prototyping and testing, making it easier for developers to iterate and improve their software.

Large Community and Support
Python has one of the largest developer communities, with thousands of developers contributing to the language's libraries, frameworks, and tools. The vast community ensures that there are plenty of resources available for developers, making it easier to learn, solve problems and get help when needed.

Versatile
Python's versatility makes it an excellent language for software engineering. Python can be used for various applications ranging from web development, scientific computing, artificial intelligence, and machine learning. Python's extensive range of libraries and frameworks, including Flask, Django, Numpy, and Pandas, makes it easier for developers to create sophisticated software applications.

Time-saving and efficient
Python is a time-saving and efficient language. Python's syntax and built-in libraries allow developers to write code more quickly and efficiently, reducing development time. Python's automation and scripting abilities also make it easier for developers to automate repetitive tasks, making their work easier and more efficient.

Integration
Python's integration with other languages makes it an excellent choice for software engineering. Python can be integrated with languages like C++ and Java, allowing developers to use the power of both languages in their applications. This integration enables developers to take advantage of Python's ease of use and C++ or Java's performance and scalability.

In conclusion, Python is an essential language for software engineering. Its easy-to-learn nature, large community and support, versatility, time-saving and efficient properties, and integration capabilities make it an ideal choice for developing complex software applications. Python's popularity continues to grow, and it is expected to become even more popular in the future.
What Kept Me Motivated to Keep Learning This Week
Tags: codenewbie, beginners
Published: 2023-04-13 23:33:16

**Hey y’all! Here I am after delving in from a week of trying to poke away at learning new coding things and reading your articles over on the [#codenewbie tag](https://dev.to/t/codenewbie).**

This week has thus far been one of those weeks where I find myself making every excuse to not invest time in learning new things. So, if you’re like me, let me take you on a journey through a quick couple posts that helped to motivate me.

1. {% embed https://dev.to/eduardoltorres/the-biggest-mistake-beginner-developers-make-388e %}
This article by @eduardotorres seriously gave me the boost of accountability I needed to face the fear of trying new things. They said, “This is a clear example of one of the biggest mistakes that I see beginner developers do: never believing that they are ready.”

2. {% embed https://dev.to/spencer_the_dev/being-self-taught-in-2023-1lbb %}
Taking inspiration from other self-taught coders always makes my heart happy. @spencer_the_dev says, “There is - at least for me - a real sense of satisfaction in being one of a small handful of developers responsible for your company’s entire product. It’s not going to be for everybody, but I would strongly encourage getting some time in working at dev shops or startups. It builds character. Probably.”
    
I am trying lately to evaluate different aspects to enhance my focus while working from home! I enjoy it so much but definitely need some advice when it comes to keeping on track sometimes. Luckily, we posted a discussion thread for you to get advice about the two working styles. I would imagine this would be ***especially*** helpful to those folks out there who are looking for new employment!
    
{% embed https://dev.to/codenewbieteam/remote-work-in-tech-is-it-right-for-you-3j72 %}
    
And lastly, organization is always 100% the name of my game. 
    
{% embed https://dev.to/andrewkelly/code-naming-how-to-improve-the-readability-of-your-code-2377#comments  %}
“Naming in code is important because it helps people more easily understand the code that you have written. This will help your colleagues when they come to make changes to your code in the future.” - @andrewkelly

***
    
**Thank you all for being here and for learning with me!** 
    
ALSO—I would love to hear what everyone else is using to motivate themselves this week below. Be well y’all!
Resolvendo o problema do Permission Denied do Docker
Published: 2023-04-13 23:25:24

Olá, amigos nerds! Você já se deparou com o irritante erro "Permission Denied" ao tentar utilizar o Docker? Bem, se você está aqui, eu aposto que sim. Mas não se preocupe, vamos mandar esse erro para o espaço! 🚀

Cenário do problema:

O Docker está instalado no seu sistema, mas ao executar comandos como "docker run" ou "docker ps", você se depara com a seguinte mensagem de erro:


> permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock


Parece complicado, né? Mas não se preocupe, vou te mostrar a solução! 🧩
Inclusive pode encontrar a solução na documentação oficial: https://docs.docker.com/install/linux/linux-postinstall/#manage-docker-as-a-non-root-user


Aqui está um passo a passo simples e eficaz para resolver esse problema:

Primeiro, vamos verificar se o seu usuário faz parte do grupo "docker". Execute o seguinte comando:

$ grep docker /etc/group

Se o resultado mostrar o seu nome de usuário ao lado de "docker", **você já está no grupo**! Mas se não, não se desespere, pois temos uma solução!

```
docker:x:999:seu_usuario
```

Agora, vamos adicionar o seu usuário ao grupo "docker". Abra o terminal e digite o seguinte comando (substitua "seu_usuario" pelo seu nome de usuário):

`$ sudo usermod -aG docker seu_usuario`

Se não sabe qual é seu usuário no linux basta digitar:

`$ whoami`

Parabéns! Você acabou de dar um passo importante para resolver esse enigma!


Após executar o comando anterior, faça logout da sessão atual e faça login novamente para que as alterações entrem em vigor. Como alternativa, você pode executar:

`$ newgrp docker`

Este comando iniciará uma nova sessão de shell com a associação de grupo atualizada, mas é recomendável fazer logout e login novamente para garantir que as alterações se apliquem a todas as suas sessões de shell atuais e futuras.

Finalmente, verifique se o erro foi resolvido executando o comando "docker ps". Se você não encontrar mais o erro, comemore! 🎉 

E aí está, problema resolvido!

Outra solução:

`sudo chmod 666 /var/run/docker.sock`

Por quê esta não é a melhor solução?

Segundo a documentação https://docs.docker.com/engine/security/#docker-daemon-attack-surface


> A execução de contêineres (e aplicativos) com o Docker implica na execução do daemon do Docker. Este daemon requer rootprivilégios, a menos que você opte pelo modo sem raiz e, portanto, esteja ciente de alguns detalhes importantes.

> Em primeiro lugar, apenas usuários confiáveis ​​devem ter permissão para controlar seu daemon Docker . Essa é uma consequência direta de alguns recursos poderosos do Docker. Especificamente, o Docker permite que você compartilhe um diretório entre o host do Docker e um contêiner de convidado;
Introduction to Python Programming Language
Tags: webdev, beginners, programming, python
Published: 2023-04-13 23:19:17

Python is a popular high-level programming language that is widely used for developing various applications. Guido van Rossum created Python in the late 1980s, and it has since become one of the most popular programming languages in the world. Python is an interpreted language, which means that it does not need to be compiled like other programming languages such as C or Java. Instead, Python code is interpreted by an interpreter, which converts the code into machine-readable code that can be executed by the computer.

Python is known for its simplicity and ease of use, making it an excellent choice for beginners to programming. The language has a clean and readable syntax, making it easy to learn and understand. Python is also an object-oriented language, which means that it is designed to work with objects and classes. This allows developers to organize their code into reusable modules, making it easier to maintain and update.

One of the strengths of Python is its wide range of libraries and modules that are available for developers to use. These libraries and modules can be used to perform various tasks, such as web development, data analysis, machine learning, and artificial intelligence. Some of the popular Python libraries and modules include NumPy, Pandas, Matplotlib, TensorFlow, and PyTorch.

Python is also a versatile language that can be used for a wide range of applications, including web development, desktop applications, scientific computing, and game development. Python's versatility is due to its ability to be integrated with other programming languages and technologies, such as JavaScript, HTML, CSS, and SQL. This makes Python an excellent choice for full-stack development.

In conclusion, Python is a popular and versatile programming language that is widely used for developing various applications. Its simplicity, ease of use, and wide range of libraries and modules make it an excellent choice for beginners to programming and experienced developers alike. With its object-oriented design and ability to integrate with other technologies, Python is an excellent choice for developing a wide range of applications, from web development to scientific computing and game development.
Shop'till you drop!
Tags: python, game, project, begginers
Published: 2023-04-13 23:14:43

This game is part of the projects required for the Data Science path from Codecademy. 

The rationale was to code a game where the player require some basic knowledge of math, shopping, in other words, anybody could play the game, and in the way practice some basic tools.


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

The complete code could be cloned in:
[https://github.com/fjorwb/ShopTilYouDrop-Game]

Completing this project allowed me to review a lot of structures and functionalities learned along the path as well as research and applied others not known. So, run this project made me a little more expert in coding with Python.
Resolvendo o problema do popup de recursos do Flameshot no Ubuntu 22.04
Published: 2023-04-13 22:42:39

O **Flameshot** é uma poderosa ferramenta de captura de tela para Linux, que permite aos usuários tirar screenshots e fazer anotações diretamente nas imagens capturadas. 

Se você acabou de instalar o Ubuntu 22.04 e está enfrentando problemas para usar todos os recursos do Flameshot, este guia irá ajudá-lo a resolver esses problemas e aproveitar ao máximo esta excelente ferramenta.

**Passo 1**: Instalar o Flameshot

Abra o terminal e execute os seguintes comandos para instalar o Flameshot:

`sudo apt update
 sudo apt install flameshot`

**Passo 2:** Configurar o Flameshot para funcionar corretamente

O Ubuntu 22.04 utiliza o servidor gráfico Wayland por padrão, o que pode causar alguns problemas de compatibilidade com o Flameshot. Para resolver isso, siga os passos abaixo:

1. Abra o terminal e digite o seguinte comando para editar o arquivo custom.conf do GDM:

`sudo nano /etc/gdm3/custom.conf`

Descomente a linha:

`WaylandEnable=false `

removendo o símbolo # no início da linha. Em seguida, salve o arquivo e feche o editor pressionando Ctrl + X, seguido de Y e Enter.

Adicione a variável de ambiente QT_QPA_PLATFORM=xcb ao seu arquivo **.bashrc** ou **.zshrc** (dependendo do shell que você está usando). Para fazer isso, abra o arquivo no terminal com um dos seguintes comandos:

nano ~/.bashrc
ou
nano ~/.zshrc

Insira a seguinte linha no final do arquivo:

`export QT_QPA_PLATFORM=xcb`

Salve o arquivo e feche o editor, como explicado no Passo 2.
Reinicie o computador para que as alterações entrem em vigor.

Com essas configurações, o Flameshot deve funcionar corretamente no Ubuntu 22.04, permitindo que você use todos os recursos de captura e marcação de tela.
Discovering Flask
Tags: flask, jinja
Published: 2023-04-13 22:21:42

I recently finished an assignment from my bootcamp utilizing Flask and Jinja, and I have to say I'm really enjoying my first time experimenting with more back-end materials. Getting to see how file redirections (app.route() stuff) and search queries work in the grand scheme of things was absolutely fascinating to me. It's like there was a click; In the past I always wondered what went on in the search bar of a webpage, that massive string of letters and numbers and punctuation seemed like some crazy random AI generated code that magically turned into a webpage. Now I understand how you get directed from one page to another, how the styles can all stay the same thanks to a base html and css file, how data gets transferred through the query string... 

I really thought when I started out that I'd want to be a front-end developer (primarily), but my excitement to keep learning about the back-end is making me question things. Even despite the occasional frustration with not being able to clearly, visually See what's wrong when an error is thrown (vs, you know, a page section turning upside down and put on the wrong z-axis), I've found that everything is incredibly logical and back-end debugging isn't as scary as I initially thought. 

I've been having a little bit of trouble just memorizing the syntax for pulling inputs from the submission forms (and then the syntax to utilize it- how to borrow information back and forth between python and html), but I'm trying to code along with the videos and practice a bit on my own to get that imprinted on my brain. Has anyone else had difficulty with this? Maybe any good websites with exercises for ways to practice this kind of stuff, or personal suggestions on things to try to make that would utilize flask and python and forms/arguments?
Day 735 : We're Almost There
Tags: hiphop, code, coding, lifelongdev
Published: 2023-04-13 22:20:12

_liner notes_:
- Professional : Had a couple of meetings. Got to demo the application I am working on. Everything worked fine and everyone seems to like how it's coming along. Watched a recording of another meeting that happened early this morning. Responded to some community questions. Then finished the day cleaning up the code for my proof of concept application.

- Personal : Made some pretty good progress on adding page transitions with the View Transitions API for my side project. There's like 3 main types of transitions, gallery to details page, details to details page and details to gallery page. Got everything pretty much working except the details to gallery page which is the most difficult because of the way I have the gallery page set up. It's really a nice to have and not really necessary. I also went through some tracks for the radio show.

![In a very green valley in Applecross, Scotland with the mountainside tops covered in clouds](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x1e7kenbkbgwzm6trakj.jpg)

Going to see how far I can get with the final page transition for my side project. We're almost there. Also want to pick up some albums on Bandcamp and go through tracks for the radio show.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube AyQ6AbmY_Iw %}