teleren/devto huggingface dataset:
Using FastImage to detect image dimensions in Ruby
Tags: ruby, rails, webdev, html
Published: 2021-09-28 15:58:51

On Forem (the open source software that powers DEV, etc.) we have these display units with customizable content an admin can set.

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

As you can see, this contains an image... which will need to load asynchronously as all images do in HTML. If `height` and `width` are set, then the browser will save the space for the image to take up once it fully loads. If these values are not set (and no custom styles are set), this will cause the page content to "jump", which is not good for UX, and is penalized by Google as "cumulative layout shift"...

More on cumulative layout shift:

{% link https://dev.to/ben/fixing-cumulative-layout-shift-41ja %}

These images are _user-generated-content_, and we do not want to ask admins to manually declare the image size. They may get it wrong, but even if they get it right, it's not exactly the best use of their time if the application can handle it for them.

Detecting image dimensions is not rocket science, but you don't want to reinvent the wheel or do it inefficiently. Enter FastImage.

{% github https://github.com/sdsykes/fastimage %}

FastImage inspects the image and and read the minimal information needed for the task, in this case determining dimensions. In Forem, we already had in place a process for proxying the images so that they are served by the appropriate CDN instead of direct from the upload source, so adding FastImage was a matter of adding this as an option to that step in the process.

I added an option in our image manipulation step called `synchronous_detail_detection` which, if true, takes the time to inspect images and output the proper attributes.

Doing this synchronously is the least complicated way to do this, and I felt like it was appropriate for this functionality given that it is only used by _admins_. When we use FastImage to detect details on posts, which can be created by any member of the site, it makes more sense to do this inspection asynchronously to ensure a post with 15 images can successfully save without timing out.

The code for the functionality described is all visible in this pull request, where I made several changes to clean up this particular functionality.

{% github https://github.com/forem/forem/pull/14789 %}

Happy coding!
🌈 Launching the EuroPython Society Fellow Grant
Published: 2021-09-28 15:31:54

*(Originally posted on https://www.europython-society.org/launching-the-europython-society-fellow-grant/)*

We are excited to announce the new EuroPython Society Fellow Grant.

The grant is intended to honor and show gratitude towards members of the [EuroPython Society (EPS)](https://www.europython-society.org/) and the [EuroPython Workgroups](https://www.europython-society.org/workgroups/) who have contributed significantly towards our mission, the EuroPython conference and the Society as an organization.

## EuroPython Fellows
EuroPython Fellows are eligible to a lifetime free attendance of the EuroPython conference and will be listed on our [EuroPython Society Fellow Grant page](https://www.europython-society.org/europython-society-fellow-grant/).

The EuroPython Board will decide on new Fellowships based on nominations by the EPS members and its own deliberations.

## Our first Fellows
To launch the grant, the current board has decided to make all board members since 2012 who have served at least two terms and are not members of the current board [EuroPython Fellows](https://www.europython-society.org/europython-society-fellow-grant/#fellows):
* [Alexander Hendorf](https://twitter.com/hendorf)
* [Alexandre Manhaes Savio](https://twitter.com/alex_savio)
* [Anthon van der Neut](https://twitter.com/avanderneut)
* [Borja Ayerdi](https://twitter.com/bayerdi)
* [Christian Calogero Barra](https://twitter.com/christianbarra)
* [Darya Chyzhyk](https://twitter.com/DaryaChyzhyk)
* [Fabio Pliger](https://twitter.com/b_smoke)
* [Jacob Hallén](https://twitter.com/jacobhallen)
* [Vicky Twomey-Lee](https://dev.to/whykay)

The board will announce more Fellows in the coming weeks. If you are an EPS member and want to nominate another member as a Fellow, please write to board@europython.eu and include the reasons why you believe the member should become a Fellow.

The EPS Board would like to congratulate all of the above Fellows and thank them for their tireless work towards our goals.

Enjoy,
EuroPython Society
https://www.europython-society.org/
How to install OpenGL in Ubuntu in C++?
Tags: opengl, cpp, linux, ubuntu
Published: 2021-09-28 15:05:29

## What Is OpenGL?

OpenGL is a Graphics rendering API which is operating system independent, window system independent and has high-quality color images composed of geometric and image primitives. OpenGL APIs can use following - 

1. GL
  - OpenGL API implementation (http://www.opengl.org)
2. GLU
  - OpenGL Utility
3. Glut
  - GLUT (OpenGL Utility Toolkit) – Glut is portable windowing API and it is not officially part of OpenGL.
  - OpenGL Utility Toolkit (http://www.opengl.org/resources/libraries/glut/)
4. FLTK
 - FlashLight ToolKit (http://www.fltk.org/)
5. GLEW


Now lets see how to install OpenGL in Ubuntu.

Now because GLUT (OpenGL Utility Toolkit) depends upon OpenGL and a number of other related libraries, if we install GLUT then OpenGL will be automatically be installed.

First update the repository using the given command
```sh
$ sudo apt-get update
```

Run the following command to install OpenGL.

```sh
$ sudo apt-get install libglu1-mesa-dev freeglut3-dev mesa-common-dev
```
Now to test if OpenGL libraries are working fine on our Linux machine, we will create a C++ program and test it.

So create a following C++ Program.

```cpp
#include <GL/glut.h>
 
void displayMe(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glBegin(GL_POLYGON);
        glVertex3f(0.5, 0.0, 0.5);
        glVertex3f(0.5, 0.0, 0.0);
        glVertex3f(0.0, 0.5, 0.0);
        glVertex3f(0.0, 0.0, 0.5);
    glEnd();
    glFlush();
}
 
int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE);
    glutInitWindowSize(400, 300);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("Hello world!");
    glutDisplayFunc(displayMe);
    glutMainLoop();
    return 0;
}
```
Now give the command below to compile your code.

```bash
$ g++ main.cpp -o firstOpenGlApp -lglut -lGLU -lGL
```
Now run your OpenGl program with following command

```bash
$ ./firstOpenGlApp
```

You will see something like this on your screen if everythings went well.
![OpenGl in Ubuntu using C++](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a0tf014804bftdcz8dvn.png)
Testes (Código Limpo: Que Bruxaria é Essa?!?! - Parte 7)
Tags: javascript, cleancode
Published: 2021-09-28 14:57:44

Testar é mais importante do que enviar para produção. Se você não tem testes ou tem uma quantidade inadequada destes, toda vez que você envia o seu código, não terá certeza de que não quebrou nada. Cabe ao seu time decidir o que constitui uma quantidade adequada de testes, mas é o 100% de cobertura (todas as declarações e ramificações) é o modo pelo qual você adquire autoconfiança e paz de espírito como desenvolvedor. Isso significa que além de usar um excelente "framework" de testes, você também precisa de uma boa ferramenta de cobertura. Não há desculpa para não escrever testes. Há muitas "frameworks" bons de testes JS, então encontre um do agrado da sua equipe. Quando você encontrar o que funciona para seu time, tenha o objetivo de sempre escrever testes para cada nova funcionalidade/módulo que introduza. Se o seu método favorito é o Desenvolvimento Orientado a Testes (TDD), é bom, porém o ponto principal é apenas ter certeza de que você está alcançando seus objetivos de cobertura antes de lançar qualquer funcionalidade ou refatorar uma existente.

## Um único conceito por teste

### Não é recomendável: 

```javascript
import assert from "assert";

describe("MomentJS", () => {
  it("handles date boundaries", () => {
    let date;

    date = new MomentJS("1/1/2015");
    date.addDays(30);
    assert.equal("1/31/2015", date);

    date = new MomentJS("2/1/2016");
    date.addDays(28);
    assert.equal("02/29/2016", date);

    date = new MomentJS("2/1/2015");
    date.addDays(28);
    assert.equal("03/01/2015", date);
  });
});
```

### É recomendável: 

```javascript
import assert from "assert";

describe("MomentJS", () => {
  it("handles 30-day months", () => {
    const date = new MomentJS("1/1/2015");
    date.addDays(30);
    assert.equal("1/31/2015", date);
  });

  it("handles leap year", () => {
    const date = new MomentJS("2/1/2016");
    date.addDays(28);
    assert.equal("02/29/2016", date);
  });

  it("handles non-leap year", () => {
    const date = new MomentJS("2/1/2015");
    date.addDays(28);
    assert.equal("03/01/2015", date);
  });
});
```

E aí? Gostaram? Até a próxima tradução! 🤗
Function Store - New functionality installed with a click.
Tags: firebase, tooling, functions
Published: 2021-09-28 14:57:28

Hey Everyone - Functions Store just launched on Product Hunt and we would love your feedback!
We’ve spent that last few months building:
- A Marketplace of reusable, expert-built, and well-tested Google Cloud Functions
- A Platform of tools to simplify building web apps on Google Cloud and Firebase
- An opportunity for developers around the world to generate a new income stream
- 20x faster to implement new features for your web app
Check Us Out Here: [https://www.producthunt.com/posts/function-store](https://www.producthunt.com/posts/function-store)

Thanks to everyone who take time out of their busy days to help support by voting and providing feedback!
Hey Everyone - Functions Store just launched on Product Hunt and we would love your feedback!
Published: 2021-09-28 14:53:13

We’ve spent that last few months building:
- A Marketplace of reusable, expert-built, and well-tested Google Cloud Functions
- A Platform of tools to simplify building web apps on Google Cloud and Firebase
- An opportunity for developers around the world to generate a new income stream
- 20x faster to implement new features for your web app
Check Us Out Here: [https://www.producthunt.com/posts/function-store](https://www.producthunt.com/posts/function-store)

Thanks to everyone who take time out of their busy days to help support by voting and providing feedback!
Hook error using Truffle React box (transforming the App.js from Class component to Functional component)
Published: 2021-09-28 14:44:38

Hello! Not an expert Solidity/React user here. I got Truffle React box and I am making a website. My example is very easy. I have this Nav element: 

https://codeshare.io/xvgqBL

Which is defined here:

https://codeshare.io/6pmYZg

Simple. Now, due to some hook errors in React, I decided to convert my App.js file. When you download this box, the App is a Class component. It means you cannot use hook inside it (as far as I know). So my next step was transform that Class component into a Functional component (some users from the React community helped me in this task). The result was:

https://codeshare.io/nzPkBM

The code was reviewed and seems to be fine. I cannot find any errors in it either. But it is again throwing a hook error, but some users think this could be a red herring because as far as I know I am not using any hook. If I remove <Navbar /> tag at the end of the App.js file, the app works perfectly.

The error when I run npm run start: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c7g5qkn3ouhcqs6qw885.png

I can provide a sandbox with my project if it's necessary. Please, this is driving me crazy.

Additionally, I checked my version:

 - `npm view react version`: 17.0.2
 - `npm view react-native version`: 0.65.1

But, in my json file it seems I have another version:

      "name": "client",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "dotenv": "^10.0.0",
        "react": "16.11.0",
        "react-dom": "16.11.0",
        "react-scripts": "3.2.0",
        "truffle-hdwallet-provider": "^1.0.17",
        "web3": "1.2.2"
Button Project Updates
Published: 2021-09-28 14:41:01

In my Webcomponents class I am making a button. My partner Jimmy and I decided to be unique we will be creating a circular button. So far the project is going okay. We continue to make small bursts of progress but I have yet to really make great strides with the project. I missed class last week because of the Fall Career Fair but I know that my partners used a CSS generator which helped us a lot. Last week was very chaotic for me but this week I will have lots of time to sit down and work on this button. Hopefully I will be able to find a laptop charger because I left mine in Pittsburgh. This week will be the final push to make sure all functionality is working and the styles are the way I want them. 

This is what our reusable button looks like right now. 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jq3gxotqs1h25b3bkzm9.png)

My goals for the project includes dynamic loading, checking all accessibility issues, and perfecting our CSS styles. Jimmy is working on getting disable to work right now. 

You can find our button [here](https://github.com/3B4B/circle-button-fj)
Widget Share Button with Web Share API in Blogger
Tags: blogger, javascript
Published: 2021-09-28 14:38:41

From this https://stackoverflow.com/a/59269039/15504481 I was succesfully implement some svg share button with web share api function, but i want some condition when browser doesn't support web share api then my share button should not appear or replace it with conventional share buttons.

right now i just put my button inside <b:if cond='data:blog.isMobileRequest'> witch is only when user open my blog with mobile phone this button will appear.

please open with chrome mobile on smartphone to check.
https://www.catatandroid.com/2020/06/cara-import-preset-lightroom-dng-xmp.html?m=1

Please anybody help. Thank you.
I Made Shortlink Generator with NextJs & Spreadsheet
Tags: react, nextjs, spreadsheet, javascript
Published: 2021-09-28 14:36:52

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

i made short link generator with spreadsheet as database, and fullstack with nextjs 😆
 
if want a check :
[Preview web app](https://shrt-link.vercel.app/)
[repo code](https://github.com/m4har/shortlink-generator)
[spreadsheet](https://docs.google.com/spreadsheets/d/1qIQnxzzSiS1qZ5hWZ3CoVQTSB1tdNQLa7EPo5uhSL-c)
Explaining lazy evaluation in C#
Tags: csharp, dotnet
Published: 2021-09-28 14:30:50

Countless were the times I've fired up Visual Studio to write the following example explaining what lazy evaluation is and why it's better to expose collections as `IEnumerable<T>`:

```cs
using System.Collections.Generic;
using System.Linq;
using static System.Console;

// If you replace the lazy call below with the eager one you get an out of memory error
var oneToTen = LazyInfinity().Take(10);

foreach (var n in oneToTen)
    WriteLine(n);

// "In eager evaluation, the first call to the iterator will result in the entire collection being processed."
// "A temporary copy of the source collection might also be required."
static IEnumerable<int> EagerInfinity()
{
    var i = 0;
    var infinity = new List<int>();

    while (true)
        infinity.Add(++i);

    return infinity;
}

// "In lazy evaluation, a single element of the source collection is processed during each call to the iterator."
static IEnumerable<int> LazyInfinity()
{
    var i = 0;

    while (true)
        yield return ++i;
}
```

More at:

- https://docs.microsoft.com/dotnet/csharp/iterators
- https://docs.microsoft.com/dotnet/standard/linq/deferred-execution-lazy-evaluation
Hi, I'm Tricky, and I just started learning webdev, about a week ago. Here is a small website I made :D
Tags: webdev, html, css, javascript
Published: 2021-09-28 14:28:41

Here is the website ->

https://www.tricky.ml/

Here is the repo ->

https://github.com/Tricky4747/Tricky4747.github.io

Let me know your thoughts :)
Css only fullscreen element
Published: 2021-09-28 14:25:33

Hi! I wanted to share with you my solution to a well known headache during sites development: fullscreen hero image with only CSS. 

After spending a lot of time on it, and reading a lot, i came up with a pretty working solution (i wouldn't say a 100% working solution) but yet a solid one:

```css
.fullscreen-wrapper {
  width: 100%;
  height: 100vh;
  /** mobile non iOS devices */
  @media (hover: none) and (pointer: coarse) {
    height: calc(100vh - 56px);
    @media (orientation: landscape) {
      min-height: 100vh;
      height: auto;
    }
  }
  /** iOS devices */
  @supports (-webkit-touch-callout: none) {
    height: -webkit-fill-available;
    @media (orientation: landscape) {
      min-height: auto;
      height: -webkit-fill-available;
    }
  }
}
```

Let me know what you think and if it works!
Update an object in nested array in MongoDB
Tags: mongodb, database, javascript, node
Published: 2021-09-28 14:06:46

Hello Reader 👋

To update an object inside a nested array in MongoDB you can use this approach, Its well tested and working.

#### Case:
Update nested array objects. See below picture for a better Idea what we are going to do. We will update the object which is nested by 3 levels of array.

```javascript
{
 discussionList[
  discussionList [
   {
     object-value-to-be-updated.
   }
  ]
 ]
} 
```

![mongodb - update an object inside multilevel nested array](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u0h9ievy3ybu66mc2b3v.jpg)

#### Solution: 


```javascript
public courseCategoryPostCommentReplyUpdate(operation: CommentReplyUpdateMutation): Promise<IDocumentUpdateType> {
    return this.courseCategoryPostCommentsModel.updateOne(
      {
        "postId" : operation.postId,
        'discussionList': {
          '$elemMatch': {
            '_id': operation.commentId,
            "discussionList._id": operation.replyId
          }
        }
      },
      {
        $set: {
          "discussionList.$[outer].discussionList.$[inner].payload": operation.payload,
          "discussionList.$[outer].discussionList.$[inner].isUpdated": true,
          "discussionList.$[outer].discussionList.$[inner].commentUpdateTime": new Date()
        }
      },
      {
        arrayFilters: [
          { "outer._id": operation.commentId},
          {"inner._id": operation.replyId}

      ]
      }
    );
  }
```
*FootNotes - this code is to update the reply of a comment.*

That's how you can perform operations on an object in nested array in mongoDB document. You can also update/delete the objects which are having the more level of nesting by just modifying the query.

### Example of delete and get
##### Delete
```javascript
// Informational Note:
  // Delete nested array values in mongodb


  public courseCategoryPostCommentReplyDelete(operation: CommentReplyDeleteMutation): Promise<IDocumentUpdateType> {
    return this.courseCategoryPostCommentsModel.updateOne(
      {
        'postId': operation.postId,

        'discussionList': {
          '$elemMatch': {
            '_id': operation.commentId,
            'discussionList._id': operation.replyId
          }
        }
      }, {
        $pull: {
          'discussionList.$[outer].discussionList': {
            user: operation.userId,
            _id: operation.replyId
          }
        }
      },
      {
        arrayFilters: [
          { 'outer._id': operation.commentId }
        ],
        multi: false
      }
    );
  }
}

```

#### GET

```javascript
public courseCategoryPostCommentRead(postId: string): Promise<IComment> {
    return this.courseCategoryPostCommentsModel.findOne<IComment>({
      postId: postId
    }).populate('discussionList.user').populate('discussionList.discussionList.user').exec();
  }
```
I was using GraphQL. You may need to iterate over the result and show the comments/replies as per that.

Please let me know if the code needs an explanation. Thanks 🙂
[PT-BR] Minhas duas features preferidas do Java 17
Tags: java, jdk17
Published: 2021-09-28 13:56:06

No dia 14/09/2021, foi lançada a versão 17 do Java, sendo ela uma versão LTS *(Long Term Support)*. Assim como nas últimas versões, a 17 trouxe algumas features bem divertidas. Minha ideia nesse post é mostrar as duas que mais me chamaram atenção, que são a **409:Sealed Classes** e a **406:Pattern Matching for Switch**. 

#Sealed Classes  
  
*Sealed* classes e interfaces restringem quais outras classes ou interfaces devem estendê-las e/ou implementa-las. O objetivo é permitir que o autor da classe ou interface tenha mais controle sobre a mesma, além de prover um jeito mais declarativo de restringir o uso da super classe. Um outro objetivo é o suporte a *pattern matchings*. 

```java
public abstract sealed class Automovel 
    permits com.exemplo.automovel.Carro,
            com.examplo.automovel.Moto { ... }
```

Uma vez que eu defino quais classes irão poder estender de Automovel, qualquer outra classe diferente de Carro e Moto não deve ser permitida. É importante ressaltar, que as classes que irão estender uma *sealed class*, deverão estar no mesmo módulo, caso esteja usando *JPMS (Java Platform Module System)* ou no mesmo pacote, caso não esteja usando *JPMS*. Para a classes que estendem, existem algumas regras. São elas: 

1. Uma subclasse deve ser declarada como final para manter a hierarquia. 

2. Uma subclasse deve ser declarada como *sealed* e permitir a extensão de um novo conjunto de classes.

3. Uma subclasse deve ser declarada como *non-sealed* e assim permitir que qualquer classe a estenda. 

#Pattern Matching for Switch

Estender a correspondência de padrões para *switch* permite que uma expressão seja testada em relação a vários padrões, cada um com uma ação específica, de forma que consultas complexas orientadas a dados possam ser expressas de forma concisa e segura. O objetivo é melhorar a expressividade e a aplicabilidade das extensões e instruções *switch*, além de certificar que todas as expressões e instruções existentes continuem a compilar sem alterações. 

```java
static void printarTipoAutomovel(Automovel automovel) {
   switch(automovel) {
     case Carro -> System.out.println("É um carro");
     case Moto -> System.out.println("É uma moto");
     default -> System.out.println("Automóvel não identificado");
   }
}
```

É importante ressaltar que a **JEP 406: Pattern Matching for switch** está como preview, o que significa que ela pode ser retirada e não fazer parte das próximas versões do Java. 

#Concluindo

O objetivo do post era trazer as features que mais me interessaram no Java 17, sendo essa uma escolha totalmente pessoal. Existem muitas outras features legais, que podem ser vistas em: https://openjdk.java.net/projects/jdk/17/. Espero que gostem da leitura. Dúvidas, sugestões e/ou críticas, estou à disposição. 

Referências
https://openjdk.java.net/jeps/409
https://openjdk.java.net/jeps/406