teleren/devto huggingface dataset:
Day 381 : Issues
Tags: hiphop, code, coding, lifelongdev
Published: 2021-06-04 21:50:30

_liner notes_:
- Professional : Whew! Today I spent most of it working with a community member on a question they had. I think we got to a point where they can get what they wanted to work. It's not dealing with the stuff I normally work on so it was a good learning exercise.

- Personal : So, last night, since I got the dashboard working so I can add and remove data from the database, I wanted to replace the hard coded information on the main site with data coming from the back end. I wanted to only call the back end once for the data and then put it in a store that I can use in the components that need them. Got it working locally and deployed it, and it broke. haha Researched and found what could be the problem. Looked like it could be issues with the server side rendering. Refactored my code, got it working locally and deployed and it broke again. So like before I just rolled back to a previous deployment that worked and noticed that the data was coming through to the site. Turns out that somehow a config file got reverted to the original version so it didn't even know about my application. At least now I know 2 different ways to solve the problem. haha. Other than that, I just went through tracks for the radio show.

![View of the ocean at sunset through grass on a beach in Shoalhaven Heads, Australia](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vgwtwnf7n34ef39dv6lo.jpg)

Decided to push back the first broadcast to the end of the month so I can have time to really get things working right. Really need to figure out the notification situation. Once that's done, I can start to promote the site for people to sign up for notifications. Going to work on that and put together the radio show for tomorrow.

Have a great night and weekend!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube j3k-vkjAXpU %}
AWS Auto Tab Completion When Using Oh My Zsh 
Tags: ohmyzsh, awscli, mac, aws
Published: 2021-06-04 20:38:34

I installed AWSCLI with homebrew (you don't have to if you don't want)

##Adding to your .zshrc
Add `aws` to you plugins for oh my zsh
Something like this:
`plugins=(terraform git aws)` NOTE: Terraform and git are there for example.

Then I put this at the bottom.
``` bash
#Auto tab complete for AWS Cli
export PATH=usr/local/bin/aws_completer:$PATH
autoload -Uz compinit && compinit
```
10 Developer Articles You Should Read From May 2021
Tags: learning, ibmcloud, video, tutorial
Published: 2021-06-11 00:41:17

---
title: 10 Developer Articles You Should Read From May 2021
published: true
date: 2021-06-04 20:34:20 UTC
tags: Learning, IBMCloud, video, tutorial
canonical_url: https://maxkatz.org/2021/06/04/10-developer-articles-you-should-read-from-may-2021/
---

