teleren/devto huggingface dataset:
How To Install Extensions in BlueJ if you have Mac OSX
Published: 2022-04-05 21:03:15

I'm very distracted and I kwnow that there are many people like me, so if you are distracted like me and you wanna install an extension in BlueJ, you have to follow the next steps:

1.- You have to download and Install BlueJ you can go to https://www.bluej.org/

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

2.- Now you have a BlueJ Folder like this

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

3.- Open the folder and Command-click BlueJ.app and choose Show Package Contents


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

4.- Extensions are installed by placing the extension jar file into an extension directory

<BLUEJ_HOME>/BlueJ.app/Contents/Resources/Java/extensions2


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

5.- Now open your BlueJ, go to help >installed extensions and you will can see your "installed extensions"


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


And in case you didn't see it before, all this information can be found on the same BlueJ page, I found it after reading carefully and searching unsuccessfully all over the web.

https://www.bluej.org/extensions/extensions2.html

BlueJ 5 has a rewritten extensions API [explained here.](https://www.bluej.org/extensions/extensions2.html) the extensions page still exists for those interested in extensions for BlueJ 4 and older only, but for BlueJ5 and later you can use [this extensions](https://www.bluej.org/extensions/extensions2.html) 

**WRITING EXTENSIONS**


1.- Since BlueJ 5 you can write your own extension, if you wanna find out how to write your own extensions, you can [read this](https://www.bluej.org/extensions/writingextensions2.html) 
2.- You will need [BlueJ extension API documentation](https://www.bluej.org/doc/extensionsAPI2/)
3.- If you wanna share an extension with BlueJ you have to contact them [here
](https://www.bluej.org/support.html)

[Lee este post en español](https://medium.com/@shalimhoms/c%C3%B3mo-instalar-extensiones-en-bluej-si-tienes-macos-97f7dc432b24)
April 5th, 2022
Tags: cors
Published: 2022-04-05 20:59:41

**CORS **
Cross-Origin Resource Sharing

a HTTP header based mechanism used when requesting resource to another origin from an origin

origin : like address for server

https://google.com:80

protocol : https://
host : google.com
port : :80

the system that compare origins is activated under browser. That is, when the server receives the request from another origin, the server sends response unless there is a restriction that the server will take request from same origin. Then, browser will compare the response whether CORS is violated or not. 

browser : https://hyunin.com
server : https://server.com

1. send request to server 
2. send response to the browser
3. the browser check if the origin is different or not. If different, the response is thrown.

Because of that, this CORS does not work between server communication.


**Working of CORS**

when requesting resources from another origin, the application-browser- use HTTP protocol and the request header includes Origin with value

Origin: https://hyunjin.com

then when the server send response, the response header includes Access-Control-Allow-Origin with allowed value. The browser will compare ACAO and request origin

**1. when requesting preflight**

preflight means the pre-request before actual request for checking if it is safe to send request. For this, OPTIONS method is used. 

browser send pre-request(OPTIONS/resources - Origin:https://hyunjin.com) to the server
the server send response(200 ok Access-Control-Allow-Origin: *) to the browser. 
browser send actual request to the server
the server send response

more specifically,
In preflight,
there are origin, Access-Control-Request-headers, Access-Control-Request-Method
In the response to the preflight,
there are Access-Control-Allow-Origin

**2. simple request**

No preflight and others are same

the condition for this,
1. the request method should be one of GET, HEAD, POST
2. only Accept, Accept-Language, Content-Language, Content-Type, DPR, Downlink, Save-Data, Viewport-Width, Width should be used
3. when content-type, application/x-www-form-urlencoded, multipart/form-data, text/plain

resource: https://evan-moon.github.io/2020/05/21/about-cors/
Design Pattern: Factory Method
Tags: csharp, tutorial, architecture, oop
Published: 2022-04-05 20:52:56


Os designs de criação, nos quais se inclui o Factory, são utilizados para criar objetos sem expor ao cliente a lógica pela qual aquele objeto é criado. Assim, as subclasses ligadas a uma interface ou classe abstrata podem ser instanciadas sem que o cliente se importe com o tipo específico do objeto sendo criado.

De uma maneira mais prática, o diagrama abaixo é um exemplo de implementação de uma Factory:
![SAMPLE FACTORY UML](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l84m586e14v1ejhael6q.png)

Pode parecer sem sentido o simples ato de levar o construtor de um objeto para uma outra parte do programa, mas é justamente esse pequeno ato que gera a abstração que queremos, algo extremamente benéfico quando se trata de grandes projetos. Assim podemos sobrescrever o método de criação em uma subclasse, alterando o objeto criado, não é necessário reescrevermos toda a lógica de criação para cada subclasse que quisermos adicionar ao nosso programa, aplicamos princípios SOLID em nosso código, geramos um baixo acoplamento e facilitamos a manutenção.

Quando utilizar o Factory Method:
* Quando o cliente não sabe de antemão o tipo de objeto que deverá ser criado.
* Para permitir a extensão do código sem ter que realizar alterações em outras partes do projeto.
* Para eliminar duplicação de código na criação de objetos.

Prós do Factory Method:
* Evita acoplamento
* Facilita Manutenção
* Responsabilidade única ([SOLID](https://en.wikipedia.org/wiki/SOLID#:~:text=In%20software%20engineering%2C%20SOLID%20is,engineer%20and%20instructor%20Robert%20C.))
* Aberto/Fechado ([SOLID](https://en.wikipedia.org/wiki/SOLID#:~:text=In%20software%20engineering%2C%20SOLID%20is,engineer%20and%20instructor%20Robert%20C.))

Contras do Factory Method:
* Os produtos para serem retornados precisam ter uma classe ou interface base em comum.
* _Gera uma grande quantidade de classes no seu projeto._ No entanto cabe aqui uma observação: é responsabilidade do desenvolvedor considerar os trade-offs daquilo que ele implementa. Nesse caso da quantidade de classes, podemos abrir mão de um pró do Factory de forma a diminuir a quantidade de classes, porém aumentando o acoplamento do código (usando switch case na Factory por exemplo, transformando o padrão em um Simple Factory)
* Outros patterns podem oferecer mais flexibilidade, como Builder e Prototype, porém trazendo maior complexidade. Assim muitos projetos iniciam utilizando Factory e depois migram para outros design patterns.

Para um tutorial prático de como aplicar o Factory Method [CLIQUE AQUI](https://vaivoa.github.io/factory-method-design-pattern/).

{% user guilhermepirani %}

![linha horizontal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n8bndcx2jkn1jz1dy98v.png)
# Disclaimer

A VaiVoa incentiva seus Desenvolvedores em seu processo de crescimento e aceleração técnica. Os artigos publicados não traduzem a opinião da VaiVoa. A publicação obedece ao propósito de estimular o debate.

![logo vaivoa](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1wmziqv74ghhgyi9p0om.png)
You don't need... JavaScript to do tabs
Tags: javascript, css, tutorial, a11y
Published: 2022-04-05 20:47:28

## Intro

The current development ecosystems we code in make it _so easy_ to make a highly interactive experience with client-side code. Sometimes we reach for JavaScript (or worse yet, a whole framework) when we should hold off on that for as long as possible. 

This is the first of (hopefully) many entries in a series I like to call **You don't need...**

## What do we need for tab navigation?

To do tabs we need to do 2 things:

1. Track the current tab index
2. Show and hide tab content based on the index

And CSS can do both!

## The principals

CSS has a class of selectors called a sibling selector (`+` for immediately after and `~` for somewhere after) which will select a sibling element (one that is on the same "level" and shares their containing element).

CSS also has `nth` pseudo selectors, specifically the `:nth-of-type(i)` selector which will select the `i`th element of whatever selector you put before it.

The CSS principal you need to understand is the `:checked` pseudo selector which applies to `input` elements that have been checked (like a radio button or check box

## Getting it done

### Track the current tab index

In JavaScript we would update the tab index whenever we clicked on the tab. CSS has a way of tracking `input` element state with `:checked` as mentioned above so we can detect this in CSS with `input.tab:checked:nth-of-type(i)` where `i` is the index of the tab selected. We can make a new rule for every tab but it's kind of useless without some action based on the index

### Show and hide tab content based on selected index

For starters, the default state of a tab is hidden so I think `display: none` on our tab content is obvious. And showing it is as simple as `display: block`. The trick is showing the `i`th content when the `i`th tab is selected. For that we use the `~` (general sibling) selector. As long as your tabs are of one type (probably a `label` element for each of your hidden `input` state-managing elements) and your content is another type (a `div` maybe?) then you can group them as different "types" and use a rule like `input.tab:checked:nth-of-type(1)~div.tab-content:nth-of-type(1)` to select the first tab content element whenever the first tab is selected

## A working example

[JSFiddle link](https://jsfiddle.net/brq8g0um/)

You can also change the input type to `checkbox` for toggles [JSFiddle link](https://jsfiddle.net/dsj7poar/)

## How long does it take for you to resort to JavaScript to perform interactivity on an otherwise static site?

I am curious what other people think of avoiding JavaScript. I personally prefer to avoid it if the site is going to be mostly static since it means all my `noscript` users still have a good experience. At the very least, I want them to be able to sucessfuly use the site in a limited form, even if the optional frills I throw in do not function
JavaScript Navigator Media Devices 📷 🎙️
Tags: navigator, mediadevices, getusermedia, picture
Published: 2022-04-05 20:47:08

As you know, with [<u>Navigator.mediaDevices</u>](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/mediaDevices) you can access to connected media input devices in your machine like cameras and microphones.

Taking advantage of the potential of this amazing API you can create pretty awesome web app in a few code lines.

For example you can create a simple app to 
_take a picture_ using the computer onboard camera.

The _MediaDevices.getUserMedia()_ method prompts the user for permission to use a media input which produces a MediaStream with tracks containing the requested types of media.

It returns a _**Promise**_ that resolves to a MediaStream object, using this async function you can attach the camera stream as source in your video web page

```
const video = document.querySelector('video');
// Navigator video stream
async function videoStream (){
    try{
        const stream = await navigator.mediaDevices.getUserMedia({
            video:true,
            audio:false
        });
        // Set video source
        video.srcObject = stream;
  }catch(err){
        console.log(err);
    }
}

```

## Some Privacy and security considerations

As an API that may involve significant privacy concerns, getUserMedia()'s specification lays out a wide array of privacy and security requirements that browsers are obligated to meet.

_getUserMedia()_ is a powerful feature which can only be used in **secure contexts**; in insecure contexts, navigator.mediaDevices is _undefined_, preventing access to getUserMedia(). 
A secure context is, in short, a page loaded using _HTTPS_ or the file:/// URL scheme, or a page loaded from _localhost_.
In addition to that, user permission is always required to access the user's audio and video inputs.

This is a little [youtube guide](https://youtu.be/Vbj4PtmL0ko) that show how simple it is implementig navigator API 📸.
official.auction
Tags: javascript, webdev, programming, python
Published: 2022-04-05 20:45:33

Hello, Dev Community

We are looking for an expert solution from software engineers to build an online auctions website with blogging inside. 

Let's connect to build it together.

To know more please visit.
[official.auction](https://www.official.auction
)

Or send us a direct message here at dev.to

I will be happy to connect.
Thanks & Regards
ASN
Single Axis Solar Tracking System using Arduino
Tags: beginners, arduino, tutorial, cpp
Published: 2022-04-05 20:17:55

Welcome back to my blog today we will be making a single-axis solar tracking system using Arduino UNO

**Required Components**
1. Arduino Uno rev3
2. Servo motor SG90
3. Breadboard small
4. LDR 5mm (Light Dependent Resistor)
5. Resistor 10k ohms (2x)
6. Jumper Wires (10x)
7. Solar Panel 5.5v 
8. 9v Battery
10. Battery connector

**Tools Required**
1. Glue Gun
2. Soldering Iron
3. Arduino IDE
4. Laptop

## Background
Solar panels generate the most electricity when the incoming light is perpendicular to the panel. A solar tracker rotates the panel along one or two axes (altitude and azimuth) so that it always faces the sun directly. This can add up to 25% more energy compared with a fixed panel.

## Assembly
1. Connect LDR to 5 Volts and another Pin to A0 and then to a 10K resistor connected to the ground.

2. Connect the second LDR to 5 Volts and another pin to A1 and then to a 10K resistor connected to the ground.

This is a voltage splitter that will give a variable voltage to the analog inputs depending on the light hitting each LDR.

3. Connect the servo brown wire to the ground of the battery, the red wire to the 9V, and the orange wire to digital pin 9.

Servo need's more power to function properly

## Let's have a look at Circuit Diagram!!!

![Block Diagram for Single Axis Solar tracking Using Arduino](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f7vm8o9ku22o34o6ub4k.jpg)

## Code

```
//Code Written by TECH_TELE
#include <Servo.h>
Servo sg90;

int ldr_1 = A0; // lrd pin connected to A0
int ldr_2 = A1; // LDR pin connected to A1
int servo_pin = 9;
int pos = 90;// initial position
int servo_max=178;      // maximum position for servo
int servo_min=2;        // minimum position for servo

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(ldr_1, INPUT);
  pinMode(ldr_2, INPUT);
  sg90.attach(servo_pin);// servo pin declared 9 Line no 5
  sg90.write(pos);
  
}

void loop() {
  double ldrStatus1 = analogRead(ldr_1);
  double ldrStatus2 = analogRead(ldr_2);
  Serial.print("LDR1 Status:");
  Serial.print(ldrStatus1);
  Serial.println("");
  Serial.print("LDR2 Status:");
  Serial.print(ldrStatus2);
  Serial.println("");
if(ldrStatus1>ldrStatus2){
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    sg90.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15); 
  }
  }
if(ldrStatus1<ldrStatus2){
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    sg90.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);
  }
}
}
```
The Functional, Usable, Delightful of... Chopstick Rests
Tags: ux, design, webdev, delightful
Published: 2022-04-05 20:10:07

## <center>Functional</center>
![Origami chopstick rest made from chopstick wrapper](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m59vug0w7zwtv2fc6iz7.jpg)
<center>A flimsy paper stand.  _It will last the whole meal._</center>
<hr />
## <center>Usable</center>
![Wooden chopstick rest with a spoon and pair of chopsticks resting in grooves designed for this purpose](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uaxzysjgnr0zucxa6o98.jpg)
<center>A sturdy, re-usable, wooden rest, with neat little grooves for the chopsticks and a spoon.</center>
<hr />
## <center>Delightful</center>
![Two cat-shaped porcelain chopstick rests](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/secnwau9gw9jlf7fyahl.jpg)
<center>It's a cat!  Look at the cute little cat, hanging on to your chopsticks for you!  Tickle the cat's little tummy-wummy!</center>
I created a library for mobile developers who cares about color.
Tags: javascript, reactnative, typescript
Published: 2022-04-05 20:10:04

You know that moment when you needed a color to be a little bit lighter or darker? 

But you don't want to manually make it lighter or darker?

Well... me too.

So that's why a created [react-native-color-toolkit](https://github.com/juniorklawa/react-native-color-toolkit)

With this library you can have access to a lot of color modification functions like:

- brighten
- darken
- desaturate
- greyscale
- lighten
- saturate

Let's imagine an example where you have a color, but you want that color to be 50% darker, with [react-native-color-toolkit](https://github.com/juniorklawa/react-native-color-toolkit) you just need to call a function like this:

```jsx
<View  style={{justifyContent:  'center', alignItems:  'center'}}>
	<View  style={[styles.box, {backgroundColor: '#2196F3'}]} />
	<Text  style={styles.subtitle}>Original color</Text>
</View>
<View  style={{justifyContent:  'center', alignItems:  'center'}}>
	<View  style={[styles.box, {backgroundColor: darken('#2196F3', 0.5)}]} />
	<Text  style={styles.subtitle}>Modified color</Text>
</View>
```

Will give you this result:

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

---

## react-native-color-toolkit also have also have 

- Conversion functions (like rgb to Hsl)
- Utility functions (like get the alpha value of a color)
- Material Colors Palette (like Colors.red[700])


I hope it can make your mobile developer life easier.

Feel free to open pull requests and make contributions.

[Link](https://github.com/juniorklawa/react-native-color-toolkit) to the repo and documentation.
Visualize explain results from postgresql in pgcli
Tags: pgcli, python, postgres, pev
Published: 2022-04-05 19:55:05


Recently I wrote a [visualizer](https://github.com/dkuku/pyev)  for explain query responses from postgresql. I also integrated it into pgcli and it got merged few days ago. You can install it currently with:
```sh
pip install git+https://github.com/dbcli/pgcli@main
```
or wait for `3.4.2` release and update.
To switch between normal mode and explain mode you can press `F5`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2fzhn17xc70cnak0cxzo.png)
Remember to set Cache-Control headers on your secured pages
Tags: header, security, cache, tutorial
Published: 2022-04-05 19:49:45

Last week we had a production issue about a potential data leak.

When users would logout of their profile they could navigate back and view the pages as if they were logged in. This could be  potentially harmful when you are on a public or shared computer. Obviously you should trust the website that the logout button forgets all trace of you ever logging in.

After a short investigation we found that an update a couple days prior removed the `Cache-Control` header. 

It should be set to something like this:

![cache-control example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q1jc8e5yx5uvadk3r003.png)
 

There are 3 main options to set in cache-control:
`no-store`
https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.2
This is the most strict option of all. It tells the browser to not store any response or request in the cache at all.

`no-cache`
This tells the browser that it should re-validate the cache with the server before using it again. It doesn't mean that the response isn't stored in the cache.

`must-revalidate`
This tells the browser that the validation of the cache should happen when the date expired on the cache, using the header 'max-age' value. It doesn't mean that the response is always explicitly validated.

Setting our `Cache-Control header` to `no-store, no-cache` we will have no cache in our browser. Now if we logout of our profile and navigate back there is no cached page to return to. This will trigger a 'refresh' like behavior and fore the login page to show.

Our users are safe again! And we didn't even have to update our software.
Drag and Drop in React
Tags: react, typescript
Published: 2022-04-05 19:30:54

In this example it was created whit **React** and **typescript**

- Drag and drop area
```
<div
  onDrop={handleDrop}
  onDragOver={handleDragOver}
  onDragEnter={handleDragEnter}
  onDragLeave={handleDragLeave}
>
</div>
```
- Actions

```
  const handleDragOver = ( e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
  };

  const handleDragEnter = ( e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
  };

  const handleDragLeave = ( e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
 };

 const handleDrop = ( e: DragEvent<any>) => {
    e.preventDefault();
    e.stopPropagation();
    // the 'files' constant contains the documents
    const files = e.dataTransfer.files;
 };
```
Idea Proyecto
Published: 2022-04-05 19:25:31

En mi aplicación el usuario podrá visualizar hasta 3 feeds de diferentes redes sociales/páginas webs al mismo tiempo. En ella el usuario básico registrado, podrá registrarse en una web, ( guardar usuario y contraseña; de forma segura, en mi web) de esta forma cada vez que quieras ver esa red social no hará falta iniciar sesión. Los usuarios podrán editar los registros. Editar perfil, editar datos básicos del usuario (email,contraseña,nombre…). Proponer una web, el usuario podrá enviar una petición para añadir una red social nueva. Visualizar, añadir y borrar feeds se podrá editar lo que estás viendo, ver un feed 1, ver 2, borrar 1 y añadir otro, etc…
Además, habrán usuarios administradores, los cuales se dedicaran a aceptar peticiones y gestionar usuarios