teleren/devto huggingface dataset:
The incredible power of Deno Deploy
Tags: deno, deploy, distributedsystems, global
Published: 2022-03-23 16:40:51

As you folks might know [Deno](https://deno.land/) is a modern evolution of Node.js, from the original creator Ryan Dahl, which aims to improve on the design of and avoid many of the pitfalls of the original. It is a fast Rust based runtime for JavaScript/TypeScript.

[Deno Deploy](https://deno.com/deploy) is an accompanying service that instantly deploys Deno code to dozens of [regions](https://deno.com/deploy/docs/regions) around the world with a single publicly available URL in front of it. It automatically routes requests to the nearest deployed region based on the caller's location! And all this with one click of a button!

_It... is... incredible!!!_

In comparison, achieving something similar in AWS is almost comically [complicated](https://aws.amazon.com/blogs/compute/building-a-multi-region-serverless-application-with-amazon-api-gateway-and-aws-lambda/) (sorry, I know AWS teams work hard but still... ¯\\\_(ツ)_/¯).

Having dabbled in serverless development and ops in the past, I wanted to see if Deno Deploy indeed lived up to its promise. So I wrote and deployed a simple script that displays the environment variable `DENO_REGION` in the response.

```ts
import { serve } from "https://deno.land/std@0.120.0/http/server.ts";

function handler(req: Request): Response {
  return new Response(
    `<pre style="font-size:10em;">
       DENO_REGION=<br>
       ${Deno.env.get("DENO_REGION")}
     </pre>`,
    { headers: { "content-type": "text/html" } }
  );
}

console.log("Listening on http://localhost:8000");
await serve(handler);
```

As soon as I clicked the **Save & Deploy** button, my URL was live: https://show-region.deno.dev

![Deployed Deno code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hj64uqy6qqrz62twow4w.png)

But how do we know if requests from around the world will be routed to the nearest region as claimed?

Enter [GeoPeeker](https://geopeeker.com/) - an excellent service that loads any webpage from different locations around the world and grabs screenshots from there.

Passing our URL to GeoPeeker shows:

[![Deno regions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v8fsgx2ndkk1s3sqhs1t.png)](https://geopeeker.com/fetch/?url=https%3A%2F%2Fshow-region.deno.dev%2F)

As we can clearly see, the request from Singapore is routed to `asia-southeast1`, Brazil to `southamerica-east1` and so on. Very cool indeed!

You can get started with Deno Deploy [here](https://deno.com/deploy) - have fun!
DC motor control: Welcome to the jungle
Tags: opensource, motor, tutorial, luos
Published: 2022-03-23 16:31:44

Get your knowledge of DC motor control off the ground.
⏩ https://www.luos.io/blog/dc-motor-control-welcome-to-the-jungle

Learn more about: direction control, voltage, PWM, speed control, etc.

Use this article as a map to find your way through the jungle! Follow your guide Simon Baudry (Simon (FR)#2786) on Luos Discord: https://discord.gg/luos
Cambiando mi paradigma a la nube.
Tags: cloud, devops, aws
Published: 2022-03-23 16:01:44

Hace unos meses tomé la decisión de estudiar los servicios de AWS, busqué un curso que me ayudara a aprender la teoría y también prácticas utilizando los recursos con los que cuenta la plataforma.
La verdad que me lleve una grata sorpresa (no soy un experto en temas de infraestructura y despliegue, pero como todo desarrollador debemos saber de eso), me di cuenta que son una gran herramienta y que, de ser posible, muchas empresas y desarrolladores deberían tener presente en sus proyectos la utilización de ellas.
Este post no es para enseñar sobre el tema, sino para dar un mensaje de que tanto AWS, Microsoft Azure o su par de Google, nos dan una rapidez y flexibilidad como nunca.
Personalmente me metí más en AWS y me preparo para la certificación de Cloud Practitioner, siento que luego de darle una pasada creo que mi paradigma cambio totalmente.
En ella podemos encontrar soluciones para una variedad muy amplia de problemas, desde instancias o capacidades de cómputo escalables, registro de dominio o herramientas que te ayudarán en el proceso de entrega continua y despliegue (CI/CD), como también diferentes tipos de almacenamientos en la nube.
Sin más, si lees esto y aun no le has dado un intento de conocer qué son y qué podemos hacer con estas plataformas, te doy un consejo, HAZLO!
Saludos.
Face Detection with OpenCV (for complete Dummies)
Tags: python, opencv
Published: 2022-03-23 15:59:50

---
title: Face Detection with OpenCV (for complete Dummies)
published: true
canonical_url: https://www.aloneguid.uk/posts/2022/03/face-detection/
description: 
tags:
  - python
  - opencv
//cover_image: https://direct_url_to_image.jpg
---

This is a very dumb and straightforward tutorial that is meant to be a complete newbie intro into face detection. I'll be using [OpenCV](https://opencv.org/) for this, and python for simplicity, however if you want to scale you might want to rewrite this in C++. Python is great for prototyping so I'll stick with this.

## Install Dependencies

You can grab `opencv-python` from [pypi](https://pypi.org/project/opencv-python/) - this is an unoptimised version that works on CPU - more than enough for prototyping.

## Write Code

First, import OpenCV and load the image you want to work with, optionally resizing it. You need to grayscale the image before applying further classification.

```python
import cv2 as cv

img1 = cv.imread("band-small-faces.jpg")

# resize if needed
# img2 = cv.resize(img1, None, fx=0.3, fy=0.3, interpolation=cv.INTER_CUBIC)
img2 = img1  # not resizing in this case
img3 = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)
```

This is the image provided as input:

![band-small-faces](https://www.aloneguid.uk/posts/2022/03/face-detection/band-small-faces.jpg)

Then, you need something called a Haar classifier that does the magic:

```py
haar_cascade_face = cv.CascadeClassifier("./data/haarcascades/haarcascade_frontalface_default.xml")
```

As an input it needs a model to work with. I'm passing a model that detects frontal faces. I've [attached](haarcascades.zip) available models for you to download (apparently you need to create `data/haarcascases` folder where your python script is).

If you get an error similar to

```cv2.error: OpenCV(4.5.5) ...opencv-python\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'```

it usually means that path to the xml is invalid (thanks for useful messages!).

And to display model results:

```python
for (x, y, w, h) in faces_rects:
    cv.rectangle(img2, (x, y), (x + w, y + h), (0, 255, 0), 3)

cv.imshow("Display", img2)
k = cv.waitKey(0)

```

![image-20220323155153397](https://www.aloneguid.uk/posts/2022/03/face-detection/image-20220323155153397.png)

As you can see, most of the faces were detected! Last person's leg looks like a face (you need to play with model parameters to rule this out). Last face wasn't detected because it's not frontal! Maybe use another model if you need to detect more.

Same way you can detect other things with OpenCV, just supply another pre-trained model. For instance, face expressions, eyes, eyeglasses, bodies, plate numbers etc.
HashTable Data Structure
Published: 2022-03-23 15:58:51

In the next few posts, I'll be talking about some data structures

======================================

Today, I'll be talking about 
 and how we can implement it from scratch using Java.



- Hash table → data structure lets us construct a mapping from keys to values via a technique called "hashing"

- Hashing → is a technique that retrieves the value using the index obtained from a key without performing a search.



Each Hash table contains:

- Array to hold data.

- Hash function (is a function that maps a key 'x' to an index in a fixed range)



Type of hash functions:
-----------------------
 → There are various types of hash functions in the data structure:

- Division Hash Function (h(k) = k mod m )

k → key, m → hash table size

ex: h(1276) = 1276 mod 10 = 6



- Multiplication Method ( h(k) = floor( n( kA mod 1 ) ) )

k → key and A → can be any constant value between 0 and 1, n → hash table size

ex: n = 4, a = 0.568, key = 56 ,

h(56) = floor( 4 * ((560.568) mod 1)) = floor (4 (31.808 mod 1))

= floor (4 * 0.808) = floor(3.232) = 3



- Mid Square Hash Function (h(K) = h(k x k)) → squaring the value of the key and then extracting the middle r digits as the hash value

ex: k = 50 , k*k = 2500, r = 2

h(50) = 50 , then the hash value obtained is 50



The characteristic of a good hash function:
-------------------------------------------

- It should be easy to compute.

- It reduces the chance of collisions.

    - A hash collision is when two objects x, y hash to the same value (i.e. H(x) = H(y)).

- It should guarantee an even distribution of the values.



Example:

Consider an example of hashtable of size 4, Item are in (key,value) format.

- (1 ,20)  => key → 1   , hash = 1   % 4 = 1 ,  array index → 1

- (2 ,70)  => key → 2   , hash = 2   % 4 = 2 ,  array index → 2

- (3,36)   => key → 3   , hash = 3   % 4 = 3 ,  array index → 3

- (42,80) => key → 42 , hash = 42 % 4 = 2 ,  array index → 2

- (4,25)   => key → 4   , hash = 4   % 4 = 0 ,  array index → 0

Hash collisions happened in 

(2 ,70) , (42,80)  hashed to index → 2



What do we do if there is a hash collision?

We use one of many hash collision resolution techniques to handle this



Hash collision resolution techniques:
------------------------------------

- Separate chaining (Open Hashing)

    - Deals with hash collisions by maintaining a data structure (usually a linked list) to hold all the different values which hashed to a particular value.


- Open addressing (Closed Hashing)

   - Deals with hash collisions by finding another place within the hash table until an empty bucket is found.

   - There are various methods to find these empty buckets:

       - Linear Probing

       - Quadratic Probing

       - Double Hashing



In the attached images you'll find a two different implementations of HashTables without handling the hash collisions.



Next post I'll be talking about how to handle the hash collisions.



Github: shorturl.at/fvAOZ



Resources:
---------
- shorturl.at/gnvN2

- shorturl.at/gvwAV

- shorturl.at/djG24

- shorturl.at/hvzL5


#datastructures #java #github
Yet Another Perl Switch Statement
Tags: perl, switch
Published: 2022-03-23 15:56:58

---
title: Yet Another Perl Switch Statement
published: true
description: Discussing a Perl switch I have never seen before
tags: #perl #switch
//cover_image: https://direct_url_to_image.jpg
---

I am in the middle of a project at my job where we are converting some Perl to Python :-(. In the conversion I was explaining this invocation of a `switch` statement:

```perl
for (ref($thing)) {
    /ARRAY/ && do {
        some_array_thing($thing);
        last;
    };
    /LIST/ && do {
        some_list_thing($thing);
        last;
    };
    ## default;
    some_scalar_thing($thing);
}
```

After explaining how the `for` statement sets `$_`, I was asked, "Why not just set `$_`?"

Indeed, why not? You can play with the following code here: http://tpcg.io/KN9H82

```perl
use strict;
use warnings;

{
    local $_ = 'foo';
    /bar/ && do { print 'we got bar'; last };
    /foo/ && do { print 'we got foo'; last };
    /eek/ && do { print 'we got eek'; last };
    print 'we dropped through';
}
```

with output
```
we got foo
```

So, my questions are:

* Why have I never seen this in any discussion of Perl's `switch` synonyms?
* Is there any inherent problem with this?
Cut your Rails boot times on Heroku in half with a single command
Tags: heroku, rails, ruby, devops
Published: 2022-03-23 15:52:07

TLDR;

`heroku labs:enable build-in-app-dir -a <APP_NAME>`

Now enjoy your Rails app booting ~twice as fast after your next deploy 🙌

## But why?

One of the tradeoffs with majestic monoliths is that the larger they grow, the more code has to be loaded and interpreted at boot time. In massive code-bases, such as Shopify's and Github's, booting can take more than a minute (see eg. [Upgrading Github to Ruby 2.7](https://github.blog/2020-08-25-upgrading-github-to-ruby-2-7/)).

Particularly requiring files (eg. `require "foo"`) tends to become a bottleneck due to Ruby having to iterate through all possible load paths to lookup matching files. This gets time consuming when it’s applied to thousands of files.

To alleviate this problem, the engineers at Shopify created [bootsnap](https://github.com/Shopify/bootsnap), a gem which automatically detects and caches exact load paths to make those require calls fast (see [Bootsnap: Optimizing Ruby App Boot Time](https://shopify.engineering/bootsnap-optimizing-ruby-app-boot-time) for details).

The bootsnap gem has been a default Rails gem since version 5.2 which was released back in 2018 and has been improving boot times in most environments ever since. But what about on Heroku?

## Bootsnap on Heroku

As it turns out due to a quirk in how Heroku's Ruby buildpack initially builds the application in a `/tmp` folder before moving the results over to `/app`, the cache generated by bootsnap gets invalidated and can't be used at all. But after enabling the `build-in-app-dir` labs feature the entire build process takes place inside of `/app` which allows bootsnap to work as intended.

The feature is enabled via the [heroku CLI](https://devcenter.heroku.com/articles/heroku-cli) tool:
`heroku labs:enable build-in-app-dir -a <APP_NAME>`

At [Mynewsdesk](https://mynewsdesk.com) this reduced the boot times of our 17 year old Rails codebase from ~16 seconds to ~8 seconds. The improvement is particularly noticeable when booting one off dynos via eg. `heroku console` or `heroku run rails db:migrate`.

There is a [Github issue](https://github.com/heroku/heroku-buildpack-ruby/issues/979) on this topic in the `heroku-ruby-buildpack` repo with some success stories in the comment section and a hint that `build-in-app-dir` may become the default behaviour in the future.

So far there have been no reports of issues after enabling this feature but you might want to try this on your staging environments first before enabling it in production to be sure. If any issues do turn up, don't forget to share your experience in the Github issue.

This is the first post in a planned series of tips and tricks for using Heroku efficiently. Feel free to follow me here on dev.to or [@dbackeus on Twitter](https://twitter.com/dbackeus) to get notified when new posts are published.
Feature roadmap
Tags: devops, programming
Published: 2022-03-23 15:49:46

Have you ever felt like you're drowning in planned features or issues that depend on each other?
I am currently and I'm trying to find a way out. Does anyone know a tool where you can visually plan which features depend on others so its easy to see what has to be done next and what has to be done until a certain goal is reached?
I'm think of something that looks like the boxes connected through lines as used in the material editor of blender.
Any suggestions?
How do you plan your code? The OODA loop
Tags: codenewbie, beginners, discuss, 100daysofcode
Published: 2022-03-23 15:37:55

Sometimes we just want to dive into our code, head first. 

But one user in our Codacy Community shared with us the OODA loop framework, in hopes to help other developers. 

> "My University teachers always told us that we should plan our code before starting, but that’s a lesson that only sunk in after wasting more time due to lack of planning."

**[Read the full community post here](https://community.codacy.com/t/how-do-you-plan-your-code-the-ooda-loop/858)** to learn more about the OODA loop, where it comes from and what it means.

Join over 400 developers in our community and participate in the discussion!
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tj05grero0y2876jisxv.png)
Leetcode Daily Challenge - Broken Calculator
Tags: programming, python, data, leetcode
Published: 2022-03-23 15:04:33

Today's challenge on Leetcode in based on a Maths/ Greedy Problem. It is a medium level problem and sounds easy but may leave you scratching your head in terms of an optimal solution.

[991. Broken Calculator]
(https://leetcode.com/problems/broken-calculator/)

---

**Problem Statement**

> There is a broken calculator that has the integer startValue on its display initially. In one operation, you can:
> multiply the number on display by 2, or
> subtract 1 from the number on display.
> Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator

```
Input: startValue = 2, target = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
```

---

##Thought Process:
The immediate thought striking your mind would be to increase the startValue using * operator (in case of a smaller startValue) or decrease it by subtracting to make it equal to target and count the steps we took in our journey.

It can lead to errors so the desired method is to do the otherwise backward approach. To reduce the target using the exact opposite operators of division and subtraction to count the occurrences of operations. 

In case, target becomes lesser than startValue, we will increment until the startValue and return the difference along with the actual counter. Confused about this step, proceed further and understand.

---


##Logic 

1. The approach is simple, we declare a counter and run a loop which is terminated once our target value is no more greater than the startValue.

2. In case our target is odd, we increment the value of target by 1 else we will divide the target value into half.

3. Eventually, once the loop is terminated, we will return the summation count of times the loop ran and the difference between the startValue and target.

4. Difference between startValue and target will be decremented on other side of startValue to make it equal to the target along with the counter that ran along the loop.

---

##Code


![Python Solution](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ep0ihcbfzzvs3usemt7b.png)

---
In case, you are looking to learn practice Python from scratch or want to practice DSA then do checkout my YouTube Channel for free lectures and code-along sessions!
[Code Broski: Click here to redirect to Python Fundamentals playlist!](https://www.youtube.com/watch?v=CffZDfq_8Vk&list=PLnGsOhprawFPahp6KOsxY77C6QKddgIkm)
Create Invite on Azure B2C with Graph API
Published: 2022-03-23 14:58:55


<sub>Photo by <a href="https://unsplash.com/@diana_pole">Diana Polekhina</a> on <a href="https://unsplash.com/s/photos/invitation">Unsplash</a></sub>

While reading [this great post](https://damienbod.com/2022/03/11/create-azure-b2c-users-with-microsoft-graph-and-asp-net-core/) from Damien Bod, i had the idea to do the same for inviting users in Azure B2C.

## Configure Permissions in Azure

Following [the doc](https://docs.microsoft.com/en-us/graph/api/invitation-post?view=graph-rest-beta&tabs=csharp), we require the following:
- permission User.Invite.All (permission type : Application) and grant Admin Consent

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

Get from your application:
- your tenant ID
- your Application ID
- a Secret Value

## Code

Once you have configured the permission, you can use the following code (with you IDs / Secret):

```csharp
	string[] scopes = new string[1] { "https://graph.microsoft.com/.default"};
	var tenantId = "<YOUR_TENANT_ID>";

	// Values from app registration
	var clientId = "<YOUR_APPLICATION_ID>";
	var clientSecret = "<YOUR_SECRET>";

	var options = new TokenCredentialOptions
	{
		AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,	
	};

	// https://docs.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
	var clientSecretCredential = new ClientSecretCredential(
		tenantId, clientId, clientSecret, options);

	var _graphServiceClient = new GraphServiceClient(clientSecretCredential, scopes);
	

	var invitation = new Invitation()
	{
		InvitedUserEmailAddress= "<EMAIL>",
		InviteRedirectUrl ="<YOUR_APPLICATION_URL>",
		SendInvitationMessage = false,
	};

_graphServiceClient.Invitations.Request().AddAsync(invitation); 
```
using the following NuGet packages :
- [Microsoft.Identity.Web](https://www.nuget.org/packages/Microsoft.Identity.Web)
- [Microsoft.Graph](https://www.nuget.org/packages/Microsoft.Graph)

Hope this helps !
Learn Python in depth
Tags: python, beginners, tutorial, webdev
Published: 2022-03-23 14:43:46


"There's no shortcut, read lots of code then write lots of code."

**1. Start and learn the basics**

First start by download and installing Python. Choose Python 3.x, setup your coding environment, configure the Python path etc.

To get started, there are some online tutorials that can assist you, like

https://pythonbasics.org/
https://docs.python.org/3.11/tutorial/index.html
https://www.tutorialspoint.com/python/
https://pythonprogramminglanguage.com/
https://www.javatpoint.com/python-tutorial

**2. Study courses**

Courses can help to boost your knowledge. There are many courses out there, that will give you a kick start in developing software applications. Instead of struggling through the documentation, why not follow short video tutorials that explain clearly?

**3. Work on projects**

Once you mastered the basics and can use modules, it's time to make your own apps. Learn through projects on daily, weekly and monthly basis.

Daily Basis   - 1 problem solving(Basic)
weekly Basis  - small project or intermediate level problems
Monthly Basis - one original project either forked from github or 
                your own project

**4. Master libraries**

Libraries or modules are building blocks that help you create your app. There are thousands of modules, so which one do you need for your app?

It depends on what you want to make. For web apps, it's popular to use Django or Flask. For Machine Learn, tensorflow and sklearn are popular modules. For desktop software, you can use wxwidgets, pyqt, tkinter or other modules.