Sunday, September 30, 2018

A city council challange

I've decided to stand for an election for a city council. Thererefor posting a link to my local non-politician group just so we appear in Google: Wspólny Olsztyn and to my profile: Paweł Szczur. Kandydat KWW Wspólny Olsztyn do Rady Miasta Olsztyna.

I don't promise to build a cosmodrome or a new highway. My purpose is to make Olsztyn a smart city. Smart city as a city which makes decisions based on data, not necessarily buys a ton of new solutions and pretends it's smart.

I want to introduce a data based thinking into the city board and public institutions. The investitions should have KPI and we, as citizens should be presented with results. No more wishful thinking and guessing.

Thursday, May 11, 2017

Tensorflow custom operation - problem with word2vec operation

This is just a quick note for myself. One beautiful afternoon I got a below error:

tensorflow.python.framework.errors_impl.NotFoundError: 
models/tutorials/embedding/word2vec_ops.so: 
undefined symbol: _ZN10tensorflow16ReadFileToStringEPNS_3EnvERKSsPSs
The distributed package of Tensorflow uses gcc 4.
If you compile from sources on more or less up to date Ubuntu or Debian, you probably will have gcc 5 or newer installed.
gcc 5 and gcc 4 ABI are not compatible, thus your Tensorflow and operations MUST be compiled with same ABI.
You have two choices either compile the Tensorflow with old ABI support by providing
-cxxopt="-D_GLIBCXX_USE_CXX11_ABI=0"
flag to bazel build or ensure your operations are compiled with new ABI.
You can also force gcc5 to use old ABI (source):

TF_INC=$(python -c 'import tensorflow as tf; print(tf.sysconfig.get_include())')
g++ -std=c++11 -shared word2vec_ops.cc word2vec_kernels.cc \
  -o word2vec_ops.so -fPIC -I $TF_INC -O2 -D_GLIBCXX_USE_CXX11_ABI=0

More could be found in Tensorflow doc: https://www.tensorflow.org/install/install_sources#build_the_pip_package

References:

Friday, January 27, 2017

To shadow or to not?

Long story short: it's easy to accidentally shadow a variable by using := operator in if statement. Be aware:

package main

import (
 "fmt"
)

func f() (int, int) { return 2, 2 }

func main() {
 var x = 1
 if x, y := f(); x == y {
  fmt.Printf("%d %d\n", x, y)
 }
 fmt.Printf("%d\n", x)
 x, y := f()
 fmt.Printf("%d %d\n", x, y)
}
The output is:

2 2
1
2 2
Run in Golang Play: https://play.golang.org/p/lymn2gl6Wi.

Saturday, July 9, 2016

JavaScript not evaluating all functions in condition

I’ve just been struck by a simple though nuance code optimization. I’ve met it probably thousands times. In fact, some style guides I’ve followed forbids to do what I’ve just done ;-)

First let me explain what we want to achive. We want to call 3 functions and early return if all 3 returned false. Does the below code look good for you?

if (!func0() && !func1() && !func2()) {
    return;
}

Unfortunately it’s wrong. The JavaScript execution engine will optimize it and if the func0 call returns true (negated by !) then the func1 and func2 won’t be called at all.

This phenomenon has a name and it’s called short-circut evaluation, quoting Wikipedia:

the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression

This applies to third and further arguments. Thus the lesson is: never put function calls in logical statements, at least not functions you want guarantee to be executed.

Changed code:

var skip = !func0();
skip &= !func1();
skip &= !func2();
if (skip) {
    return;
}

I’m sure the world is full of this kind of bugs.

Tuesday, May 10, 2016

Postmortem culture

Culture

It happens, something goes wrong, the system goes down, it stops proceeding orders or serve ads or … situation becomes nervous.

I would say one of the main differences how organisation handles those critical situations is a pretty good indicator of it shape. I’ve seen a companies putting the employees under huge pressure during incidents and blaming after.

Then, I’ve worked for Google and… When you make mistake, the impact factor happens to be thousands QPS. You look at graph and see how some stats goes down or crazily spike. You rollback or do emergency release and it starts (ok, it’s more complex, but hey). You (in most cases more than you) are responsible for writing a postmortem.

What is a postmortem?

