teleren/devto huggingface dataset:
How SASS, SCSS is making our life easier
Tags: css, scs, javascript, webdev
Published: 2022-05-15 11:05:25

I have just posted a very short yet productive article on medium & hope you can cover it with-in 2 minutes https://medium.com/@imhamad/how-sass-scss-is-making-our-life-easier-89df347ff0c4

so just spare out a minute and crack on!
Cheers
Lazy load images, native solution, no javascript or plugins
Tags: lazy, load, images, browser
Published: 2022-05-15 10:53:05

Browsers now have native functionality to lazy load images.
Just add the loading attribute to your images:
```html
<img loading="lazy" />

<!-- 
A bonus for if you want to know when the image has been loaded - 
useful for showing a loader or running some code:
-->
<img loading="lazy" onload={someFunction} />
```

More useful img properties/attributes:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-loading

Browser support:
https://caniuse.com/loading-lazy-attr

Remember as a developer it is your duty to use these new features. Do not support browsers that do not have these features (like IE) as that is counter intuitive and holds us as a community back. If more developers stopped developing for crappy browsers, clients wouldnt expect us to code for them and we can enjoy the ease of features like the above.
Cache API in JavaScript - with just 20 lines of code.
Tags: cache, javascript, webdev, tutorial
Published: 2022-05-15 10:44:46

```javascript
let cache = {};
async function getData(url){
    let result = "";
    if(cache[url] !== undefined) return cache[url].value;
    
    await fetch(url)
    .then(response => response.json())
    .then(json => cache[url] = {time: new Date(), value: json});

    return cache[url].value;
}

// Interval to clear cache;
setInterval(function (){
    if(Object.keys(cache).length > 0){
        let currentTime = new Date();
        Object.keys(cache).forEach(key => {
            let seconds = currentTime - cache[key].time;

            if(seconds > 10000){
                delete cache[key];
                console.log(`${key}'s cache deleted`)
            }
        })
    }
}, 3000);
```

Now you can call your API's like this.

```javascript
getData("https://jsonplaceholder.typicode.com/todos/1")
.then(data => console.log(data));
```

> If there is a cache value of the current api call then it will return values from cache otherwise call the api and return data while adding the response to cache.

##### Preview

![Image Cache API in JavaScript - with just 20 lines of code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ph0q3y76d8ix3cpcjgoo.png)

I'm assuming this is much better than RTK Query and React Query 😅.
100 Days of Code: The Complete Python Pro Bootcamp for 2022 - Day 15 (Coffee Machine Order)
Published: 2022-05-15 10:30:26

```python
from art import logo
print(logo)

MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

profit = 0
resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}


def is_resource_sufficient(order_ingredients):
    """Returns True when order can be made, False if ingredients are insufficient."""
    for item in order_ingredients:
        if order_ingredients[item] > resources[item]:
            print(f"Sorry there is not enough {item}.")
            return False
    return True


def process_coins():
    """Returns the total calculated from coins inserted."""
    print("Please insert coins.")
    total = int(input("how many quarters?: ")) * 0.25
    total += int(input("how many dimes?: ")) * 0.1
    total += int(input("how many nickles?: ")) * 0.05
    total += int(input("how many pennies?: ")) * 0.01
    return total


def is_transaction_successful(money_received, drink_cost):
    """Return True when the payment is accepted, or False if money is insufficient."""
    if money_received >= drink_cost:
        change = round(money_received - drink_cost, 2)
        print(f"Here is ${change} in change.")
        global profit
        profit += drink_cost
        return True
    else:
        print("Sorry that's not enough money. Money refunded.")
        return False


def make_coffee(drink_name, order_ingredients):
    """Deduct the required ingredients from the resources."""
    for item in order_ingredients:
        resources[item] -= order_ingredients[item]
    print(f"Here is your {drink_name} ☕️. Enjoy!")


is_on = True

