teleren/devto huggingface dataset:
Dive head-first into $770+ of programming eBooks
Tags: python, webdev, android, javascript
Published: 2021-04-19 19:14:36

[Humble Book Bundle: Head First Programming by O’Reilly](https://www.humblebundle.com/books/head-first-programming-oreilly-books?partner=indiekings)

Dive head-first into learning to program! Learn to master the mechanics of programming in Java, Python, Go, C, and more with our newest bundle, courtesy of O’Reilly! Get ebooks like Head First Python, 2nd Edition, Head First C, Head First C#, 3rd Edition, and Head First Java, 2nd Edition. Plus, your purchase will support Code for America!

Pay CA$1.25 or more. Normally, the total cost for the eBooks in this bundle is as much as US$772. You choose the price and increase your contribution to upgrade your bundle! This bundle has a minimum CA$1.25 purchase.

Read them anywhere. The eBooks in this bundle are available in PDF, MOBI, and ePub formats, so they work on your computer, e-readers, iPads, cell phones, and a wide array of mobile devices!

Support charity. Choose where the money goes — between the publisher and Code for America via PayPal Giving Fund.
Go - how to create a JSON body with an array (slice) of maps?
Tags: help, go
Published: 2021-04-19 19:12:59

I'm learning Go and am trying to build a JSON request body of this shape the `name` values are created dynamically based on a provided string. The JSON looks like this based on the input string `"joan,john"`

```json
{
    "reviewers": [
        {"user": {"name": "joan"}},
        {"user": {"name": "john"}}
    ]
}
```

I've searched how to build a slice of maps and have put together the code below but am getting complier errors. Where are am I going wrong? 

```go
type HTTPRequestBody struct {
    Reviewers ReviewersArray `json:"reviewers,omitempty"`
}

type ReviewersArray struct {
    Rs []struct {
        Users User
    }
}

type User struct {
    User Name `json:"user`
}

type Name struct {
    Name string `json:"name`
}

func addReviewers(reviewers string) *ReviewersArray {
    reviewersSplit := strings.Split(reviewers, ",")
    rArray := &ReviewersArray{}
    for _, r := range reviewersSplit {
        u := &User{User: Name{Name: r}}
        // Error: cannot use u (variable of type *User) as struct{Users User} value in argument to append
        rArray.Rs = append(rArray.Rs, u)
    }
    return rArray
}

func main() {
    testReviewers := "joan,john"

    prReviewers := addReviewers(testReviewers)
    requestBody := &HTTPRequestBody{
        // Error: cannot use prReviewers (variable of type *ReviewersArray) as ReviewersArray value in struct literal
        Reviewers: prReviewers,
    }

    jsonData, _ := json.MarshalIndent(requestBody, "", "  ")
    fmt.Println(string(jsonData))
}
```
Transparently serialize and deserialize ValueObjects to JSON
Tags: rails, json, valueobject, 5days5blogposts
Published: 2021-04-19 19:03:16

This is the way I choose when I want to serialize and deserialize  _ValueObjects_ transparently to JSON in Rails app

### Put serialization methods into module
```ruby
module ValueObjectJsonSerialization
  def to_json(*args)
    #override AtiveSupport to_json extensions if active
    args = JSON::SAFE_STATE_PROTOTYPE.dup if args == []
    {
      :json_class => self.class.to_s,
    }.merge(as_json).to_json(*args)
  end

  def as_json(_=nil)
    # unused argument to satisfy ActiveSupport as_json signature
    { :json_class => self.class.to_s }.merge(_as_json)
  end
end

```
### Use them in your ValueObject class and make it transparently serializable

```ruby
class PublicationDate
  include ValueObjectJsonSerialization
  def initialize(y, m=nil, d=nil)
    @y, @m, @d = y, m, d 
  end
  
  def self.json_create(h)
    new(h['y'], h['m'], h['d'])
  end

  def _as_json
    { y: @y, m: @m, d: @d }.compact
  end
