Thursday, December 1, 2016

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

Wednesday, November 30, 2016

Sneaky Online Tools to Help You Spy on Your Competitors

Being spy in this competitive edge is always an agreeable idea that everyone thinks even before starting a new business. Well, I may late to discuss this conversation but I can unveil some of the best information and tools that could help you stand on your competitors. It is actually a game to...

[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Irfan Ahmad via Digital Information World

Google Data Studio: a Nifty, Free, Easy-to-use Data Vis Tool

As a digital marketer, you can often be overwhelmed with the amount of information and data needed to be analyzed in order to evaluate your efforts. Traffic, conversion rate, user location, behavior and acquisitions --- just to name a few --- all have to be examined to define the progress of your digital marketing campaign.

Client reporting is one of the biggest challenges digital marketers face when undertaking projects. Although endless numbers and stats may make some sense to internet professionals, generally customers are not as tech savvy.

Anyone can export masses of information from Google Analytics to an excel spreadsheet, but how do you present the data in a way that's easy to digest? The answer is --- Data Visualization.

What is Data Visualization?

Data Visualization is a way of representing complex data and stats in a pleasing, visually-appealing way. Visual data may include components like pie and graph charts, maps or tables, and can be presented in different forms, such as infographics, videos, illustrations and interactive reports.

Why is it important? The answer is simple. Our brains absorb visual information better, faster, more easily.

Benefits of Data Visualization

The benefits of visualizing data include:

  • providing clearer information for clients
  • making it easier to view and analyze patterns and trends
  • enabling interaction with the data
  • allowing for more information to be absorbed, and more quickly
  • better identify peaks and troughs.

In this post, we're going to assess how a new tool, Google Data Studio, can help us build beautiful and interactive reports.

Google Data Studio

Google Data Studio (GDS) is a new tool by Google that makes it easy to create beautiful, engaging, responsive, branded and interactive reports. It does this by pulling metrics from Google's properties, such as Google Analytics, Adwords and YouTube Analytics, as well as spreadsheets and SQL databases.

For this article, we’ll be using Data Studio to create a visual report using Google Analytics data. To do this, you first need to have an active Google Analytics property that is properly integrated with the website.

The same applies to other reports. If you wish to pull the data from your Adwords or YouTube Analytics, make sure to sign in with an appropriate Google account that has that data.

Getting started

The following 18 steps will walk you through the process of creating a visual report from your Google Analytics data.

Step 1

Go to Google Data Studio and log in with your Google Analytics credentials:

Step 1

Continue reading %Google Data Studio: a Nifty, Free, Easy-to-use Data Vis Tool%


by Dmytro Spilka via SitePoint

How the Pomodoro Skyrocketed My Productivity & Saved My Business

Pomodoro Timer

I looked at the clock. Another 6 hours, another day passed, no words on the page.

With your income tied to your output, having a string of non-productive days hurts your bank account, and maybe even your sanity.

We live in a world that’s filled with an infinite amount of glorious distractions. If you work online, then you know the pain all too well.

You tell yourself, “I’ll just check Facebook for a second". Seems harmless enough. An hour later you emerge from the black hole. Your motivation gone and self-esteem destroyed. It’s not just Facebook, we have email, text messaging, phone calls, Netflix, text messaging, Skype, Reddit, and on and on.

Or, maybe you feel like you’re working, but when you look up at the end of the day your to-do list is just as big? What’s going on?

Welcome to the age of distraction. If you don’t pick up your sword and slay this dragon it’ll eat you alive.

Here’s how I used a simple online timer to skyrocket my productivity and save my business in the process.

How My Business Almost Failed

I’ve been writing for the web for four years now. Ghostblogging is my bread and butter. But, after doing this for a while, something happened.

My business stopped growing. I kept missing deadlines, and I spent days in front of a computer without a single blog post to show for it.

I thought I had to quit writing forever and had some serious dark days.

Little did I know it wasn’t my motivation that was lacking, it was my ability to focus. My days flittered away by endless distractions. When I closed my computer in frustration at the end of the day, I felt drained and tired, but my work kept piling up.

If you run your own business, then learning how to be productive is one of the more important tools in your arsenal.

Willing ourselves to focus is a losing battle. There has to be a better way.

Why We Struggle to Focus

As much as we’d hate to admit it, we’re not born to stare at our computer screens for hours and hours on end. We get tired. Our bodies yell at us. Generally, we just need a break.

On top of that, we haven't yet adapted to this technological world we spend our lives immersed in. Mixing our general lack of body care and constant state of overwhelm, we're faced with the perfect storm of procrastination.

Chances are, whenever you sit down to work you immediately feel the pull to check something else. This is completely normal. Our rambling minds have a tendency to lean towards prostration and distraction.

David Rock, author of Your Brain at Work, believes the inability to focus comes from overwhelm triggered by the amount of information we have to digest every single day. Along with how our new technologies have become so good at distracting us.

It seems the world is working against our ability to focus and get things done.

But, it doesn’t have to be this way forever. I’m not saying I’ve found the perfect solution, but the method we’re about to dive into below makes focusing much easier and enjoyable.

How a Simple Timer Saved My Business

“Time = Life, Therefore, waste your time and waste your life, or master your time and master your life.” — Alan Lakein

Having a single unproductive day isn’t going to kill your business, but what about when this happens again and again? You look up and a week or two have gone by and you haven’t produced anything of value. Yikes!

Then, as the pressure to do more builds up, you’re existing in a constant state of overwhelm — which is difficult to work its way out of.

Needless to say when I was just about at my wits end I stumbled across this blog post (thanks Glen!). I had heard the Pomodoro Method mentioned online before, but it sounded too much like a pasta sauce for me to try it out.

I only wish I heeded the wisdom of the Pomodoro much sooner.

Why the Pomodoro Method Works and How to Do It

Francesco Cirillo invented the Pomodoro Method in the 1980s as a cutting-edge time management method.

It’s based upon the idea that people can only focus on tasks for a certain amount of time. As much as we like the idea of being in the “zone” for an 8-hour workday, it just isn’t possible. Unless you’re DaVinci, which in that case, keep on working.

So, instead of trying to sit at your desk for the 9 to 5 grind, or whatever hours your schedule allows for, you break your day up into manageable chunks.

Research suggests that taking frequent breaks can increase our levels of mental agility.

The goal of this method is to help reduce distractions and keep you in a state of flow. After all, it’s much easier to ward off distractions when all you’re doing is working for 25 minutes.

The traditional Pomodoro Method has you work in 25-minute focus sessions. After the 25 minutes are complete you'll take a five minute break. It's quite simple.

After you’ve completed four of these 30-minute sessions you take a longer break of 20 to 30 minutes. I usually take a nap, or dive into a book during these longer breaks.

Then, you repeat the process until you’ve abolished your to-do list.

The 25-minute time block is just a suggestion. You can work in shorter or longer stints, or experiment until you find your sweet spot.

1. Pick an App or Timer of Your Choice

If you’re set on testing out this method, then all you need is a timer.

You can use the timer on your cell phone, your watch, an online timer like Tomato Timer, an app like Pomodairo, or even an old school egg timer.

The method you use doesn’t matter as much as its ease of use. When starting a new habit you want to reduce friction as much as possible.

Continue reading %How the Pomodoro Skyrocketed My Productivity & Saved My Business%


by Kevin Wood via SitePoint