while is_on:
    choice = input("​What would you like? (espresso/latte/cappuccino): ")
    if choice == "off":
        is_on = False
    elif choice == "report":
        print(f"Water: {resources['water']}ml")
        print(f"Milk: {resources['milk']}ml")
        print(f"Coffee: {resources['coffee']}g")
        print(f"Money: ${profit}")
    else:
        drink = MENU[choice]
        if is_resource_sufficient(drink["ingredients"]):
            payment = process_coins()
            if is_transaction_successful(payment, drink["cost"]):
                make_coffee(choice, drink["ingredients"])
```
React Create Element - React Without JSX
Tags: react, createelement
Published: 2022-05-15 10:29:22

React has taken the top spot among all other JS frameworks and libraries, according to the Stack Overflow survey, 2021. The reason might be anything from being open-source to flexible (it can work with any other package or library to create an awesome app) or having JSX as its syntax which is very popular due to its ease of access.

But, JSX is not the only syntax that React has. We can also make apps without using JSX with React.createElement() which can be declared as the only syntax of React.

React is an open-source library and there are many things that it has to offer to a developer like virtual DOM, Props, etc, but the thing is it can be a little tricky at first time due to its diverse nature. This is why a comprehensive syllabus for React JS is crucial to your learning experience and can help you learn to React in a structured way.

In this blog, we will first uncover the reason why React.createElement has been called the original Syntax of React and then we will dive deep into the topic of React without JSX or React with createElement.

Let’s start…

## In this article

1. What is React.createElement?
2. React.createElement Syntax
3. React.createElement Arguments
4. Understanding the Render Method
5. An Alternate Way
6. Wrapping it up
7. The Route Most Taken

## What is React.createElement?
React.createElement can be considered as the original syntax of React because it allows us to write codes in React with just plain JS which the browser can understand and we don’t need additional bundlers like webpack, Flux, ES6, React-Router, etc.

But with JSX, we need things like ES6 classes and the Babel webpack to convert these ES6 classes into ES5 so that our browser can easily understand them.

## Then Why JSX?
JSX stands for JavaScript Syntax Extension which means that it is just an extension of the original syntax that has made the code readable, understandable and editable with the help of ES6 classes.

We can also say that it is nothing more than a syntactic form of the syntax that makes it easy to use and understand with the help of ES6 classes, and Babel converts these classes back into ES5 for our browser to understand.

Every code written in JSX is first converted into createElement syntax and then sent to the browser.

The image given below will help you understand this concept easily.

![Converting a code written in JSX into React.createElement with the help of Babel](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9bzi5wtlyvbdt8x3leq7.png)
 
[Continue Reading](https://www.knowledgehut.com/blog/web-development/react-create-element).
Java Class Attributes
Tags: java, javascript, beginners, tutorial
Published: 2022-05-15 10:09:07

Create a class called "Main" with two attributes: x and y:

**public class Main {
  int x = 5;
  int y = 3;
}**

## Accessing Attributes

You can access attributes by creating an object of the class, and by using the dot syntax (.):

**public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println(myObj.x);
  }
}**
Superbus, an Azure service bus explorer for macOS
Tags: servicebus, azure, messaging, amqp
Published: 2022-05-15 09:51:58

Superbus started with my own need for a service bus explorer when I switched from Windows to macOS 2 years ago.
On windows I used to work with the well known [service bus explorer](https://github.com/paolosalvatori/ServiceBusExplorer), but on macOS the only alternative is very expansive, and I don't like the UX, so I decided to create one.
[superbus](https://superbus.app/) makes it easy and enjoyable to manage your Azure Service Bus namespaces.
Main features :

- topic/subscription/queue management
- real time remote search
- view message and properties
- send message
- edit/resend message
- purge queue

I created a [github repo](https://github.com/PopAndCode/Superbus/) where you can follow [the public roadmap](https://github.com/PopAndCode/Superbus/projects/1)
convert images to ASCII characters!
Tags: python
Published: 2022-05-15 09:51:23

## ever wanted to convert your image to Ascii characters? here is how you can achieve it!!

we will be converting this image of Mario, into ascii characters
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wykjapahq2r9bgeh0e8f.png)

## step 1:- loading in the image and resizing
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p688yy34wsm3jwtww1xv.png)
we resize the image since there are a LOT of pixels. so we resize it by 50%! this will make the final output smaller and we will not be compromising on the quality(since there are a lot of pixels to begin with!) 

## step 2:- converting the image to a pure black and white image
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n01wwl1yx57o5prnu2am.png)
here we convert the image to a pure black and white image. we do this since text characters don't have color. now we can save this black and white data to a new image
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdfu3ota572kkv9pevrg.png)
here is what the image looks after the conversion!

## step 3:- converting this black and white data to text characters
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/il4no4spcn99trl5hiqb.png)
here we read in the data from the fresh black and white image which we saved in the last step. we also have a count variable which helps us to break the line for every time we finish a row section of the image 
now we check the color of each of these pixels, if its black(0), we simply write in a "~". on the other hand if its white(255), we write in a "."
we now save this data into a text document!

## here is how it looks like finally
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aegf5539j2utsrg68are.png)
I have resized my code editor so you all can see this masterpiece!
Comic book button animation
Tags: react, webdev, showdev, github
Published: 2022-05-15 09:31:42

I really liked the style from Spider-Man Into the Spider-Verse, I thought that maybe I can make something similar for a button animation with react and framer motion. 

You have the result [here.](https://dribbble.com/shots/18145123-Button-Animation) and the github project [here.](https://github.com/eduardconstantin/Comic-book-button-anim)

There is always room for improvements, feel free to contribute.
How I found a bug in 2000 files
Tags: development, bugs
Published: 2022-05-15 09:28:23

---
title: How I found a bug in 2000 files
published: true
tags: development, bugs
canonical_url: https://strdr4605.com/how-i-found-a-bug-in-2000-files
cover_image: https://strdr4605.com/how-i-found-a-bug-in-2000-files.jpg
---

I was adding a new eslint plugin that will sort imports in js/ts files.   
After adding [eslint-plugin-simple-import-sort](https://github.com/lydell/eslint-plugin-simple-import-sort), 
I run `eslint --fix` and found about 2000 files changed. 
As there was only reorder of imports I thought that there should not be any issues.

I was surprised when I found a very strange 

```
TypeError: Cannot read properties of undefined
```

Reverting the import order did not help to fix the issue.  
And now I started thinking  about how I can find the issue without going through all 2000 files. 

Then an idea came. As all changes are independent,
I could do a commit for every file change and then run a `git bisect` and find the file that causes the problem.

So I created a bash script that will get all file names from `git status` and create a commit with the file name:

Let's see how:

```bash
git status --porcelain # prints git status in a format that can be parsed
# M utils/index.ts
# M components/Button.tsx
# ...
```

Then we pipe this result to `awk` and print only the file name:

```bash
git status --porcelain | awk '{print $2}'
# utils/index.ts
# components/Button.tsx
# ...
```

read each line (filename), and do a commit with `--no-verify` to not trigger pre-commit check:

```bash
#!/bin/bash
(git status --porcelain | awk '{print $2}') | 
while read -r line
do
    git add $line
    git commit -m "Add file $line" --no-verify
