elegance

More elegant way to make a C++ member function change different member variables based on template parameter?

Today, I wrote some code that needed to add elements to different container variables depending on the type of a template parameter. I solved it by writing a friend helper class specialized on its own template parameter which had a member variable of the original class. It saved me a few hundred lines of repeating myself without adding...

More elegant way to initialize list of duplicated items in Python

If I want a list initialized to 5 zeroes, that's very nice and easy: [0] * 5 However if I change my code to put a more complicated data structure, like a list of zeroes: [[0]] * 5 will not work as intended, since it'll be 10 copies of the same list. I have to do: [[0] for i in xrange(5)] that feels bulky and uses a variable so s...

Reorganizing named fields with AWK

I have to deal with various input files with a number of fields, arbitrarily arranged, but all consistently named and labelled with a header line. These files need to be reformatted such that all the desired fields are in a particular order, with irrelevant fields stripped and missing fields accounted for. I was hoping to use AWK to ha...

Elegantly escaping errors

I have statements such as @user = User.find(current_user.id) throughout my app. Sometimes a user might enter with a nil variable (such as a new user for whom current_user is nil). I'm sure the dumb way to do this would be to scatter if statements everywhere like... if current_user.exists? @user = User.find(current_user.id) else re...

Cocoa -- toggling a BOOL without repeating its name.

If a BOOL has a nice short name, it's easy enough to write: myBOOL = !myBOOL; But what if the BOOL has a long name? objectWithLongishName.memberWithLongishName.submember.myBOOL = !(objectWithLongishName.memberWithLongishName.submember.myBOOL); . . . does not look so pretty. I'm wondering if there is an easy way to toggle the BOO...

Elegant Python?

I am trying to teach myself Python, and I have realized that the only way I really learn stuff is by reading the actual programs. Tutorials/manuals just cause me to feel deeply confused. It's just my learning style, and I'm like that with everything I've studied (including natural languages -- I've managed to teach myself three of them...

What's the more elegant way to declare a const in C#

I'm refactoring a library in C# and I found a lot of upper case constants: INTERVAL, TIME, SECONDS. I think this a kind of unnecessary, and personally I prefer declare everything with camel case. Exist some exactly definition about the better way? ...

python: elegant way to deal with lock on a variable?

I have code that looks like something like this: def startSearching(self): self.searchingLock.acquire() searching = self.searching if self.searching: self.searchingLock.release() self.logger.error("Already searching!") return False self.searching = True self.searchingLock.release() #some...

twisted: how to communicate elegantly between reactor code and threaded code?

I have a client connected to a server using twisted. The client has a thread which might potentially be doing things in the background. When the reactor is shutting down, I have to: 1) check if the thread is doing things 2) stop it if it is What's an elegant way to do this? The best I can do is some confused thing like: def cleanup(s...

Efficient way to read a specific line number of a file. (BONUS: Python Manual Misprint)

I have a 100 GB text file, which is a BCP dump from a database. When I try to import it with BULK INSERT, I get a cryptic error on line number 219506324. Before solving this issue I would like to see this line, but alas my favorite method of import linecache print linecache.getline(filename, linenumber) is throwing a MemoryError. Inte...

x or y: acceptable idiom, or obfuscation?

I have to extract values from a variable that may be None, with some defaults in mind. I first wrote this code: if self.maxTiles is None: maxX, maxY = 2, 2 else: maxX, maxY = self.maxTiles Then I realized I could shorten it to: maxX, maxY = self.maxTiles if self.maxTiles is not None else (2, 2) But then I realized this migh...

Learning Python

Hi all, Was coding something in Python. Have a piece of code, wanted to know if it can be done more elegantly... # Statistics format is - done|remaining|200's|404's|size statf = open(STATS_FILE, 'r').read() starf = statf.strip().split('|') done = int(starf[0]) rema = int(starf[1]) succ = int(starf[2]) fails = int(starf[3]) size = in...

SQL: The most elegant way to generate permutations in SQL server

Given a the following table: Index | Element --------------- 1 | A 2 | B 3 | C 4 | D We want to generate all the possible permutations (without repetitions) using the elements. the final result (skipping some rows) will look like this: Results ---------- ABCD ABDC ACBD ACDB ADAC ADCA ...

Elegant way to bias random boolean

I'd like to create a random boolean in JavaScript, but I want to take the previous value into account. If the previous value was true, I want it to be more likely for the next value to be true. At the moment I've got this (this is in the context of a closure - goUp and lastGoUp are locals to the containing scope): function setGoUp() { ...

Who is doing investigations into measurement of functionality and usability?

I have developed some ideas about system construction, that are a little different to mainstream development. I am developing a demonstration/proof of concept project. So far, I have found that useful information about the completeness of a system can be gathered by taking an indirect view of the development. This indirect view is ba...

gtk: nicer way to make cellrenderercombo finish editing as soon as an entry is selected

I have a TreeView with a CellRendererCombo in it. Currently, I've connected the editing signal to a function which changes the underlying model and does some other actions based on the new value. However, this is annoying for the user. Dropping down the list and clicking on a new item does not seem to cause editing to "finish". Instead t...

Elegant way to handle "impossible" code paths

Occasionally I'll have a situation where I've written some code and, based on its logic, a certain path is impossible. For example: activeGames = [10, 20, 30] limit = 4 def getBestActiveGameStat(): if not activeGames: return None return max(activeGames) def bah(): if limit == 0: return "Limit is 0" if len(activeGames)...

Cleaning up code littered with InvokeRequired

I know that when manipulating UI controls from any non-UI thread, you must marshal your calls to the UI thread to avoid issues. The general consensus is that you should use test InvokeRequired, and if true, use .Invoke to perform the marshaling. This leads to a lot of code that looks like this: private void UpdateSummary(string text) {...

How to create a list or tuple of empty lists in Python?

I need to incrementally fill a list or a tuple of lists. Something that looks like this: result = [] firstTime = True for i in range(x): for j in someListOfElements: if firstTime: result.append([f(j)]) else: result[i].append(j) In order to make it less verbose an more elegant, I thought I wi...

What is the most elegant way in Perl to expand an iterator into a list?

I have an iterator with this interface: $hit->next_hsp The current implementation to listify it is: my @list; while ( my $hsp = $hit->next_hsp ) { push( @list, $hsp ); } Now I'm thinking that there might be better ways to do this in less code. What do you say, stackers? ...