I want to share three developer articles, tutorial and videos from [IBM Developer](http://developer.ibm.com) North America team. These resources offer high-quality developer education so I believe you will find them valuable.

[![Code Engine](https://katzmax.files.wordpress.com/2021/06/code-engine-may2020-articles.jpg?w=1000)](https://katzmax.files.wordpress.com/2021/06/code-engine-may2020-articles.jpg)<figcaption>Code Engine</figcaption>

📖[Enterprise Java Developer Relations and Community Engagement](https://developer.ibm.com/blogs/enterprise-java-developer-relations-and-community-engagement/) by Dave Nugent

📖[Deploy a Cloud Native Application to Code Engine in 5 Easy Steps!](https://dev.to/ibmdeveloper/deploy-a-cloud-native-application-to-code-engine-in-5-easy-steps-4bcg) by Jenna Ritten

📖[Run Batch Jobs with the Code Engine CLI](https://dev.to/ibmdeveloper/run-batch-jobs-with-the-code-engine-cli-5g5h) by Jenna Ritten

📖[Think Lab 2124 : Build & Deploy AI/ML Models w Multiple Datasets w AutoAI – Tutorial A](https://dev.to/ibmdeveloper/think-lab-2124-build-deploy-ai-ml-models-w-multiple-datasets-w-autoai-part-a-24pk) by Jenna Ritten

📖[Think Lab 2124 : Build & Deploy AI/ML Models w Multiple Datasets w AutoAI – Tutorial B](https://dev.to/ibmdeveloper/think-lab-2124-build-deploy-ai-ml-models-w-multiple-datasets-w-autoai-tutorial-b-167) by Jenna Ritten

📖[Creating Your Own Chat Room with React, Node, and Socket.io in the Cloud: Part 1](https://dev.to/ibmdeveloper/creating-your-own-chat-room-with-react-node-and-socket-io-in-the-cloud-part-1-13dg) by Bradston Henry

📖[Creating Your Own Chat Room with React, Node, and Socket.io in the Cloud: Part 2](https://dev.to/godspowercuche/creating-your-own-chat-room-with-react-node-socket-io-and-the-cloud-part-2-9o0-temp-slug-5763248) by Bradston Henry

📺[From Amateur to Professional: The One KEY Tip I Give All Aspiring Devs](https://dev.to/godspowercuche/from-amateur-to-professional-the-one-key-tip-i-give-all-aspiring-devs-5fib-temp-slug-6569084) by Bradston Henry

📖[How to Deploy a Basic Flutter App to the Cloud](https://dev.to/ibmdeveloper/how-to-deploy-a-basic-flutter-app-to-the-cloud-ggn) by Bradston Henry

📺[What is the Best Programming Language for Beginners? | Ask A Dev](https://dev.to/bradstondev/what-is-the-best-programming-language-for-beginners-ask-a-dev-9ha) by Bradston Henry

One more thing. If you are looking to join our live online meetups, you will find weekly developer education events on our [Crowdcast channel](http://crowdcast.io/ibmdeveloper).
Enable Apple Remote Desktop from commandline
Published: 2021-06-04 20:22:23

Enable for all users

```
sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -access -off -restart -agent -privs -all -allowAccessFor -allUsers

```
Disable for all users
```
sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -deactivate -configure -access -off

```

https://support.apple.com/en-us/HT201710
How to keep all constants in Flutter
Tags: flutter, dart
Published: 2021-06-04 20:20:54

A clean and simple way to keep constants in Flutter is to make an own Dart library in the project for the constants.

For example, we have a project structure like this.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/94ykfa2sv5p2abzy1whw.png)

**constats.dart**
```
const String BUTTON_LABEL = 'Submit';
```
The const keyword is used to represent a compile-time constant. Variables declared with const keyword are implicitly final. [Link](https://dart.dev/guides/language/language-tour#final-and-const)

You can then use import statement to access to the constants:
```
import 'package:<project_name>/assets/constants.dart' as constants;
...
ElevatedButton(
  child: const Text(constants.BUTTON_LABEL),
)
...
```
How do you create (and remember) master passwords?
Tags: security, password, help, discuss
Published: 2021-06-04 20:14:18

I fear to even think of creating a new master password / PIN (without relying on variation play).

I mean, practically.

Passphrase?

- How many words?
- I don't speak English, so which language? Non-ASCII scripts? Keyboard-layout-based? (Typing non-ASCII on QWERTY)
- Does it need punctuations? How do you add them? How many?

Non-passphrase?

Next is, how long would it take to memorize it without tools / helpers? What helpers did you use?

Lastly, how many masters do you have? How closely they are related?

Related, also. How about numerical PINs?
100 algos in 100 days (Day 3)
Published: 2021-06-04 19:31:53

##The stolen breakfast drone

i.e. find-unique-int-among-duplicates

Struggling a bit today given quite a busy work day learning about azure blobs and functions... but no excuses!

Brute Force (o(n))
Add the integers to a set.  
If the set has it already = it is a duplicate => remove it. Will be left with the sole unique.

How can you do this with bit manipulation? The answer is using XOR - super cool! 
<code>^=</code>
This allows for o(1)
How to put pom.xml version and build date in properties?
Tags: java, maven, webapp
Published: 2021-06-04 19:27:55

While working on webapp API in Java I need to send the app version and the build date to the frontend. But how to make this? 

As my API build is based on maven I thought about getting version from `pom.xml` file. So, let's make it this way!


## Solution! Almost...

I need to put in the `pom.xml` file configuration responsible for resources filtering:

```xml
<build>
 <!-- clipped -->
   <resources>
     <resource>
       <directory>src/main/resources</directory>
       <filtering>true</filtering>
     </resource>
   </resources>
</build>
```

And in the `app.properties` properties which will be replaced during build:

```properties
build.version=${pom.version}
build.date=${timestamp}
```

After the build my `app.properties` is filled with expected data:

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

Now I can access version from POM and last build in Java app easily!

## And fin^H^H... another problem?

Everything works smoothly, I can get the version from the `pom.xml` and also the build date. But... a favicon is now broken! What?!

Frontend is deployed along with backend (using [Javalin static files feature](https://javalin.io/documentation#static-files) and files were loaded from resources folder.

It turns out that the resource filtering plugin processe `favicon.ico` (in fact all `.ico` files) and broke them by saving them incorrectly. So I need to exclude those files from filtering!


## Final solution

Final configuration in the `pom.xml` looks like in snippet below. 

It processing all files in `src/main/resources` except all `.ico` files. But I want `.ico` in resource folder - so I need add them but without filtering (processing them).

```xml
<build>
 <!-- clipped -->
   <resources>
     <resource>
       <directory>src/main/resources</directory>
       <filtering>true</filtering>
       <excludes>
         <exclude>**/*.ico</exclude>
       </excludes>
     </resource>
     <resource>
       <directory>src/main/resources</directory>
       <filtering>false</filtering>
       <includes>
         <include>**/*.ico</include>
       </includes>
     </resource>
   </resources>
</build>
```

And that's all - everything is now OK ;-)
Move files from Google Cloud Storage to Azure Blob Storage programmatically
Tags: azureblobstorage, googlecloudstorage, file, movedata
Published: 2021-06-04 18:59:15

Copying files from Google Cloud Storage to Azure Blob Storage programmatically can be achieved by streaming the data directly from cloud storage to blob storage. We will be using google cloud storage and azure storage client libraries for java in this blog.

Streaming allows to transfer the data without requiring the file to be saved first. Saving the entire file in memory and then writing it to the destination can exhaust the memory leading to OutOfMemoryError if the file is large. Instead, we will iterate through and read some bytes at a time, do some processing and clear them.

###ReadChannel
ReadChannel, extended from java.nio.channels.ReadableByteChannel, is a reading channel for reading object’s content. Cloud storage client library comes with a reader method which returns ReadChannel to read blob’s content

###BlobOutputStream
BlobOutputStream is a stream for writing into azure blob storage. It is extended from java.io.OutputStream

**Maven dependencies**
`<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-storage</artifactId>
<version>1.70.0</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-storage</artifactId>
<version>8.4.0</version>
</dependency>`
(keyvault and azure active directory dependencies will be required for retrieving sas token)

**Get Storage service object**
`StorageOptions options = StorageOptions.newBuilder().setProjectId(projectId).setCredentials(GoogleCredentials.fromStream(new FileInputStream(jsonKeyPath))).build();
Storage storage = options.getService();`

**Get CloudBlockBlob instance**
// assuming sas token is retrieved from Azure keyVault
`CloudBlockBlob cloudBlob = new CloudBlockBlob(new URI(contentUri + sasToken));`

**Stream data**
`try (ReadChannel reader = storage.reader(bucketName, blobPath);
BlobOutputStream outputStream = blob.openOutputStream()) {
ByteBuffer bytes = ByteBuffer.allocate(64 * 1024);
while (reader.read(bytes) > 0) {
bytes.flip();
outputStream.write(bytes.array());
bytes.clear();
}
} catch (Exception e) {
// handle
}
}`
Γέφυρα για σύνδεση εμπορικού με eshop (πχ Opencart με Pylon) 
Published: 2021-06-04 18:50:25

Συχνά η ενημέρωση του ηλεκτρονικού καταστήματος γίνεται πονοκέφαλος όταν έχουμε τα είδη μας σε εμπορικό πρόγραμμα και θα πρέπει να ενημερώνουμε τα αποθέματα στο e-shop και αντίστροφα.


Ακόμη περισσότερο όταν έχουμε όλα τα είδη μας στο εμπορικό και θα πρέπει να τα περάσουμε στο νέο ηλεκτρονικό κατάστημα.

Εκτός από τα παραπάνω, έχουμε και τις παραγγελίες. Κάθε παραγγελία που ολοκληρώνεται στο ηλεκτρονικό κατάστημα, θα πρέπει να την καταχωρούμε και στο εμπορικό για να έχουμε σωστές αναφορές πωλήσεων και σύνολα.


Εδώ έρχεται να δώσει λύση η λεγόμενη 'Γέφυρα'. Τι ονομάζουμε Γέφυρα και πώς λειτουργεί;

Η Γέφυρα είναι ένα λογισμικό που επιτρέπει την διασύνδεση του εμπορικού με το eshop. Το λογισμικό αυτό μπορεί να είναι Windows software η Web service.


Πως λειτουργεί μια Γέφυρα;

Η Γέφυρα προγραμματίζεται να ενημερώνει σε τακτά χρονικά διαστήματα τα αποθέματα, τα είδη και τις κατηγορίες, έτσι το ηλεκτρονικό κατάστημα είναι πάντα ενημερωμένο με βάση το εμπορικό.

Το σύστημα αυτό λειτουργεί όμως αμφίδρομα, ενημερώνει από το εμπορικό όταν γίνεται μια παραγγελία στο eshop, εισάγοντας την και στο εμπορικό. Με αυτόν τον τρόπο και το εμπορικό καθώς και το ηλεκτρονικό κατάστημα είναι πάντα ενημερωμένα.


Σε περιπτώσεις λοιπόν που το εμπορικό δεν διαθέτει κάποιο API η κάποιον αυτόματο τρόπο εξαγωγής και εισαγωγής δεδομένων (χωρίς ανθρώπινη ενεργεία), τότε συνήθως υλοποιούμε ένα windows software που αναλαμβάνει να συνδεθεί με την βάση δεδομένων του εμπορικού και να εισάγει και να αντλεί δεδομένα (προϊόντα, παραγγελίες κλπ).


Συνοπτικά τα πλεονεκτήματα μια Γέφυρας:

Αυτόματη εισαγωγή προϊόντων από το εμπορικό στο eshop.

Αυτόματη ενημέρωση προϊόντων και αποθεμάτων.

Αυτόματη αποστολή παραγγελιών από το eshop στο εμπορικό.

Δυνατότητα εισαγωγής προϊόντων με συνδυαστικά χαρακτηριστικά-επιλογές, όπως χρώμα-μέγεθος, με ξεχωριστό απόθεμα ανά συνδυασμό.


Η εταιρία μας, με εμπειρία στην υλοποίηση παρόμοιων εργασιών, αναλαμβάνει την δημιουργία Γέφυρας για όλων των τύπων εμπορικά και ηλεκτρονικά καταστήματα.

https://www.forgedsoft.com/blog/gefyra
Convertendo Números Romanos em Arábicos com c#
Tags: csharp, dotnet
Published: 2021-06-04 18:48:21

Um tempo atrás eu fiz uma entrevista para uma consultoria onde uma das etapas era um code challenge "ao vivo" com outra pessoa seguindo a dinâmica de eu ter que ir falando como eu iria construindo o raciocínio lógico da tarefa em questão. 

Segue a minha resolução:
{% gist https://gist.github.com/brunosalmeida/5a1ac80969159ce7b734cb34609b4cd4.js %}

Minha linha de raciocínio foi dividida em 3 partes:
 - Começar como os casos mais simples, ou seja converter os números que representam uma letra só (ex: X é 10, V é 5).
 - Traduzir os números composto por duas letras em que os valores são somados (ex: XV é 15). 
 - Converter os números cujo a ordem é subtrair o valor correspondente a letra ao invés de somar (ex: IV é 4)

Tendo quebrado o problema em problemas menores eu comecei por criar as coisas que eu iria precisar. E a primeira delas foi criar uma estrutura de "de para" do algarismos romanos para números. E foi o que eu fiz com o tipo Dictionary que me permite criar uma estrutura de chave-valor onde as chaves seriam os números romanos e os valores o números arábicos. 

Então se eu quisesse o número 5 bastava eu pedir ao dicionário o valor da chave "V" e assim por diante.
Como os números romanos são na verdade letras eu resolvi transformar o algarismo romano digitado num array de chars assim eu poderia navegar sob eles e pegar um de cada vez. Por exemplo se o valor digitado fosse "XV" eu teria que percorrer essa string pra pegar primeiro X e depois o V.

Usando o for para percorrer o array até o final eu tenho 3 validações:
- Na primeira eu valido se index usado para o controle do for é igual ao tamanho do array. Eu faço isso para poder saber se é a última ou a única posição do array. Se for eu recupero o numero referente a letra no dicionário e somo a uma variável que armazena o resultado final e termino o loop.
- Se a primeira validação é falsa eu armazeno a número arábico correspondente em uma variável assim como o próximo valor depois deste. Ex: "XV" eu armazeno o valor correspondente de X e de V e as comparo.
- Se o valor arábico do próximo algarismo romano for menor que o valor arábico do atual eu tenho que subtrair o mesmo da variável que guarda o resultado final. Caso contrário eu somo o valor atual a variável que guarda o resultado final.
Exhaustive pattern matching in TypeScript
Tags: typescript
Published: 2021-06-04 18:32:48

The switch statements does not enforce exhaustive pattern matching (objective), the syntax is incredibly ugly (subjective) and is a poorly designed language feature (arguably objective). Thankfully, we can eliminate the shortcomings of the switch statement and improve the quality of our code using pattern matching instead.

There is a TC39 Stage 1 pattern matching proposal for the curious types [here](https://github.com/tc39/proposal-pattern-matching).

-----


# Example 1 (simple):

Say you have a string literal union type:
```typescript
type Icon = "chart" | "file-check" | "paper-plane" | "users";
```

and you want to conditionally render the appropriate icon so your first approach is the old trusted switch statement:

```tsx
const renderIcon = (icon: Icon): JSX.Element => {
  switch (icon) {
    case "chart":
      return <ChartIcon />;
    case "file-check":
      return <FileCheckIcon />;
    case "paper-plane":
      return <PaperPlaneIcon />;
    case "users":
      return <UsersIcon />;
  }
};
```

Here, the function's explicit return type is our only saving grace so to speak — not the switch statement itself. If we were to instead use the implicit return type of `JSX.Element | undefined` and then forget a case, the TypeScript compiler would not yell at us. I would therefore argue as a developer I have failed my current task as well as preventing those behind me from introducing bugs because I did communicate my intent clearly — this function needs to account for **all** possibilities, return a `JSX.Element` and have zero side effects. 

We can refactor this using a library called [ts-pattern](https://www.npmjs.com/package/ts-pattern) to achieve that intent.

```tsx
const renderIcon = (icon: Icon): JSX.Element => {
  return match(icon)
    .with("chart", () => <ChartIcon />)
    .with("file-check", () => <FileCheckIcon />)
    .with("paper-plane", () => <PaperPlaneIcon />)
    .with("users", () => <UsersIcon />)
    .exhaustive();
};
```

# Example 2 (advanced):

Say you have a branded type / discriminate union type / tagged union type:
```typescript
type V1Report = {
  id: string;
  results: { /* whatever */ },
  year: string;
}

type V2Report = {
  id: string;
  results: { /* whatever */ },
  year: string;
}

type Report = { tag: "v1", value: V1Report } | { tag: "v2", value: V2Report }

// later in some function
match(report)
  .with({ tag: "v1" }, (v1Report) => /* do something with report */)
  .with({ tag: "v2" }, (v2Report) => /* do something with report */)
  .exhaustive()
```
How to create a function component in react
Tags: react, webdev, tutorial, beginners
Published: 2021-06-04 18:29:10

Below are the two ways of creating function component.
``` javascript
import React from "react";
function FirstComponent() {
 
  return (
    <div >
      <h1>Hello react!!!</h1>
    </div>
  );
}
export default FirstComponent
```
or 
The below code is using *arrow function* for creating function component.

``` javascript
import React from "react";
const FirstComponent = () => {
  return (
    <div >
      <h1>Hello react!!!</h1>
    </div>
  );
}
export default FirstComponent
```
The above two function components can be imported *without enclosing the component name inside curly braces* because *default* has been used with *export*.

**Note:** *There can be only one default export per module.*

`export default FirstComponent`
 
`import FirstComponent from "FirstComponent"`

But if there is only *export* in front of a function component  then the import requires curly braces around the component's name.

`export const FirstComponent = () => {}`

`import {FirstComponent} from "FirstComponent"`
Fix: SVG Colors not working properly
Tags: webdev, javascript, html, image
Published: 2021-06-04 18:18:42

We were trying to change the color of an svg. But our initial images were not of the same color. After a while we figured out the best way would be to force them to an initial color and then do filtering. 

Here is how our plain svgs looked 
![Plain SVGs](https://res.cloudinary.com/dycur35xt/image/upload/v1622830947/assd_nmalcd.png)

Here is our code 

```
<img 
src={item.icon} 
style=
{{ 
    height: "100%", 
    width: "auto", 
    borderRadius: "10px", 
    display: "block", 
    filter: "brightness(0) saturate(100%) invert(31%) sepia(82%) saturate(6098%) hue-rotate(256deg) brightness(93%)" 

}} />
```

The brightness(0) and saturate(100%) turn the image to black.
💡 React Hooks: async function in the useEffect
Tags: react, javascript, webdev, programming
Published: 2021-06-04 17:58:09

When you're new to React Hooks, you may notice that you get warnings and bugs if you use an async function inside the useEffect Hook. Let's find out why this happens. 

There are dozens of articles and [issues](https://stackoverflow.com/questions/53332321) about how to use async in the React Hooks:



# Why is this happening?

[Async functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) always return a promise so you will not have the actual value until the Promise is fulfilled.

### Anti-Pattern: async function directly in the useEffect
React can run this async function but can not run the cleanup function.
Don't use raw async function directly in the useEffect.

```javascript
useEffect(async () => {
  console.log('Hi :)')

  return () => {
    console.info('Bye!') // It won't run
  };
}, []);
```

### Code example: using unmount in async functions.

You don't have to unmount callback unless you use await expression before it.
```javascript
unmount = await (async () => {
  console.log('Hi :)')

  return () => {
    console.info('Bye!')
  };
})()
unmount()
// Hi :)
// Bye!
```


### Code example: using unmount in a function.

```javascript
unmount = (() => {
  console.log('Hi :)')

  return () => {
    console.info('Bye!') // 👍 
  };
})()
unmount()
// Hi :)
// Bye!
```


### Code example: using async function in the useEffect.
You can create an async function in the useEffect callback, as Nick mentioned in [his article](https://dev.to/stlnick/useeffect-and-async-4da8).

```javascript
  useEffect(() => {
    (async () => {
      const products = await api.index()
      setFilteredProducts(products)
      setProducts(products)
    })()

    return () => {
      unsubscribeOrRemoveEventHandler() // 👍 
    }
  }, [])
```

I hope you find this article useful.