teleren/devto huggingface dataset:
Mechanical Keyboards - I get it now
Published: 2022-07-13 18:33:43

---
title: Mechanical Keyboards - I get it now
published: true
date: 2022-06-22 16:03:33 UTC
tags: 
canonical_url: https://alex.party/posts/2022-06-22-mechanical-keyboards-i-get-it-now/
---

So a couple of months ago I purchased 2 of ["The Key v2"](https://drop.com/buy/stack-overflow-the-key-v2-macropad) as an impulse purchase. I got a link to it a couple of minutes before the link went out to everyone, and so I pulled a Phillip J. Fry.

![Phillip J. Fry from the tv show Futurama thrusting a handful of cash while saying "Shut up and Take my Money"](https://alex.party/uploads/takemymoney.jpeg "We've all been here.")

They arrived yesterday, and so i plugged one in. The joke about these keyboards is that they have 3 buttons: Control, C, and V. Everything a good programmer needs to copy and paste from stack overflow. However, these boards run QMK, which allows the keyboard to be reflashed with updated key mappings.

While I have multiple mechanical keyboards, none of them are reprogrammable. I had always figured it'd be too much effort to customize a keyboard, and do you really want to keep up with it? Boy howdy was I wrong.

I get it now.

I currently have my little 3 button keyboard set up with multiple layers acting as media keys, as well as space for other future functions. Now I am going to be looking more at keyboards where I can permanently remap my caps lock key to function the way I like it to. (If you tap capslock it functions as f24. If you hold it down it becomes the ["hyper key"](https://medium.com/@Brovalex/superpower-the-caps-lock-key-28be84869cb))

Originally Posted as [Mechanical Keyboards - I get it now](https://alex.party/posts/2022-06-22-mechanical-keyboards-i-get-it-now/) at alex.party
Implementing Worker Pools in Kotlin to upload Images over WebDav to a Hetzner StorageBox
Tags: kotlin, springboot, webdev, programming
Published: 2022-06-22 16:02:56

# Worker pools
Recently while doing a project with Go I came across Worker Pools on [GoByExample](https://gobyexample.com/worker-pools) to do parallel processing. I didn't find many resources for implementing Worker Pools in Kotlin, but it seemed a good idea for my current Spring Boot + Kotlin webapp.

# Kotlin
Kotlin uses coroutines for concurrency which are fairly similiar to goroutines.

Coroutines use structured concurrency to delimit the lifetime of each coroutine to a certain scope.

To be able to create a workergroup we need to create a coroutinescope that is persistent over the livetime of our application. We achieve this behaviour with the SupervisorJob() context.

```
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
```

We then create a buffered channel as queue for our image data and the url where we want to upload it.

```
val channel = Channel<Pair<String, ByteArray>>(10000)
```

I'm using the Spring @PostConstruct annotation to create the worker group and listen to the channel for new data.
Each time a item is in the queue we launch the upload function, if no item is in the queue the function is suspended.

```
@PostConstruct
    fun createWorkerGroup() {
        coroutineScope.launch {
            for (x in 1..5) {
                launch {
                    println("Create Worker $x")
                    while (true) {
                        uploadImage(channel.receive())
                    }
                }
            }
        }
    }
```

Finally we can send our data to our channel inside a runBlocking coroutine scope:

```
runBlocking {
  uploadService.channel.send(Pair(url, image.bytes))
}
```


# WebDav

In my webapp users upload images from their mobile phone to my webserver, afterwards I want to upload these pictures to a [Hetzner Storage Box](https://www.hetzner.com/storage/storage-box) over webdav as a cheap alternative to an S3 object storage.

I use the [sardine](https://github.com/lookfirst/sardine) java webdav client library for its simplicity.

The usage is very straightforward, you configure the client with:

```
val sardine = SardineFactory.begin("webDavUsername", "webDavPassword")
```

The uploadImage Function is called every time a new image is sent over the channel we created earlier. In this function we call sarding.put() to save the image file.

```
sardine.put("https://username.your-storagebox.de/foldername/imagename.jpg", ImageByteArray)
```

That is all we need to have a highly parallel File Service

You can view the Sourcecode at Github: [UploadService.kt](https://github.com/tschuehly/weddingGame/blob/master/src/main/kotlin/de/tschuehly/weddingGame/service/UploadService.kt#L40=) [ImageService.kt](https://github.com/tschuehly/weddingGame/blob/512ace07fa1d0a57253b63bbb5cbf5ab3880e151/src/main/kotlin/de/tschuehly/weddingGame/service/ImageService.kt#L19)
Program Error Signals
Tags: computerscience, beginners, programming, tutorial
Published: 2022-06-22 16:01:19

**Signals in computers are a way of communication between the process and the OS.** When a running program undergoes some serious error then the OS sends a signal to the process and the process further may not execute. Some processes may have a signal handler that does some important tasks before the process leaves the CPU. 

Error signals generally cause termination of the program and a core dump file is created named core, which stores the state of the process at the moment of termination. This file can be investigated using the **debugger** to know the cause of program termination. 

## SIGFPE – 
This error signal denotes some arithmetic error that occurred like division by zero, or floating-point error.

## SIGILL –
 
This signal denotes illegal instruction. When a garbage instruction or instruction that a program has no privilege to execute, is executed then this signal is generated. 

## SIGSEGV – 
The signal is generated when a process tries to access a memory location not allocated to it, like de-referencing a wild pointer which leads to a “segmentation fault”.

## SIGBUS – 
The name is an abbreviation for “Bus error”. This signal is also produced when an invalid memory is accessed.

## SIGABRT – 
If an error itself is detected by the program then this signal is generated using call to abort(). This signal is also used by the standard library to report an internal error. assert() function in c++ also uses abort() to generate this signal.


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

## SIGSYS – 
This signal is sent to process when an invalid argument is passed to a system call. 

## SIGTRAP – 
This signal is sent to process when an exception has occurred. This is requested by the debugger to get informed. For example, if a variable changes its value then this will trigger it. 

Thanks for reading
Hope you will find it helpful
Welcome Thread - v179
Tags: welcome
Published: 2022-06-22 15:58:58

---
title: Welcome Thread - v179
published: true
description: Welcome to DEV! A thread of hellos and intros.
tags: welcome
canonical_url: 
---

![The word "Hi" is shown in multiple colors and bouncing around](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hm27w0urxaql0yd8tla0.gif)

### Welcome to DEV!

1. Leave a comment below to introduce yourself! You can talk about what brought you here, what you're learning, or just a fun fact about yourself.

2. Reply to someone's comment, either with a question or just a hello. 👋 

**Great to have you in the community!**
V8 Isolates are taking over the world
Tags: webdev, javascript, serverless
Published: 2022-06-22 15:54:03

# V8 Isolates are taking over the world

Cloudflare Workers with Vercel

Deno Deploy with Netlify and Supabase

Oxygen (from Shopify)



All of these companies have something in common. You guessed it, they all use V8 Isolates for one of their product.

You might be thinking, what are those "V8 Isolates" this guy is talking about? Well, let's read this explanation from [Cloudflare](https://developers.cloudflare.com/workers/learning/how-workers-works/):

> V8 orchestrates isolates: lightweight contexts that provide your code with variables it can access and a safe environment to be executed within. You could even consider an isolate a sandbox for your function to run in.

It's cheaper to run a code within an Isolate than a container or a virtual machine, both in terms of time and resources. It's faster to start an Isolate than Node.js. It costs less to run a single process running multiple Isolates, than running multiple processes. It's being used by more and more big companies.

---

So, what are the drawbacks?

Honestly, I didn't found a lot.

The most obvious one is that its usage to run client-provided JavaScript is still fairly recent compared to containers and virtual machines. The ecosystem is not yet mature, even tough there's more and more [funding](https://deno.com/blog/series-a).

The second I can think of is that every company is implementing its own runtime, with its own APIs, duplicating the work. Luckly, a community group was created, initiated by Cloudflare and Deno, named [WinterCG](https://wintercg.org/).

It aims to

> provide a space for JavaScript runtimes to collaborates on API interoperability.

This is a way to provide a unified API for all those new runtimes, but I'm still sad that none of them is open-source (Cloudflare announced few months ago that their [runtime will be open-source](https://blog.cloudflare.com/workers-open-source-announcement/), but that's not yet the case).

---

That's why I started working on an open-source platform named [Lagon](https://github.com/lagonapp/serverless), aiming to provide a cloud-based and self-hosted version of a Serverless Runtime for running JavaScript and TypeScript. I want to give the community a really good software, even tough it requires a lot of work to do so.

Here is the GitHub repository if you want to take an early look: [github.com/lagonapp/serverless](https://github.com/lagonapp/serverless)

I would love to know if this idea seems interesting for anyone, so feel free to leave your tought in the comments. I'm convinced that even more amazing products using V8 Isolates will be released in the future. Long live to Isolates!
Tips to Optimize Backend Performance
Tags: api, programming, architecture, performance
Published: 2022-06-22 15:53:50


As the number of users/requests of an application increases, it becomes important that it maintains its performance.

Let's look at a few improvements that we can do to enhance application performance.


## Query Optimization

Make database queries more efficient using one of these ways:

- Use only indexed columns in a query
- Make fewer database calls by using joins when advantageous.
- Use a query cache to avoid making duplicate queries.

## Caching

Use a cache(distributed or local) to store data that is frequently accessed. This may include:

- results of database queries
- results of expensive computations
- responses to frequent idempotent requests

## Database optimization

Don't just optimize the queries, also optimize the way data is being stored.

- Use indexes to make queries faster
- Use normalization to clean up data, separate data into meaningful chunks, or make it easier to query
- Alternatively, use denormalization when possible to reduce the need to use joins for tables always queried together.
- If using NoSQL, make use of shards and partitions for faster lookup.

## CDN

CDNs are content delivery networks that provide content to the user.

The main use of CDNs is to serve static content such as images, CSS, and JavaScript from locations that are geographically close to the user.

They can also serve dynamically generated content including:

- JSON data in GET requests which does not change frequently with respect to its URL
- HTML content that is generated on the server-side

## Fail fast

Make sure your application does not spend time processing bad requests.

- Validate requests as soon as they are received
- Use rate limiting and deduplication to avoid DDoS attacks. 
- If calling other services, use a circuit breaker to prevent cascading failures

## Keep the network light

Use lighter request and response formats to reduce the amount of data that is sent over the network.

- Use PATCH requests instead of PUT if updating small parts of a resource
- Prefer JSON over XML because of the compactness of the format.
- Use the GraphQL approach if querying large amounts of data but need only specific values back.
- Use compression for APIs which return large sizes (MBs) of data.

---

Thanks for reading. This should give you some ideas which you can implement in your low-level design to optimize performance. 

These are only some of the popular techniques. Feel free to add any of your advice in the comments. If you want to connect with me, you can find me on [Twitter](https://twitter.com/abh1navv)
Dark side of WWW glossary
Tags: programmingmemes
Published: 2022-06-22 15:44:36

<u>Dark glossary</u> :
**fatal** (_e.g. fatal error_) – something about death?..
**zombie** process – something horrifying?..
**orphan** process – sad part of one's life
**terminate** process – make life of the program 'softwarelly' dead

Did I missed anything, please leave comment below
How to debug a Time Trigger Azure Function Locally
Tags: azure, programming, csharp, productivity
Published: 2022-06-22 14:56:50

Very often I have to develop timer triggered Azure Function with C#.
To optimize the development time, of course, it is not possible to wait every time the timer (especially if the timer is every morning at 7:00AM 🙂).

Let's see how we cannot waste our time waiting the trigger but launch an Azure Function time triggered instantly.

## Solution
The default method of an Azure Function has a parameter called "RunOnStartup" hidden by default.
If you want to run the Azure Function at the startup, set it to true and launch the debug session again.

```csharp
[FunctionName("Function1")]
public void Run([TimerTrigger("0 */5 * * * *", RunOnStartup = true)]TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}
```

By the way, in this case the function will be launched also in the production environment when you restart the Azure Function or when you deploy a new version of the function.
To prevent that, you can use the conditional compilation directive in the function method.

```csharp
#if DEBUG
     RunOnStartup= true
#endif
```
Below you can find the full code with the compilation directive for the debug exception.

```csharp
[FunctionName("Function1")]
public void Run([TimerTrigger("0 */5 * * * *", 
#if DEBUG
     RunOnStartup= true
#endif    
)]TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}
```

That's all folks!
Happy debugging. 🦸
Standard Queues vs FIFO Queues no AWS SQS
Tags: aws, sqs
Published: 2022-06-22 14:51:40

Este artigo pretende ser mais um da série de resumos para aqueles que pensam em fazer o exame de AWS Certified Cloud Practitioner. Mais informações encontram-se ao fim do artigo. O assunto desse artigo é Mensageria no AWS.

# **Introdução**
Amazon SQS(Simple Queue Service) é um serviço de mensageria oferecido pela AWS com o objetivo de permitir, numa arquitetura de microsserviços, o desenvolvedor a dissociar os componentes do seu aplicativo para que eles possam funcionar e falhar de forma independente.

# **Vantagens de seu uso:**
* Libera o desenvolvedor do trabalho de gerenciar seu próprio sistema de fila de mensagens;
* Permite o envio, recebimento e armazenamento de mensagens entre componentes
* Aumenta a tolerância a falhas do seu aplicativo.
* Permite o compartilhamento de dados confidenciais entre componentes usando criptografia
* Dimensiona com eficiência à medida que seu aplicativo cresce

# Tipos de filas
1. Standard Queue 
2. FIFO Queue

A Standard Queue é o tipo de fila padrão oferecido pelo AWS SQS. Suas características são: 
* Número quase ilimitado de transações por segundo por chamada de API
* Best-effort ordering, em outras palavras tentativa de sempre entregar as mensagens na ordem em que foram recebidas, porém pode ocasionalmente enviar mais de uma cópia da mensagem enviado fora de ordem
* Garantia de que a entrega da mensagem ocorrerá pelo menos uma vez.

Já a FIFO Queue (first in first out) é um tipo mais aprimorado de fila. Suas características são:
* Limitadas a 300 transações por segundo por chamada de API sem lote e 3000 mensagens com lote (quando você agrupa 10 mensagens (máximo) por operação)
* Garantia de entrega das mensagens na ordem recebida
* Garantia de que a entrega da mensagem ocorrerá apenas uma vez e permanecerá disponível até que um consumidor a processe e a exclua. Duplicatas não são introduzidas na fila

Os casos de uso ideais para cada um dos tipos são:
* Standard: Casos em seja mais importante a quantidade de transações por chamada de API do que a entrega na ordem e a ausência de duplicatas 
* FIFO: Casos em que seja extremamente importante a entrega na ordem e a ausência de duplicatas

Mais informações:
https://aws.amazon.com/pt/sqs/
Introduction to Data Structures and Algorithms
Published: 2022-06-21 07:06:46

Data structures are forms of collecting data in computer memory for efficient storage and performance of various operations. Data structures allow us to organize different kinds of data using the most appropriate and efficient approach. We have either primitive or abstract data structures. Primitive data structures include Integers, Boolean, Float, or Char types. Abstract data types are more complex and ideal for storing large data sets with underlying connections and relationships. Examples of Abstract data structures are Stacks, Queues, Linked List, Graphs, and Trees.


An algorithm is a set of instructions a computer follows to solve a specific problem. These instructions are logical and solve either a single or several predefined tasks. Algorithms must satisfy the following properties:   

- **Input**: should accept 0 or more inputs 
- **Output**: should give back an output
- **Definiteness**: should have clear and well-defined steps 
- **Finiteness**: should have a finite number of steps 
- **Correctness**: Algorithm steps should generate correct outputs 

Algorithms make use of appropriate data structures to solve problems. Because computer resources are finite, algorithms aim to be efficient and fast. Fast and efficient algorithms take less time to execute and consume less space in memory. Therefore, an algorithm's performance is measured based on its corresponding time and space complexity. 

Computer systems and solutions may process large numbers of inputs. Given the limit in computer resources such as memory and time, algorithms design aims to allow the software to scale with increasing inputs gracefully while remaining performant. 

Often, different algorithms are available to implement a solution. The most efficient algorithm is, however, always preferred. Efficient and fast algorithms ensure the best use of computer resources. An understanding and mastery of data structures and algorithms allow a computer programmer to write efficient solutions, optimize inefficient algorithms, and write software solutions that can scale predictably.
Pros and Cons of Graph Databases Vs. Alternatives
Tags: discuss, architecture, design
Published: 2022-06-22 14:38:13

What is your opinion of graph databases when compared to SQL databases and traditional noSQL databases (excluding graph DBs)? What are the pros and cons of usage of a graph DB such as neo4j? How does it stand up to different use-cases such as representation of timeseries data? What are the pros and cons of each DB alternative?
Day 2 : 100DaysOfSwift🚀
Tags: ios, 100daysofcode, swift, beginners
Published: 2022-06-22 14:07:12

Day 2 :

## arrays, sets, Tuples, dictionaries and enums

1.Swift’s strings, integers, Booleans, and Doubles allow us to temporarily store single values, but if you want to store many values you will often use arrays instead.

An array stores values of the same type in an ordered list.

```
var Names: [String] = ["Saurabh","Sachin"]
```

Array position start with 0,so if you want to read sachin then

```
Name[1]
```

2. Sets are unordered collections of unique values.

```
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

or 

var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]


```

If you try to insert a duplicate item into a set, the duplicates get ignored. 

```
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop","Rock","Classical"]
```
You can create set from Array

```
var Names= set(["Saurabh","Sachin"])
```

3.Tuples are created by placing multiple items into parentheses, like this:

```
var name = (first: "Taylor", last: "Swift")

```
access item from tuple

```
name.0
or
name.first
```
Remember, you can change the values inside a tuple after you create it, but not the types of values.So, if you tried to change name to be (first: "Justin", age: 25) you would get an error.

4.A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering

```
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
```
5.According to the Swift documentation enumeration is defined as “a common type for a group of related values and enables you to work with those values in a type-safe way within your code”. 
for more details about enum [Click Here..](https://codewithchris.com/swift-enum/)

6.Creating empty collections
Arrays, sets, and dictionaries are called collections, because they collect values together in one place.
Empty Dictionary

```
var teams = [String: String]()
```
we can add

```
teams["Paul"] = "Red"
```

empty Array

```
var results = [Int]()
```
empty set

```
var words = Set<String>()
var numbers = Set<Int>()
```
Calc()
Tags: webdev, beginners, programming, tutorial
Published: 2022-06-22 14:06:32

When I use the calc function in css like this (40em / 2) as a padding value do you know that the units 40em scale twice for instance I have this code:

<header>
<h1> Click on me</h1>
</header>
Now I use css
Header{
Font-size: 5px
}
H1{
Padding:calc(40em / 2)
} 
Now the 40em unit scale twice 40*5 twice that is 200+200\2
The padding value give us 200 why must the em scale twice that is my question to any of my seniors who could help me figure this out
A Blogging Web You Can Share Everything to People | My React Project
Tags: webdev, javascript, programming, react
Published: 2022-06-22 13:53:43

[https://monkey-blogging-iota.vercel.app/](https://monkey-blogging-iota.vercel.app/) 
This is my recent React Project. I am in university now and I have just started coding for over 6 months.
I am just a beginner so If you have some ideas or feedbacks. Don’t be shy, comment below. I appreciate that so much ❤️