teleren/devto huggingface dataset:
Ruby Science Saturday: use Mixin Modules or Reopen Classes? 👩‍🔬🔬🧬🧪
Tags: ruby, performance, todayilearned, benchmarking
Published: 2020-02-22 14:11:39

Ruby legend [Xavier Noria](https://twitter.com/fxn) recently penned a tweet that got me thinking about how we organize and package up our native Ruby code:

![Xavier Noria Tweet](https://i.imgur.com/NNpVk4Q.png)

How often do we just dump our code into mix-in modules (that never get reused) when our classes get too large? What if we continued to organize our code into separate files, but reopened classes?

This is something we can debate all day in the comments, but that sparked my **Ruby Science** question:

__What if one of these approaches was faster?__

Well, thanks to [benchmark-ips](https://github.com/evanphx/benchmark-ips), (which I have also bundled into my own [performance logging gem](https://github.com/Schwad/schwad_performance_logger)) we don't have to wonder. 

I fired up three example cases (Reopen, Include mixin module, Extend mixin module) and ran them against each other in a simple test case. Code below:

```
module MixinDependency
  def open_door
    puts 'Door is open!'
  end
end

class DoorOpenerMixin
  include MixinDependency

  def close_door
    puts 'Door is closed!'
  end
end

class DoorOpenerMixinExtend
  extend MixinDependency
end

class DoorOpenerReopen
  def close_door
    puts 'Door is closed!'
  end
end

class DoorOpenerReopen
  def open_door
    puts 'Door is open!'
  end
end
```

And we tested it with:

```
require 'benchmark/ips'

Benchmark.ips do |x|

  x.report('Include') { DoorOpenerMixin.new.open_door }
  x.report('Extend') { DoorOpenerMixinExtend.open_door }
  x.report('Reopen') { DoorOpenerReopen.new.open_door }

  x.compare!
end
```

Results? Nothing exciting.

```
Comparison:
              Extend:   214816.5 i/s
              Reopen:   197784.3 i/s - same-ish: difference falls within error
             Include:   182298.2 i/s - same-ish: difference falls within error
```

Even inconclusive findings are still __findings__, and I hope you enjoyed seeing how I picked through this hypothesis to give a clear answer. If you're unfamiliar with benchmark-ips, copy this code and try it out yourself! It really is one of my favorite tools in my toolbox.

One _small_ but fun finding, I tried running this on different Ruby versions, you can see a clear speed bump since Ruby 2.1! Here's the results on the old version:


```
Comparison:
              Extend:   178840.8 i/s
             Include:   167210.7 i/s - same-ish: difference falls within error
              Reopen:   166005.2 i/s - same-ish: difference falls within error
```

If you have any 'experiments', feel free to share your results and thoughts below! 🥼 🤔
Active Record Transactions in Ruby on Rails
Tags: rails, activerecord, transactions, ruby
Published: 2020-02-22 14:10:48

I have learned a lot by reading the API docs at [ Ruby on Rails Active Record Transaction ](https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html "Ruby on Rails Active Record Transaction").

> Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. 

The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. 

Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically you should use transaction blocks whenever you have a number of statements that must be executed together or not at all.

## Examples

### 1. Withdrawal and Deposit:

```ruby
ActiveRecord::Base.transaction do
  david.withdrawal(100)
  mary.deposit(100)
end
```

So, while running the withdrawal method of the user model, if an error comes then the next method of user deposit is not called.

Similarly, if the withdrawal of David is done but an error comes in the deposit method of Mary then changes occurred during David’s withdrawal method will be rollback so the money will not be transferred at all.

### 2. Object Duplication:

I normally use Active Record Transactions when I am about to duplicate an instance that also has a relation of `has_many` with other model instances.

```ruby
class Post < ApplicationRecord
  ...
  def duplicate!
    ActiveRecord::Base.transaction do
      post_dup = self.dup
      post_dup.save!
      comments.find_each do |comment|
        comment_dup = comment.dup
		comment_dup.post_id = post_dup.id
        comment_dup.save!
      end
    end
  end
end
```

So, the duplicated post doesn’t get saved until unless all the comments of the post are duplicated and save with duplicate post id.

## Callbacks of Active Record Transaction

Active Record Transactions have two callbacks `after_commit`, and `after_rollback`.

`after_commit` is called when the transaction is completed successfully.

`after_rollback` is called when the transaction is unsuccessful.

## Models are children of Application Record:

> Transactions are per-database connection, not per-model.

As the transaction is the part of `ActiveRecord::Base` so all models can access transactions using class or instance. For Example, below are all valid snippets:

```ruby
Account.transaction do
  balance.save!
  account.save!
end
```

```ruby
balance.transaction do
  balance.save!
  account.save!
end
```

## Rails 6 multiple database connection issues:

A transaction acts on a single database connection. If you have multiple class-specific databases, the transaction will not protect interaction among them. One workaround is to begin a transaction on each class whose models you alter:

```ruby
Student.transaction do
  Course.transaction do
    course.enroll(student)
    student.units += course.units
  end
end
```

This is a poor solution, but fully distributed transactions are beyond the scope of Active Record.
pass Statements (Dutch)
Tags: python, dutch, nederlands
Published: 2020-02-22 13:28:37

In sommige programmeertalen is er een statement die niets doet. In de assembly taal is er de `nop` operatie. Hoe zit het met Python?

In <a href="https://python.org">Python</a> kun je het `pass` statement gebruiken. Het `pass` statement doet niets.

## Waarom pass

Python heeft de syntactische eis dat code blokken (for, if, def, class etc.) niet leeg zijn. 

Lege codeblokken zijn nuttig in verschillende contexten, bijvoorbeeld wanneer je nu geen tijd hebt om ze te implementeren. 

```python
def complexeFunctie():
    pass
```

Andere doeleinden zijn het <a href="https://pythonprogramminglanguage.com/try-except/">afhandelen van een exceptie</a> die geen nieuw gedrag toevoegt.

```python
class CustomException (Except):
    pass
```

Hieronder vindt u nog enkele voorbeelden van pass

## Pass voorbeelden

Als er niets moet gebeuren in een codeblok, is er een pass statement nodig om zo'n blok geen IndentationError te laten produceren.


U kunt dit voor allerlei doeleinden gebruiken. Binnen een een lus:

```python
>>> while not True:
...     pass
```

Dit zal wachten op een toetsenbordonderbreking (Ctrl+C)

In een <a href="https://pythonbasics.org/class/">class</a> die u moet implementeren, maar die u later zult implementeren:


```python
>>> class Example:
...     pass
...
```

Maar pas op, als een klasse niet geimplementeerd is, kun je nog steeds objecten maken:

```python
>>> obj = Example()
>>> 
```

In een functie die u later implementeert:

```python
>>> def hallo():
...     pass # Implementeer dit later
```

**Gerelateerde links:**
* <a href="https://medium.com/better-programming/how-to-use-pass-break-and-continue-in-python-6e0201fc032a">Hoe gebruik je een pass, pauze en continue</a>
* <a href="https://pythonbasics.org">Python beginners tutorial</a>
Dictionary als tabel printen (Dutch)
Tags: python, dutch, nederlands
Published: 2020-02-22 13:00:30

In <a href="https://python.org">Python</a> kunt u gemakkelijk geformatteerde strings gebruiken om variabelen te weergeven.
  
Met geformatteerde strings (f-strings) kun je variabelen in een string opnemen door de string te voorzien van het voorvoegsel *f* of *F* en expressies te schrijven als `{expressie}`.

Als je een f-string hebt, kun je de `:10` gebruiken om er zeker van te zijn dat deze 10 karakters breed is. Zo kun je een dictionary als tabel weergeven.

Als u nieuw bent met Python programmeren, moet u eerst <a href="https://pythonbasics.org">de basis leren</a>.

## Formatteer dictionary als tabel met f-strings

Als u een nieuwere versie van Python heeft (>3.5) kunt u gebruik maken van f-strings. Hiermee kunt u de strings eenvoudig weergeven.

Eerst definiëren we een <a href="https://pythonbasics.org/dictionary/">dictionary</a>, dan itereren we erover met een for-loop en formatteren we het met f-strings.

```python
>>> table = { "Alice": 12, "Jim": 15, "Tim": 19 }
>>> for name, id in table.items():
...     print(f'{name:10} => {id:10d}')
... 
Alice      =>         12
Jim        =>         15
Tim        =>         19
>>> 
```

Als u een header wilt toevoegen, roept dan eerst de print functie op, met als parameter de header tekst.

```python
d = { "Alice": 128, "Bob": 256, "Tim": 512, "Jim": 1024 }
print(f"Key{' ':14} Value{' ':15}")
for k, v in d.items():
    print(f"{k:8}{v:15}")
```

Dit geeft het volgende resultaat

```python
Key   Value               
Alice 128
Bob   256
Tim   512
Jim   1024
```

## Bestaande functies

Je kunt ook een bestaande functie gebruiken, zoals deze die ik op het web heb gevonden. Persoonlijk geef ik de voorkeur aan het formatteren met f-strings, maar dit is misschien wat je zoekt.

```python
def printTable(myDict, colList=None):
    if not colList: 
        colList = list(myDict[0].keys() if myDict else [])
    myList = [colList] # 1st row = header
    for item in myDict: 
        myList.append([str(item[col] or '') for col in colList])
    #maximun size of the col for each element
    colSize = [max(map(len,col)) for col in zip(*myList)]
    #insert seperating line before every line, and extra one for ending. 
    for i in  range(0, len(myList)+1)[::-1]:
         myList.insert(i, ['-' * i for i in colSize])
    #two format for each content line and each seperating line
    formatStr = ' | '.join(["{{:<{}}}".format(i) for i in colSize])
    formatSep = '-+-'.join(["{{:<{}}}".format(i) for i in colSize])
    for item in myList: 
        if item[0][0] == '-':
            print(formatSep.format(*item))
        else:
            print(formatStr.format(*item))

d = { "Alice": 128, "Bob": 256, "Tim": 512, "Jim": 1024 }
printTable([d])
```

Deze geeft de tabel weer in ascii art:


```
------+-----+-----+-----
Alice | Bob | Tim | Jim
------+-----+-----+-----
128   | 256 | 512 | 1024
------+-----+-----+-----
```

**Gerelateerde links:**
* <a href="https://pythonprogramminglanguage.com">Python tutorial</a>
* <a href="https://www.python.org/dev/peps/pep-0498/">Python f-strings</a>
Abandon the digital world
Tags: books, beginners, productivity
Published: 2020-02-22 08:40:55

---
title:Abandon the digital world
published: true
description: 
tags: #books #beginners # productivity
---

Call me old school, but I love reading books - actual books like the ones you use offline. And call me nerdy, but I love coding. Combine these two activities and you are going to end up with amazing titles. 

I believe that, next to the always present argument that reading trains your brain, holding these sources of information in your hand as physical object has a completely different effect on you and your brain. 
I have been reading the books “Clean Code” and “Clean Architecture” both written by Robert C. Martin over the course of the last few weeks, and although many things he writes about seem to be trivial, you really need to read or at least hear about some topics so you actually start paying attention to those things mentioned. In “Clean Code” for example he talks about comments. Sure, I know that sounds like something you would at most write three sentences about, but there is a total of 20 pages dedicated to this topic. There are things the light still needs to touch for you, details that you were oblivious to. 

Learning how to code, understanding how to use the right keywords at the right spot, being able to translate your thoughts into a programming language of your choice and being able to debug this pile of lines you produced after discovering a bug, is just the fundamental understanding you had to build up. Now we are not just talking about code, we are talking about code of which you can say:

“It works, and I know why! That is the next level and you want to reach it. “

This kind of quality content, providing such a degree of depth into the topics it covers, is barley found in an article or a tutorial. These titles have an awesome build up and really set the scene for you with all the fundamentals first, get you in the right mood if you so will, before throwing the complex stuff at you. This is something you cannot do within a five-hundred-word blog or even a thirty-minute YouTube video. Be honest, how many times do you end up with thousands of tabs opened in your browser only to google some concept or technical term you did not know and completely lost yourself within a tutorial on how to get started with entity framework and the Wikipedia page of newton’s flaming laser sword? Also, who just looked up the sword?

That being said, I encourage you, no matter if you are a beginning or even more than just an advanced developer, treat yourself with a delightful book, a hot cup of coffee and start reading today!
Daily Developer Jokes - Saturday, Feb 22, 2020
Tags: jokes, dailydeveloperjokes
Published: 2020-02-22 13:00:17

---
title: "Daily Developer Jokes - Saturday, Feb 22, 2020"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
cover_image: "https://private.xtrp.io/projects/DailyDeveloperJokes/thumbnail_generator/?date=Saturday%2C%20Feb%2022%2C%202020"
published: true
tags: #jokes, #dailydeveloperjokes
---

Generated by Daily Developer Jokes, a project by [Fred Adams](https://xtrp.io/) ([@xtrp](https://dev.to/xtrp) on DEV)

___Read about Daily Developer Jokes on [this blog post](https://xtrp.io/blog/2020/01/12/daily-jokes-bot-release/), and check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/).___
### Today's Joke is...
![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e1258febded7.png)

---
*Have a joke idea for a future post? Email ___[xtrp@xtrp.io](mailto:xtrp@xtrp.io)___ with your suggestions!*

*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:___ Why couldn’t the user update a file on a shared server?

___A:___ They didn’t have the write permissions
 -->
What is Learn With Geeks on GitHub
Tags: github, organization, slimcoder
Published: 2020-02-22 12:40:53

---
title: What is Learn With Geeks on GitHub
published: true
description: 
tags: github , organization , slim coder
cover_image: https://avatars3.githubusercontent.com/u/61349424?s=400&u=43702bf396f901fe3763d02eff4920eb6b1779f1&v=4
---

Learn with geeks is my new initiative on GitHub . 
It is plateform in which you can share your sample code / boilerplate's and things which you learned. You are free to transfer any repo but that repo should be informative for dev community.

I'm founder of learn with geeks and i need members for this organization.

If you are interested to join this organization on GitHub. 
please mail me at : sharma_vivek62@yahoo.com
Organization Github : https://github.com/learnwithgeeks
Optimising User-Centric Performance Metrics
Tags: webperf, javascript
Published: 2020-02-22 12:20:16

Knowing about user-centric performance metrics and thereby optimising them, inevitably improves user experience.

The simplest way to do so is to use less javascript code on the client. But some times, that is not an option. As such, knowing how to _deliver_ your javascript is a plus.

Let's look at how to optimise user-centric performance metrics next.

#### OPTIMISING FIRST PAINT (FP) & FIRST CONTENTFUL PAINT (FCP)

The different ways to optimise paint times for your web projects are:
- Reducing the number of _render-blocking_ stylesheets and scripts,
- Caching critical resources to speed up repeat visits,
- Minifying and compressing text-based assets to speed up their download times,
- Do less javascript work on page load.

The [App Shell Model](https://developers.google.com/web/updates/2015/11/app-shell) is a great way to optimise paint times for Progressive Web Apps.

#### OPTIMISING FIRST MEANINGFUL PAINT (FMP) & TIME-TO-INTERACTIVE (TTI)

The recommended way to optimise FMP is by optimising the Critical Rendering Path.

TTI can be improved by _deferring_ or removing unnecessary javascript work that occurs during page load. 


As to how to go about doing all of the above stated recommendations, we will go through them one by one in the next post.
Exceptions (Dutch)
Tags: python, beginners, dutch, nederlands
Published: 2020-02-22 11:45:38

<a href="https://python.org">Python</a> Toepassingen kunnen aangepaste Exceptions oproepen door een nieuwe Exception klasse te creëren. Deze moeten over-erven van de 'Exception'-klasse.

## Wat is een Exception?

Een exception is een fout. Een exception kan worden gegooid met het `raise` keywoord. Ze kunnen worden afgehandeld met een <a href="https://pythonprogramminglanguage.com/try-except/">try-catch</a> blok.

U kunt dit proberen in de Python-shell, door `raise Exception("uw bericht")` in te typen.

    ➜ ~ python3
    Python 3.7.5 (standaard, 20 november 2019, 09:21:52) 
    GCC 9.2.1 20191008] op linux.
    Typ "help", "copyright", "credits" of "licentie" voor meer informatie.
    >>> raise Exception("No can do")
    Traceback (laatste oproep):
      Bestand "<stdin>", regel 1, in <module>
    Exception: Nee, dat kan niet
    >>> 

Alle ingebouwde Exceptions maken gebruik van de `Exception` klasse. Bij het maken van een nieuw type Exceptie klasse, moet van de Exception klasse Except geeerfd worden (<a href="https://pythonbasics.org/inheritance/">inheritance</a>).

## Custom Exception

Het onderstaande programma maakt een aangepaste Exceptie `HappyError`, die erft van de `Exception` klasse.

```python
class HappyError(Exception):
    pass

raise HappyError("To happy to run")
```

Het bovenstaande programma gooit dan de `HappyError` uitzondering:

    ➜ ~ python3 program.py
    Traceback (laatste oproep):
      Bestand "t.py", regel 5, in <module>
        raise HappyError("To happy to run")
    __main__.HappyError: To happy to run

Veel modules definiëren hun eigen uitzonderingen.

Optioneel kunt u de <a href="https://pythonbasics.org/constructor/">constructor</a> op deze manier overschrijven:

```python
class ValidationError(Exception):
    def __init__(zelf, bericht, fouten):
        super().__init__(bericht)

        # Nu voor uw aangepaste code...
        self.errors = fouten
```

Maar met Python 3 Exceptions hoef je niets te overrulen. Als je alleen maar een informatieve boodschap wilt voor je uitzondering, doe dan dit:

```python
class MyException(Exception):
    pass

raise MyException("Gaat iets mis")
```
async/await Crash Course
Tags: javascript, node
Published: 2020-02-22 11:41:38

🔥 Learn async/await (very basics) here 👇



When you learn async/await in #JavaScript,

you quickly fall into words like

- Synchronous & Asynchronous code

- Event Loops

- Promises

These things aren't easy to understand in one go.

Complex theories gatekeep beginners.

So, we will only learn about practical stuff.


---


Let us first learn about "Promises"

In the below snippet, what we are intending is to 
output `Done First`
and then output `Done Last`.

But the below snippet outputs "Done Last" first.

That is now JavaScript behaves. It does not wait by default.

![Code Snippet](https://i.ibb.co/d0Nc65D/1.png)

---

To make JavaScript wait for a second 

to output `Done First`

and then print `Done Last`...

We use `Promise` constructor. 

It accepts a function as the only argument. 

The function receives few params. 2 of them being `resolve` and `reject`

![Code Snippet](https://i.ibb.co/4p2VXw9/2.png)

`resolve` accepts arguments.

These arguments later become the params in the .then() function.

So, the .then() function runs only after the promise is resolved.

Well, don't create a Promise just for a "console.log after setTimeout".

This was just for explanation. 🙂

---

Now, here's the async/await part.

```js
promise.then(() => console.log('Done Last.'))
```

can also be written as

```js
 await promise
 console.log('Done Last.')
```

Just like in the below snippet. It just works!

Wondering what's the `async` part in the below snippet?

![Code Snippet](https://i.ibb.co/zs8X16s/3.png)

---

The await keyword only happens to work inside an async function.

An async function tells the compiler ahead of time that the function will be returning a Promise and will not have a value resolved right away.

![Code Snippet](https://i.ibb.co/8D39DNp/4.png)

---

I hope that gives a basic idea about what async/await is and what it does.

Here are two nice resources about it 🔥

- [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)

- [https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261)

---

If you spot a mistake, let everyone know 🙌

---

### About me

I am Kumar Abhirup, a 16-year-old JavaScript React developer from India who keeps learning a new thing every single day.

[Connect with me on Twitter 🐦](https://twitter.com/kumar_abhirup)
[My personal website and portfolio 🖥️](https://kumar.now.sh)

_Comment below your better ways, and suggestions to improve this post. :)_
ReactJS -- If it is setting a state with the same value, will the component be re-rendered?
Tags: javascript, react
Published: 2020-02-22 11:38:22


## Function component -- `setValue(v)`

if `v` is the same value as before, then the function component won't be re-rendered (the function component won't be called).

Example: https://stackblitz.com/edit/react-zo3hnj?file=index.js


## Class component -- `setState({ data: v })`

if `v` is the same value as before, then the class component will be re-rendered (the class component's render() will be called).

Example: https://stackblitz.com/edit/react-fb8npx?file=index.js
Which mac is good for developing?
Tags: discuss, laptop, webdev
Published: 2020-02-22 11:33:10

I would love to start developing iOS applications, but at the same time I want to combine it with my work developing web pages (Laravel, Other PHP Frameworks, etc.).

I wanted to ask your opinion about which mac laptop you recommend for programming.

I hope I explained myself well, hahahaha.

Thanks in advance.