done
```

After running this script I had about 2000 commits where I could run [`git bisect`](https://git-scm.com/docs/git-bisect) and find the issue.
`git bisect` reduced the number of checks from **2000** (theoretically) to just **11**.

I found the file that caused the issue, and it was completely unrelated to the file where the error was thrown. 
So I just eslint ignored the sorting rule in that file (till later investigation). 
Then I did a soft reset to undo all 2000 commits and pushed a single commit that successfully adds the new eslint plugin and rules to the project.
Pessimistic locking in Rails by example
Tags: rails, programming, tutorial, ruby
Published: 2022-05-15 08:36:52

Recently my colleague [Chris Lubomanski](https://dev.to/lubekpl) added an [optimistic locking](https://api.rubyonrails.org/classes/ActiveRecord/Locking/Optimistic.html) to one of our tables in the database. Before that I've never heard of it, but it was very easy to understand. The official Rails documentation explains this type of locking quite good.

Rails also allows to do a [pessimistic locking](https://api.rubyonrails.org/classes/ActiveRecord/Locking/Pessimistic.html) on a database table, but in my opinion, the official documentation for this type of locking is bit poor and doesn't explain the topic well enough.

This is how I would explain in simple terms what pessimistic locking does: if you lock a database record in one thread(or process, it doesn't matter) and perform a database transaction on that record(for example, an update operation), you won't be able to read/update/delete that record from some other thread WHILE the transaction in the first thread is executing.

Here's an example:
![Pessimistic locking example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r9zd0syd6kf3de5sfa41.png)

I'm fetching the first record from `people` table, but prepending `.first` method with `.lock` method. Because of that, the `SELECT` query has `FOR UPDATE` statement at the end. It means that the fetched record is locked while the transaction is executing involving that record. Simple, right?

Have I convinced you that the record will be locked during the transaction? Probably not. Let me show an example that should convince you.

Since this transaction gets executed very fast, I can't show you that the record is indeed locked, unless I do a few little adjustments to the transaction. I'm going to make the transaction sleep for some time, and then I'll open one more Rails console and try to access the locked record. You'll see  that the record is being locked indeed while the transaction is executing in the first Rails console. Take a look:
![Pessimistic locking long transaction example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p515xwjaean3hdpwk50k.gif)
 
See? While the transaction in the left console was executing, in the right console I wasn't even able to fetch the locked record from the database. Only after the transaction finished, I was able to get the record.

![Homer Simpson, big lock](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3drcu4ree8q4a0ecfeym.gif)

I hope this example helped you to understand the pessimistic locking better.

Note: I was using MySQL database.
Coding Techniques for Solving Algorithmic Problems
Published: 2022-05-15 08:41:39

---
title: Coding Techniques for Solving Algorithmic Problems
published: true
date: 2022-05-15 08:32:19 UTC
tags: 
canonical_url: https://enzircle.com/coding-techniques-for-solving-algorithmic-problems
---

How many times have you seen an algorithm problem and had no idea how to start solving it? Do not worry. You are not alone. I struggle with the process of solving algorithm problems all the time. Often, I just stare at the problem or start typing away at the keyboard until I get the right solution, spending hours in the process.

![Coding techniques](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i6gg4zqp851zau75hijf.png)

It turns out that there are underlying patterns for most of these problems. Finding the right technique to solve an algorithm problem can be the difference between a correct solution and spending hours staring at a problem.

I have summarized some patterns that help me solve algorithmic problems in a short study note. There are 14 techniques overall. Each method is explained with examples that illustrate how it can be used to solve specific types of problems. You can learn how to apply these techniques to solving problems in order to produce correct solutions more efficiently.

![Sliding windows technique study notes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ivsmmi2f7o6to0jplx9.png)

I also provide just a summary of the coding techniques without the code examples for quick reference.

![Coding techniques quick guide](https://cdn.hashnode.com/res/hashnode/image/upload/v1652603366433/oEn2QeEdn.png)

With a bit of practice, you will be able to apply these patterns to any algorithm problem and start solving problems. Pick up your free copy of coding techniques today!

{% embed https://joashxu.gumroad.com/l/dejhv %}
Django Template - Tips
Tags: python, django, expressions, programming
Published: 2022-05-15 08:01:27

Found these helpful :

**Iterating dictionary**

`{% for key, values in data.items %}
    <tr>
        <td>{{key}}</td>
        {% for v in values[0] %}
        <td>{{v}}</td>
        {% endfor %}
    </tr>
    {% endfor %}`

**_Loop counter _**

`{% for item in item_list %}
    {{ forloop.counter }} #  index 1 start
    {{ forloop.counter0 }} #  index 0 start
{% endfor %}`

**Mathematical operations**

`{% load mathfilters %}


