JavaScript recursive zip function Could the performance of this function be optimized (without making the code much longer)?

The function zips two arrays into another.

function zip(p,q) {
  if( p.length > 1 || q.length > 2) {
    return ([[p[0],q[0]]]).concat(zip(p.slice(1),q.slice(1)));
  } else {
    return ([[p[0],q[0]]]);
  }
}

How exactly does the slice work? Is it immutable, like getting the tail in Haskell?
What values are inside the value returned by .concat()? Are these copy-constructed values from references, or are these references and are copied when a new array is constructed with the call to .concat()?

Recursive memory hog!!

I have to say that this is not at all a practical way to zip two arrays.

Recursive functions are huge memory hogs in JS if done badly

In Javascript calling a function adds a minimum of about 1 - 1.5K to the call stack, and you create copies each array of each call, ouch..

Test

I ran your function giving it two 8Mb array (1,000,000 numbers each) and it crashed Chrome. Something I would expect to do using a function like zip.

Crashed at 0.01% complete

Canary 65 devtools has a live performance monitor, so I ran that and I watched memory climb in less than a second to 1GB befor the browser interrupted and paused the code. The heap is full and the function was only 97 iterations in (approx 0.01% complete).

Why the memory usage?

Your use of Array.slice is the reason. Slice creates a shallow copy of each array. So if you have an array of size 100 and slice at 1 you now have two arrays for a total of 199 items.

Lets follow the recursion with 2 3 itemed arrays

function zip(p,q) {
  if( p.length > 1 || q.length > 2) {
    return ([[p[0],q[0]]]).concat(zip(p.slice(1),q.slice(1)));
  } else {
    return ([[p[0],q[0]]]);
  }
}

Make the call

zip([1,2,3],[4,5,6]);

zip(p.slice(1),q.slice(1));       // create 2 copies 2 bytes each
>> zip(p.slice(1),q.slice(1))     // create 2 copies 1 bytes each
>> >>  return ([[p[0],q[0]]]);

At this point there are arrays [3,6], [3], [6], [2,3], [5,6], [1,2,3], [4,5,6]