end
```

### DEMO
```
require 'json'
[9] pry(main)> PublicationDate.new(2021, 4)
=> #<PublicationDate:0x00005652cd6a5c40 @d=nil, @m=4, @y=2021>
[10] pry(main)> PublicationDate.new(2021, 4, 19).to_json
=> "{\"json_class\":\"PublicationDate\",\"y\":2021,\"m\":4,\"d\":19}
[11] pry(main)> JSON.load PublicationDate.new(2021, 4, 19).to_json
=> #<PublicationDate:0x00005652cd717d18 @d=19, @m=4, @y=2021>
```
Insertion sort
Tags: ruby, sorting, algorithms
Published: 2021-04-19 19:01:15

The best analogy for insertion sort is a deck of cards. And you need to put them in the right order from smallest to greatest. You hold at least one card constant while you move the other cards around it to sort everything into order. The element that you considering could be moved one spot or over multiple spots.


```ruby
def insertion_sort(array)
  return array if array.size <= 1

  (array.length).times do |i|
    while i > 0
      if array[i-1] > array[i]
        array[i], array[i-1] = array[i-1], array[i]
      else
        break
      end
      i-=1
    end
  end
  array
end
```

- return array if it's empty or include one element
- iterate through array with `(array.length).times`, `i` represents the index of the array
- in the loops when element's index > 0 
- we set `if/else` condition and if previous value larger than current we swap them, else we terminate loops
- if loops does not terminate we decrease index of array and continue

> Time Complexity: О(n^2)
> Space Complexity: О(n)
3 things I like to keep in mind when unit testing
Tags: newbie, testing, unittesting, codenewbie
Published: 2021-04-19 18:58:18

What’s the difference between good and bad unit tests? 🧐

Bad unit tests feel right in the beginning. They make you feel confident, because hey, you write tests.

But nothing really changes… Once you get into the refactoring part, and you have to refactor tests as well. And their assertions for the result. This leads to even longer development, even though you invested time in tests at the begging of the project. So this leads us to the conclusion that… not are tests are equally valuable. Some of them raise false alarms. Some unit tests don’t help you catch regression errors. Bad unit tests may be as well slow and are difficult to maintain.

Don’t write unit tests just for sake of writing unit tests! There are 3 things I always keep in mind when I am designing my unit tests.

## Focus on the behavior, not on the implementation

When writing unit tests, especially testing the domain model, I avoid mocking anything. The reason is the fact that I want to focus on the behavior, on the outcome of the method. My goal is not to check how this is achieved. Because of this, I am able to change the implementation at any time, without worrying about rewriting the entire test.

## Test your tests

This year, I first heard about mutation testing. It was a wow moment for me. Now, whenever I write unit tests, I check myself with the mutant. I check whether I have covered all the cases (and hence, killed all the mutants 👽). Using that tool is like using Grammarly, for example. First, you get a lot of corrections. But as you go, the number decreases, because you learn by doing. The same story goes with the mutant. Check your tests once you’re done to make sure you covered all the cases. You can read more about mutation testing here.

## Don’t generalize early on

I found out that generalizing things too early (over-following the DRY principle) may actually slow you down in the long run. By generalizing I mean making (soon to be over-parametrized) seeding methods for the arrange part. Or too many hierarchical classes, just to avoid writing something twice. I always start simple, allow some duplication, and see where this takes me. I find myself refactoring the code often, especially when I work with a new domain. I found out that introducing generalization too early in tests makes it harder. Later, when it feels a little bit too messy, I really like introducing a builder pattern for seeding the data.

What are the rules that you follow when testing?

----------------------------

Originally published at [lukaszcoding.com](https://lukaszcoding.com/3-things-i-keep-in-mind-when-unit-testing/)
#RenderRoundtable - The Truth About DE&I Work
Tags: javascript, react, career, news
Published: 2021-04-19 18:32:19

For this week's #RenderRoundtable, we had an open and honest conversation about what goes into building environments that are diverse, equitable, and inclusive. Founder and CEO of [Black Tech Pipeline](https://blacktechpipeline.com/about/) and the creator of the #BlackTechTwitter movement, not only did [Pariss Athena](https://twitter.com/ParissAthena?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor) walk us through her non-traditional journey to web development (I bet you didn't know she was a celebrity waxer!), but she also discussed the *true* nature of diversity work, and the mental, emotional and physiological toll that constantly explaining and qualifying your experiences takes.

While Pariss humored us with fun tidbits about her past, being able to sit in a room and say: "I've experienced this, I see you, and I hear you." is what the #RenderRoundtable is all about-- and is one of the driving forces behind the creation of Black Tech Pipeline. Pariss is doing great work when it comes to vetting companies' true reasoning behind wanting to be more diverse, as well as keeping tabs on candidates.  It was a fantastic conversation that inspired tons of our listeners to examine both how to navigate the cultures they work in and the culture they are looking to provide for others. 

####As always, these conversations will take place on Twitter Spaces every Thursday at 7 pm EST, so be sure to tune in next week for what is sure to be an amazing chat with none other than the legendary [Angie Jones](https://angiejones.tech).

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

**Angie is a force to be reckoned with in tech. And we'll be discussing her journey as a technologist, Master Inventor, and mentor for young black women and girls in technology.**

*We'll be taking questions from the audience as well, so don't be shy!*

For more information on how to find us on Spaces, and to get your tickets before they sell out (y'all know these tickets cover amazing meals cooked by chefs, and delicious drinks right?): check out our [website](renderatl.com), be sure to say hi on [Twitter](twitter.com/renderatl), see what we're up to on [Instagram](instagram.com/renderatl), and subscribe to our [newsletter](https://bit.ly/3etgr5N) for *exclusive* conference details. 

Until next time!
Viral Math Problems: 6 / 2 * (1 + 2)
Tags: javascript, go, python, deno
Published: 2021-04-19 18:23:26

# Viral Math Problems: 6 / 2 * (1 + 2)

> How do computers solve - 6 / 2 * (1 + 2) ?

The answer is 9.

--- 

[Code & Repo for current solutions](https://github.com/immannino/viral-math-problem)

## C answer - 9

code:

```c
#include "stdio.h"

