StringBuilder vs. String considering replace

It is true that StringBuilder tends to be better than concatenating or modifying Strings manually, since StringBuilder is mutable, while String is immutable and you need to create a new String for each modification. Just to note, though, the Java compiler will automatically convert an example like this: String result = someString + someOtherString + … Read more

Change the values of a NumPy array that are NOT in a list of indices

I don’t know of a clean way to do something like this: mask = np.ones(a.shape,dtype=bool) #np.ones_like(a,dtype=bool) mask[indices] = False a[~mask] = 999 a[mask] = 888 Of course, if you prefer to use the numpy data-type, you could use dtype=np.bool_ — There won’t be any difference in the output. it’s just a matter of preference really.

Replacing a HashSet Java member

Do a remove before each add: someSet.remove(myObject); someSet.add(myObject); The remove will remove any object that is equal to myObject. Alternatively, you can check the add result: if(!someSet.add(myObject)) { someSet.remove(myObject); someSet.add(myObject); } Which would be more efficient depends on how often you have collisions. If they are rare, the second form will usually do only one … Read more

How to remove spaces from a string in Lua?

It works, you just have to assign the actual result/return value. Use one of the following variations: str = str:gsub(“%s+”, “”) str = string.gsub(str, “%s+”, “”) I use %s+ as there’s no point in replacing an empty match (i.e. there’s no space). This just doesn’t make any sense, so I look for at least one … Read more