<h1>Basic math filters</h1>

<ul>
    <li>8 + 3 = {{ 8|add:3 }}</li>

    <li>13 - 17 = {{ 13|sub:17 }}</li>

    {% with answer=42 %}
    <li>42 * 0.5 = {{ answer|mul:0.5 }}</li>
    {% endwith %}

    {% with numerator=12 denominator=3 %}
    <li>12 / 3 = {{ numerator|div:denominator }}</li>
    {% endwith %}

    <li>|-13| = {{ -13|abs }}</li>
</ul>
`
String expressions

<h4>Skills</h4>
`{% with form.instance.skills|split:"," as skills %}
    {% for skill in skills %}
        {{ skill }}<br>
    {% endfor %}
{% endwith %}`

extracting character
`<a href="tel://+1{{ phone|cut:'-' }}">Phone</a>`
Today's Daily Dose of Programming Humor
Tags: jokes, dailydeveloperjokes
Published: 2022-05-15 08:00:23

---
title: "Today's Daily Dose of Programming Humor"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
published: true
tags: #jokes, #dailydeveloperjokes
---

Hi there! Here's today's Daily Developer Joke. We hope you enjoy it; it's a good one.

![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e1258f70cd7f.png)

---

For more jokes, and to submit your own joke to get featured, check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/). We're also open sourced, so feel free to view [our GitHub Profile](https://github.com/dailydeveloperjokes).

### Leave this post a ❤️ if you liked today's joke, and stay tuned for tomorrow's joke too!

_This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit._

<!--
Joke text:
___Q:___ Are computers dangerous?

___A:___ Nah, they don't byte. They just nibble a bit.
 -->
C++ Concepts In Action
Tags: cpp, cpp20, templates
Published: 2022-05-15 05:23:16

C++20 has a new feature called Concept that allows developers to specify constraints on template parameters. Template meta programming is a complex topic that stumps even seasoned veterans. I found an interesting usage of this feature to ensure that I can write an overloaded stream insertion operator that can output C++ containers that support range based iteration (basically types that have begin and end methods).

```
#include <iostream>
#include <unordered_map>
#include <array>
#include <vector>
using namespace std;