In short, it’s a document describing what happened. I know in many companies it looks different, many adopted it after some ex-Googler has joined them (can we call it Googleism? or Googleisation?). What is important in Google’ postmortems is it’s purpose and main pur aim of postmortem is: to learn and never repeat old mistakes.

That changes the perspective dramatically. Writing about your own fuckup is not trivial and writing in no-blame way is even harder. It’s not easy even for local stars (local genius theory). How to write postmortem? What to put in it? How it should look? Check out the links

What’s next?

The document usually should be created in next 24-48h after, unless the incident is very complex or not understood. Usually, the PM are open for comments, so everyone may ask a question for some details. When ready and the document went through some ‘peer-review’, it’s should be sent to all interested parties (mailing group, #slack, whatever) and it should be discoverable. Means, it should end up in bug tracker under the issue (because, you have an open issue about the outage, right?). It should be kept in some postmortems’ database. Thus, even if it’s not you who pushed a binary or write the code, you will learn. And in the future, you can always look for similar cases.

Wednesday, May 4, 2016

Read from file: Length-prefixed protocol buffers

File format

In short it’s binary encoded protobuf message prefixed with the size. For longer description please check Length-prefix framing for protocol buffers.

In most languages the file is read as stream. If you need to open and parse a file which holds lenght-prefixed protobuf messages in Python, you read internet and you find a code which read the whole file. It’s huge bottleneck. The hit in a performance between reading whole file then parsing byte after byte and using BufferedReader was in 1000x. Thus enjoy my little piece of code:

def ReadItm(fname, constructor, size_limit = 0):
    ''' Reads and parses a length prefixed protobuf messages from file. 
        The file MUST not be corrupted. The parsing is equivalent to parseDelimitedFrom.
    '''
    f = None
    if fname.endswith('.gzip'):
        f = gzip.open(fname, 'rb')
    else:
        f = open(fname, 'rb')
    reader = BufferedReader(f)
    bytes_read = 0
    while size_limit<=0 or bytes_read<size_limit:
        buffer = reader.peek(10)
        if len(buffer) == 0:
            break
        (size, position) = decoder._DecodeVarint(buffer, 0)
        reader.read(position)
        itm = constructor()
        itm.ParseFromString(reader.read(size))
        bytes_read = bytes_read + position + size
        yield itm
    f.close()

Thursday, April 7, 2016

Go: imagick image croping after rotation problem

I need to load image rotate it by some angle, then crop some part of it. Seems trivial, isn't?

I use: gopkg.in/gographics/imagick.v2/imagick package.

Load image
iwand := imagick.NewMagickWand()
defer iwand.Destroy()
if err := iwand.ReadImage(s); err != nil {
 log.Panicf("cannot open image %s", err)
}
Rotate it, fill new area with yellow
w := iwand.GetImageWidth()
h := iwand.GetImageHeight()
log.Printf("old size: %d,%d", w, h)
pwand := imagick.NewPixelWand()
pwand.SetColor("yellow")
if err := iwand.RotateImage(pwand, 45); err != nil {
 log.Panicf("problem with rotation: %s", err)
}
Calculate the position and size of the rectangle to cut
newW := calcSize(w, h)
newH := newW

w = iwand.GetImageWidth()
h = iwand.GetImageHeight()
log.Printf("new size: %d,%d", w, h)

x := int((w - newW) / 2)
y := int((h - newH) / 2)
Make the area red (with transparency), just for learning
dwand := imagick.NewDrawingWand()
pwand.SetColor("red")
pwand.SetOpacity(0.5)
dwand.SetFillColor(pwand)
dwand.Rectangle(float64(x), float64(y), float64(newW+uint(x)), float64(newH+uint(y)))
iwand.DrawImage(dwand)
Crop and save to file
log.Printf("w,h,x,y: %d,%d,%d,%d", newW, newH, x, y)
if err := iwand.CropImage(newW, newH, x, y); err != nil {
 log.Fatalf("problem with crop: %s", err)
}
iwand.WriteImage(d)

Input file
Original image (from: https://en.wikipedia.org/wiki/Linux)

Output file
Image rotated and cropped

Need to repage!
log.Printf("w,h,x,y: %d,%d,%d,%d", newW, newH, x, y)
iwand.ResetImagePage("")
if err := iwand.CropImage(newW, newH, x, y); err != nil {
 log.Fatalf("problem with crop: %s", err)
}
iwand.WriteImage(d)
Rotated and cropped - fixed
Full source: gist

Friday, March 11, 2016

Android developer road

So, I'm going through a quick Android developer course. The main target is to learn how to provide the best Android apps with minimal effort. Assumption is we all know Java ;-)

The start

A good starting point is:
http://developer.android.com/training/index.html

I don't recommend to read it all at the beginning. I would suggest:
Others as needed, Best Practices for Interaction and Engagement (http://developer.android.com/training/best-ux.html) also helps.

The above gives you a rough overview. The real stuff comes in API Guides (http://developer.android.com/guide/components/index.html). I do recommend to read the first three sections:
This gives you a high level overview of how the Android works.

The lifecycle

You basically should have it at your desk. You will use it often. It's been reported to have some inaccuracies but it's still better than the Google provided simplified version.



Codelabs

Google provides two interesting codelabs:
If you have to provide some early results quickly, skip above readings and just do the codelab.

Other must-to-know

Butterknife - http://jakewharton.github.io/butterknife/ - saves you lot of boilerplate with binding view elements to variables.
Android ContentProvider Generator - it will save you a lot of time on boilerplate code - https://github.com/BoD/android-contentprovider-generator
Mosby - http://hannesdorfmann.com/mosby - if you go with MVP this is must to use.
Dagger - dependency injection framework - http://google.github.io/dagger/users-guide

And when you consider which Android version to support, check:
Android stats Dashboard - gives an overview of the Android version distribution - http://developer.android.com/about/dashboards/index.html

Learning

Monday, February 8, 2016

No, because no

I need Math.Round from Go's standard library, poor me:


I know it's hard. But hey, most languages provide it.

Rob Pike:
Floating point numbers don't have digits.
The bar for being useful needs to be pretty high to be in the Go math package. We accepted most of what's in the C library but we're not going to take all the routines from other libraries. The Javascript round is a 1-liner: int(f+0.5). 

Wednesday, January 27, 2016

Angular-2.0.0.beta1

Http problem

I was getting an error:
error TS2305: Module '"angular2/http"' has no exported member 'HTTP_PROVIDERS'
may be caused by simply outdated angular2.d.ts installed through tsd.
DefinitelyTyped.org typings for Angular2 are outdated, tsd install angular2 gives old .d.ts which makes typescript unhappy. What’s the new approach or which angular.d.ts is appropriate?
When appropriate angular2 node package is installed everything works fine.

Duplicate properties

The other error I’ve encounter (Angular-2.0.0.beta.1):
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(6,14): error TS2300: Duplicate identifier 'PropertyKey'.
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(6,14): error TS2300: Duplicate identifier 'PropertyKey'.
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(9,5): error TS2300: Duplicate identifier 'done'.
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(10,5): error TS2300: Duplicate identifier 'value'.
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(248,5): error TS2300: Duplicate identifier 'EPSILON'.
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(283,5): error TS2300: Duplicate identifier 'MAX_SAFE_INTEGER'.
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(290,5): error TS2300: Duplicate identifier 'MIN_SAFE_INTEGER'.
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(346,5): error TS2300: Duplicate identifier 'flags'.
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(498,5): error TS2300: Duplicate identifier 'prototype'.
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(561,5): error TS2300: Duplicate identifier 'size'.
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(570,5): error TS2300: Duplicate identifier 'prototype'.
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(581,5): error TS2300: Duplicate identifier 'size'.
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(590,5): error TS2300: Duplicate identifier 'prototype'.
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(605,5): error TS2300: Duplicate identifier 'prototype'.
ts/node_modules/angular2/typings/es6-shim/es6-shim.d.ts(619,5): error TS2300: Duplicate identifier 'prototype'.
ts/typings/es6-shim/es6-shim.d.ts(6,14): error TS2300: Duplicate identifier 'PropertyKey'.
ts/typings/es6-shim/es6-shim.d.ts(9,5): error TS2300: Duplicate identifier 'done'.
ts/typings/es6-shim/es6-shim.d.ts(10,5): error TS2300: Duplicate identifier 'value'.
ts/typings/es6-shim/es6-shim.d.ts(248,5): error TS2300: Duplicate identifier 'EPSILON'.
ts/typings/es6-shim/es6-shim.d.ts(283,5): error TS2300: Duplicate identifier 'MAX_SAFE_INTEGER'.
ts/typings/es6-shim/es6-shim.d.ts(290,5): error TS2300: Duplicate identifier 'MIN_SAFE_INTEGER'.
ts/typings/es6-shim/es6-shim.d.ts(346,5): error TS2300: Duplicate identifier 'flags'.
ts/typings/es6-shim/es6-shim.d.ts(498,5): error TS2300: Duplicate identifier 'prototype'.
ts/typings/es6-shim/es6-shim.d.ts(561,5): error TS2300: Duplicate identifier 'size'.
ts/typings/es6-shim/es6-shim.d.ts(570,5): error TS2300: Duplicate identifier 'prototype'.
ts/typings/es6-shim/es6-shim.d.ts(581,5): error TS2300: Duplicate identifier 'size'.
ts/typings/es6-shim/es6-shim.d.ts(590,5): error TS2300: Duplicate identifier 'prototype'.
ts/typings/es6-shim/es6-shim.d.ts(605,5): error TS2300: Duplicate identifier 'prototype'.
ts/typings/es6-shim/es6-shim.d.ts(619,5): error TS2300: Duplicate identifier 'prototype'.

I simply solved it by specifying the files in tsconfig.json explicitly through files. A better solution is to remove typings/es6-shim/.

Thursday, December 17, 2015

Google Identity Toolkit for Android - weird compilation error

I’m hacking tiny Android app, one of the libraries I use is Google Identity Toolkit (it’s super easy to integrate). A documentation states that a Play Services should be added as dependency:
compile 'com.google.android.gms:play-services:8.3.0'
For any non trivial application it’s going to be a problem resulting in below error (or similar):
Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/usr/lib/jvm/java-8-oracle/bin/java'' finished with non-zero exit value 2
Search on Internet points to StackOverflow question: com.android.build.transform.api.TransformException. Apparently the bugs are related. The exit return code 2 is meaningless unless one has any clues. Anyway, the problem can be solved by replacing the dependency by:
compile 'com.google.android.gms:play-services-plus:8.3.0'
compile 'com.google.android.gms:play-services-auth:8.3.0'
I’ve opened an issue on Google Identity Toolkit - Android sample project asking for more documentation.
The error is related to a constraint of Android Dalvik runtime of to 65K Reference Limit. There are two solutions for the problem: decreasing the references (usually by chosing smaller dependencies, in our case subpackages instead of the full Play Services) and using so called multidex (some 3rd party blog).

Monday, October 19, 2015

Google Analytics doesn't work a.k.a. name collision in JavaScript

Today is another great day I’ve encounter a trivial bug hard to catch. It goes as follow. I went to Google Analytics to setup a new page. I’ve followed the instruction and I’ve copied into a source:

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-AAAAAAAA-X', 'auto');
  ga('send', 'pageview');

</script>

and it didn’t work ;-)

First I’ve thought is my mistake, i’ve put a code just before </html>, but after trying </head> it wasn’t any better.

I’ve tried to copy paste the code to developer console and tadah, it works! Here I should mention that I use both Google Closure Library and Google Closure Compiler on my site. After thinking and poking the code for a moment I’ve made an educated guess:

Closure compiler compiled code is colliding a name with Google Analytics!

Took me 1 minute to verify and yes, I’ve got it.

The solution was straight:

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','dzialaj');

  dzialaj('create', 'UA-AAAAAAAA-X', 'auto');
  dzialaj('send', 'pageview');

</script>

Just for quick explanation, the string I’ve changed is a parameter to function which sets up a Google Analytics code on a website, it is a name that should be used as a Analytics main function and may be anything one wants.

Thursday, October 8, 2015

Save yourself and pass the context by

One of extending packages of Go is golang.org/x/net/context package. The idea comes form task oriented programming. You get a task to execute but want to attach some data to it. It appears to be useful when programing a RPC or web server solutions. In such cases your listener creates a context object and pass it to handlers. The handlers keep it and use it when appropriate.

This idea guided most Google App Engine APIs for Go. Now they’ve introduced a Managed VM’s which are something between App Engine and Compute Engine. The refactored libraries can be found here: google.golang.org/appengine.

The standard way of logging in App Engine was to get a context and call methods:

func SomeHandler(w http.ResponseWriter, req *http.Request) {
    ctx := appengine.NewContext(req)    
    ctx.Infof("got request!")
}

Whereas the new way:

func SomeHandler(ctx context.Context, w http.ResponseWriter, req *http.Request) {
    log.Infof(ctx, "got request!")
}

The new way has one huge advantage, it allows you to pass any context which implements interface context.Context. It also requires to replace all appengine/log imports by a new package google.golang.org/appengine/log

The Go’ standard log library doesn’t have a concept of context at all.

Reasoning

I guess I should explain the advantage of using a context based log instead of standard one. In a case of task oriented application it allows the programmer to group all log messages related to given task. It’s a common practice to group messages by the place of the log function callback (the file and line where the log message is written). More sophisticated grouping includes process id and it may be a task id (or context in our case). Just imagine how much time it saves during debugging. It also allows much more sophisticated analysis of the server event flow without running in debugging mode.

I’ve created a tiny wrapper around both github.com/golang/glog library and google.golang.org/appengine/log: github.com/orian/utils/net/log. It should allow you to log both at App Engine and stand alone processes. Enjoy.

A real in depth explanation can be found in Go blog' article: Go Concurrency Patterns: Context

Tuesday, September 29, 2015

Upgrading an ASUS Z87 PLUS motherboard firmware

I needed to upgrade a firmware (in fact, it should have been done a long time ago). The steps goes as follow:

  1. Find a firmware: (https://www.asus.com/Motherboards/Z87PLUS/HelpDesk_Download/)
    http://dlcdnet.asus.com/pub/ASUS/mb/LGA1150/Z87-PLUS/Z87-PLUS-ASUS-2103.zip
  2. Unpack it and localize Z87-PLUS-ASUS-2103.CAP (or some other older version Z87-PLUS-ASUS-2004.CAP or Z87-PLUS-ASUS-1802.CAP)
  3. Prepare a FAT flash device
  4. Copy the firmware *.CAP file to flash root directory and rename to: Z87PL.CAP
  5. Plug flash into the 'flashback' USB port at the back of PC (it's next to ethernet with a green border around)
  6. Press flashback button on a motherboard, it's below a power plug, labeled as "BIOS_FLBK"
The FLBK_LED should start blinking (if it stops blinking means it cannot read firmware or the file is broken). It will take few minutes. DONE.


BTW. It sucks that Asus just doesn't say what should be the name of a firmware file. They could just use FIRMWARE.CAP and it would be fine. There are other ways of protecting people from themselves than encoding the model in a file name.

Tuesday, September 15, 2015

Slow compilation in Golang

Because I'm lazy and Go tends to not backport it's libraries, I've decided to migrate a project from go1.4 to go1.5. Everything would be great but the compilation process of the new version is noticeably slower than the old one.

Compile all your dependencies

What I've noticed some time ago is that if you change the version of Go the libs stay at old version. This causes them to be built on each go run you invoke. And if you use a library which automates rebuilding the binary on change like reflex () than you may wait long.

List all deps

To list all dependencies your application or library have you can invoke:
go list -f '{{.Deps}}' | tr "[" " " | tr "]" " " | xargs go list -f '{{if not .Standard}}{{.ImportPath}}{{end}}' > deps
(borrowed from from go-nuts)

Rebuild all packages

After that you can call:
go install -a $(tr -d '\n' < deps)

Update all packages

Alternative to the above, updates the code:
go install -u $(tr -d '\n' < deps)

Speedup

For my code it was from 15 seconds to below 1 second.

Apply to all subpackages in a project

As Craig Furman suggested in a comment (thanks):
go list -f '{{.Deps}}' ./... | tr "[" " " | tr "]" " " | \
  xargs go list -f '{{if not .Standard}}{{.ImportPath}}{{end}}' | \
  xargs go install -a

Saturday, September 12, 2015

MySQL under the hood hurts

Recently I've been poking around MySQL, i've forgot how it's when someone makes a lot of decisions for you, e.g. that a column of type TIMESTAMP should have a default value set to CURRENT_TIMESTAMP or that on each row write it should be automatically updated to CURRENT_TIMESTAMP, and btw did you know, that NOW() and CURRENT_TIMESTAMP are not equal (check this)?

The simplest way to discover what MySQL have done for you is to either read the documentation (which is kind of long) or:

SHOW CREATE TABLE table;
This will print you the full command necessary to recreate the table in the same state as it's currently:
CREATE TABLE `table` (
  `user_id` int(11) DEFAULT NULL,
  `user_name` varchar(255) DEFAULT NULL,
  `tags` text,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `state` int(11) DEFAULT '0',
  `date_of_publication` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `auth_fb_share` tinyint(1) DEFAULT NULL,
  CONSTRAINT `table_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`),
) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8

But why is it a problem?
Because by default CURRENT_TIMESTAMP inserts the value with timezone shift, but without the information about time zone. Let's say it's 2015-09-09 21:23 +02:00. The TIMESTAMP keeps the data as UTC (+00:00). The proper value should be: 2015-09-09 19:23.
But the CURRENT_TIMESTAMP will insert the data as: 2015-09-09 21:23 skipping time zone information.
This causes a shift of X hours depending what's a server timezone is.

Thursday, July 30, 2015

Go: a list of structure field names

package main

import (
 "fmt"
 "reflect"
)

type User struct {
 Name     string
 Age      int
 Password string
}

func GetFieldNames(s interface{}) []string {
 t := reflect.TypeOf(s)
 if t.Kind() == reflect.Ptr {
  t = t.Elem()
 }
 if kind := t.Kind(); kind != reflect.Struct {
  fmt.Printf("not a struct kind: %s", kind)
  return nil
 }
 var ret []string
 for i := 0; i < t.NumField(); i++ {
  field := t.Field(i)
  ret = append(ret, field.Name)
 }
 return ret
}

func main() {
 u := User{}
 fmt.Println(GetFieldNames(u))
 fmt.Println(GetFieldNames(&u))
}
At Go Playground: http://play.golang.org/p/6LDoCIKFeH
The function returns a slice of strings. Each is a name of a field. If a pointer is an argument the underlying type's field names are returned. The function ended up in: github.com/orian/utils/reflect. A documentation is browsable at: https://gowalker.org/github.com/orian/utils/reflect.
A short explanation:
  • First get a reflect.Type of a given argument s
  • If s' kind is a pointer, get a descriptor of underlying type.
  • If underlying type is not a struct, return error..
  • Iterate over fields, add field names and return the result slice.

Wednesday, July 1, 2015

TIL: clicked element reference in JavaScript console

I had a break from WebDev for around 2 years. I'm rediscovering things now. Today I've learnt: $0
  • Right click on the element of interest in your browser and select 'inspect element'. You should see the browser debugger with the element you clicked on highlighted.
  • The debugger allows you to access the currently selected element in the console as $0 variable.

Thursday, June 11, 2015

TIL: never depend on the order of evaluation of sub-expressions in a stream

The code below may result in a 6 different execution orders. It will surprise and hurt you, so don't do that ;-)
std::cout << wizard.CastSpell("abracadabra") << wizard.DrinkPotion("Rosanke") << wizard.Mana();
More info can be found:

Monday, June 1, 2015

Endless extracting of tar.bz2 archive

Funny story. Over a year ago I've backed up a project directory to tar.bz2 archive. Today I've decided to check what's inside. I've encountered a frozen window of 'extract here' option from file context menu.

I've killed the extract process and rerun it from a terminal:
tar -xvvf archive.tar.bz2
After few normal lines i've seen smth (in fact thousands of such lines):
hrwxr-x--- user/group       0 2013-02-06 23:20 workspace/a/b/a/b/f.go link to workspace/a/b/f.go
hrwxr-x--- user/group       0 2013-02-06 23:20 workspace/a/b/a/b/a/b/f.go link to workspace/a/b/a/b/f.go
This clued me, that probably the archive kept the symbolic links. After Googling and reading tar manual I had this idea: let's remove a symlink from an archive:
tar --delete -f archive.tar workspace/a/b/a
This worked just well :-)