Thursday, December 1, 2016

N + 1: When More Queries Is a Good Thing

Over the last week I have been trying to understand how eager loading works in Rails to eliminate the infamous N+1 query problem by reducing the number of queries fired. My initial hypothesis was that reducing the number of queries as much as possible was the goal. However, I was surprised by what I discovered.

Using includes to Reduce Queries

Most posts that you read about the infamous N + 1 Query Problem cite the includes method to address the issue. includes is used to eager load associations related to the model by using the minimum number of queries possible. For this, under the hood, it uses a preload or left outer join, depending on the situation. I will explain both situations in subsequent sections.

Continue reading %N + 1: When More Queries Is a Good Thing%


by Parth Modi via SitePoint

Lune

Lune

'Lune' is a One Page WordPress theme pack with multiple landing page layouts covering several industries. Main demos include digital agency portfolio, app, resume, ebook and more. Features include 10 different header layouts, 7 footer layouts, MailChimp integration, Google recaptcha integration (for forms), fancybox popup gallery, isotope portfolio filter and great to know the WordPress theme comes with Visual Composer (valued at $34) page builder.

Don't need WordPress? There is an HTML version of Lune!

by Rob Hope via One Page Love

HTTPie, a Human-Friendly cURL-Like Tool

Let's Go: Golang Concurrency, Part 1

Overview

Every successful programming language has some killer feature that made it successful. Go's forte is concurrent programming. It was designed to around a strong theoretical model (CSP) and provides language level syntax in the form of the "go" keyword that starts an asynchronous task (yeah, the language is named after the keyword) as well as a built-in way to communicate between concurrent tasks. 

In this article (part one), I'll introduce the CSP model that Go's concurrency implements, goroutines, and how to synchronize the operation of multiple cooperating goroutines. In a future article (part two), I'll write about Go's channels and how to coordinate between goroutines without synchronized data structures.

CSP

CSP stands for Communicating Sequential Processes. It was first introduced by Tony (C. A. R.) Hoare in 1978. CSP is a high-level framework for describing concurrent systems. It is much easier to program correct concurrent programs when operating at the CSP abstraction level than at the typical threads and locks abstraction level.

Goroutines

Goroutines are a play on coroutines. However, they are not exactly the same. A goroutine is a function that is executed on a separate thread from the launching thread, so it doesn't block it. Multiple goroutines can share the same OS thread. Unlike coroutines, goroutines can't explicitly yield control to another goroutine. Go's runtime takes care of implicitly transferring control when a particular goroutine would block on I/O access. 

Let's see some code. The Go program below defines a function, creatively called "f", which sleeps randomly up to a half second and then prints its argument. The main() function calls the f() function in a loop of four iterations, where in each iteration it calls f() three times with "1", "2" and "3" in a row. As you would expect, the output is:

Then main invokes f() as a goroutine in a similar loop. Now the results are different because Go's runtime will run the f goroutines concurrently, and then since the random sleep is different between the goroutines, the printing of the values doesn't happen in the order f() was invoked. Here is the output:

The program itself uses the "time" and "math/rand" standard library packages to implement the random sleeping and waiting in the end for all goroutines to complete. This is important because when the main thread exits, the program is done, even if there are outstanding goroutines still running.

Sync Group

When you have a bunch of wild goroutines running all over the place, you often want to know when they are all done. 

There are different ways to do that, but one of the best approaches is to use a WaitGroup. A WaitGroup is a type defined in the "sync" package that provides the Add(), Done() and Wait() operations. It works like a counter that counts how many go routines are still active and waits until they're all done. Whenever you start a new goroutine, you call Add(1) (you can add more than one if you launch multiple go routines). When a goroutine is done, it calls Done(), which reduces the count by one, and Wait() blocks until the count reaches zero. 

Let's convert the previous program to use a WaitGroup instead of sleeping for six seconds just in case in the end. Note that the f() function uses defer wg.Done() instead of calling wg.Done() directly. This is useful to ensure wg.Done() is always called, even if there is a problem and the goroutine terminates early. Otherwise, the count will never reach zero, and wg.Wait() can block forever.

Another little trick is that I call wg.Add(3) just once before invoking f() three times. Note that I call wg.Add() even when invoking f() as a regular function. This is necessary because f() calls wg.Done() regardless of whether it runs as a function or goroutine.

Synchronized Data Structures

The goroutines in the 1,2,3 program don't communicate with each other or operate on shared data structures. In the real world, this is often necessary. The "sync" package provides the Mutex type with Lock() and Unlock() methods that provide mutual exclusion. A great example is the standard Go map. 

