What is idiomatic code?

Idiomatic means following the conventions of the language. You want to find the easiest and most common ways of accomplishing a task rather than porting your knowledge from a different language. non-idiomatic python using a loop with append: mylist = [1, 2, 3, 4] newlist = [] for i in mylist: newlist.append(i * 2) idiomatic … Read more

Pairs from single list [duplicate]

My favorite way to do it: def pairwise(t): it = iter(t) return zip(it,it) # for “pairs” of any length def chunkwise(t, size=2): it = iter(t) return zip(*[it]*size) When you want to pair all elements you obviously might need a fillvalue: from itertools import izip_longest def blockwise(t, size=2, fillvalue=None): it = iter(t) return izip_longest(*[it]*size, fillvalue=fillvalue) With … Read more

What is the “Execute Around” idiom?

Basically it’s the pattern where you write a method to do things which are always required, e.g. resource allocation and clean-up, and make the caller pass in “what we want to do with the resource”. For example: public interface InputStreamAction { void useStream(InputStream stream) throws IOException; } // Somewhere else public void executeWithFile(String filename, InputStreamAction … Read more

When to use std::size_t?

A good rule of thumb is for anything that you need to compare in the loop condition against something that is naturally a std::size_t itself. std::size_t is the type of any sizeof expression and as is guaranteed to be able to express the maximum size of any object (including any array) in C++. By extension … Read more

What is the pythonic way to detect the last element in a ‘for’ loop?

Most of the times it is easier (and cheaper) to make the first iteration the special case instead of the last one: first = True for data in data_list: if first: first = False else: between_items() item() This will work for any iterable, even for those that have no len(): file = open(‘/path/to/file’) for line … Read more

How do I reverse an int array in Java?

To reverse an int array, you swap items up until you reach the midpoint, like this: for(int i = 0; i < validData.length / 2; i++) { int temp = validData[i]; validData[i] = validData[validData.length – i – 1]; validData[validData.length – i – 1] = temp; } The way you are doing it, you swap each … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)