teleren/devto huggingface dataset:
Python's 'heapq' module
Tags: python, beginners, devtips, learning
Published: 2018-12-21 09:53:23

---
title: Python's 'heapq' module
published: true
description: Finding the largest and smallest items in a collection with Python's 'heapq' module
canonical_url: https://wangonya.com/post/heapq/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/fqkl1ssffibfip6mz3ya.jpg
tags: python, beginners, devtips, learning
---
Often when working with collections of data, you may want to find the smallest or largest item. It's easy enough to write a function that iterates through the items and returns the smallest or largest one, or use the builtin `min()`, `max()`, or `sorted()` functions. Another interesting way may be implementing a heap (priority) queue.

Python provides a pretty convenient module called `heapq` that does that for you. `heapq` comes with a cool set of inbuilt functions that you can read more about in the [docs](https://docs.python.org/3.0/library/heapq.html). For this short post, I just want to show how you can easily find the smallest and largest items in a collection

## Finding the smallest items
Find 3 of the smallest items using the `nsmallest` function:
```python
import heapq

numbers = [9, 45, 21, 4, 63, 3, 109]

print(heapq.nsmallest(3, numbers)) # [3, 4, 9]
```

Also, converting a list into a heap using the `heapify` function automatically sets the smallest item as the first:
```python
import heapq

numbers = [9, 45, 21, 4, 63, 3, 109]

heapq.heapify(numbers)
print(numbers)
# Output: [3, 4, 9, 45, 63, 21, 109]
```

You can then pop from the heap with `heappop()`:
```python
heapq.heappop(numbers) # 3
print(numbers)
# Output: [4, 45, 9, 109, 63, 21]

heapq.heappop(numbers) # 4
print(numbers)
# Output: [9, 45, 21, 109, 63]
```

## Finding the largest items
Find 3 of the largest items using the `nlargest` function:
```python
import heapq

numbers = [9, 45, 21, 4, 63, 3, 109]

print(heapq.nlargest(3, numbers)) # [109, 63, 45]
```

## A more practical example
```python
import heapq

people = [
    {'fname': 'John', 'lname': 'Doe', 'age': 30},
    {'fname': 'Jane', 'lname': 'Doe', 'age': 25},
    {'fname': 'Janie', 'lname': 'Doe', 'age': 10},
    {'fname': 'Jane', 'lname': 'Roe', 'age': 22},
    {'fname': 'Johnny', 'lname': 'Doe', 'age': 12},
    {'fname': 'John', 'lname': 'Roe', 'age': 45}
]

oldest = heapq.nlargest(2, people, key=lambda s: s['age'])
print(oldest)
# Output: [{'fname': 'John', 'lname': 'Roe', 'age': 45}, {'fname': 'John', 'lname': 'Doe', 'age': 30}]

youngest = heapq.nsmallest(2, people, key=lambda s: s['age'])
print(youngest)
# Output: [{'fname': 'Janie', 'lname': 'Doe', 'age': 10}, {'fname': 'Johnny', 'lname': 'Doe', 'age': 12}]
```

It should be noted though that the `nsmallest(n, iterable)` and `nlargest(n, iterable)` functions perform best for smaller values of `n`. For larger values, it is more efficient to use the `sorted()` function. Also, when `n==1`, it is more efficient to use the builtin `min()` and `max()` functions.
Next js is the best option for static sites 
Tags: nextjsreact
Published: 2018-12-21 08:33:09

---
title: Next js is the best option for static sites 
published: true
description: well it looks like everybody wants a full stack sites now adays , if you look at the sites build today you notice there is full stack more than what we used to have. so static sites are being also delivered by javascript or using fullstack , which i don't used to recommend til i got introduced to next js . next js is best for static sites. static sites should be searched and should load quick , as next js provides
tags: nextjs react
---
How hackers are creating knowledge
Tags: knowledge, hackernews, knowledgebase
Published: 2018-12-21 08:27:50

---
title: How hackers are creating knowledge
published: true
description: After reading seven Hacker News threads with more than twelve hundred comments I've found no tool I would immediately jump in to create personal knowledge.
tags: knowledge, hacker news, knowledge base 
canonical_url: https://morethemes.baby/2018/09/14/how-hackers-are-creating-knowledge/
---

After reading [seven](https://morethemes.baby/2018/04/25/how-others-create-knowledge/) Hacker News threads with more than twelve hundred comments I’ve found no tool I would immediately jump in to create personal knowledge.

Five of the threads are pretty recent — summer and autumn of 2018 — revealing a clear pain point the community suffers.

They include not just knowledge creation but proper note taking and goal tracking, information organization and searching, universal syncing and access (mobile), interoperability (data portability) and tool stability (the development stops after a few years).

There were over fifty suggestions for tools to use — like these collected by [SaasHub](https://www.saashub.com/reviews/post-news-ycombinator-2018-07-15-ask-hn-favorite-note-taking-software) from one of the threads.  The consensus is that instead of a common tool a set of tools must be used, each tailored for a different task.

It’s clear Evernote missed this train and Org mode for Emacs is a winner, together with individual solutions like hacking plain text / markdown files and folders together.

Many hackers rely on tools offered by default by their operating system like Google Keep and Suite, Microsoft OneNote and Apple Notes. Others are using tools like Simplenote, Zim Wiki, Notion, Workflowy, Quiver, Vim Wiki, Notational Velocity and Zotero of course.

Some even still use pen and paper. Anki was noticed only a few times. And only half a dozen people were found really digging into this subject of creating knowledge.

It seems these tasks and things are hard, highly personal together with the tools used in the process.

We all have different data use patterns which require highly flexible, customizable tools and services no one offers in a single pack.

Some tools are good for archiving, tagging, categorizing and others are good to distill knowledge, create knowledge, and make remember things. Sometimes search is more important than organization.

In this chaotic order — at the end — a few good advices were found. General rules we can say, which made the day.

1. Make sure organizing knowledge doesn’t becomes a goal itself. Get a use case first then start organizing information around that.
2. Make a distinction between passive and active information. Information for archival and information as knowledge which personal, working for you.
3. Don’t over-engineer.
Seven essential qualities of open source
Tags: opensource, matthewbutterick
Published: 2018-12-21 08:22:52

---
title: Seven essential qualities of open source
published: true
description: 
tags: open source, Matthew But­t­er­ick
canonical_url: https://morethemes.baby/2018/09/19/seven-essential-qualities-of-open-source/
---


[Matthew But­t­er­ick](https://practicaltypography.com/seven-essential-qualities-of-open-source.html) of Practical Typography nails it:

1. Open source arises from a spirit of cap­i­tal­ist competition.
2. Open-source de­vel­op­ers are paid.
3. Open source re­de­fines what is valuable.
4. Open source re­lies on meritocracies.
5. Open source re­lies on benev­o­lent dictators.
6. An open-source project re­quires mul­ti­ple developers.
7. Open source is part of the project’s DNA or it’s not.

If these are not met, he says, it’s not open source it's just *file sharing*.
Headless CMS is Structured CMS
Tags: gutenberg, wordpress, headlesscms, destructuring
Published: 2018-12-21 08:17:59

---
title: Headless CMS is Structured CMS
published: true
description: Structured content and the new breed of visual content designer tools
tags: gutenberg, wordpress, headless cms, destructuring
canonical_url: https://morethemes.baby/2018/12/07/headless-cms-is-about-structured-cms/
---

We all know the future of Content Management Systems is headless: content is created in a certain specialized system which is not necessarily responsible to deliver it to end users.

Up until now these two facets were bundled. You’ve created a post in the WordPress dashboard and displayed to your users again using a WordPress theme.

In the future you’ll be able to create content in any system, anywhere, and still be able to display in your website as it was created on your own website’s backend. This is called headless and semantic, distributed web. The bright new future we all need.

Why this change?

The nature of the web is napstering: decomposing monolithic and monopolistic structures by eliminating the middlemen. The newly born layers will form a new market with new leaders, which later will be napstered again. The law of entropy, one might say.

WordPress became a monolith and a monopoly in the sense that it controlled both the server, the data, the content and the presentation layer. And it was napstered by many new markets like microservices instead of servers; federated data instead of one single centralised database; better visual content designers and editors like Wix, Contentful, and co; React and other component frameworks instead of themes on front-end.

It was a revelation to read [Strategies For Headless Projects With Structured Content Management Systems](https://www.smashingmagazine.com/2018/11/structured-content-done-right/) on Smashing Magazine by Knut Melvær who is behind one of the most interesting new players in this scene, Sanity.io
Private copy of method in Python base class
Published: 2018-12-21 07:58:44

---
title: Private copy of method in Python base class
published: true
description: 
tags: 
---
There is an example of code in Python documentation as follows: 
Mapping:
    def __init__(self, iterable):
        self.items_list = []
        self.__update(iterable)
    def update(self, iterable):
        for item in iterable:
            self.items_list.append(item)
    __update = update #private copy of original update () method
 
In the last line of code is the comment #private copy of original update(). According to the literature, this is supposed to create a private copy of the update method in the base class in case an update method is created in a sub class. 

Does anyone have any insight on the significance of doing this?
DSCE Hack, 2016
Tags: esp8266, iot, arduino, hackathon
Published: 2018-12-21 06:29:45

---
title: DSCE Hack, 2016
published: true
description: DSCE Hack
tags: esp8266, iot, arduino, hackathon
---



Dayananda Sagar College of Engineering, the college I am a part of currently, conducted an open themed 16-hour hackathon for the Computer Science Engineering students of the college during March 2016. Mostly people from the second and third year were participating, with me being the only kid from the first year.

I wanted to build a product roughly in the IoT area, a mentor from DERBI, a entrepreneurship cell in my college, suggested that I try to show him a fully functional IoT stack, I agreed and started with one.

HackIndia had thought me a thing or two about IoT, in this demo, I had 2 LEDs that represented the state of bulbs in 2 rooms, the LEDs were connected to a laptop which was in turn connected to the Internet. I had a separate circuit built with just a motion sensor, it was connected to a different laptop and sent requests to turn on/off the LEDs that were connected to the first laptop. Apart from the motion sensor, you could also change the state of the switches with the help of an Android app we quickly wrote from scratch, it also sent requests to the LED connected laptop. This was all possible because of a web server running on the first laptop, we made a front end for this server and this allowed you to switch the LEDs from the computer too. So you had like 3 toggle-able access points per LED, you could easily replace the LED with an actual household appliance with a single channel relay per appliance.

This allows you to control your home appliances with the help of technology, you could potentially scale this system to detect movement and in the absence of any, you could automatically switch off all the lights in the house to save electricity. In order to improve the product, you could potentially add thermos-sensors so that you could know the temperature of the room, and alter the speed of the fan to match a given user temperature, you could also add light sensors so that you could dim lights that are in the presence of natural sunlight. Adding Google's Nest API support would go a long way in helping new devices interact with the existing IoT stack, most of the toggling could be handled through the Nest API, we therefore do not need to build client side interfaces to the user.

Right now this was built with an Arduino as it was just a demo, if you were to implement this to scale, you'll ideally want to look at ESP8266 with a strong base signal so that you can do peer-2-peer control of the appliances, it'll also work out significantly cheaper. The cost-barrier to entry to a product that'll be built with an ESP8266 could be as low as Rs. 350 per appliance at home, that's Rs. 280 for the ESP8266 and Rs. 70 for the single channel relay.

The judges were impressed with my product and I was placed First in this hackathon, I received a medal, a certificate and an Amazon gift voucher of Rs. 1000.
AoC Day 21: Chronal Conversion
Tags: adventofcode, discuss
Published: 2018-12-21 05:35:01

---
title: "AoC Day 21: Chronal Conversion"
published: true
description: "Day 21: Wherein we try to achieve an integer underflow in time... Or something."
cover_image: https://thepracticaldev.s3.amazonaws.com/i/5x0zf6qrbstxxbwidmgp.png
tags: adventofcode, discuss
series: Advent of Code  
---

...

Honestly?  Your guess is as good as mine.  It's [Day 21](https://adventofcode.com/2018/day/21), and we're exploiting an integer underflow bug in the space-time continuum?  In order to save Christmas?  I guess?

I think I'm going to have to spend some time on this one before I even understand exactly what it is that we have to do.  All I know is that we are fiddling with the registers in our time machine again so that we don't go back in time indefinitely forever.

Ho.  Ho.  Ho.

Good luck!  🤶
Check which commands you typed in the command line and don’t repeat yourself!
Tags: commandline, linux
Published: 2018-12-21 08:33:39

---
title: Check which commands you typed in the command line and don’t repeat yourself!
published: true
tags: command line,linux
canonical_url: https://flaviabastos.ca/2018/12/21/check-which-commands-you-typed-in-the-command-line-and-dont-repeat-yourself/
---

Recently I needed to repeat a series of long~ish commands in the command line but I never quite memorized them so I ended up resourcing to arrow-up-arrow-up-arrow-up _</ad nauseum>_ until I found the command I was looking for.

But there is a better and super simple way: `history`

Typing `history` in the command line will list all the recent typed commands (I’m not sure how far it goes…) so you don’t need to remember anything. Now the problem is when you have a very long output. You end up scrolling-scrolling-scrolling _</ad infinitum_>_…_

In this case you can use `| grep` (pipe (|), the thing on the same key as the \ in your keyboard) to limit the results. For example: I remember that the command I want has the word ‘prune’ in it but I can’t remember the exact command, so I run:

`history | grep prune`

and I will get only a list of commands that contain the word ‘prune’.

Now that I have the full command I can also save some typing. See that the history output has a number before the list of commands?

```
6050 docker ps6051 docker images6052 docker rmi c516053 docker ps -a6054 docker image ls6055 docker volume prune -f6056 docker system prune -a6057 docker images6058 docker ps
```

Well,  if you type !command-number, that command will be executed. From my list above, if I type

`!6055`

The command `docker volume prune -f` will run again.

It took me a while to starting using these shortcuts. I didn’t see how searching for a command and calling its shortcut was useful until my history got super long and I started using some commands so rarely that it was hard to recall them from memory.

> The post [Check which commands you typed in the command line and don’t repeat yourself!](https://wp.me/pa0b0y-29) was originally published at [flaviabastos.ca](https://flaviabastos.ca/)
Much needed filterMap in JavaScript
Tags: javascript, map, filter, discuss
Published: 2018-12-21 04:49:46

---
title: Much needed filterMap in JavaScript
published: true
description: JavaScript Array needs filterMap
tags: javascript, map, filter, discuss
---

Most often we perform `filter` followed by `map` and it turns out that combining both in one function would certainly avoid multiple iteration.

```JavaScript
Array.prototype.filterMap = function(filter) {
   const r = [];
   for(let i=0; i<this.length; i++) {
      const item = filter(this[i], i, this);
      if (item !== undefined) {
         r.push(item);
      }
   }
   return r;
};

// usage..

emails = customers.filterMap(
   (c) => c.active ?
      { name: c.name, email: c.email } :
      undefined);

// as opposed to

emails = customers.filter( (c) => c.active)
            .map( (c) => ({ name: c.name, email: c.email }));

```

Ideally we can change behavior of `Array.map` to adapt `Array.filterMap` but we don't know what impact it will have on numerous libraries.

Perf: https://jsperf.com/array-filtermap/1
Linux Distribution for web and software development 
Tags: linux, distribution
Published: 2018-12-20 17:38:12

---
title: Linux Distribution for web and software development 
published: true
description: 
tags: Linux, distribution
---

What would be the best linux distribution that suits web and software development? 

###Ubuntu 
Works out of box, beautiful and crisp. But I feel its overloaded with that gnome 3 Desktop interface and is very slow due to those unnecessary animations

###Kububtu 
KDE sure feels very slow. It gives lots of customisation but too much customisations always breaks something

###Debain
So far the best distribution I have used. But softwares in their repo are old. I always have to tinker and add some PPT to get new things

###Mint
Perfect Windows Copy. Works Good. Feels good. Loaded with unnecessary crap. I don't think anyone uses so many programs they have given. 

###Arch
Great if you are actually learning Linux system administration. At beginning Aur seems great but that gives way for bugs. In few days, system becomes buggy. 

Guys, is there any other Distro that is well balanced with appearance, performance, stable but not too outdated software repo. Correct me if I am wrong about something Distro I have shared.
TabNine: You Had Me At Sidekiq Options
Tags: vim, atom, editors
Published: 2019-01-30 12:23:13

---
title: TabNine: You Had Me At Sidekiq Options
published: true
tags: [vim, atom, editors]
canonical_url: https://scottw.com/tab-nine-you-had-me-sidekiq-options
---

[Tabnine](https://tabnine.com) is a nifty new tab completion plugin for a variety of editors (such as Vim and Atom).

It is free to use on small projects and requires an upgrade for larger projects. It has worked amazingly well, and I was already pretty sure I was going to upgrade…and then it offered this as a completion:

![Screenshot of Vim Monokai Theme](https://scottw.com/assets/images/posts/screenshots/tabnine.png)

This may seem trivial, but in nearly 20 years of tab competing/IntelliSense (in the Microsoft world), this is the first time I had really seen intelligence applied to the suggestion. `sidekiq_options` is the configuration API for a background worker. Guessing the completion when I typed `side` was expected. Being smart enough to realize that I always follow up with one of two specific queues took it over the top.

I made my purchase right away. $99 is a steal.
Microsoft Flow – Adding Some Delay
Tags: development, delay, flow, powerautomate
Published: 2022-06-15 17:25:56

---
title: Microsoft Flow – Adding Some Delay
published: true
date: 2018-12-21 00:17:00 UTC
tags: Development,delay,flow,PowerAutomate
canonical_url: https://barretblake.dev/2018/12/microsoft-flow-adding-some-delay/?utm_source=rss&utm_medium=rss&utm_campaign=microsoft-flow-adding-some-delay
---

In a previous post, I walked through saving tweets to an Azure table so they could be retweeted later with an #ICYMI tag. As with most processes of learning, we do the hard way first to learn the concepts. And then we learn the easier ways to do it. As it so happens, Flow provides a much easier way to do this. We're going to add some delay.

The post [Microsoft Flow – Adding Some Delay](https://barretblake.dev/2018/12/microsoft-flow-adding-some-delay/) first appeared on [Barret Codes](https://barretblake.dev).
Git - Adding Submodule
Tags: git, vsc
Published: 2019-09-14 14:15:22

---
title: Git - Adding Submodule
published: true
tags: git, vsc
canonical_url: https://tech.serhatteker.com/post/2018-12/git-adding-submodule/
---

### Adding a Submodule to a Git Repository

Adding a submodule to your git repository is actually quite simple. For example, if you are in the working directory of the repository, to add a new submodule:

```sh
$ git submodule add <git url>
```

+   `git submodule add` – This simply tells Git that we are adding a submodule. This syntax will always remain the same.
+   `<git url>` – This is the external repository that is to be added as a submodule.

If you want to more control over `add` feature:

```sh
$ git submodule add -b <branch> <git url> <folder/subfolder>
```

+   `<branch>` – This fetching different branch from your `default` branch, e.g `master`
+   `<folder/subfolder>` – This add your submodule to another subfolder

to `activate` the submodule:


```sh
$   git submodule init
```
I'm learning typescript, what do I need to know?
Tags: typescript, discuss
Published: 2018-12-20 20:51:51

Next semester in uni we're focussing on web dev, and very heavily on typescript. So I'm getting myself a headstart and begging to learn it now. I've been learning the core basics through lynda.com but I know for sure there is more I'm going to need to know that what this online course will provide me.

So what are some good things to learn, research, test with etc 

(I also have a JavaScript background already)

Anything posted is much appreciated.

Thank you <3 Happy deving!
Test Rails Fast and Stable
Tags: ruby, rails, test, metz
Published: 2018-12-20 20:07:43

---
title: Test Rails Fast and Stable
published: true
description: 
tags: ruby, rails, test, metz
---

In this Metz's video [RailsConf 2016 - Get a Whiff of This by Sandi Metz](https://www.youtube.com/watch?v=PJjHfa5yxlU), she demoed how to refactor and make test fast and stable by Fake object. 

    class Foo --> class Sale

Test Foo with fake Sale.

Code is here:

![](https://thepracticaldev.s3.amazonaws.com/i/noicqltg41rfsqr5y0jl.png)

# Test Any Slow or Unstable API

You can use this method to test any I think.