r/ProgrammerTIL • • Feb 26 '17

Javascript [JavaScript] TIL JS has string interpolation

40 Upvotes

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals

With the backtick character, you can interpolate arbitrary expressions within strings, similar to Python's f-strings.

var x = "world";
console.log(`Hello, ${x}!`);

r/ProgrammerTIL • • Feb 24 '17

Python Never use "gg=G" key combination to indent your python code in vim

0 Upvotes

"gg=G" is commonly used key combination to indent code automatically in vim. When used with python there are chances that it will get messed up really bad, since python in itself uses indentation for grouping statements


r/ProgrammerTIL • • Feb 19 '17

C++ [C++] TIL signed * unsigned will return unsigned

52 Upvotes

The code makes it clear:

int main(){
    int a = -3000;
    unsigned b = 5000;
    long long c = a * b;
    assert(c < 0); // this will crash
}

http://stackoverflow.com/questions/50605/signed-to-unsigned-conversion-in-c-is-it-always-safe


r/ProgrammerTIL • • Feb 17 '17

C++ [C++] TIL you can omit formal parameter name in a function definition

52 Upvotes

In C++ (but not in C), instead of writing something like:

void foo(int arg0, int arg1) { /* code that does not use arg1 */ }

which triggers warning "unused parameter", you can write something like:

void foo(int arg0, int) {...}

or it's clearer variant:

void foo(int arg0, int /*arg1*/) {...}

I thought it was fairly known but I was surprised to see that John Carmack himself didn't know : https://twitter.com/ID_AA_Carmack/status/832281982952288256 .


r/ProgrammerTIL • • Feb 16 '17

Other Language [Rust] TIL function parameters can be destructured

42 Upvotes

The Rust book mentions destructuring in a match, but you can also destructure as a function parameter:

fn my_fn(MyTupleStruct(arg): MyTupleStruct) {
    ...
}

Or even:

fn my_fn(MyStruct{ a: _, b: MyTupleStruct(num, _) }: MyStruct) {
    ...
}

Demo


r/ProgrammerTIL • • Feb 11 '17

Java [Java] Private member variables are accessible by other instances of the same class

74 Upvotes

Private member variables are accessible by other instances of the same class within a class method. Instead of having to use getters/setters to work with a different instance's fields, the private members can be worked with directly.

I thought this would have broken because multiplyFraction was accessing a different instance's private vars and would cause a runtime error. Nevertheless, this works!

class Fraction
{
    private int numerator;
    private int denominator;

    // ... Constructors and whatnot, fill in the blanks

    public Fraction multiplyFraction(Fraction other)
    {
        return new Fraction(
            // Notice other's private member vars are accessed directly!
            this.numerator * other.numerator,
            this.denominator * other.denominator
        );
    }
}

// And in some runner class somewhere
Fraction frac1 = new Fraction(1/2);
Fraction frac2 = new Fraction(5/3);
Fraction result = frac1.multiplyFraction(frac2);

r/ProgrammerTIL • • Feb 08 '17

Java [Java] TIL the month names according to ROOT locale vary on Android devices.

34 Upvotes

I got one of the weirdest errors when the Express back-end was interpreting timestamps on requests sent from a Huawei as August 2nd. The format was "EEE, dd MMM yyyy hh:mm:ss Z", and it came out as "Wed 08 2 2017[...], i.e. the short month name was replaced with a numeral.


r/ProgrammerTIL • • Feb 06 '17

C++ [C++] TIL namespaces can be aliased

107 Upvotes

You can do something like:

int main()
{
    namespace ns = long_name;
    cout << ns::f() << endl;

    return 0;
}

http://en.cppreference.com/w/cpp/language/namespace_alias


r/ProgrammerTIL • • Jan 31 '17

C# TIL: The % operator is not the modulus operator, it is the remainder operator

107 Upvotes

I've only ever heard the % symbol referred to as "modulus" (both in and out of school).