template<typename ContainerType>
concept SupportsRangeBasedFor = requires(ContainerType container) {
    container.begin();
    container.end();
};

template<typename KeyType, typename ValueType>
ostream& operator<<(ostream& os, const pair<KeyType, ValueType>& p) {
    os << p.first << "->" << p.second;
    return os;
}

ostream& operator<<(ostream& os, SupportsRangeBasedFor auto&& container) {
    os << "[ ";
    for (const auto& element : container) {
        os << element << ' ';
    }
    os << ']' << endl;
    return os;
}

int main()
{
    cout << vector<int>{1,2,3} << endl;
    cout << array<int,3>{4,5,6} << endl;
    cout << unordered_map<int,int>{{8,9},{10,11},{11,12}} << endl;
    //struct Foo {};
    //cout << Foo {} << endl; // Compiler Error: No overload for operator<< that accepts Foo
    return 0;
}
```

Running this program produces this output:

```
~/code/cpp/concepts > ./concept
[ 1 2 3 ]

[ 4 5 6 ]

[ 11->12 10->11 8->9 ]

```
So, we have a single overload that can support any container that has a begin and end method. This is not magic, you could have got this to work without `SupportsRangeBasedFor` concept, but the magic is what the concept prevents from happening: 

Without the constraint on the template parameter, compiler would have happily chosen `operator<<` overload for `Foo` and you would get an indecipherable blob of errors caused by the fact that `Foo` doesn't have `begin` and `end` methods. You will see errors of this nature:

```
concept.cpp:22:30: error: invalid range expression of type 'Foo'; no viable 'begin' function available
    for (const auto& element : container) {
                             ^ ~~~~~~~~~
concept.cpp:35:10: note: in instantiation of function template specialization 'operator<<<Foo>' requested here
    cout << Foo {} << endl; 
```

Not only that, the compiler would match any `ostream.operator<<(...)` call to this overload because the template parameter type (introduced by `auto` type specifier) will match all types. 

The type constraint expressed by the concept explicitly forbids the compiler from picking up your template function for types that you don't wish to support. This is a pretty neat feature and I hope to be using this quite widely in my future development to limit the types that my implementation should be chosen for :)