int main() {
    int a = 6 / 2 * ( 1 + 2);
    printf("C answer - %d\n", a);

    return 0;
}
```


## Golang answer - 9

code:

```golang
package main

import "fmt"

func main() {
	a := 6 / 2 * (1 + 2)

	fmt.Printf("Golang answer - %d\n", a)
}

```


## Node.JS answer - 9

code:

```javascript
const a = 6 / 2 * (1 + 2)
console.log(`Node.JS answer - ${a}`)
```


## Deno answer - 9

code:

```javascript
const a = 6 / 2 * (1 + 2)
console.log(`Deno answer - ${a}`)
```


## Python2 answer - 9

code:

```python
a = 6 / 2 * ( 1 + 2)

print("Python2 answer - " + str(a))
```


## Python3 answer - 9.0

code:

```python
a = 6 / 2 * ( 1 + 2 )

print("Python3 answer - " + str(a))
```


### Ruby answer - 9

code:

```ruby
a = 6 / 2 * (1 + 2)

puts "Ruby answer - #{a}"
```
Create no-code ML Models with Azure Machine Learning - LIVE - Apr 24
Tags: azure, machinelearning, beginners, tutorial
Published: 2021-04-19 17:48:28

### I am speaking at Global AI Student Conference

On April 24th, the Global AI Student Conference takes place and I am really excited to be part of it! I will talk about Azure Machine Learning and show how to create a linear regression model in Azure Machine Learning Designer.

Date: **April 24, 2021**
Time: **10:00-18:00 UTC**
Location: Global
Topic: AI, Machine Learning and more...
Registration & program: [aiconf.education](https://aiconf.education)

### My session

Title: **Create no-code ML Models with Azure Machine Learning and Microsoft Learn**
Time: **12:30-13:00 UTC**
Topic: Machine Learning

#### Details:
In this session, I will explain the concept of Machine Learning and Regression and show how to build a no-code regression model that predicts the price of an automobile in Azure Machine Learning Designer.

What you will learn in this session:
* Create an Azure Machine Learning workspace.
* Build and train a regression model in Azure Machine Learning Designer.
* Evaluate and publish that model.

#### Self-Paced Learning from Microsoft Learn 
[Create a Regression Model with Azure Machine Learning designer](https://docs.microsoft.com/el-gr/learn/modules/create-regression-model-azure-machine-learning-designer/)
The Underlying Architecture of WSL and why is WSL 2 better
Tags: wsl, linux, windows
Published: 2021-04-19 17:43:36

As we know, WSL or Windows Subsystem for Linux is a pretty handy tool, it helps you use the Linux command line on windows, no dual boot or partitioning required

Yeah I won't beat around the bush more, lets learn about its architecture

## WSL versions 
There are 2 versions of WSL now
1. WSL 1: The more widely used version now
2. WSL 2: The fairly newer and faster one

Both of them have fairly underlying architectures, so I will be explaining them separately

# WSL 1
So WSL 1 works using a translation layer, it has unmodified binaries for applications such as apt, grep, etc

When these libraries make a system call, such as accessing memory or network, they would usually make a request to the Linux kernel, while in WSL, it requests the translation layer, the translation layer converts the UNIX system call to a call compatible with the Windows NT kernel. 

This worked great but the problems are obvious, passing every system call through a translation layer would result in performance hits, and wouldn't have all of the system calls translated which may result in commands failing to execute due to an unmapped system call, this resulted in the making of WSL 2

# WSL 2
The WSL 2 moved into a virtualization-based approach in which you have an actual Linux kernel sitting inside a very lightweight VM
powered by the [Windows Hypervisor Platform](https://docs.microsoft.com/en-us/virtualization/api/). This made file IO much faster due to the avoidance of the translation layer

This resulted in full system call compatibility and much better performance overall 

## Conclusion
 I am pretty sure this article gave you a rough understanding of how WSL works, I will link more comprehensive articles about the architecture but this is a high-level idea about the same

Some articles for the same include
https://docs.microsoft.com/en-us/windows/wsl/faq
https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux

btw, If you do find any factual errors, please comment about it below so I can correct them

This video was hugely inspired by [This video](https://www.youtube.com/watch?v=MrZolfGm8Zk) by Microsoft, do check it out

Bye
How to use @DateTimeFormat to format Date Time request param in SpringBoot RestAPI Examples
Tags: springboot, datetimeformat, restapi
Published: 2021-04-19 17:41:47

https://ozenero.com/how-to-use-datetimeformat-to-format-date-time-request-param-in-springboot-restapi-examples

How to use @DateTimeFormat to format Date Time request param in SpringBoot RestAPI Examples

[no_toc]
In the tutorial, we show how to work with DateTime request param in SpringBoot RestAPI using <code>@DateTimeFormat</code>.

<!--more-->
<h2>@DateTimeFormat with DateTime Request Param</h2>
<code>@DateTimeFormat</code> is used to declare a field or method parameter should be formatted as a date or time. 

We can use <code>@DateTimeFormat</code> with ISO date time pattern, or custom format pattern string:

- Common ISO enum value: <code>DATE</code>, <code>TIME</code>, <code>DATE_TIME</code>
<ul>
<li>DATE: <code>yyyy-MM-dd</code>, example <code>2019-03-28</code>
</li>
<li>TIME: <code>HH:mm:ss.SSSXXX</code>, example <code>01:30:00.000-05:00</code>
</li>
<li>DATE_TIME: <code>yyyy-MM-dd'T'HH:mm:ss.SSSXXX</code>, example <code>2019-03-28T01:30:00.000+07:00</code>
</li>
</ul>

Example <code>@DateTimeFormat</code> with <code>@RequestParam</code> in Spring RestAPI:

More at:

https://ozenero.com/how-to-use-datetimeformat-to-format-date-time-request-param-in-springboot-restapi-examples

How to use @DateTimeFormat to format Date Time request param in SpringBoot RestAPI Examples
Kotlin Properties – Read/Write Properties from/to .properties/.XML File
Tags: kotlin, xmlfile
Published: 2021-04-19 17:34:29

https://ozenero.com/kotlin-properties-read-write-properties-file-properties-xml-file

Kotlin Properties – Read/Write Properties from/to .properties/.XML File

In the post, we show how to Read/Write Properties from/to .Properties/.XML files by Kotlin language.

<!--more-->
<h3>I. Kotlin - Read/Write Properties from/to .Properties file</h3>
<h5>1. Write Properties to .Properties file</h5>
<h6>1.1 Properties store() method</h6>
We use <code>java.util.Properties.store()</code> methods:

<pre><code class="language-java">
// 1.
fun store(out: OutputStream, comments: String): Unit

-> Writes this property list (key and element pairs) in this Properties table 
to the output stream in a format suitable for loading into a Properties table using the load(InputStream) method.

// 2.
fun store(writer: Writer, comments: String): Unit

-> Writes this property list (key and element pairs) in this Properties table 
to the output character stream in a format suitable for using the load(Reader) method.
</code></pre>
<h6>1.2 Kotlin Program – write Properties to .properties file</h6>

More at:

https://ozenero.com/kotlin-properties-read-write-properties-file-properties-xml-file

Kotlin Properties – Read/Write Properties from/to .properties/.XML File
Wait!
Tags: webdev, javascript, utility
Published: 2021-04-20 08:23:04

---
title: Wait!
published: true
date: 2021-04-19 17:32:00 UTC
tags: webdev, javascript, utility
canonical_url: https://thomasxbanks.com/articles/wait/
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dyuhppasriiyl5abscog.jpg
---

Why the rush&hellip;?!

Whether you're faking an API response, introducing deliberate cognitive drain, or simply want to slow things down this utility function has got you, baby! 😎

```js
const delay = ms => new Promise(rv => setTimeout(rv, ms))
```

## Cool! How do I use it?

```js
delay(500).then(() => console.log(`hello world`))
```

Nice! Does it work with `async/await`?

Heck, yes, it does!

```js
const functionName = async () => {

  doFirstThing()

  await delay(500)

  doNextThing()
}
```

<p class="codepen" data-height="265" data-theme-id="dark" data-default-tab="js,result" data-user="thomasxbanks" data-slug-hash="wvoVwXL" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="Delay">
  <span>See the Pen <a href="https://codepen.io/thomasxbanks/pen/wvoVwXL">
  Delay</a> by thomas×banks (ツ) (<a href="https://codepen.io/thomasxbanks">@thomasxbanks</a>)
  on <a href="https://codepen.io">CodePen</a>.</span>
</p>
<script async src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>
Asynchronous Web Scraping with Python, aiohttp, and asyncio
Published: 2021-04-19 17:20:14

One of the features of our Rotating Proxy Service Proxies API is the enormous concurrency it offers straight from the free plan itself. This is because we wanted the ability to scale our customer's web scrapers to be there from moment one. People do ask us what the best way to make concurrent requests on their side is. So we thought we would put together a getting started code that helps you understand and get started with async requests in Python.

Async is a better option than multi-threading because it's challenging to write thread-safe code.

So here is an example of fetching multiple URLs simultaneously using aiohttp module.

We will try and fetch all the URLs from this array.
First, we will initialize everything by loading the modules we need.
We need a function to handle individual fetches.
Notice how we use the start_time is stored in an array for each URL, and the time taken is calculated and printed.

The fetch_urls calls the ensure_future function to make sure the URLs finish fetching.
The fetch_async sets up the event loops and uses the run_until_complete to wait till all the URL fetches are completed to pass the control back so we can print the total time taken.
Putting it all together
And when you run it.
And when you run it.
This will scale, but If you want to use this in production and want to scale to thousands of links, then you will find that you will get IP blocked quickly by many websites as well. In this scenario, using a rotating proxy service to rotate IPs is almost a must.

Otherwise, you tend to get IP blocked a lot by automatic location, usage, and bot detection algorithms.

Our rotating proxy server Proxies API provides a simple API that can solve all IP Blocking problems instantly.

With millions of high speed rotating proxies located all over the world
With our automatic IP rotation
With our automatic User-Agent-String rotation (which simulates requests from different, valid web browsers and web browser versions)
With our automatic CAPTCHA solving technology
Hundreds of our customers have successfully solved the headache of IP blocks with a simple API.

A simple API can access the whole thing like below in any programming language.

You dont even have to take the pain of loading Puppeteer as we render Javascript behind the scenes, and you can just get the data and parse it any language like Node, Puppeteer or PHP or using any framework like Scrapy or Nutch. In all these cases, you can just call the URL with render support like so.
Beautiful Soup Vs. Proxies API
Published: 2021-04-19 17:19:35

The world of web scraping is varied and complex, and Proxies API sits at one of the most crucial junctions. They are allowing web scrapers/crawlers to bypass IP blocks by using a single API endpoint to access our 20 million-plus high-speed proxies on rotation.
One of the questions we get frequently is how we are different from services like OctoParse or Diffbot. Many times it is like comparing Apples and Oranges. Still, when we send this comparison table to our customer's developer team, their CXO, their marketing, or SEO team, they typically get it quite quickly if we are a convenient service or not.

So here is how we are different from Beautiful Soup.

One of the aftermaths of the Internet Explorer era is how badly formed most HTML on the web is. It is one of the common realities you are hit with when you start any web scraping project.

No library wrangles with bad HTML as well as beautiful Soup

Beautiful Soup provides a few simple methods and Pythonic idioms for navigating, searching, and modifying a parse tree: a toolkit for dissecting a document and extracting what you need. It doesn't take much code to write an application. It also handles all encoding issues automatically.

Link https://www.crummy.com/software/BeautifulSoup/