return ([[p[0],q[0]]]).concat( << <<

This is when you hit peek memory use, just before the above return you add another array [1,4,3,6] so you have stored in memory 18 references

return ([[p[0],q[0]]]).concat( <<
End.

Result is an array with 6 references.

Calculating memory use

You memory usage assuming same sized arrays is

len = array.length; // both arrays are the same size

totalReferences = (len / 2) * (len + 1) * 2 + 6

So for 2 array of size 100

(100 / 2) * (100 + 1) * 2 + 6 === 10,106

And for larger

1,000   === 1,001,006
10,000  === 100,010,006
100,000 === 10,000,100,006

How to improve.

Can Tail Call Optimisation (TCO) help?

TCO basically lets you call a function without adding a new context to the call stack. This makes calling a function almost as fast as running inline code. This would be the single best thing to have happened to the language for decades (and its only decades old), if it happened :(.

Javascript ES6 spec has (the very anticipated and needed) TCO but it remains the only unimplemented ES6 feature on Chrome, Firefox, and Edge. Reason?? I believe too many pages are kept running due to call stack overflow error, TCO prevents this and thus a bad recursion function blocks the page rather than throws an error.

Don't hold your breath waiting for TCO, for now its not going to help.

The only solution

In reality without TCO you can not safely do this via recursion. The call stack size is much smaller than the max array size. If you do recursion you would have to limit the array sizes, but even then you can not know how deep you are already in the call stack when you start, so there is no safe way to do this (Yes all recursive functions in javascript are fatally flawed, until TCO)

Quick simple and low memory use.

function zip(a, b) {
    const min = Math.min(a.length, b.length);
    var i, j, c;
    c = [];
    i = j = 0;
    while (j < min) {
        c[i ++] = a[j];
        c[i ++] = b[j ++];
    }
    if (a.length < b.length) { [a, b] = [b, a] }
    while (j < a.length) { c[i ++] = a[j ++] }
    return c;
}


Deleting everything between two quotes in a string Is this the easiest way to delete everything between and including the two first quotes (if present) in an std::wstring?

unsigned int firstQuotePos = logFileName.find_first_of(L"\"");
unsigned int secondQuotePos = logFileName.find_first_of(L"\"", firstQuotePos + 1);

if (firstQuotePos != std::wstring::npos && secondQuotePos != std::wstring::npos)
{
    logFileName = std::wstring(logFileName.begin(), logFileName.begin() + firstQuotePos)
        + std::wstring(logFileName.begin() + secondQuotePos + 1, logFileName.end());
}

C++ is very picky about types.
You should always try and use the correct ones:

unsigned int firstQuotePos = logFileName.find_first_of(L"\"");
unsigned int secondQuotePos = logFileName.find_first_of(L"\"", firstQuotePos + 1);

should be:

std::string::size_type firstQuotePos  = logFileName.find_first_of(L"\"");
std::string::size_type secondQuotePos = logFileName.find_first_of(L"\"", firstQuotePos + 1);

Next there is already an erase that does this:

if (firstQuotePos != std::string::npos)
{
    logFileName.erase(firstQuotePos, (secondQuotePos - firstQuotePos));
}


Changing all comments' size in range to autosize I have a code that turns all comments size to autosize, however as I have quite a few cells with comments, this code runs a little slow, to the point where it will become non responsive for awhile.

Sub AutoSizeComments()
    Dim c as range, ws as worksheet

    Set ws = ActiveSheet

    'Loop through each comment on worksheet
    For Each c In ws.Cells.SpecialCells(xlCellTypeComments)

        c.Comment.Shape.TextFrame.AutoSize = True

    Next c
End Sub

After some research online, I still could not find a way to make this faster. As I am new to VBA coding, I am not sure if there is any way to make this code run faster. Thanks for helping and if this is the fastest way, let me know too. Thank you all.

as I research more and tried different ways, I have found that I can use the application.screenupdating way to make my whole program run faster and since this question have been unanswered for quite awhile, I will mark this as my answer once a week has past since I asked this question. however I will still be checking to see if there is any better answers posted here till then. Thank you all!

Sub AutoSizeComments()
    Dim c as range, ws as worksheet

    Application.ScreenUpdating = False
    Set ws = ActiveSheet
    'Loop through each comment on worksheet
    For Each c In ws.Cells.SpecialCells(xlCellTypeComments)
        c.Comment.Shape.TextFrame.AutoSize = True
    Next c
    Application.ScreenUpdating = True
End Sub


Scraping webpage elements with VBA script With some help I've put together a macro to scrape webpage elements by tag ID from URLs (indicated in column A of an Excel sheet) and insert the text into columns B, C and D. The code loops from 1st row until 1000th. So far so good.

The problem is that it seems to be taking SOOOO much time. Is there any way to speed up the process? I feel like my use of IE pages isn't optimal.

(Please note that I'm aware that On Error the code is copying previous data as new but I have a manual easy work around to clean the data, which works fine until I get around to fixing that issue.)

Sub getCountry()
'
' GetCountry Macro
'
' Keyboard Shortcut: Ctrl+k
'
  Dim IE      As Object: Set IE = CreateObject("InternetExplorer.Application")
  Dim ws      As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
  Dim Country As String
  Dim Category As String
  Dim Network As String
  Dim n As Integer
  n = 729
  For n = 729 To 1000
    With IE
    Visible = False
    .navigate ws.Range("A" & n).Value
    Do
      DoEvents
        Loop Until .readyState = 4
      End With
      On Error Resume Next
      Country = Trim$(IE.document.getElementByID("youtube-user-page-country").innerText)
      On Error Resume Next
      Category = Trim$(IE.document.getElementByID("youtube-user-page-channeltype").innerText)
      On Error Resume Next
      Network = Trim$(IE.document.getElementByID("youtube-user-page-network").innerText)
      ws.Range("B" & n).Value2 = Country
      ws.Range("C" & n).Value2 = Category
      ws.Range("D" & n).Value2 = Network
    Next n
  IE.Quit
  End Sub

The indentation is terribly misleading.

Compare yours:

  For n = 729 To 1000
    With IE
    Visible = False
    .navigate ws.Range("A" & n).Value
    Do
      DoEvents
        Loop Until .readyState = 4
      End With

To how Rubberduck's Smart Indenter default settings do it:

For n = 729 To 1000
    With IE
        Visible = False
        .navigate ws.Range("A" & n).Value
        Do
            DoEvents
        Loop Until .readyState = 4
    End With

If I glance at your code, I've no idea where the With block ends, and at second glance it appears to end in the middle of a Do loop body (which would be illegal) - it takes a third read to pick up the matching Loop keyword hidden in the code.

Before modifying anything, fix the indentation.

Running Rubberduck inspections reveal that variable Visible is never declared, which means Option Explicit isn't specified at the top of the module, which means VBA will happily compile typos, and that can easily lead to very hard-to-debug problems. ALWAYS specify Option Explicit, and declare all variables.

The macro is implicitly Public, n should probably be declared As Long, and the procedure name should be PascalCase, i.e. GetCountry, although the name suggests it's getting some value, which usually implies a Function that returns that value - Sub procedures do something, they don't get stuff.

On Error Resume Next will make your macro keep running in error state, which makes the assignments fail and, as you noted, the previous iteration's value gets repeated. Why not "reset" the 3 values at the end of each iteration? That way a failed getElementByID would write an empty string instead of duplicating data. That said...

    On Error Resume Next
    Country = Trim$(IE.document.getElementByID("youtube-user-page-country").innerText)
    On Error Resume Next
    Category = Trim$(IE.document.getElementByID("youtube-user-page-channeltype").innerText)
    On Error Resume Next
    Network = Trim$(IE.document.getElementByID("youtube-user-page-network").innerText)

Error handling doesn't work that way; only the first OERN changes anything, the other two are perfectly redundant. If you want to restore error handling you need to do On Error GoTo 0:

    On Error Resume Next 'suppresses run-time errors
    Country = Trim$(IE.document.getElementByID("youtube-user-page-country").innerText)
    Category = Trim$(IE.document.getElementByID("youtube-user-page-channeltype").innerText)
    Network = Trim$(IE.document.getElementByID("youtube-user-page-network").innerText)
    Err.Clear 'clears error state
    On Error GoTo 0 'restores run-time errors

As for speeding things up, assuming lightning-speed scraping this would be the bottleneck:

    ws.Range("B" & n).Value2 = Country
    ws.Range("C" & n).Value2 = Category
    ws.Range("D" & n).Value2 = Network

You know how many iterations you're making, therefore you know from the start how many rows you're going to be writing to the worksheet; the fastest way to write to a worksheet isn't one cell at a time.

Declare a 2D array, populate it in your loop, and dump the array onto the worksheet to perform all Range writes in one single, instantaneous operation. Otherwise you're having Excel raise Worksheet.Change events, repainting itself, and possibly re-calculating things every time you write to a cell.

You could "cheat" and do Application.ScreenUpdating = False at the top and set it back to True at the end of the procedure, but that wouldn't be any more efficient code. Go with the 2D array.


Custom class for a borrowed unique_ptr? In C++11, I tend to have master objects that maintain sole ownership of a collection of some children objects.  Let's assume these children objects are non-copyable (for instance, boost::noncopyable).

Other code needs to access these children objects to do some temporary processing, but not keep references, or share ownership over these objects.

As such, my master objects tend to have some sort of a get_child() method.

As an example, let's say I have a Master object like this:

class Master {
private:
  std::vector<std::unique_ptr<Child>> children;
  ...
public:
  ??? get_child(int index);
};

When writing the get_child() method, I have 2 obvious options:

Return by pointer:

Child* get_child(int_index) {
  return children[index].get();
}

Return by reference:

Child& get_child(int index) {
  return *(children[index]);
}

I thought I didn't like either of these (for reasons I explain below), so I came up with the following:

borrowed_ptr<Child> get_child(int index) {
  return make_borrowed<Child>(children[index].get());
}

where borrowed_ptr is a trivial class wrapping a pointer with no smarts.  I provide its implementation at the end of this question.

To me, borrowed_ptr indicates that there exists a unique_ptr someplace, and this borrowed_ptr should be used for a short time, and not be recorded for any circumstance.

I don't like returning by raw pointer (1.) because I feel that Child* doesn't imply that there exists a unique_ptr<Child> someplace.  Namely, I already have a lot of raw pointers floating around (think handles received from libraries, or my code which is not using smart pointers).  I feel borrowed_ptr gives a little more information over a raw pointer.

I don't like returning by reference (2.) because of an additional reason.  I am worried that I will write

Child child = get_child();

and invoke a copy when I didn't intend to.

My question: Is borrowed_ptr silly? Does it raise red flags with experienced C++ developers?  Is it a faux pas?  Does it feel like a code smell?  Do you feel I should rather do 1., 2. or something else altogether?

Here is my implementation of borrowed_ptr:

template<typename T>
class borrowed_ptr {
private:
  T* ptr;
public:
  borrowed_ptr(const unique_ptr<T>& r) {
    ptr = r.get();
  }

  inline T* operator->() {
    return ptr;
  }
  inline const T* operator->() const {
    return ptr;
  }
  inline T& operator*() {
    return *ptr;
  }
  inline const T& operator*() const {
    return *ptr;
  }
};

My question: Is borrowed_ptr silly? Is it a faux pas? Does it feel like a code smell?

It seems a bit overengineered to me (YMMV).

  Do you feel I should rather do 1., 2. or something else altogether?

Something else. Consider this alternative:

class Master {
private:
    std::vector<std::unique_ptr<Child>> children;
    ...
public:
    // an observed ptr is not modified in any way by client code
    typedef Child const * const ObservedChildPtr;

    ObservedChildPtr get_child(int index) const;
};

This has the following advantages:

the semantics for an observed (i.e. not modified) pointer became part of the class' API
it is explicit and self-explanatory (like your borrowed_ptr)
it is minimalistic (you don't define/need the extra class)
it provides a natural expansion point, in case you actually do need the extra class (see line above) - if you need to expand it, replace Child const * const with a class definition.
client code can be written in terms of Master::ObservedChildPtr (which you can change later without having to update client code).


Python random word generator I want to implement a random word generator that would not use Import statements. The solution is working for a *nix system. The solution does yield a random word, but please suggest:

How to make the function optimally/safely return words with a higher position in the list(e.g. now we're almost guaranteed to return an 'A' word)
How to get a word with min/max length instead of length
Should I break this into smaller functions?
How to make the code more readable/higher performance
Is there a better approach to this problem? How to tell which modules are better off imported instead of implemented from scratch(except for the built-ins)?

def generate_random_word(length=8):
    """
    Return a random string from /usr/share/dict/words on a *nix system
    """
    with open('/usr/share/dict/words', 'r') as words_file, open("/dev/random", 'rb') as random_file:
        random_words = words_file.read().split('\n')
        size_words = [x for x in random_words if len(x) == length]
        for _ in range(0, 100):
            while True:
                try:
                    random_word = size_words[(int.from_bytes(random_file.read(1), 'big'))]
                except IndexError:
                    continue
                break

    return random_word

I am surprised that you chose to use /dev/random  although I can understand that for some purposes like generating private keys a source of strong entropy is preferred and there are even devices for that. Then this discussion could interest you. But the built-in random module in python should be sufficient here.
To read the file to a list of items you can just do this:
with open('/usr/share/dict/words', 'r') as f:
    lines = f.read().splitlines()

Good thing is that you are using the context manager for the open function.
Try to avoid IndexError rather than handle it and ignore it.
If your file is small (check size before opening) you can be lazy, load all items to a list, then filter it, and return one item at random:
def generate_random_word(min_length=8, max_length=13):
    with open('/usr/share/dict/words', 'r') as f:
        lines = f.read().splitlines()

    # select words matching desired length
    # selection = [line for line in lines if len(line) <= max_length and len(line) >= min_length ]
    selection = [line for line in lines if min_length <= len(line) <= max_length]
    # no match found
    if len(selection) == 0:
        return None

    return random.choice(selection)

If no matching item is found (or the file is empty) then I chose to return None.
If you want to filter lines at the source the implementation could be like this:
def generate_random_word(min_length=8, max_length=13):
    with open('/usr/share/dict/words', 'r') as f:
        selection = [line for line in f.read().splitlines() if min_length <= len(line) <= max_length]

    # no match found
    if len(selection) == 0:
        return None

    return random.choice(selection)

The file has to exist but it can be empty, then there is no error but the function will return None. Use os.exists to test that the file is present.
Yes, there is an import but it is a built-in module, does not require installation of a third-party module with PIP. It is also portable and not just Unix.
However, if you insist on /dev/random and want no import one thing you could do is retrieve a random integer like what you are doing now and use it in a modulo-type fashion against the list of matching items, to pick one word at random. Be careful with implementation as you may introduce unwanted bias in the selection. Random functions exist for a reason.
While it is possible to rely solely on /dev/random reimplementing the functionality with decent randomization will result in more code and reinventing the wheel.


Bidirectional numeric (floating point) sequence iterator I wanted a neat iterator that will always give me neat sequence of step spaced numbers. This is what I came up with, but I am a bit skeptical that I covered all cases.

/**
 * Creates numeric range iterator. The iterator will iterate between start and end.
 * Start may be larger than end. The output will contain both start and end, but no value
 * will appear twice.
 * @param {number} start
 * @param {number} end
 * @param {number} step
 * @yields {number}
 * @returns {IterableIterator<number>}
 */
function* numrange(start = 0, end = 100, step = 1) {
    if (start > end) {
        step = -1 * step;
    }

    let i = start;
    for (; shouldLoop(i); i += step) {
        yield i;
        if (i!=end && !shouldLoop(i + step)) {
            yield end;
        }
    }

    function shouldLoop(ival) {
        return start > end ? ival >= end : ival <= end;
    }
}

Can this be improved?

Counter intuitive?

Infinite loops.

The function is an iterator so this may not be undesired or potentially fatal for the application. However some inputs would make one wonder about the callers intent.

numrange(0, 100, 0); // will endlessly return 0
numrange(0, 100, -1); // will return 0, -1, -2, ... Infinity
numrange(0, -100, 1); // will return 0, 1, 2, ... Infinity

Not part of sequence.

There are situation where the last value can be out of sequence

numrange(0, 4, 2); // will return 0, 2.5, 4.

Or two values are returned rather than one.

numrange(4, 4, 1); // will return 4, 4.

Names

The function name should be numRange to be consistent with JS camelCase convention.
The argument ival (should be iVal) in shouldLoop is excessive, you could just have used i.
The function name shouldLoop can also be simplified as it expresses a question "should loop?" which can be shortened considering the context of its use to "loop?"

Logic and flow

The function shouldLoop is called 2 times each iteration, there is no need to do this, on top of this there are cases where the first clause of the inner statement is redundant. eg numRange(0, 20, 1.01) BTW use strict inequality !== rather than !=

You can improve efficiency if you removed the inner statement and yielded end after the loop. You would also need to change the return condition inside the function shouldLoop to start > end ? ival > end : ival < end

Each time you iterate you test if start > end This is known from the very start of the function and is thus repeating the same logic for no need. Use the condition to assign one  of two functions and avoid the repeated logic.

Rewrite

Thus you can have the same behavior as your original code with

function* numRange(start = 0, end = 100, step = 1) {
    const loop = start > end ? (i) => i > end : (i) => i < end;
    if (start > end) { step = -1 * step }
    for (let i = start; loop(i); i += step) {
        yield i;
    }
    yield end;
}

Example

Fixing what I see as problems (as outlined at the start of the answer)

Ensure that step is in the correct direction no matter what its sign.
Check if step is 0 and just return the start if so.
Check if end is part of the sequence and ignore it if not.

Using the var as argument start to count.

.

function* numRange(start = 0, end = 100, step = 1) {
    step = Math.sign(end - start) * Math.abs(step);
    if (step) {
        const loop = step > 0 ? () => start < end : () => end < start;
        while (loop()) {
            yield start;
            start += step;
        }
        if (start !== end) { return }
    }
    yield start;
}


"Guess the Number" game in C This is my first program in C. I'd rather not form any bad habits now. Is there anything that looks like bad practice, or something just looks wrong?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
    srand(time(NULL));
    int r = rand() % 10 + 1;
    int correct = 0;
    int guess;
    int counter = 0;

    printf("Guess my number! ");

    do {
        scanf("%d", &guess);
        if (guess == r) {
            counter++;
            printf("You guessed correctly in %d tries! Congratulations!\n", counter);
            correct = 1;
        }

        if (guess < r) {
            counter++;
            printf("Your guess is too low. Guess again. ");
        }

        if (guess > r) {
            counter++;
            printf("Your guess is too high. Guess again. ");
        }
    } while (correct == 0);

    return 0;
}

Here are some of the improvements i can suggest:

move your counter variable , from the inside the if statements , as increasing the count is independent of the if condition.
Use srand(time(NULL)); , below the declarations , or else , your compiler may throw this warning , when compiled using C90 standard.

warning: ISO C90 forbids mixed declarations and code [-pedantic]

So to ensure portability , avoid statements between declarations.
In the long run , more meaningful and formal names , can be used instead of names like r and guess.

In my personal opinion , these two changes would be better:

Using a break; , when the correct number is guessed , can eliminate the need for using an extra variable correct.
I would prefer to use just a  while() instead of do{}while();, if the program logic permits it.

Here is the program , modified with the changes , i listed above:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{

int random_num = 0;
int guessed_num = 0;
int counter = 0;

srand(time(NULL));
random_num = rand() % 10 + 1;

printf("Guess my number! ");

    while(1)
    {
        counter++;

        scanf("%d", &guessed_num);

        if (guessed_num == random_num)
        {
            printf("You guessed correctly in %d tries! Congratulations!\n", counter);
            break;
        }

        if (guessed_num < random_num)
            printf("Your guess is too low. Guess again. ");

        if (guessed_num > random_num)
            printf("Your guess is too high. Guess again. ");

    }

return 0;
}


Get a list of indexes for list A based on criteria in list B in Python I have one list of data with duplicate IDs and a second list of data with attributes for the IDs.

>>>a
[1,1,1,1,2,2,3,3]
>>>b
['No','No','Yes','No','Yes','No','No','No']

I want to create a list (c) that holds indexes for a that match the following criteria:

1) Only one index per ID in a

2) Indexes for IDs that have a 'Yes' in b take precedent

3) For IDs that don't have a 'Yes' any index is fine.

Using the above data as an example, the output would look like:

>>>c
[2,4,6]

So, you can see the data more easily:

>>> for c,(x,y) in enumerate(zip(a,b)): print(c,x,y)
...
0 1 No
1 1 No
2 1 Yes # grab this index ID 1
3 1 No
4 2 Yes # grab this index for ID 2
5 2 No
6 3 No  # grab this index, but either would have been fine for ID 3
7 3 No

Below is code that I've written. I am looking for a more efficient and Pythonic way to do it.

filterwhen='Yes'
uni=set(a)
sortedMain=sorted([list((i,c)) for c,i in enumerate(a)]) # sort list a
order=[i.pop() for i in sortedMain]
sortedFilt=[b[i] for i in order] # sort list b to keep data matched
sortedMain=[x for i in sortedMain for x in i]

c=[]
for i in uni:
    dex=[c for c,x in enumerate(sortedMain) if x==i]
    test=list(map((lambda x: x.lower().strip()==filterwhen.lower().strip()),[sortedFilt[i] for i in dex]))
    if any(test)==True:
        selecteddex=test.index(True)
        c.append(dex[selecteddex])
    else: c.append(dex[0])

print(c)

a has over 58,000 elements and 26,000+ are unique. Due to all the iterations, it takes too long to run this.

Consider doing this only with a single for loop, i.e. zip the two
lists, sort them by IDs and Yes/No (Yes first so those end up in
front in each block), enumerate and then, while keeping track of the
current block ID, simply always take the first element from each block
and append it to c.  E.g.:

a=[1,1,1,2,2,3,3,1]
b=['No','Yes','No','Yes','No','No','No','No']

d = list(enumerate(zip(a, b)))

def compare(x, y):
    same_ids = cmp(x[0], y[0])
    return -cmp(x[1], y[1]) if same_ids == 0 else same_ids

d.sort(cmp=compare, key=lambda x: x[1])

c = []
last = None
for i, (x, y) in d:
    if last != x or last == None:
        c.append(i)
    last = x

At the price of more memory consumption you could also just do a linear
scan and keep a dictionary around that records the best choice per ID so
far.  E.g.:

from itertools import izip

a=[1,1,1,2,2,3,3,1]
b=['No','Yes','No','Yes','No','No','No','No']

known = {}
for i, (x, y) in enumerate(izip(a, b)):
    current = known.get(x)
    if not current or y == 'Yes' and current[1] == 'No':
        known[x] = (i, y)

c = [i for (i, _) in known.itervalues()]


Multidimensional array of objects that retrieves the id, title, and smallest box art URL for every video Is there a way to simplify this code?

// array
const movieLists = [
        {
            name: "New Releases",
            videos: [
                {
                    "id": 70111470,
                    "title": "Die Hard",
                    "boxarts": [
                        { width: 150, height: 200, url: "http://cdn-0.nflximg.com/images/2891/DieHard150.jpg" },
                        { width: 200, height: 200, url: "http://cdn-0.nflximg.com/images/2891/DieHard200.jpg" }
                    ],
                    "url": "http://api.netflix.com/catalog/titles/movies/70111470",
                    "rating": 4.0,
                    "bookmark": []
                },
                {
                    "id": 654356453,
                    "title": "Bad Boys",
                    "boxarts": [
                        { width: 200, height: 200, url: "http://cdn-0.nflximg.com/images/2891/BadBoys200.jpg" },
                        { width: 140, height: 200, url: "http://cdn-0.nflximg.com/images/2891/BadBoys140.jpg" }

                    ],
                    "url": "http://api.netflix.com/catalog/titles/movies/70111470",
                    "rating": 5.0,
                    "bookmark": [{ id: 432534, time: 65876586 }]
                }
            ]
        },
        {
            name: "Thrillers",
            videos: [
                {
                    "id": 65432445,
                    "title": "The Chamber",
                    "boxarts": [
                        { width: 130, height: 200, url: "http://cdn-0.nflximg.com/images/2891/TheChamber130.jpg" },
                        { width: 200, height: 200, url: "http://cdn-0.nflximg.com/images/2891/TheChamber200.jpg" }
                    ],
                    "url": "http://api.netflix.com/catalog/titles/movies/70111470",
                    "rating": 4.0,
                    "bookmark": []
                },
                {
                    "id": 675465,
                    "title": "Fracture",
                    "boxarts": [
                        { width: 200, height: 200, url: "http://cdn-0.nflximg.com/images/2891/Fracture200.jpg" },
                        { width: 120, height: 200, url: "http://cdn-0.nflximg.com/images/2891/Fracture120.jpg" },
                        { width: 300, height: 200, url: "http://cdn-0.nflximg.com/images/2891/Fracture300.jpg" }
                    ],
                    "url": "http://api.netflix.com/catalog/titles/movies/70111470",
                    "rating": 5.0,
                    "bookmark": [{ id: 432534, time: 65876586 }]
                }
            ]
        }
    ];

    const arr1 = movieLists
        .map(function (outterItem) {
            return outterItem.videos
                .map(function (innerItem) {
                    return [innerItem.boxarts
                        .reduce(function (acc, currentValue) {
                            if (acc.width * acc.height < currentValue.width * currentValue.height) {
                                return acc
                            } else {
                                return currentValue
                            }
                        })]
                        .map(function (lastItem) {
                            return {
                                id: innerItem.id,
                                title: innerItem.title,
                                boxart: lastItem.url
                            }
                        })
                })
        })

    // flatten deep
    const newArray = (function flattenDeep(arr1) {
            return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
        })(arr1);

    console.log(newArray)

Arrow Functions and ternaries

I'll start by saying that you can simplify syntactically using ternaries and ES6 Arrow functions without losing readability. These will make the code look smaller and simpler, despite being the same solution.

It would look like this:

const arr1 = movieLists.map(outterItem =>
    outterItem.videos.map(innerItem =>
        [innerItem.boxarts
            .reduce((acc, currentValue) => acc.width * acc.height < currentValue.width * currentValue.height ?
                acc :
                currentValue
            )
        ]
        .map(lastItem =>
            ({
                id: innerItem.id,
                title: innerItem.title,
                boxart: lastItem.url
            })
        )
    )
)

Naming

The names you gave in to some variables/parameters aren't very good and make the code somewhat hard to read.

For instance in the maps:

.map(function (outterItem) {
    return outterItem.videos
        .map(function (innerItem) {

Both outterItem and innerItem are too vague to actually mean anything. And you can't really know what they hold unless you take a another look at the data. The outterItem is the first level object of the array, which is a sort of category object, while the innerItem would be each video of the videos array.

Solution

The solution itself seems overly complex for the problem at hand, because you do a double map, to a reduce, to a final map. And then you flatten the result with reduce. Then flatten is needed because the generated structure is deeper than you needed it to be.

A way simpler solution would be:

2 for loops to run through each video
Find the smallest box art in the video with reduce
Add the desired object to the resulting array with push

This avoids the need to flatten anything.

Following this logic, the whole code would become:

const finalVideos = []
for (let category of movieLists){
    for (let video of category.videos){
        const smallestBoxArt = video.boxarts.reduce((acc, curr) => acc.width * acc.height < curr.width * curr.height ? acc : curr)
        finalVideos.push({
            id: video.id,
            title: video.title,
            boxart: smallestBoxArt.url
        });
    }
}

console.log(finalVideos)

If you feel the reduce line as a bit too long or just repeats the area code too much, you can even create a simple function for it:

const area = obj => obj.width * obj.height;

And change the reduce to use it:

const smallestBoxArt = video.boxarts.reduce((acc, curr)=>area(acc) < area(curr) ? acc:curr)


Base classes for a GUI I am creating a GUI library to better learn C++ and wanted to see if there is anything to improve/simplify.

And I also wanted to be able to call an event of a parent and then for it to iterate all its children and those children to iterate their children and so forth, but I did not want to have a foreach loop in every subclass thus the IterateEvents loop. Is there a better way?

#pragma once

#include <functional>
#include <memory>
#include <vector>

#include <iostream>

namespace bui {
    class Element {
    public:
        int x = 0;
        int y = 0;
        int width = 0;
        int height = 0;
        Element* parent;
        std::function<void(void)> function;

        std::vector<Element*> children;

        Element(int x, int y, int width, int height, Element* parent) {
            this->x = x;
            this->y = y;
            this->width = width;
            this->height = height;

            if (parent != nullptr) {
                parent->children.push_back(this);
            }
        }

        ~Element() {

        }

        template <typename T>
        bool pointInElement(T x, T y) {
            return (x > this->x && y > this->y && x < this->x + this->width && this->y < this->y + this->height);
        }

        virtual void Event() = 0;
        virtual void Draw() = 0;

        void IterateEvents() {
            this->Event();
            for (auto &i : children) {
                i->Event();
            }
        }
    };

    extern std::vector<Element*> TopLevelWindows;

    class TopLevelWindow : public Element {
    public:
        TopLevelWindow(int x, int y, int width, int height, Element* parent) : Element(x, y, width, height, parent) {
            TopLevelWindows.push_back(this);
        }

        void Event() {
            std::cout << "TopLevelWindow\n";
        }

        void Draw() {
            //Draw stuff
        }

        ~TopLevelWindow() {

        }
    };

    class Window : public Element {
    public:
        Window(int x, int y, int width, int height, Element* parent) : Element(x, y, width, height, parent) {
        }

        void Event() {
            std::cout << "Window\n";
        }

        void Draw() {
            //Draw stuff
        }

        ~Window() {

        }
    };

    class Button : public Element {
    public:
        Button(int x, int y, int width, int height, Element* parent) : Element(x, y, width, height, parent) {
        }

        void Event() {
            std::cout << "Button\n";
        }

        void Draw() {
            //Draw stuff
        }

        ~Button() {

        }
    };
}

Point and Size structures

I would go even further than @glampert and create Point and Size structures as well as a Rectangle one. Experience has shown that this kind of small classes are extremely useful and can be used at many places in a GUI library (for example, getting the coodinates of the mouse can return a Point, computing the centre of a rectangle too, etc...). Moreover, once you have Point and Size classes, you can overload some of their operators to implement expressive and unambiguous operations such as multiplication by an integer.

In the long run, you will see that it is easier to reason with these objects, and you can even return them from functions while you can't return x and y if they're not in a structure.

Back to the Rectangle

Here is a concrete example of what your class does but should be actually performed by a Rectangle class instead:

template <typename T>
bool pointInElement(T x, T y) {
    return (x > this->x && y > this->y && x < this->x + this->width && this->y < this->y + this->height);
}

This should look like this, assuming that you have a Rectangle member named box and that your Rectangle class has a method named contains which takes a Point and returns a bool:

template<typename T>
bool pointInElement(const Point<T&>& point) const {
    return box.contains(point);
}

Constructor initialization list

Whenever possible, try to use the constructor initialization list. As it is now, your code constructs an Element instance, then assigns values to its fields. If you leave the job to the constructor initialization list, your object will be directly constructed with the appropriate values:

Element(int x, int y, int width, int height, Element* parent):
    x(x), y(y),
    width(width), height(height) {

    if (parent != nullptr) {
        parent->children.push_back(this);
    }
}

As you can see, it even allows to drop the this-> needed to differentiate the variables. The syntax only allows the member names on the left and the name resolution picks the parameters first on the right.

About the virtual destructor

I bet that you will want runtime polymorphism with your widgets. In this case, follow @glampert's advice: make the destructor virtual and public. If it does not do anything, the simplest thing to do is to explicitly default it:

virtual ~Element() = default;

Now, if a destructor is public and virtual in a base class, then the derived class automagically have a virtual destructor, you don't have to write anything. Therefore, the simplest thing to do would be to simply remove the destructors from TopLevelWindow, Window and Button if they don't do anything more than Element's destructor; you program will then be correct but simpler.


Testing #initialize of class Author I am trying to test #initialize of class Author:

# lib/author.rb
class Author
  attr_reader :name, :filename, :website

  def initialize(name, filename, website)
    @name = name
    @filename = filename
    set_filename_from_name if filename == :auto
    @website = website
  end
end

In reality there are 8-9 properties of Author, not just 3 and I've decided to require them all in #initialize.

I am trying to dry up my specs, but I have lots of repetitions.

I have created a helper module:

#spec/helpers/create_author.rb
module CreateAuthor
  # Creates author with default values except for those listed
  # under params.
  def create_author(params = {})
    defaults = {
      name: "Ford",
      filename: "Ford",
      website: 'www.ford.com'
    }
    opt = defaults.merge(params)

    Author.new(opt[:name],
      opt[:filename],
      opt[:website])
  end
end

But now I have untested code which I need to test. This is spec for that helper method:

# spec/authors_helper_spec.rb
require_relative 'helpers/create_author'

describe 'Create Author Helper' do
  # subject do
  #   Class.new { include CreateAuthor }
  # end
  include CreateAuthor

  let(:defaults) do
    {
      name: "Ford",
      filename: "Ford",
      website: 'www.ford.com'
    }
  end

  describe '#create_author' do
    it 'returns author with default values when called with no parameters' do
      author = create_author()

      expect(author.class).to eq(Author)
      expect(author.name).to eq(defaults[:name])
      expect(author.filename).to eq(defaults[:filename])
      expect(author.website).to eq(defaults[:website])
    end

    it 'returns author with custom name when specified' do
      author = create_author(name: 'New Name')

      expect(author.class).to eq(Author)
      expect(author.name).to eq('New Name')
      expect(author.filename).to eq(defaults[:filename])
      expect(author.website).to eq(defaults[:website])
    end
  end
end

I will need to do similar thing for other class, so I will just change create_author(options={}) to create_class(class, options={}) and test that.

How can I DRY this up and make it less verbose?

You could use the following solution unless it's important to call initialize in "create_author".

# spec/helpers/create_author.rb
module CreateEntity
  def create_entity(klass, params = {}, defaults = {})
    opt = defaults.merge(params)

    entity = klass.allocate
    opt.each do |key, value|
      entity.instance_variable_set("@#{key}", value)
    end
    entity
  end

  def create_author(params = {})
    create_entity(Author, params, {
      name: "Ford",
      filename: "Ford",
      website: 'www.ford.com'
    })
  end
end

create_author(name: "Ford 1")


Checking whether one string is a rotation of another Given a method isSubstring, two strings s1 and s2, check whether s1 is a rotation of s2 using only one call to isSubstring.

Any comments on the code below?

I would like to check the complexities as well:

For isSubstring:

runtime: \$O(n^2)\$
memory: in place

For isRotation:

runtime: \$O(n^2)\$
memory: \$O(n)\$

import static org.junit.Assert.*;

import org.junit.Test;

public class Solution {
  // Find whether string s1 is a rotation of string s2
  // using only one call to isSubstring

  static boolean isSubstring(String s1, String s2) {
    // return true if s1 is a substring of s2
    // false otherwise
    int n1 = s1.length();
    int n2 = s2.length();
    for (int i = 0; i < n2; i++) {
      if (i+n1>n2){
        return false;
      }
      else if (s1.equals(s2.substring(i,i+n1))) {
        return true;
      }
    }
    return false;
  }

  static boolean isRotation(String s1, String s2) {
    // return true if s2 is a rotation of s1
    // false otherwise

    // concatenate all the rotated strings of s1
    StringBuffer allRotated = new StringBuffer();
    int n1 = s1.length();
    int n2 = s2.length();
    if (n1 != n2) {
      return false;
    }
    allRotated.append(s1);
    for (int i = n1 - 1; i > 0; i--) {
      allRotated.append(s1.substring(i) + s1.substring(0, i));
    }

    // Return true if s2 is a substring of allRotated
    String rotated = allRotated.toString();

    return isSubstring(s2, rotated);
  }

  @Test
  public static void abcTest() {
    String abc = "abc";
    String cab = "cab";
    String bca = "bca";

    assertTrue(isRotation(abc, cab));
    assertTrue(isRotation(abc, bca));
  }

  @Test
  public static void falseTest(){
    String abc = "abc";
    String cba = "cba";
    assertFalse(isRotation(abc,cba));
  }

  @Test
  public static void evenTest(){
    String abcd = "abcd";
    String dcba = "dcba";
    assertFalse(isRotation(abcd,dcba));
  }

  @Test
  public static void identityTest(){
    String aaaa = "aaaa";
    assertTrue(isRotation(aaaa,aaaa));
  }
  public static void main(String[] args) {
    abcTest();
    falseTest();
    evenTest();
    identityTest();
  }

}

I have a couple of comments on the code that you have posted.

First, your isSubstring function is not checking for a 0 length n1 string, so it will always return true for an empty string - is that what you want?

Second, your isSubstring function is calling s2.substring for every possible position until it finds a match.  You can limit the number of calls by performing a simple pre-check to see if s1.charAt(0) == s2.charAt(i).  If this is not true, then you know the substring will not match, saving you the overhead of calling the substring() function and creating the additional substring, and then performing the full String.equals() comparison.

Third, your rotation function is overly complex.  Since you're just doing an inString comparison, you only have to concatenate the input string to itself once, and then all valid rotations will be a substring of it.  To show the example visually, given an input string of "abcd", and the valid rotations of "bcda", "cdab", and "dabc":

abcdabcd
 bcda
  cdab
   dabc

All of the rotations are substrings of the double-concatenated version.  This accomplishes the same result of your function, but uses \$O(2n)\$ memory.  You originally listed yours as using \$O(n)\$ memory, but that is too low - you are using \$O(n^2)\$ memory, because you are concatenating all the permutations of the rotations.

Finally, your runtime \$O(n^2)\$ calculations aren't quite right, because you are short-circuiting out once you know that the string being searched is too long to be in the remainder.  Unless the input string is 1 character, then the number of permutations being checked is actually smaller - and if you add in the first character optimization I listed above, the total cost of the function would go down even further.


Using TryXXX pattern to avoid exceptions I have been using the TryXXX and GetXXX pattern lately to give clients a choice whether to trap an exception or to read a boolean. An example of this concept would be System.Integer.TryParse and System.Integer.Parse.

It is my understanding that you should get two benefits from this:

using an if statement in calling code instead of try-catch
a performance benefit from not causing an exception.

In this class, I am attempting to do this, but I think I am getting only benefit 1, not benefit 2. I am drawing a blank as how to not throw any exception without code duplication.

       Public Function ConvertFractionToDecimal(ByVal fraction As String) As Decimal

        If String.IsNullOrWhiteSpace(fraction) Then Throw BuildBadFractionException(fraction)

        'will accept fractions of the form:
        'X-Y/Z
        'X Y/Z
        'Y/Z
        'will not accept negative signs in numerator, denominator, or whole number

        Dim whole As String
        Dim numen As String
        Dim denom As String

        Dim loc1 As Integer
        Dim loc2 As Integer

        fraction = fraction.Trim
        If fraction Like "*?-*?/?*" Then
            loc1 = InStr(fraction, "-")
            loc2 = InStr(fraction, "/")
        ElseIf fraction Like "*? *?/?*" Then
            loc1 = InStr(fraction, " ")
            loc2 = InStr(fraction, "/")
        ElseIf fraction Like "*?/?*" Then
            loc2 = InStr(fraction, "/")
        Else
            Throw BuildBadFractionException(fraction)
        End If

        If loc1 > 0 Then
            whole = Mid(fraction, 1, loc1 - 1).Trim
        Else
            whole = "0"
        End If
        numen = Mid(fraction, loc1 + 1, loc2 - loc1 - 1).Trim
        denom = Mid(fraction, loc2 + 1).Trim

        Dim Uwhole As UInt32
        Dim Unumen As UInt32
        Dim Udenom As UInt32
        If Not UInt32.TryParse(whole, Uwhole) Then Throw BuildBadFractionException(fraction)
        If Not UInt32.TryParse(numen, Unumen) Then Throw BuildBadFractionException(fraction)
        If Not UInt32.TryParse(denom, Udenom) Then Throw BuildBadFractionException(fraction)

        Return CDec(Uwhole + Unumen / Udenom)

    End Function

    Public Function TryConvertFractionToDecimal(ByVal fraction As String, ByRef result As Decimal) As Boolean
        Try
            result = ConvertFractionToDecimal(fraction)
            Return True
        Catch ex As Exception
            result = 0
            Return False
        End Try
    End Function

    Private Function BuildBadFractionException(ByVal fraction As String) As InvalidOperationException
        Return New InvalidOperationException(String.Format("'{0}' is not a recognisable fraction.", fraction))
    End Function

I was going to edit my first answer, but as I wrote the example code I wanted to show, and refactored, and refactored again, ...the result went so far away from the original code that I thought it warranted a separate answer.

So I copied your code into Visual Studio, and started by implementing the changes I suggested in my other answer. Quickly though, I felt the need to extract a FractionInfo type, a Structure that would hold the Whole, Numerator and Denominator parts of a fraction, so that I could write the regex part into a separate function that would return an instance of this FractionInfo type.

Being a Structure, I wanted to make that type immutable, so I implemented an Empty property that returned a Shared default instance... and then I tried doing If result = FractionInfo.Empty and noticed the = operator needed to be implemented - I'm lazy, so instead I just implemented Equals, and since when you override Equals you also need to override GetHashCode, I implemented GetHashCode as well.

So the ConvertFractionToDecimal function started like this:

Dim info As FractionInfo = GetFractionInfo(value)
If info.Equals(FractionInfo.Empty) Then Throw BuildBadFractionException(value)

And then I thought "great, now I can get rid of pretty much the whole rest of the code!" ...and then it struck me: you're not showing where your Convert.../TryConvert... methods are written, but I'm assuming they're not written in a Structure called Fraction.

And to follow the single responsibility principle, the only logical place to put such conversion methods would be in a value type called Fraction.

I suggest you take a look at this question and answers (disclaimer: it's one of my questions on this site) - it's C#, but the basic idea is essentially the same.

After much refactoring, this is what I ended up with - I'm not fully satisfied with it because it will throw a FormatException whenever parsing fails, even when one would expect an OverflowException. It does throw an ArgumentNullException when you give it Nothing, but the produced stack trace might be a little surprising.

Private Shared Function TryParseMatchGroups(ByVal groups As Match, ByRef result As Fraction) As Boolean

    Dim success As Boolean
    Dim wholePart As String = groups.Groups("whole").Value
    Dim numeratorPart As String = groups.Groups("numerator").Value
    Dim denominatorPart As String = groups.Groups("denominator").Value

    Dim whole As Integer
    Dim numerator As Integer
    Dim denominator As Integer

    success = Integer.TryParse(IIf(String.IsNullOrEmpty(wholePart), "0", wholePart), whole) _
        And Integer.TryParse(IIf(String.IsNullOrEmpty(numeratorPart), "0", numeratorPart), numerator) _
        And Integer.TryParse(IIf(String.IsNullOrEmpty(denominatorPart), "0", denominatorPart), denominator)

    If success Then
        result = New Fraction(whole, numerator, denominator)
    Else
        result = Fraction.Empty
    End If

    Return success

End Function

Public Shared Function Parse(ByVal value As String) As Fraction

    Dim result As Fraction
    Dim match As Match = regexp.Match(value)

    If match.Success And TryParseMatchGroups(match, result) Then
        Return result
    Else
        Throw New FormatException()
    End If

End Function

Public Shared Function TryParse(ByVal value As String, ByRef result As Fraction) As Boolean

    If value Is Nothing Then Return False

    Dim match As Match = regexp.Match(value)
    Return match.Success And TryParseMatchGroups(match, result)

End Function

These functions are Shared, exactly like Decimal.Parse and Decimal.TryParse are. Here's the rest of the type:

Public Structure Fraction

    Private Const pattern As String = "^((?<whole>[0-9]+)?\s+?)?(?<numerator>[0-9]+)\s?/\s?(?<denominator>[0-9]+)\s*?$"
    Private Shared ReadOnly regexp As Regex = New Regex(pattern)
    Private Shared ReadOnly emptyValue As Fraction = New Fraction()

    Private ReadOnly WholePart As Integer
    Private ReadOnly NumeratorPart As Integer
    Private ReadOnly DenominatorPart As Integer

    Public Sub New(ByVal whole As Integer, ByVal numerator As Integer, ByVal denominator As Integer)
        WholePart = whole
        NumeratorPart = numerator
        DenominatorPart = denominator
    End Sub

    Public ReadOnly Property Whole() As Integer
        Get
            Return WholePart
        End Get
    End Property

    Public ReadOnly Property Numerator As Integer
        Get
            Return NumeratorPart
        End Get
    End Property

    Public ReadOnly Property Denominator As Integer
        Get
            Return DenominatorPart
        End Get
    End Property

    Public Shared ReadOnly Property Empty As Fraction
        Get
            Return emptyValue
        End Get
    End Property

    Public Function ToDecimal() As Decimal
        Return Whole + CDec(Numerator) / CDec(Denominator)
    End Function

    Public Overrides Function Equals(obj As Object) As Boolean
        Dim other As Fraction = DirectCast(obj, Fraction) 'let it blow up on InvalidCastException
        Return other.Whole = Me.Whole _
            And other.Denominator = Me.Denominator _
            And other.Numerator = Me.Numerator
    End Function

    Public Overrides Function GetHashCode() As Integer
        'ok this is a bit like cheating.. but so much easier than implementing the real thing
        Return Tuple.Create(Me.Whole, Me.Numerator, Me.Denominator).GetHashCode()
    End Function

    Public Overrides Function ToString() As String
        If Me.Whole <> 0 Then
            Return String.Format("{0} {1}/{2}", Me.Whole, Me.Numerator, Me.Denominator)
        Else
            Return String.Format("{0}/{1}", Me.Numerator, Me.Denominator)
        End If
    End Function

You'll notice this implementation doesn't support negative fractions either - I'll leave that for you to explore and implement yourself. Note that vb.net isn't my primary language, so there might be stylistic errors in here.

If you looked at my A fraction of the code post, you've noticed there's many, many members missing here, mostly operators; you'll probably want a Fraction to at least support the = and <> operators, but the Equals implementation might be good enough as well. To make the type more usable you'll want to add MinValue and MaxValue, and perhaps a Zero value (0/1) and a Simplify() method. And of course you'll want to support negative fractions.

Basically, what this answer is suggesting that no answer has suggested yet, is to implement a [full-blown?] Fraction type, and to encapsulate your parsing logic in there: putting it anywhere else will break SRP.


Could this connection and query class be improved? Wrote this class it allows me to connect to database and display as many columns as I wish to. I can just give it desired parameters and I'm done. I've commented about the parameters that need it to be passed.

     include('connect.php');
   //include this file. This is our class

   $connection = new connection_to_db;
   //instantiate class

   $connection->make_connection("host_name", "user", "pass", "database_name");
   //1st param: your host name
   //2st param: your username
   //3rd param: your password
   //4th param: your database name

   $connection->run_test_query("shouts", "id", 2);
   //1st param: your table name.
   //2nd param: which column to show.
   //3rd param: how many results to display.

class connection_to_db{
     function make_connection($host, $user, $pass, $db){
       global $conn;
       try{
         $conn = new pdo("mysql: host=". $host . ";dbname=". $db, $user, $pass);
       }catch(PDOException $error){
         echo $error->getMessage();
         die();
       }
     }

     function run_test_query($shouts, $column_to_show, $count){
       global $conn;
       $query = $conn->prepare("SELECT * FROM $shouts LIMIT $count");
       $query->execute();

       while($result = $query->fetch(PDO::FETCH_ASSOC) ){
         echo $result["$column_to_show"] . "</br>";
       }
     }
   }

convention for PHP class names is PascalCase, so your class should be ConnectionToDb.
you are inconsistent with your indentation (2 vs 4 spaces).
select * is discouraged. Don't just select everything if you only need one column, select only that column.
limit is actually a vector for SQL injection. You should also clean table before using it in a query. Even if the data isn't user supplied right now, as this is a class, which is meant for reuse, you can never be sure how it will be used in the future.
Don't just echo unsanitized data from the database (because it might be user supplied), this can result in an XSS vulnerability.

 isn't valid HTML, use
 or

I don't see the benefit of having this as a class. I would just remove make_connection and add the connection as a parameter to run_test_query.
run_test_query isn't a very good name.


Filtering a dictionary by subject of definitions I am writing a function to filter a "dictionary" by the "subject" of its definitions.

The dictionary data structure is a hash-map of this kind:

{ "word1" {:foo :bar
           :definitions [{:definition "def1" :subject ["Subject1" "Subject2"]}
                         {:definition "def2" :subject ["Subject3" "Subject1"]}]}
  "word2" {:foo :baz
           :definitions [{:definition "def3" :subject "Subject2"}
                         {:definition "def4" :subject ["Subject2" "Subject3"]}]}

The function needs to return a new dictionary with only definitions of the specified subject (no word entry if no definition available).

I came up with two (working) different functions that returns the same exact result.
The first version uses map, the second version uses loop/recur.

map version:

(defn filter-by-subject [dict subject]
  (apply hash-map
         (flatten (map (fn [[word entry]]
                           (let [definitions (definitions-for-subject entry subject)]
                              (if (> (count definitions) 0)
                                  [word (assoc entry :definitions definitions)]
                                  [])))
                       dict))))

loop/recur version:

(defn filter-by-subject2 [dict subject]
  (loop [old-dict dict
         new-dict {}]
     (if-let [[word entry] (first old-dict)]
             ;; then
             (recur (dissoc old-dict word)
                    (let [definitions (definitions-for-subject entry subject)]
                       (if (> (count definitions) 0)
                           (assoc new-dict word
                                  (assoc entry :definitions definitions))
                           new-dict)))
             ;; else
             new-dict)))

Supporting functions:

(defn subjects-of-definition [definition]
  (let [sbjs (:subject definition)]
     (if (coll? sbjs)
         sbjs
         [sbjs])))

(defn definitions-for-subject [entry subject]
  (into [] (filter (fn [definition]
                       (some #{subject} (subjects-of-definition definition)))
                   (:definitions entry))))

I would like to hear your opinion on these functions.

Do they follow the common "functional style"?
Which version of the two do you find more readable, clear, understandable or even faster?

UPDATE

A little clarification.
If a word has two definitions, one of subjects A and B, and one of subjects B and C, and we filter by subject A, the resulting dictionary will have only the first definition of word (the one of subjects A and B).

Some examples:

=> (def dictionary { "Bit" { :definitions [
                                { :definition "A unit of information storage on a computer"
                                  :subject "IT" }
                                { :definition "Beijing Institute of Technology"
                                  :subject ["Acronyms" "Education"] }] }
                     "Matrix" { :definitions [
                                { :definition "A rectangular array of numbers, symbols or expressions"
                                  :subject "Mathematics"}
                                { :definition "A 1999 science fiction film"
                                  :subject "Movies"}]}})
#'user/dictionary

=> (filter-by-subject dictionary "Education")
{"Bit" {:definitions [{:subject ["Acronyms" "Education"], :definition "Beijing Institute of Technology"}]}}

=> (filter-by-subject dictionary "IT")
{"Bit" {:definitions [{:subject "IT", :definition "A unit of information storage on a computer"}]}}

=> (filter-by-subject dictionary "Movies")
{"Matrix" {:definitions [{:subject "Movies", :definition "A 1999 science fiction film"}]}}

(note that, for example, filtering by "Education" deletes the "IT" definition of "Bit".)

Updated answer:

Thanks for clarifying the question, the examples helped. Here is my new attempt:

(defn update-subjects [dict subj]
  (map (fn [[k {val :definitions}]]
         [k {:definitions
             (filter (fn [{s :subject}]
                       ((into #{} (flatten [s])) subj)) val)}]) dict))

(defn my-filter [dict subj]
  (into {} (->> (update-subjects dict subj)
                (remove (comp empty? :definitions second)))))

(= (my-filter dictionary "IT") (filter-by-subject dictionary "IT"))
=> true

in this solution, I first remove all the definitions which subjects do not match, and then I remove all the entries with empty definitions. I used the threading macro (->>) for readability.

original answer:

Here is another way of implementing your subject filter:

(defn subject-filter [p m]
   (filter (fn[[k {v :definitions}]]
               (some (fn [{x :subject}]
                        ((into #{} (flatten [x])) p)) v)) m))

This implementation makes use of two important features:

Destructuring - an idiomatic method of extracting items from a data structure in clojure. I highly recommend keeping the following link handy at all times http://blog.jayfields.com/2010/07/clojure-destructuring.html
Sets as a predicate - in clojure, if a set is in a function position, it acts as a function that returns true iff the first argument is in the set. So it is very idiomatic to write (if (#{1 2 3} i) .. ..) to know if i is either 1, 2 or 3. Perhaps you could even use sets instead of arrays in your data definition for :subject, which will make this code even shorter and faster, and your DS more "correct" - you could never keep two identical subjects and :subject will be a predicate of a query subject.

Just a note, you could also do without so much destructuring, and get a more concise function:

(defn my-filter [p m]
   (filter (fn[[k v]] (some (fn [x] ((into #{} (flatten [(:subject x)])) p)) (:definitions v))) m))


Network programming - asynchronous, single-threaded, nickname-only chat server I am starting to learn network programming. I have implemented a very simple chat server based upon TCP, where the users only need to provide username.
The assumption is that the server makes use of no additional threads and the sockets are not blocking. The code:

import sys
import time
import socket
import select

class User:
    def __init__(self, name, sock):
        self.name = name
        self.sock = sock

class Server:
    def __init__(self, host, port):
        self.users = []

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.bind((host, port))

    def accept_usr(self):
        usock, _ = self.sock.accept()
        usock.send(b"Please, choose your username: ")
        uname = usock.recv(1024)
        self.users.append(User(uname, usock))
        _, writes, _ = select.select([], self._usocks(), [])
        for w in writes:
            w.send(bytes(f"{uname} has joined us!", encoding="ascii"))

    def handlerr(self, errs):
        for s in errs:
            s.close()

    def update(self):
        reads, writes, errs = select.select([*self._usocks(), self.sock], self._usocks(), self._usocks())
        for r in reads:
            if r is self.sock:
                self.accept_usr()
            else:
                uname = [u for u in self.users if u.sock is u.sock][0].name
                msg = r.recv(1024)
                for w in writes:
                    w.send(bytes(f"{uname}: {msg}", encoding="ascii"))
        self.handlerr(errs)

    def run(self):
        self.sock.listen(5)
        while 1:
            self.update()
            time.sleep(0.1)

    def _usocks(self):
        return [u.sock for u in self.users]

if __name__ == "__main__":
    s = Server("localhost", int(sys.argv[1]))
    s.run()

I would be grateful for any hints and comments.

EDIT:
An obvious improvement that comes to my mind is to store the mapping of socket->User in a dict so that I'll be able to quickly determine the author of the message being sent.

Packet fragmentation

Have a read through this: https://stackoverflow.com/a/17668009/313768

usock.recv(1024) is fragile, and under many circumstances simply won't work for a handful of reasons. You'll need to do some reading about the fundamentals of TCP/IP to understand why that is, but basically, you can't assume that you'll get the data you want all in one chunk.

Context manager

You hold onto some sockets, which are resources that should be closed when you're done with them even if something goes wrong. This is a job for a context manager. You can make your class a context manager so that calling code can be sure that your resources are closed off, regardless of what else happens.

Have a read through this: https://docs.python.org/3/library/stdtypes.html#typecontextmanager

Presentation versus logic

    usock.send(b"Please, choose your username: ")

Typically, this is not done, and instead a pre-chosen number is sent over the wire, leaving the client to choose how to ask the user a particular thing. This becomes especially important when graphics get involved, or when you need to do translation/internationalization.

The first thing

[u for u in self.users if u.sock is u.sock][0].name

should be

next(u for u in self.users if u.sock is u.sock).name

That said... what on earth is this doing? When would that condition ever evaluate to False?

Type hints

PEP484 type hints, such as host: str, port: int, will clarify your function arguments.


Object Attribute Stored in New List from Existing List of Objects For my CS class I the task given was to take a given Person Class with a name and age attributes.
Then, with an existing list of Person Objects, create a function that returns a tuple of (mean, median, mode) on the given age attribute.
Simple enough, but I wondered if my solution is really all that efficient. I basically iterated a new list of ages from an existing list of Person objects, and that almost feels like there's a better opportunity to optimize a solution...
Wondering if I'm missing something obvious.
from statistics import mean, median, mode

class Person:

    def __init__(self, name, age):
        """
        initializes a person objects name and age
        """
        self._name = name
        self._age = age

    def get_age(self):
        """
        returns the private data member _age
        """
        return self._age

def basic_stats(person_list):
    """
    creates a list of ages from a list of person objects then calculates
    mean, median, and mode from the statistics module
    """
    age_list = [i.get_age() for i in person_list]

    return (mean(age_list), median(age_list), mode(age_list))

In terms of performance, to create a list of ages, [i.get_age() for i in person_list] is about as good as you'll get. The only real way to avoid this is to adjust the mean, median, and mode functions to accept a key parameter (much like the built-in sort function does) so that each function will access the correct attribute of the object. I wouldn't worry about removing that list comprehension though. Unless person_list is huge, and you require this code to run often, and as fast as possible, that would be a premature optimization.
Another way to potentially speed it up would be to have a single function that iterates the list once, and calculates all three statistics in one go. Again though, I would consider that to be premature unless you had a very good reason to optimize that.
Your solution is fine until you run into a situation in which it isn't performing well. Favor readability and simplicity until performance becomes an actual concern (or you have good reason to believe that it will become an actual concern in the near future).


Unit test provider roles I am unit testing this role provider. I have a few asserts in the code for my test. I am sure there are more test I could preform. Does anyone have any suggestions for more test for this role of the membership provider?

[TestMethod]
    public void TestDeleteUserAccess()
    {
        try
        {
            string sRoleName = "TestRole";
            string sUsername = "test.user";

            // Use a known user for relationships
            AsaMembershipProvider prov = this.GetMembershipProvider();
            MembershipUser user = prov.GetUser(sUsername, false);

            // Create a new role
            AsaRoleProvider roleProv = this.GetRoleProvider();
            roleProv.CreateRole(sRoleName);

            // Verify that role exists
            bool bRoleExists = roleProv.RoleExists(sRoleName);
            Assert.IsTrue(bRoleExists);

            // Add users to that role
            string[] usernames = new string[] { sUsername };
            string[] roleNames = new string[] { sRoleName };
            roleProv.AddUsersToRoles(usernames, roleNames);

            // Verify that user is in role
            bool bRelationExists = roleProv.IsUserInRole(sUsername, sRoleName);
            Assert.IsTrue(bRelationExists);

            // Check various methods for finding role information
            string[] matchUsernames = roleProv.FindUsersInRole(sRoleName, "userx");// find constant
            foreach (string matchUsername in matchUsernames)//if match.length = 0 then roles were returned
            {
                Trace.WriteLine("Found in role " + sRoleName + ", user " + matchUsername + ". ");//check something instead of trace
            }

            string[] matchRoleNames = roleProv.GetRolesForUser(sUsername);
            foreach (string matchRoleName in matchRoleNames)
            {
                Trace.WriteLine("Found for user " + sUsername + ", role " + matchRoleName + ". ");
            }

            // Remove user from the role
            roleProv.RemoveUsersFromRoles(usernames, roleNames);

            // Verify that user is no longer in the role
            bRelationExists = roleProv.IsUserInRole(sUsername, sRoleName);
            Assert.IsFalse(bRelationExists);

            // Delete the role
            roleProv.DeleteRole(sRoleName, true);

            // Verify that no longer exists
            bRoleExists = roleProv.RoleExists(sRoleName);
            Assert.IsFalse(bRoleExists);
        }
        catch (Exception ex)
        {
            LogMessage(ex);
            Assert.Fail(ex.Message);
        }
    }

I am going to suggest a few improvements.

Most of the principles for code quality apply just as well to test code as it does to production code:
Your tests should follow Single Responsibility Principle. A test should ascertain one feature; such that any change or discovery or addition of a feature does not cause you to fix many unrelated tests. Ideally any bug introduced will cause one test to fail and that test failure will direct the programmer to the cause of the bug.

You should use Intention Revealing Names. The names of your tests should tell the reader of the tests what is being tested.

For example Implementing a Role Provider says: "CreateRole method;
Takes as input the name of a role and adds the specified role to the data source for the configured ApplicationName." One test case for that spec could be:

 public void WhenICreateARoleItExists() {
        roleProv.CreateRole(A_VALID_ROLE_NAME);

        Assert.IsTrue(roleProv.RoleExists(A_VALID_ROLE_NAME));
 }

This code is derived from your first assertion. Notice removal of code related to other assertions made the test more readable.

You can initialize your System Under Test in a [SetUp] method and assign it to a field, here roleProv, so that common initialization code does not clutter the reader's view. You should also extract repeated constant values, here A_VALID_ROLE_NAME,  to const members, and name them as descriptive as you can.

You should also test that what your system should not do. For example, the document says : "You should throw a ProviderException if the specified role name already exists for the configured ApplicationName."

  public void MultipleRolesCannotBeCreatedWithSameName() {
        var sameName = A_VALID_ROLE_NAME;
        roleProv.CreateRole(sameName);

        Assert.Throws<ProviderException>(delegate {roleProv.CreateRole(sameName);});
  }

Any unexpected exception should not be caught and indicates a broken test. Your test runner should , and most probably does, log its message and stack trace. Any expected exception should not cause the test to fail. You can remove your try/catch above.

I noticed that you write the values to the Trace if a collection is  returned from a tested method. That is totally useless. If a test does not Assert, it is not a test. A test should fail when the functionality it is testing is not working.

 // Names are just to give you an idea
 public void WhenIAddSomeUsersToSomeRolesTheirRolesIncludeAllOfThoseRoles() {
        // Given some users
        var userNames = new string[] { A_VALID_USER_NAME,  ANOTHER_VALID_USER_NAME};
        foreach(var userName in userNames) {
             createUserWithName(userName);
        }

        // And some roles
        var roleNames = new string[] { A_VALID_ROLE_NAME,  ANOTHER_VALID_ROLE_NAME};
        foreach(var roleName in roleNames) {
             createRoleWithName(roleName);
        }

        // When I add those users to those roles
        roleProv.AddUsersToRoles(userNames, roleNames);

        // Each users roles contain all of those roles
        // This could be done more idiomatically by someone more familiar with C#
        foreach(var userName in userNames) {
             Assert.That(roleNames, Is.SubsetOf(roleProv.GetRolesForUser(sUsername)));
        }
 }


What are best practices of creating database importer in Rails? I have sample database in GES files and I wrote importer in Ruby.

Sample file: WAR_APO.GES: https://gist.github.com/regedarek/cd0ce73c5d1e14ff9818

I will have several of GES files which I want to move to my data folder in app and I want to process them manually.

For most of them logic is the same but the difference are filename, model and attributes hash.
I want to also and new cases like: Update when type is U or Delete if is D

How should I refactor that:

class PrototypePharmaceuticImporter
  ID = '00'
  K  = "#{ID}K"
  F  = "#{ID}F"
  FB  = "#{ID}FB"
  D  = "#{ID}D"
  I  = "#{ID}I"
  U  = "#{ID}U"
  E  = "#{ID}E"

  TYPES = [K, F, FB, D, I, U, E]

  ARTICLE_TYPE = 57
  BARCODE = 15
  GROUP_CODE = 1
  GROUP_KEY = 40
  GROUP_NAME = 2
  FORM_CODE = 1
  FORM_KEY = 38
  FORM_NAME = 2
  FORM_SHORT_NAME = 3
  LONGNAME = 28
  PACKAGE_TYPE = 46
  PHARMACY_ONLY = 3
  PRESCRIPTION_ONLY = 47
  PRICE = 2
  WEIGHT = 14

  attr_accessor :file, :k, :f

  def initialize
    @pharmaceutics_file = File.open 'data/PAC_APO.GES', 'r'
    @forms_file = File.open 'data/DAR_APO.GES', 'r'
    @groups_file = File.open 'data/WAR_APO.GES', 'r'
    @k    = []
    @f    = []

    extract_groups_to_database
  end

  def extract_pharmaceutics_to_database
    add       = true
    tmp       = []
    type      = K

    @pharmaceutics_file.each_with_index do |line, i|
      break if (i > 96 * 1000 + 760 + 9)

      _type    = line.strip
      _changed = TYPES.include? _type

      if _changed && i > 0
        case type
        when K then @k << tmp
        when F then @f << tmp
        when FB then @f << tmp
        when I, U, D
          hash = {
            article_type: tmp[ARTICLE_TYPE],
            price: tmp[PRICE],
            weight: tmp[WEIGHT],
            package_type: tmp[PACKAGE_TYPE],
            group_code: tmp[GROUP_KEY],
            form_code: tmp[FORM_KEY],
            name: tmp[LONGNAME],
            barcode: tmp[BARCODE],
            pharmacy_only: tmp[PHARMACY_ONLY],
            prescription_only: tmp[PRESCRIPTION_ONLY]
          }
          Pharmaceutic.create(hash)
        end

        tmp  = []
        type = _type
      end

      tmp << clean(line)
    end
  end

  def extract_forms_to_database
    add       = true
    tmp       = []
    type      = K

    @forms_file.each_with_index do |line, i|
      break if (i > 96 * 1000 + 760 + 9)

      _type    = line.strip
      _changed = TYPES.include? _type

      if _changed && i > 0
        case type
        when K then @k << tmp
        when F then @f << tmp
        when FB then @f << tmp
        when I, U, D
          hash = {
            code: tmp[FORM_CODE],
            name: tmp[FORM_NAME],
            short_name: tmp[FORM_SHORT_NAME]
          }
          PharmaceuticForm.create(hash)
        end

        tmp  = []
        type = _type
      end

      tmp << clean(line)
    end
  end

  def extract_groups_to_database
    add       = true
    tmp       = []
    type      = K

    @groups_file.each_with_index do |line, i|
      break if (i > 96 * 1000 + 760 + 9)

      _type    = line.strip
      _changed = TYPES.include? _type

      if _changed && i > 0
        case type
        when K then @k << tmp
        when F then @f << tmp
        when FB then @f << tmp
        when I, U, D
          hash = {
            code: tmp[GROUP_CODE],
            name: tmp[GROUP_NAME]
          }
          PharmaceuticGroup.create(hash)
        end

        tmp  = []
        type = _type
      end

      tmp << clean(line)
    end
  end

  private

  def clean line
    line.strip
    .gsub(/^[\d]{2}/, '')
    .gsub(/\\[s|S]39/, 'ß')
    .gsub(/\\a25/, 'ä')
    .gsub(/\\A25/, 'Ä')
    .gsub(/\\o25/, 'ö')
    .gsub(/\\O25/, 'Ö')
    .gsub(/\\u25/, 'ü')
    .gsub(/\\U25/, 'Ü')
  end
end

Basically, I want to get rid of duplications in these methods.

Some notes:

As usual, I'd recommend a more functional approach. It's not a theoretical issue, functional code is more concise, more clear. When I see @k = [] I get the shakes thinking that this variable can (and will) be modified just everywhere in the class (an instance variable is just a nasty global variable -for the scope a class, granted- with a pretty name).
Also related to FP, your code is hard to abstract because it's written with procedures instead of functions: they don't take values (as arguments) and return values, everything works by side-effects through instance variables. No referential transparency, no idempotence...
Don't create so many individual constants, group them in hashes.
File.open 'data/PAC_APO.GES', 'r'. Hardcoded files in classes? mmmm.
96 * 1000 + 760 + 9. Magic number, define it as a constant so it has a name.

Answering your particular question about how to avoid repeating code for those 3 methods: whatever is different put it as arguments. If some value depends on something the caller cannot know yet about (the code under when I, U, D), then use an argument block as callback. So it might be written:

def extract_to_database(collection)
  add       = true
  tmp       = []
  type      = K

  collection.each_with_index do |line, i|
    break if (i > 96 * 1000 + 760 + 9)

    _type    = line.strip
    _changed = TYPES.include? _type

    if _changed && i > 0
      case type
      when K then @k << tmp
      when F then @f << tmp
      when FB then @f << tmp
      when I, U, D
        yield(tmp)
      end

      tmp  = []
      type = _type
    end

    tmp << clean(line)
  end
end

Note that I kept your old imperative code (a functional approach would require rewriting the full class), but at least is now DRYed. I'd strongly encourage to try the functional paradigm, it's hard at first but it pays off on the long run. My article on this matter.


Multiply a 2D array by 1D array to get a third (2D) array I've working with three dynamic arrays (all are datatype Double) - they are

  OriningalArray

This will be assigned from a range that the end user will see and will be 2 dimension

  MultiplierArray

This will be multipliers as (most of which will be 1 but some will be between +-5% and will always be same length as one of the dimensions in OriningalArray.

  NewArray

This is required as there will be certain discounts that will need to be applied to the OriningalArray and both dimension will be the same size as it.

Here's a sample for a visual reference:

I have code that works (below) and have commented it also to explain why I'm doing it that way (this is just an example and actual data size will be much bigger) but was hoping someone could tell me how to optimize it further:

Sub Test()
Dim OriningalArray() As Double ' I can't declare it a Variant and then assign it straight from the range (OriningalArray = Rng) because there may be "N/A" values in the range which, when put into an Variant Array, gives false Double value
Dim MultiplierArray() As Variant
Dim NewArray() As Double
Dim Rng As Range
Dim MultiplierRng As Range
Dim x As Long, y As Long

Set Rng = Range("D4:I9")
Set MultiplierRng = Range("D12:I12")

ReDim OriningalArray(1 To Rng.Rows.Count, 1 To Rng.Columns.Count) ' 2D Array the sze of the range
ReDim NewArray(1 To Rng.Rows.Count, 1 To Rng.Columns.Count) ' 2D Array the sze of the range

MultiplierArray = MultiplierRng

On Error Resume Next ' Turn off error handler to stop macro crashing when trying to assign "N/A" as a Double
For x = 1 To Rng.Columns.Count
    For y = 1 To Rng.Rows.Count
        OriningalArray(y, x) = Rng.Cells(y, x).Value
        NewArray(y, x) = OriningalArray(y, x) * MultiplierRng(1, x)
        'Debug.Print OriningalArray(y, x)
        'Debug.Print NewArray(y, x)
    Next y
Next x
On Error GoTo 0

End Sub

You actually don't need VBA for this but you could get the same result with an array formula.

You select the cells D8:F9 so that the D8 is active. Then you type the following formula there

=D6:F6*D3:F4

and hit CTRL+SHIFT+ENTER

if it worked you'll see {} around each formula in each cell and the results in the second table.


Vertically and horizontally center these HTML elements I have an image and a text title that I'm trying to center in a div.  I would like the image to be to the left of the title, and for both of these elements to be centered both horizontally and vertically in the div.

I've found one way to do it, by nesting the image inside of a paragraph.  I'm assuming this is not the proper way to do it, but I haven't been able to figure out any other way.

Here is a jsfiddle:  http://jsfiddle.net/FvpV3/

And here is the code:

Title

message

Does anyone know of a better way to position the image and title?

You can simplify your HTML to this:

Title

$message

By adding classes, you can re-use CSS on more than one HTML element. The class floaters is applied to both of the divs that make up the top line. The class right is only applied to the left div on the first line to make it right aligned.

The #parent:after is one example of a clearfix. There are several other versions of clearfixes.

* {
    box-sizing: border-box;
}
#parent {
    margin: 0px auto;
    width: 50%;
    border-radius: 6px;
    border: 1px solid #CFCFCF;
}
#parent:after {
  content: "";
  display: table;
  clear: both;
}
.floaters {
    float: left;
    background-color:#E4E4E4;
    width: 50%;
    height: 3em;
    padding: 5px 12px 5px 0;
}
.right {
    text-align: right;
}
.centerme {
    float: left;
    clear: both;
    text-align: center;
    background-color:#EFEFEF;
    height: 3em;
    width: 100%;
    padding-top: 12px;
}

I have a working jsfiddle for you to look at.


Fixed-Size Floating-Point Types I have created my own personal data structure libraries for C and I've re-engineered it about two times now and I've added alot of preprocessor checks and defines concerning OS type and compiler type.

One thing I've wanted to add to my personal libraries is having an informal "standard" fixed-size floating-point types.

#ifndef __float32_t_defined
#   if defined(COMPILER_CLANG) || defined(COMPILER_GCC)
#       define __float32_t_defined
        typedef float float32_t TYPE_MODE(__SF__);
#   elif FLT_MANT_DIG==24
#       define __float32_t_defined
        typedef float float32_t;
#   elif DBL_MANT_DIG==24
#       define __float32_t_defined
        typedef double float32_t;
#   endif
#endif

#ifndef __float64_t_defined
#   if defined(COMPILER_CLANG) || defined(COMPILER_GCC)
#       define __float64_t_defined
        typedef float float64_t TYPE_MODE(__DF__);
#   elif FLT_MANT_DIG==53
#       define __float64_t_defined
        typedef float float64_t;
#   elif DBL_MANT_DIG==53
#       define __float64_t_defined
        typedef double float64_t;
#   elif LDBL_MANT_DIG==53
#       define __float64_t_defined
        typedef long double float64_t;
#   endif
#endif

#ifndef __floatmax_t_defined
#   if defined(COMPILER_CLANG) || defined(COMPILER_GCC)
#       define __floatmax_t_defined
        typedef double floatmax_t TYPE_MODE(__XF__);
#   elif LDBL_MANT_DIG>=64
#       define __floatmax_t_defined
        typedef long double floatmax_t;
#   elif DBL_MANT_DIG>=64
#       define __floatmax_t_defined
        typedef double floatmax_t;
#   else
#       define __floatmax_t_defined
        typedef float floatmax_t;
#   endif
#endif

For Clang and GCC, I use the compiler extension that checks machine mode and sets the type definition to the largest width of the floating point type. I added further type definition checks in the event Clang or GCC are not used.

my main question is that, given the macros in float.h, is checking float size by its mantissa a wise/safe thing to do? If not, what alternative can I take?

float32_t   float64_t

Since the goal is:

  float32_t and float64_t is that those types are always their fixed size

the macros nearly achieve that.

  is checking float size by its mantissa a wise/safe thing to do? If not, what alternative can I take?

Big caveat: OP's expressed goal is same size, not same encoding.  Two systems may have a 32-bit float, yet different mantissa, exponent range and other properties.  The biggest "safety" concern is assuming same floating point properties with same size.

C allows for a great diversity of implementations though.  The macros accommodate most current compilers well, yet they are not specified to be always typedef 32/64 bit types.

To be clear, checking xxx_MANT_DIG, FLT_RADIX, xxx_MIN_EXP, ... is not sufficient, in general, even though it may be practically sufficient.

It fundamental comes down to:

  what should code do if it encounters a novel implementation?

I'd go with testing for the usual suspects and expand code when I encounter a true counter case.

#ifndef __float64_t_defined
  #if FLT_RADIX==2 && DBL_MANT_DIG==53 && DBL_MIN_EXP == -1021
    #define __float64_t_defined
    typedef double float64_t;
  #elif FLT_RADIX==2 && FLT_MANT_DIG==53 && FLT_MIN_EXP == -1021
    #define __float64_t_defined
    typedef float float64_t;
  // Expand list for variants that I have found
  #elif FLT_RADIX==2 && DBL_MANT_DIG==TBD && DBL_MIN_EXP == TBD
  #else
    #error TBD code for float64_t
  #endif
#endif

Note: Code like DBL_MANT_DIG==24 is not even C compliant with FLT_RADIX==2.  DBL_MANT_DIG >= 34 to meet precision requirements.   This looks like a test for a non-real machine.

I recommend 2 additions:

Report fail to typedef right away with #error

#   elif LDBL_MANT_DIG==53
#       define __float64_t_defined
        typedef long double float64_t;

// Add
#   else
#     error TBD code for float64_t

#   endif

With C11 or later, use _Static_assert

_Static_assert(sizeof (float64_t)*CHAR_BIT == 64, "Unexpected `float64_t` size");

With early compilers, see Static assert in C and others.

floatmax_t

After taking advantage or known COMPILER_CLANG, COMPILER_GCC compilers, I'd recommend more conventional code - Simply test for C99 or later.

#ifndef __floatmax_t_defined
#   if defined(COMPILER_CLANG) || defined(COMPILER_GCC)
#       define __floatmax_t_defined
        typedef double floatmax_t TYPE_MODE(__XF__);
#   elif (__STDC_VERSION__ >= 199901L)
#       define __floatmax_t_defined
        typedef long double floatmax_t;
#   else
#       define __floatmax_t_defined
        typedef double floatmax_t;
#   endif
#endif

Similar question I posed

Detecting unicorn and dinosaur compilers


Possible refactoring in binary tree I implemented a binary tree in Python, with preorder/postorder/inorder traversal methods.

class BinaryTree(object):

    def __init__(self, rootObj):
        self.key = rootObj
        self.leftChild = None
        self.rightChild = None

    def insertLeftChild(self, newNode):
        if self.leftChild == None:
            self.leftChild = BinaryTree(newNode)
        else:
            newBinaryTree = BinaryTree(newNode)
            newBinaryTree.leftChild = self.leftChild
            self.leftChild = newBinaryTree
        return self.leftChild

    def insertRightChild(self, newNode):
        if self.rightChild == None:
            self.rightChild = BinaryTree(newNode)
        else:
            newBinaryTree = BinaryTree(newNode)
            newBinaryTree.rightChild = newNode
            self.rightChild = newBinaryTree
        return self.rightChild

    def getRoot(self):
        return self.key

    def setRoot(self, obj):
        self.key = obj

    def getLeftChild(self):
        return self.leftChild

    def getRightChild(self):
        return self.rightChild

    def __str__(self):
        return '%s' % self.key

    # DFS traversal techniques.
    @classmethod
    def preorder(cls, node):
        if node == None: return False
        print node
        cls.preorder(node.getLeftChild())
        cls.preorder(node.getRightChild())

    @classmethod
    def inorder(cls, node):
        if node == None: return False
        cls.inorder(node.getLeftChild())
        print node
        cls.inorder(node.getRightChild())

    @classmethod
    def postorder(cls, node):
        if node == None: return False
        cls.inorder(node.getLeftChild())
        cls.inorder(node.getRightChild())
        print node

def buildTree():
    root = BinaryTree('a')
    firstLeft = root.insertLeftChild('b')
    firstRight = root.insertRightChild('c')
    firstLeft.insertRightChild('d')
    firstRight.insertLeftChild('e')
    firstRight.insertRightChild('f')
    return root

if __name__ == '__main__':
    binaryTree = buildTree()
    print 'Preorder'
    print BinaryTree.preorder(binaryTree)
    print 'Inorder'
    print BinaryTree.inorder(binaryTree)
    print 'Postorder'
    print BinaryTree.postorder(binaryTree)

Also, I'd like to know how go about unit testing this code. I'd appreciate guidance and links to relevant documentation.

As evidenced by the bug in Rev 1, the inconsistent naming between getRoot()/setRoot() and self.key is a trap that you've created for yourself.

Getters and setters would be better done using the @property decorator.  Follow the convention in the documentation:

class BinaryTree(object):
    def __init__(self, obj):
        self.obj = obj
        self.left_child = self.right_child = None

    @property
    def obj(self):
        """The datum stored in the node."""
        return self._obj

    @obj.setter
    def obj(self, value):
        self._obj = value

    def __str__(self):
        return str(self.obj)    # <-- Simpler than %s interpolation

    …

Your traversal algorithms should not have a print statement, as they would be useless for anything other than printing to sys.stdout.  Instead, they should yield each result.  The caller can then choose to print them or do whatever it pleases.

for obj in pre_order(root):
    print obj

A nice way to write simple unit tests and provide documentation at the same time is to use the doctest module.


await user input with async/await syntax for clarity: moved here from stackoverflow after being pointed to Code Review being the better place for this question
I love async/await and Promises since I got my hands on them. And I might be overdoing it, but it feels like there should be a good and readable way to utilize async/await to get a little closer to a flow like, functionalISH programming style.
I would love to not have to only use async/await to wait for web resources to come back but also to wait for user input when I await it.
So far i have some code working similar to this shortened demo where I wrap a one time only EventListener into a Promise:

//// MAIN ///////

(async function(){

    //...do some async await stuff here... fetching stuff from a server
    // let services = await fetch(...) for example
    let services = [{url:"x",label:"1"},{url:"y",label:"2"},{url:"z",label:"3"}]

    let service_chosen = await showServicesToUserAndAwaitInput(services);
    console.log("service_chosen:",service_chosen);
    // ... go on....
})()

//// END MAIN /////

async function showServicesToUserAndAwaitInput(services){

    if (services.length < 1){return null}

    let choice = null;

    let serviceList = document.querySelector("#serviceList");

    // show list element
    serviceList.classList.remove("hidden")

    // create some elements for the user to interact with
    for (let service of services){
        let button = document.createElement("BUTTON");
        button.innerHTML = service.label;
        button.addEventListener("click",function(){
          document.dispatchEvent(
            new CustomEvent('serviceChosen', { detail:service })
          )
        });
        serviceList.appendChild(button);
    }

    // returns promise with one time only event listener
    return new Promise((resolve,reject)=>{
        document.addEventListener("serviceChosen",function(e){
            serviceList.classList.add("hidden") // hide again for we are done
            resolve(e.detail)
        },{ once: true })
    })
}
.hidden{
  visibility: hidden
}
<div id="serviceList" class="hidden">

</div>

But something about this use of the EventListener bugs me. Also: I use a promise that always resolves, which also seems strange.
On the upside: I get to read the code top to bottom and can follow the user flow within the MAIN without having to chase down events, callbacks and so on.
Yet, it feels like I am reinventing something somebody else might have already normed. So:
Is there a better way to achieve this? Are there best practices to work with user interactions or other DOM events in a async and/or thenable way?

First of all, I would not use Promises to do event based programming.
It is not used like that, so your code will get harder to follow.
Also, I would advise you to split up your functions more and omit some comments that way.

//// MAIN ///////

let services = [
    { url: "x", label: "1" },
    { url: "y", label: "2" },
    { url: "z", label: "3" },
];

showServicesToUser(services);

//// END MAIN /////

const serviceList = document.querySelector("#serviceList");

function createButtonFromService(service) {
    let button = document.createElement("BUTTON");
    button.innerHTML = service.label;
    button.addEventListener("click", function () {
        document.dispatchEvent(
            new CustomEvent("serviceChosen", { detail: service })
        );
    });
    serviceList.appendChild(button);
}

function showServicesToUser(services) {
    if (services.length < 1) return;

    serviceList.classList.remove("hidden");

    for (let service of services) {
        createButtonFromService(service);
    }
}

function chooseService(service) {
    console.log("service_chosen:", service);
    // ... go on....
}

document.addEventListener("serviceChosen", function (e) {
    serviceList.classList.add("hidden"); // hide again for we are done
    chooseService(e.detail);
}, { once: true });
.hidden{
  visibility: hidden
}

My proposed code above is written in a scripted kind of way, with a global variable (serviceList), but you could also write this all in a class (especially if you have more code), to make it more readable and reusable.

class ServiceChooser {
    serviceListSelector;
    serviceList;
    services;

    constructor(serviceListSelector, services) {
        this.serviceListSelector = serviceListSelector;
        this.services = services;

        this.serviceList = document.querySelector(serviceListSelector);

        document.addEventListener(`serviceChosen${this.serviceListSelector}`, (e) => this.chooseService(e.detail), { once: true });
    }

    createButtonFromService(service) {
        let button = document.createElement("BUTTON");

        button.innerHTML = service.label;
        button.addEventListener("click", () => {
            const event = new CustomEvent(`serviceChosen${this.serviceListSelector}`, { detail: service });
            document.dispatchEvent(event);
        });

        this.serviceList.appendChild(button);
    }

    chooseService(service) {
        this.serviceList.classList.add("hidden");
        console.log("service_chosen:", service);
        // ... go on....
    }

    showServicesToUser() {
        if (this.services.length < 1) return;

        this.serviceList.classList.remove("hidden");

        for (let service of this.services) {
            this.createButtonFromService(service);
        }
    }
}

//// MAIN ///////

let services = [
    { url: "x", label: "1" },
    { url: "y", label: "2" },
    { url: "z", label: "3" },
];

const sc = new ServiceChooser('#serviceList', services);
sc.showServicesToUser();

// now you could add 2 service choosers, sperate from each other
const sc2 = new ServiceChooser('#serviceList2', services);
sc2.showServicesToUser();

//// END MAIN /////
.hidden{
  visibility: hidden
}