It isn't synchronized by design. That means that if multiple goroutines access the same map concurrently without external synchronization, the results will be unpredictable. But, if all goroutines agree to acquire a shared mutex before every access and release it later, then access will be serialized.

Putting It All Together

Let's put it all together. The famous Tour of Go has an exercise to build a web crawler. They provide a great framework with a mock Fetcher and results that let you focus on the problem at hand. I highly recommend that you try solving it by yourself.

I wrote a complete solution using two approaches: a synchronized map and channels. The complete source code is available here.

Here are the relevant parts of the "sync" solution. First, let's define a map with a mutex struct to hold fetched URLs. Note the interesting syntax where an anonymous type is created, initialized and assigned to a variable in one statement.

Now, the code can lock the m mutex before accessing the map of URLs and unlock when it's done.

This is not completely safe because anyone else can access the fetchedUrls variable and forget to lock or unlock. A more robust design will provide a data structure that supports safe operations by doing the locking/unlocking automatically.

Conclusion

Go has superb support for concurrency using lightweight goroutines. It is much easier to use than traditional threads. When you need to synchronize access to shared data structures, Go has your back with the sync.Mutex

There is a lot more to tell about Go's concurrency. Stay tuned...


by Gigi Sayfan via Envato Tuts+ Code

How to Find Social Media Micro-influencers for Your Small Business

sb-social-micro-influencers-600

Want to promote your small business on a budget? Have you considered partnering with less famous influencers? Highly targeted micro-influencers can help your small business gain visibility, engage an audience, and promote your products. In this article, you’ll discover how to find and connect with micro-influencers who can promote your small business. #1: Find Micro-influencers [...]

This post How to Find Social Media Micro-influencers for Your Small Business first appeared on .
- Your Guide to the Social Media Jungle


by Shane Barker via

Quick Tip: Use Bootstrap Components without jQuery

Do you use Bootstrap's JavaScript components? Do you like Vanilla JavaScript? Then you might be interested in the Native JavaScript for Bootstrap project, which aims to remove the jQuery dependency required by the components by porting them to plain JavaScript.

Why?

The motivations of such a port are mostly related to performance.

One benefit is the potential performance gain that can come from the superior execution speed of plain JavaScript over jQuery, as reported in many benchmarks.

Another performance advantage is the reduced page weight. Let's make a quick comparison. All the numbers below refers to minified gzipped files and are expressed in KBs. bootstrap.js refers to the original Bootstrap scripts, bsn.js to the Bootstrap Native scripts, and jq to jQuery. Here we are looking at the bundled files that gather together all the components, but it should be noted that both libraries have a modular structure that allows the loading of only the needed components and their dependencies.

Bootstrap.js:

  • jq 3.1.0 + bootstrap.js = 34.5 + 11.2 = 45.7
  • jq 3.1.0 slim + bootstrap.js = 27.2 + 11.2 = 38.4
  • jq 2.2.4 + bootstrap.js = 34.3 + 11.2 = 45.5
  • jq 1.12.4 + bootstrap.js = 38.8 + 11.2 = 50.0

Native JavaScript for Bootstrap:

  • minifill + bsn.js = 2.4 + 7.8 = 10.2
  • polyfill.io(on chrome 54) + bsn.js = 1.1 + 7.8 = 8.9
  • polyfill.io(on IE 8) + bsn.js = 12.1 + 7.8 = 19.9

(The polyfill.io size for IE8 was taken from here. These polyfills are discussed in the next sections)

Bar chart comparing bundle sizes of Bootstrap to Bootstrap Native

So, with the Bootstrap components the size varies over the range [38.4, 50.0] KB, while with Bootstrap Native the range shrinks to [8.9, 19.9] KB.

Browser Support

Regarding browser support, it is comparable to the original Bootstrap jQuery-based script, that is, it supports the latest browsers on the major mobile and desktop platforms and IE8+. This is accomplished by means of two polyfill strategies.

The first revolves around the use of the Polyfill.io service. All you have to do is insert the relative script tag in the document to get a set of polyfills tailored to each browser:

<script src="http://ift.tt/2gOkTuJ"></script>

The service can be configured to customize its response based on the features really used on the site. See the Pollyfill.io documentation for details.

Alternatively, it is possible to use minifill, a potentially lighter custom polyfill supplied by the project author itself.

Continue reading %Quick Tip: Use Bootstrap Components without jQuery%


by Giulio Mainardi via SitePoint

Villes & Paysages

Villes & Paysages is an international architecture and urban planning agency.
by via Awwwards - Sites of the day