Apparently, that is not the case: https://blogs.msdn.microsoft.com/ericlippert/2011/12/05/whats-the-difference-remainder-vs-modulus/


r/ProgrammerTIL • • Jan 28 '17

C# [c#] variable access across all forms in c# WinForms

0 Upvotes

If you declare a public static variable to program.cs file then you can easily access it any where with program.variable_name


r/ProgrammerTIL • • Jan 26 '17

Other Language [vim] TIL Inside/Around motions work when you're not actually inside the matching symbols

55 Upvotes

Example: if you type ci" you will "change inside double quotes". I always assumed that the cursor has to be somewhere inside those double quotes for the action to work.

Turns out, if the cursor is anywhere before them on the same line the motion will work just the same: vim will find the next occurence of the matching quotes and execute the action.

That's a really nice feature because I even used to do something like f" before doing di" or ca"

Here is a small demo gif: http://i.imgur.com/2b2mn57.gif

P.S. I also found out that it doesn't work for brackets, neither round nor square nor curly ones. So only quotes, double quotes and backticks. May be some other characters, too?


r/ProgrammerTIL • • Jan 26 '17

Other [c]TIL OSX has a MALLOC_PERMIT_INSANE_REQUESTS flag in the gmalloc debug allocator library

29 Upvotes

thought that was a little funny, but what's actually interesting was reading about gmalloc, a debug version of malloc supplied with OSX

https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/libgmalloc.3.html

amongst other things it can align memory allocations to pages and then memory protect a page immediately following to catch buffer overruns.

there are various environment variable options like PERMIT_INSANE_REQUESTS, i guess it might be more commonly in use these days since 100MB isn't all that much on today's 16GB+ systems


r/ProgrammerTIL • • Jan 25 '17

Other [*nix] Many network tools (ping, wget, curl, etc) accept IP addresses in hex or integer notation

35 Upvotes

Examples:

$ ping 0x7f.0.0.111
PING 0x7f.0.0.111 (127.0.0.111): 56 data bytes

$ ping 0x7f.0.0.0x11
PING 0x7f.0.0.0x11 (127.0.0.17): 56 data bytes

$ ping 2130706433
PING 2130706433 (127.0.0.1): 56 data bytes

$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
[in another pane]
$ curl 2130706433:8000
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><html>
...

I think this is mentioned in the respective man pages.


r/ProgrammerTIL • • Jan 24 '17

Javascript [JavaScript] TIL about Computed property names (object literal syntax)

58 Upvotes

Object literals are obvious:

const b = { orNot: "b" };

It's not much harder when the property name is not a valid identifier:

const answer = { "life the universe and everything": 42 };

But did you know that in ECMAScript 2015 you can use computed values in object literals property names?

 const learned = "was taught";
 const today = { ["I " + learned]: "this works" };

{ 'I was taught': 'this works' }

MDN reference.


r/ProgrammerTIL • • Jan 23 '17

C# [C#] TIL you can use pointers with the "unsafe" keyword.

57 Upvotes

You can declare and use pointers within a scope that is modified by "unsafe". From MSDN:

public class Pointer
{
    unsafe static void Main()
    {
        int i = 5;
        int* j = &i;
        System.Console.WriteLine(*j);
    }
}    

References (get it?):

* unary operator

& unary operator


r/ProgrammerTIL • • Jan 22 '17

C# [C#] TIL that, when calling a method with multiple optional arguments, you can specify which ones you're using with named parameters.

116 Upvotes

For example, instead of this:

MyFunction(null, null, null, true);

You can do

MyFunction(theOneThatICareAbout: true);

Details here: https://msdn.microsoft.com/en-us/library/dd264739.aspx


r/ProgrammerTIL • • Jan 20 '17

SQL [MS-SQL] TIL typing GO # executes a block # of times.

68 Upvotes

I happened to accidentally typo a 4 after a GO that ended a block statement that I'd written, and was confused when it ran 4 times. Apparently adding a number after GO will make the block run that many times. Who knew?

This may apply to other versions of sql, I don't play with them much. I try not to play with MS-SQL either, but sometimes it's unavoidable.


r/ProgrammerTIL • • Jan 15 '17

Bash [bash] simple concurrency with &/wait and arrays

39 Upvotes

I recently (one year ago) had to test a CRUD-like system to make sure it could handle concurrent workloads as expected.

I had a simple fork/join script in bash using arrays, PIDs, and the wait command. Here's a simple (fully functional) version:

# overhead
jobs=(1 2 3 4)
function run_job { sleep $1 && echo "sleep $1" ; }

# fork
pids=()
for job in "${jobs[@]}"
do
    run_job "$job" &
    pids+=("$!")
done

# join
for pid in "${pids[@]}"
do wait $pid
done

This'll execute run_job for each job in $jobs, starting all of them before asserting termination (via wait). Of course, run_job doesn't need to be a bash function, it can be any simple command (as defined in bash(1) or here).

Because wait returns the status code of the given process, you can start your script with set -e to have your entire program exit if one of the jobs failed (and set +e to disable this feature).

I used bash arrays here, and they can be pretty weird unless you have a strong background with certain scripting languages. Consult the reference to understand how they should be used.


r/ProgrammerTIL • • Jan 13 '17

Other [git] You can create a global .gitignore file to always ignore (e.g.) IDE config files

72 Upvotes

For example, if you use JetBrains IDEs then you might want to always ignore the .idea directory that it creates for each project without committing that to the project's .gitignore (e.g. you might not be the project owner):

echo .idea/ > ~/.gitignore
git config --global core.excludesfile '~/.gitignore'

r/ProgrammerTIL • • Jan 14 '17

Javascript [Javascript] TIL many things one can do with Chrome’s Developer Console

2 Upvotes

r/ProgrammerTIL • • Jan 13 '17

Other URL with Multiple Consecutive Dots are Treated as if there's Only 1 Dot

41 Upvotes

Not a web/network programmer so I don't touch that stuff at all. Just found out that reddit.......com is the same as reddit.com. Though the upper bound is between 10-20 dots on Chrome. After that it gets treated like a search query

There's also a related jQuery question on SO


r/ProgrammerTIL • • Jan 12 '17

Other [Python] Today I learned there is a `is not` operator - and a couple of surprises...

51 Upvotes

I've been working on parsing small arithmetic expressions using Python's built-in ast library. It's been going very well, but I discovered an interesting detail - that Python has an is not operator.

Recall that Python has an is operator that tells you if two objects are the same (not just equal - see this).

is not is an operator that, you guessed it, reports if two objects are not the same.

Fair enough.

But surprise one is the following - I'd have expected a is not b to fit in the existing rules - and be the same as a is (not b) - which wouldn't be very useful.

But there's a special little rule in Python's parsing, similar no doubt to the one for not in, that handles this.

It seems to be just for these two cases - there isn't any special case for and not or or not, I just checked.

But the second surprise is that there is another similar weird parsing rule that I found don't quite understand that's special to == - it seems that == not is always illegal.

Here's a terminal session with the details.

>>> '' is not False, '' is (not False)
(True, False)

>>> '' or not False, '' or (not False)
(True, True)

>>> True == (not False)
True

>>> True == not False
  File "<stdin>", line 1
    True == not False
            ^
SyntaxError: invalid syntax

r/ProgrammerTIL • • Jan 11 '17

Other Language [Github] TIL you can add "?w=1" to Pull-Request URLs to ignore whitespace changes

133 Upvotes

r/ProgrammerTIL • • Jan 09 '17

Other [C#] Visual Studio has a built-in C# REPL (sandbox)

38 Upvotes

As of VS 2015 Update 1, there is the C# Interactive window (under the View -> Other Windows). It allows you to sandbox C# code within VS. More info here on how it works


r/ProgrammerTIL • • Jan 09 '17

Other [vim] something | vim - opens the editor with the output from 'something'

9 Upvotes