Use of macros to aid visual parsing of SFINAE template metaprogramming

Rule #1 of code formatting: Write readable code.

Rule #2: Don't do anything people tell you not to do... until you know better.

The rules against macros are wise because macros can often be very unintuitive.  However, as you have noticed, there are situations where they are very helpful.  The problem with macros is that they appear to be a panacea for formatting, and it is not until  much later that you realize there were serious fundamental issues.

That being said, they're in the language.  They have uses.  So if you take the time to understand them, then you can start to use them wisely.  The two major issues for macros are:

They are global symbols, causing surprise replacements in the most unlikely of places
It is easy to write a macro that looks like it does what you want, when it actually compiles into something else.

Global symbols

Nothing is worse than having someone else's symbols screw with your code.  If someone defines a macro, and it conflicts with your code, the error is almost always unreadable.  Consider the most nefarious one, #define max (a, b) ((a)>(b) ? (a) : (b)), which is defined as part of windows.h.  If you've been writing Linux apps, you'll find this suddenly breaks when you had a local named "max."

By your choice to #undef the symbols at the end, it is clear you are aware of this.  You did a good job of making sure your defines don't hurt someone else.  However, you are still at the whim of anyone who uses the same names as you carelessly.  So good job with being careful, but you're not out of the woods.

** Surprise compilations **

The number on reason why people dislike macros is that they often do things you did not expect.  For example, in the max example, a can get evaluated twice.  Also, macros and commas don't play well.  Macros are generally unaware of brackets, so things like max(getValue(1, 2), getValue(3, 4)) can surprise you with errors.  Your code doesn't have any of these, but always be aware of the costs when you're trying to bend code style rules.

However, you do have a few interesting tidbits.  For example, did you know that you shouldn't say std::enable_if in a macro?  That will do a context-specific search for a namespace named "std."  In the wrong situations, that could cause problems.  The correct phrasing is ::std::enable_if, which forces it to look in the global scope for the right std.

Think of others

So, in you cases, the macros work.  You generally thought it through.  Now lets take this code into a business scenario.  Developers with much less macro practice than you are going to work on this code.  They are going to develop stylistic habits to take parts of how you write.  Do you really get enough readability here to warrant potentially confusing code down the line?

Options

So what else can you do?  Since macro definitions are usually treated as "hard to read," I feel no qualms writing a few struct to help out.  By using structs, I get to avoid the global issues of macros, and they always compile the way you expect them to.

Consider using a template template argument like this:

template <template <typename> Pred, T>
struct subfail_unless
: std::enable_if<Pred<typename std::decay<T>::type> >
{ };

template<typename T,
         typename subfail_unless<std::is_integral, T>::value >
explicit Object( T&& t      ) { init(long  (t)); }

template<typename T,
         typename subfail_unless<std::is_floating_point, T>::value >
explicit Object( T&& t, ... ) { init(double(t)); }

Why I like this:

If you are writing code like this, you MUST know SFINAE, so you aren't going to be threatened by the templating.
It you are are just reading this, you don't need to know why it works, you just need to recognize the words that matter.

Consider how few extra characters this has.

macros:              SUBFAIL_UNLESS(     IS_FLOATING       (T))
templates:  typename subfail_unless<std::is_floating_point, T>::value
---------------------------------------------------------------------
difference: typename                std::                     ::value

This code can now be reused in a header, instead of needing to #define it everywhere you intend to use it.  It is now using only namespaced structs, so it is as safe as any other code.


I'm going to assume your indentation got messed up on posting, but just in case, you should indent all of the code inside of the Camera class an additional time.

First off, I like that you used constants at the top of your code!  To ensure that they look and act like constants, you should make them private, static, final, and named in UPPERCASE_FORMAT.  Furthermore, I would recommend separating your constants from your class variables (such as mouseLocation and offsetX).

I'm not entirely sure how your functions are being called.  It looks like you are implementing MouseMotionListener, so I would definitely add that to your class declaration.

If that is true, then I don't see the purpose of the drag variable.  The mouseDragged function is only going to get called if the mouse is actually being dragged, so assigning a boolean when the mouse is pressed and released appears redundant.

Also, I'd recommend considering whether you want to use BigDecimal.  If round needs to be fast, then you don't want to use BigDecimal at all.  There are other techniques for rounding to the nth digit  that can be found here


An array of values. looping many times to calculate mean, closest matching array value, and then finding its index

You can remove the last line searching for the index since you can get the index in the reduce method.

Btw, you forgot to add Math.abs to deal with positive value when comparing.

Demo:

const cols = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

const mean = cols.reduce((prev, curr) => prev + curr, 0) / cols.length;

const { value, index } = cols.reduce((prev, curr, i) => {
    // You have deal in absolute
    if (Math.abs(curr - mean) < Math.abs(prev.value - mean)) {
        return { value: curr, index: i }
    } else {
        return prev
    }
}, { value: cols[0], index: 0 });

console.log({ mean, value, index })


PHP function to check whether a user is logged in

One of the problems you're facing is the pyramid of doom - deeply nested control structures that make for hard to read code.

You can simplify your code by inverting the conditions in your if-statements. For example, instead of

if(isset($_COOKIE['authToken'])) {
    // do something with authToken
    // ...
    // (potentially) lots of code
    // ...
} else {
    // throw an error / return
}

you could write

if(!isset($_COOKIE['authToken'])) {
    return;
}

// do something with authToken
// ...

By applying this to your the isLoggedIn function, you get a flatter, more easily readable equivalent:

public static function isLoggedIn(){
    Session::openSession();

    if(isset($_SESSION['userId'])){
        return true;
    }

    if(!isset($_COOKIE['authToken'])){
      return self::notLogged();
    }

    list($selector, $token) = explode(':', $_COOKIE['authToken']);
    $result = Database::query('SELECT * FROM logins WHERE login_selector = ?', array($selector))[0];

    if(!$result) {
      return self::notLogged();
    }

    if(hash_equals($result['login_token'], hash('sha256', base64_decode($token)))){
      self::relogUser($result['login_userId']);
      return true;
    }

    return self::notLogged();
}

Also, the method naming seems a little off. The name isLoggedIn implies that the function just checks if a user is logged in or not and nothing else. What the method actually does is to check if a user logged in and if not, try to log them in. If that fails, it calls the method self::notLogged.

The next step might be to tear apart the function into smaller functions that actually tell you what they do from their name alone - this will avoid confusion. See Single responsibility principle - this applies to functions as well - a function should ideally not do more than one thing.

In particular, the part of your code that performs the authentication and/or login-checking should not be concerned with what happens when authentication has succeeded/failed. Instead, they should signal their respective results to the calling function, either by returning a value or by throwing an Exception.

Exceptions have the added benefit of explicitly signaling to developers working with the code that a function has somehow failed to do what it was meant to. Better yet, they give you the freedom to express what exactly went wrong and how.

All in all, you might end up with something like this:

public static function authenticate() {
    if (self::isLoggedIn()) {
        // user is logged in already - all done!
        return;
    }

    // try to login user using authToken
    if(!isset($_COOKIE['authToken'])){
        throw new \Exception('Authentication failed! No authToken provided');
    }

    list($selector, $token) = explode(':', $_COOKIE['authToken']);
    $result = Database::query('SELECT * FROM logins WHERE login_selector = ?', array($selector))[0];

    if(!$result) {
        throw new \Exception('Authentication failed! Invalid authToken: login not found');
    }

    if(!hash_equals($result['login_token'], hash('sha256', base64_decode($token)))) {
        throw new \Exception('Authentication failed! Invalid authToken: key mismatch');
    }

    self::relogUser($result['login_userId']);
}

public static function isLoggedIn(){
    Session::openSession();
    return isset($_SESSION['userId']);
}

public static function handleAuthentication() {
    try {
        self::authenticate();
    } catch (\Exception $e) {
        self::notLogged();
    }
}


About the generated HTML

Each feed item should become an article. This would also allow you to include the generated HTML on any page without having to adjust the heading levels. Unless you know that h2 would always be the correct heading element in your case, you might want to use h1 instead.

You could give the a element the bookmark link type.

Unless you remove markup from the feed item’s description, you might want to use a div instead of a span, because a span can’t contain many elements that might appear in the description.

You could specify a class on the article element, and omit the classes on its child elements. Less potential to conflict with classes that might already be used in the document.

{title}

  {title}

{summary}


Hackerrank CTCI "Stacks: Balanced Brackets" Javascript Solution

Simplify matching parentheses

These case statements are very similar, and take a couple of lines to write:

case "}":
    if (stack.pop() !== "{") {
        isBalanced = false
    }
    break;
case "]":
    if (stack.pop() !== "[") {
        isBalanced = false
    }
    break;
case ")":
    if (stack.pop() !== "(") {
        isBalanced = false
    }
    break;

You could simplify by reworking the case statements that handle the opening parentheses:

case "{":
    stack.push("}");
    break;
case "[":
    stack.push("]");
    break;
case "(":
    stack.push(")");
    break;

And then you could replace the handling of the closers with the simpler:

case "}":
case "]":
case ")":
    if (stack.pop() !== exp[i]) {
        isBalanced = false
    }
    break;

Avoid flag variables when possible

Instead of setting isBalanced = false and the multiple checks,
it would be simpler in such cases to immediately print the result and break, for example:

next:
for (var a0 = 0; a0 < t; a0++) {
    exp = readLine().split('');

    stack = [];
    i = -1;
    len = exp.length;

    while (++i < len) {
        switch (exp[i]) {
            case "{":
                stack.push("}");
                break;
            case "[":
                stack.push("]");
                break;
            case "(":
                stack.push(")");
                break;
            case "}":
            case "]":
            case ")":
                if (stack.pop() !== exp[i]) {
                    console.log("NO");
                    continue next;
                }
                break;
        }
    }

    console.log(stack.length == 0 ? "YES" : "NO");

Naming

What is exp? It's not very obvious, but actually it's characters.
How about calling it chars?


Select a specific line after matching a pattern

You can replace this pipeline

head -1 *.txt | awk '/[a-z]/&&!/.txt/' | awk '{print $3}'

with this one awk command

awk 'FNR == 1 {print $3}' *.txt

FNR is the file record (i.e. line) number. NR is the cumulative record number of all records seen from all files.

Now, you can select the user's numeric choice with

awk 'FNR == 1 {print $3}' *.txt | awk -v n="$user_selection" 'NR == n'

or, with a single awk:

awk -v n="$user_selection" 'FNR == 1 && ++filenum == n {print $3; exit}' *.txt

If you're looking for a way to get your users to select a name from one of the files, perhaps some more advanced bash:

# read the 3rd word from the 1st line of all txt files into an array
readarray -t names < <(awk 'FNR == 1 {print $3}' *.txt)

# get the user to select one of them
PS3="Choose a name: "
select name in "${names[@]}"; do
    [ "$name" ] && break
done

echo "$name"

This really isn't a code review. Since you're asking "how can I do this", you should have asked on Stack Overflow.


How can I ascertain and test SQL injection vunerabilities on this login code?

This is vulnerable:

mysql_real_escape_string($userid);
mysql_real_escape_string($pword);

does not return the variable. Use:

$userid = mysql_real_escape_string($userid);
$pword = mysql_real_escape_string($pword);

If you really want to take care of all vulnerable SQL injections try to move to PDO. Here is a nice tutorial


Joining multiple functions data in one array

I see some redundancy right off the bat:

$ActiveMachine[$val['controllerID']]['controllerID'] = $val['controllerID'];

If the key is the controllerID, do you need a separate controllerID underneath of it?  I would suspect not. You can use the $Key in place of $val['controllerID'] in the foreach below it.

As for the rest, do you have control over the output of the functions you are using?  Can the key of those arrays be used in a smarter way?  You are using $Key => $val, but you don't use $Key once.


A Discord bot that connects to a local database (OOP)

Is this the correct way to access those methods and their variables in my register command?

Yes. Looks good to me.

I can't say I'm fond of your docstrings. But your code is perfectly clear.

You are focused on MySQL / MariaDB. I tend to access mysql through sqlalchemy, just in case in future I'll want to use sqlite or postgresql or another.

The code starting if discord_id in ... is a bit odd, perhaps it could go into a function? It is a usual expectation that calling code could import your module (define your class) more than once without odd side effects.


A suggestion I have is to use a heap data structure to store the costs, so that min can be calculated in logarithmic time.


A 'flexible' VBA approach to lookups using arrays, scripting dictionary and user input

Signature

Public Sub arrayMatchv3()

I like that the procedure is explicitly Public. Unlike a lot of other languages - including VB.NET, in VBA a member is public unless specified otherwise; being explicit is a good thing. I don't see Option Explicit atop your procedure, but I have it in my IDE and it compiles with it, so kudos for declaring all your variables!

If you're not specifying Option Explicit, you have to know that the slightest typo in a variable's name will make VBA "declare" an implicit Variant variable on-the-spot to receive the value you're assigning to what you intended to be that local variable you just declared: VBA happily compiles with undeclared identifiers, which inevitably will cause bugs that will be hard to find. With Option Explicit specified, the compiler will choke on a typo, finding them for you in a split second.

Member names in VBA should be PascalCase, so that the API you're writing feels like the API you're using when you write VBA code: the entire Excel object model, the VBA standard library, the scripting runtime library - pretty much every single VBA API out there, they all expose modules, classes, procedures, functions, properties, constants, enums, events, etc. - all in PascalCase.

I like that you're using camelCase for your locals though; I find it makes the code feel a bit easier to read, and I do it myself.

The name isn't ideal: "array match v3" is a noun - it's an "array match"... nouns make excellent module/class names: Worksheet, Workbook, Application. Procedures do something, they're verbs. If the procedure matches arrays then MatchArray would be a better name.

I see you're having a version number in the name: this supposes there's an arrayMatchv2 somewhere, and then an arrayMatchv1 or arrayMatch procedure not too far. If not, then just remove the v3 suffix.

Otherwise, you're storing versioning metadata in the code base itself - which is clutter: if arrayMatch usages have been replaced by references to arrayMatchv2, you now have as many places to revisit in the code to make sure it's now calling arrayMatchv3. If v3 fixed a bug in v2, your code base still has the bug even though v3 fixed it.

If you need versioning, use source control. You can create a repository on GitHub, and then use a tool such as Rubberduck to commit, revert, push, pull, create branches and merge them, straight from a docked toolwindow in the IDE. And then you can use GitHub to view any version, or git to fetch any specific version.

I guess that covers the method's signature =)

User input and responsibilities

  it is working well as far as I have been able to test it

To the outside world, the procedure is a complete black box: it takes no input and returns no value. Beyond the name and without peeking at the source code, we have no idea what's happening in there when we read the calling code.

Application.InputBox is called 4 times: there are 4 user inputs happening. By telling the outside world "I need 4 Range parameters to do my thing", the procedure's signature would already be telling us a lot more.

Collecting user input is a concern in its own right. All kinds of wild things can happen when a user gets involved. They can ESC out, or X-out of your dialogs, make typos, enter illegal values - many things can go wrong when a user needs to get involved.

Set workingCell = Application.InputBox("Select the first cell of your comparison column.", Type:=8)
workingLastRow = workingCell.End(xlDown).Row

Accessing workingCell.End here means the program dies with a runtime error if you (/the user) X-out or otherwise cancel the InputBox.

workingCell.End(xlDown) will stop at the first blank cell it finds: if the row can contain blank cells, your workingLastRow will not be the actual last row in the selected column. A more reliable way would be to start at the last row in workingCell's column, and go xlUp from there instead:

With workingCell.Parent
    workingLastRow = .Cells(.Rows.Count, workingCell.Column).End(xlUp).Row
End With

Take the collect user input concern out of the procedure: use parameters, and make it the caller's responsibility to figure out how to get that input - with an InputBox... or perhaps just any arbitrary set of Range objects. Don't trust the input: either raise a descriptive error, or exit early if the input isn't valid (e.g. if any parameter is Nothing).

Except... but we aren't actually working with Range objects - what we really want is a workingArray, a targetArray, a comparisonArray, a returnArray... and we return a Dictionary. 4 parameters and a return value: the Sub becomes a Function, and the inputs and outputs become much clearer already. The fact that you felt the need to split it up in the OP speaks a lot about this concern, too.

At this point things are starting to shape up:

A function to collect user input; validates and returns a Range object
A function that takes a Range and returns an array
A function that takes input arrays and returns a Dictionary
A procedure that takes a Dictionary and writes to a specified Range
A procedure that coordinates all those

By simply splitting things up and tightening variable lifetimes and scopes, and passing and returning objects and arrays, we've made it much easier to write code that can test various valid and invalid inputs and document how things behave... and automated tests are much more reliable than ad-hoc F5-debug testing.

Bugs & Assumptions

Your code is making a bad assumption here, can you spot it?

With workingCell
    workingArray = Range(.Address, Left(.Address, Len(.Address) - 1) & workingLastRow)
End With

Range is implicitly referring to the active worksheet: the unqualified call will throw an error if the active sheet is a chart! You should be using .Parent.Range to qualify the Range method call with a specific worksheet, so that the active sheet isn't an implicit dependency.

But there's another bug: that -1 is assuming .Row is less than 10, i.e. that the row number in the .Address string is 1 single digit. If the user selects anything between rows 10 and 19, the workingArray will be 100 rows too tall; if the user selects anything between rows 20 and 29, it's 200 rows you don't need, that enter the working array, and become useless iterations here:

For i = LBound(workingArray, 1) To UBound(workingArray, 1)

It's not clear from just reading the code, but I also suspect the code assumes workingCell and targetCell are on the same row, on the same sheet:

With targetCell
    targetArray = Range(.Address, Left(.Address, Len(.Address) - 1) & workingLastRow)
End With

If the two user selections aren't on the same row, then the targetArray can be missing values: it would probably be a good idea to validate that, or make the procedure fail instead of producing wrong results; that could be caught and handled in the function responsible for collecting user input. If you know that an input value is already validated, you can Debug.Assert a precondition, and the code will only ever come to a halt if the assertion fails:

Debug.Assert Not workingCell Is Nothing
Debug.Assert Not targetCell Is Nothing
Debug.Assert workingCell.Parent = targetCell.Parent
Debug.Assert workingCell.Row = targetCell.Row

Seeing that at the top of a procedure that takes workingCell As Range and  targetCell As Range parameters makes it pretty crystal-clear what the assumptions are, and allows the reader/maintainer to say "mismatching working and target rows? impossible!"


Fastest way for working with itertools.combinations

Your algorithm is of time complexity O(n^6) in ndims. If your current code needs 65 s for ndims = 40, then one could estimate the time for ndims = 500 to be roughly 8 years. Even an improvement of the most inner block's execution time by a factor of 1000 would yield an execution time of about 3 days. I guess this is not good enough.

So you should better try to improve the algorithm itself. However I do not really understand the problem the function is trying to solve and I couldn't come up with a better solution on the spot.

Also I haven't looked at numpy approaches, because you seem to have no vectorizable calculations in there.

Nonetheless I tried to make improvements to the code as is. I came up with the following:

You use only the a small fraction of myarr, so extract these parts first

myarr1 = myarr[:,1]
myarr2 = myarr[:,2]

Since you do many index lookups on these arrays turn them into lists. Numpy is not good at single index lookups.

myarr1 = myarr[:,1].tolist()
myarr2 = myarr[:,2].tolist()

Instead of substracting and comparing to 0, compare the variables directly saving one operation:

if c1>c2 and c2<c3 and c3>c4 and c4<c5 and c5>c6:

Instead of using and, you can also connect the comparisons all together, potentially saving the double variable lookups:

 if c1 > c2 < c3 > c4 < c5 > c6:

Instead of assigning the array elements to c1, c2, etc., use them directly. Since later comparisons are not executed if earlier one already return False this might save array lookups:

if myarr1[idx1] > myarr2[idx2] < myarr1[idx3] > myarr2[idx4] < myarr1[idx5] > myarr2[idx6]:

All in all I get the following code:

import numpy as np
import itertools

def combcol(myarr):
    ndims = myarr.shape[0]
    solutions = []
    for idx1, idx2, idx3, idx4, idx5, idx6 in itertools.combinations(np.arange(ndims), 6):
        c1, c2, c3, c4, c5, c6 = myarr[idx1,1], myarr[idx2,2], myarr[idx3,1], myarr[idx4,2], myarr[idx5,1], myarr[idx6,2]
        if c1-c2>0 and c2-c3<0 and c3-c4>0 and c4-c5<0 and c5-c6>0 :
            solutions.append(((idx1, idx2, idx3, idx4, idx5, idx6),(c1, c2, c3, c4, c5, c6)))
    return solutions

def combcol2(myarr):
    ndims = myarr.shape[0]
    myarr1 = myarr[:,1].tolist()
    myarr2 = myarr[:,2].tolist()
    solutions = []
    for idx1, idx2, idx3, idx4, idx5, idx6 in itertools.combinations(range(ndims), 6):
        if myarr1[idx1] > myarr2[idx2] < myarr1[idx3] > myarr2[idx4] < myarr1[idx5] > myarr2[idx6]:
            solutions.append(((idx1, idx2, idx3, idx4, idx5, idx6),(myarr1[idx1], myarr2[idx2], myarr1[idx3], myarr2[idx4], myarr1[idx5], myarr2[idx6])))
    return solutions

X = np.random.random((40, 10))
Y = [np.random.random((10, 10)) for i in range(100)]

if __name__=='__main__':
    from timeit import Timer
    for test_case in Y: assert combcol(test_case) == combcol2(test_case)
    t = Timer(lambda : combcol(X))
    t1 = Timer(lambda : combcol2(X))
    print('t : ',t.timeit(number=1),'t1 : ',t1.timeit(number=1))

With results like these:

t :  12.221544027328491 t1 :  0.8104081153869629
t :  10.69440507888794 t1 :  0.6592199802398682
t :  12.91178011894226 t1 :  0.8727250099182129
t :  11.21804690361023 t1 :  0.6851639747619629

The improvement is not even close to what you need. Also I tried to run the algorithm with ndims = 80 and got memory problems. The reason is the number of solutions: There were 18679356 solutions taking up 5 GB of RAM. With other values for ndims I found that around 5% - 25% of all possible solutions are valid! So it seems you need to change the way you output your solutions if you want to get beyond ndims = 100 on any realistic machine.

Edit: I just notice that 5 GB is a bit too much for the number of solutions. However this was the memory allocated by the python process. A run with ndims = 100 was unsuccessful due to lack of available memory.

Edit2: There is actually something far more efficient you can do, by interweaving your solution checks with the combination generation (abandoning itertools.combinations). This doesn't look so nice however:

import numpy as np
import itertools

def combcol(myarr):
    ndims = myarr.shape[0]
    solutions = []
    for idx1, idx2, idx3, idx4, idx5, idx6 in itertools.combinations(np.arange(ndims), 6):
        c1, c2, c3, c4, c5, c6 = myarr[idx1,1], myarr[idx2,2], myarr[idx3,1], myarr[idx4,2], myarr[idx5,1], myarr[idx6,2]
        if c1-c2>0 and c2-c3<0 and c3-c4>0 and c4-c5<0 and c5-c6>0 :
            solutions.append(((idx1, idx2, idx3, idx4, idx5, idx6),(c1, c2, c3, c4, c5, c6)))
    return solutions

def combcol2(myarr):
    ndims = myarr.shape[0]
    myarr1 = myarr[:,1].tolist()
    myarr2 = myarr[:,2].tolist()
    solutions = []

    for idx1 in range(ndims):
        c1 = myarr1[idx1]
        for idx2 in range(idx1+1, ndims):
            c2 = myarr2[idx2]
            if c1 > c2:
                for idx3 in range(idx2+1, ndims):
                    c3 = myarr1[idx3]
                    if c2 < c3:
                        for idx4 in range(idx3+1, ndims):
                            c4 = myarr2[idx4]
                            if c3 > c4:
                                for idx5 in range(idx4+1, ndims):
                                    c5 = myarr1[idx5]
                                    if c4 < c5:
                                        for idx6 in range(idx5+1, ndims):
                                            c6 = myarr2[idx6]
                                            if c5 > c6:
                                                solutions.append(((idx1, idx2, idx3, idx4, idx5, idx6),(c1, c2, c3, c4, c5, c6)))
    return solutions

X = np.random.random((40, 10))
Y = [np.random.random((10, 10)) for i in range(100)]

if __name__=='__main__':
    from timeit import Timer
    for test_case in Y: assert combcol(test_case) == combcol2(test_case)
    t = Timer(lambda : combcol(X))
    t1 = Timer(lambda : combcol2(X))
    print('t : ',t.timeit(number=1),'t1 : ',t1.timeit(number=1))

The result:

t :  11.706523180007935 t1 :  0.15908312797546387
t :  12.531341075897217 t1 :  0.16385602951049805
t :  11.581043004989624 t1 :  0.14388418197631836

So with that we already have nearly a factor of 100x speed-up.


There is a huge amount of guessing in your program, code like:

int next_idx(int swapped[], int s_count, int size) {
    int n, i;
    char in_arr;
    while (1) {
        in_arr = 0;
        n = rand() % size;
        for (i = 0; i < s_count; i++) {
            if (swapped[i] == n) {
                in_arr = 1;
                break;
            }
        }
        if (!in_arr) {
            break;
        }
    }
    return n;
}

Let's say the input data has 1000000 members, and we need to swap 10 of them... swapped[] array contains.... {1, 100, 500, 800, 1000, 10000} do we really just keep guessing until we hit a random value that is in the data? This is... a problem.

One solution which will produce a suitably random distribution of the swapped items relies on a 'simple' algorithm which does just one rand() per item, and there's no guess-work. This is done using a fisher-yates shuffle. But, for this problem, we don't shuffle the items, we shuffle the indexes... so:

void swap2_or_more(int a[], int size,int count) {
    int i, tmp;
    int swapped[size];

    // initialize the swapped array with all the data indices.
    for (i = 0; i < size; i++) {
        swapped[i] = i;
    }

    // Fisher-Yates shuffle the indices.
    // http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
    for (int i = size-1; i > 0; i--) {
        tmp = rand() % (i + 1);
        swap(swapped, i, tmp);
    }

    // 'rotate' the values in the first count swapped/random indexes
    tmp = a[swapped[--count]];
    while(count > 0) {
        a[swapped[count]] = a[swapped[count - 1]];
        count--;
    }
    a[swapped[0]] = tmp;
}


OpenCV 3: Using k-Nearest Neighbors to analyse RGB image

I found a way to get rid of the python loop. np.vstack() converts the image to a single row which in this case is the format findNearest() expects.

Running below code through IPythons timeit function yields a huge perfomance boost:
The version in the original answer takes 2.5s per loop.
The new version runs at 15.3ms per loop.

import cv2
import numpy as np

imgPath = r"../Images/landscape2.jpg"
img_BGR = cv2.imread(imgPath)
if img_BGR is None:
    raise FileNotFoundError("'{0}' could not be opened!".format(imgPath))

BGR_COLORS = dict(blue=(255, 0, 0), green=(0, 255, 0), red=(0, 0, 255), black=(0, 0, 0), white=(255, 255, 255))
LABELS = dict(blue=np.array([0]), green=np.array([1]), red=np.array([2]), black=np.array([3]), white=np.array([4]))
trainData = np.array([BGR_COLORS['blue'], BGR_COLORS['green'], BGR_COLORS['red'], BGR_COLORS['black'], BGR_COLORS['white']], dtype=np.float32)
responses = np.array([[LABELS['blue']], LABELS['green'], LABELS['red'], LABELS['black'], LABELS['white']], dtype=np.float32)

knn = cv2.ml.KNearest_create()
knn.train(trainData, cv2.ml.ROW_SAMPLE, responses)

img_vstacked = np.vstack(img_BGR).astype(np.float32)
ret, results, neighbours, dist = knn.findNearest(img_vstacked, 1)

height, width, depth = img_BGR.shape
results_int = results.reshape(height, width).astype(np.uint8)

def colorPixels(image, results, colorName):
    image[results[:, :] == LABELS[colorName]] = BGR_COLORS[colorName]

img_clustered = img_BGR.copy()
for colorName in BGR_COLORS.keys():
    colorPixels(img_clustered, results_int, colorName)

cv2.imshow("Original vs. Clustered", np.hstack((img_BGR, img_clustered)))
cv2.waitKey(0)
cv2.destroyAllWindows()


Sudoku solver using backtracting and depth-first-search

Overall it looks fine for a beginner-level program, you keep the functions small and separate different parts of the logic between them, which is good.

int valid(int[][9], int, int, int); You should make a habit of naming your parameters even during function declaration. Ideally the function definition is a copy/paste of the declaration.
(Minor remark) It would be clearer to write int puzzle[9][9] in the parameter list, even though it makes no practical difference. It gives self-documenting code, however.
But you should entirely avoid "magic numbers" like 9 in your code. You should have #define SUDOKU_SIZE 9 or such instead. This goes for all the divide by 3 statements too, it's not clear to the reader where the "magic number" 3 came from. This is where you would need to place a comment, since the code doesn't speak for itself.
(Major issue) Your indention style is exotic and therefore wouldn't be tolerated in a professional setting. For example the line following an if or for etc should be placed on a line of its own, and also indented (2 or 4 spaces are ok):

for (int y = 0; y < 9; ++y)
  printf("|%d", puzzle[x][y]);

For mission-critical programs, this style isn't tolerated either, but you need to always use { } compound statements even if there is just a single line.
(Minor remark) int puzzle[9][9] This could perhaps have been declared const, so you have one read-only table of the original data, and place the solution in a different matrix. You could then also have implemented const correctness for functions that do not modify this matrix.
(Minor remark) Coding style preference - avoid using the ! for operands that aren't boolean. Instead of !puzzle[x][y], I'd write puzzle[x][y]==0 since the purpose is to check if something is 0, not false.
Instead of returning 1/0 type int, you should be using true/false and bool from stdbool.h.
(Minor remark) This int main() is obsolete style in C. You should be using int main(void) instead. (C and C++ are different here)
(Minor remark) Your functions are pretty short so I'd say it is ok to return from multiple places inside them. For more complex functions, multiple returns from a function is sometimes frowned upon and it's preferred to only have a single return at the end. This is no black/white rule though. I say avoid multiple return statements unless it actually makes the code more readable. In your current program it's fine.
The matrix print could be made a function of its own, to be called from main().


Naming

Good names can greatly improve the readability of a program.
Many of the names in the posted code can be improved:

getPrefix: the function returns the common prefix. It would be good to include that important clarifying detail in the name.

If you intend to return the common parent directory, I would call the function getCommonParent.

text: the parameter is not just any text, it's an array of paths, so paths would be a better name that conveys the intention.
i: is fine in simple counting loops, but when you iterate over values that have a meaningful name, it's better to use that, for example in this example path.
test is also an overly generic name, instead of the more descriptive paths

Algorithm

The implementation will call commonPrefix method text.count + 1 times.
This is probably fine,
but you could reduce the number of calls to commonPrefix
by using a divide and conquer strategy.

For example, consider you have paths p1, p2, ..., pn.
You could call commonPrefix for each pair, to get n / 2 results.
Then you could call commonPrefix for each of those pairs.
And so on, until there is only one pair left:

p1 p2 p3 p4 p5 p6 p7 p8
|__|  |__|  |__|  |__|
 |_____|     |_____|
    |___________|
          |
          = the common prefix

Admittedly, this might be overkill for your use case.


Functions asking for user input, with default prompts

Correctness: There are some cases that aren't handled. What happens if the user enters a word instead of a number? What if the user enters 2.1? The program will exit regardless of what character the user enters when exitTimeFn() is called.

I think your overload was a clever solution to a vague instruction. To make it clear that the extra parameter is irrelevant, you could comment out the name. For example:

int askNumberFn(int /*number*/, std::string prompt)
{
    int number;
    std::cout << prompt;

Because parameters are used to supply data to functions, it doesn't make sense to pass in a value, then immediately re-assign it before use.

Parameters: I would pass the strings by const reference instead of by value.

Naming: No need for Fn at the end of every function. It's obvious that it's a function from how it's used. The names could also be slightly more descriptive: getNumberFromUser, showExitDialogue, for example.

Commenting: Generally, I'd discourage line-by-line comments explaining what each line of code is doing. It's usually a sign you need to write clearer code. The way you use it in your main function to document your testing has some merit, I think. Look into unit testing for a more scalable/professional way of doing the same thing.

If accidentally using the same input for testing is a concern, I'd just use a different variable completely. A unit testing library would provide better tools to handle this.

While I believe this fulfils the question literally, there is an implied task of reacting reasonably to invalid input. I would test more thoroughly and make sure the edges don't do anything surprising.


First of all you should split up this method into smaller ones. The inline comment give you a perfect sign what should be extracted.
Also *try with resource" can handle more than one resource in a single statement.
public void makeSeveralApiCalls() throws Exception {
  try (final CloseableHttpClient client = HttpClients.createDefault();
       final CloseableHttpResponse response = client.execute(httpGetUri());
      ){
      if (response.getStatusLine().getStatusCode() == 404) {
        // Resource not found
        postDataToMicroserviceA(client, response);
       }
    }
}

private void postDataToMicroserviceA(CloseableHttpClient client, CloseableHttpResponse response){
  try (final CloseableHttpResponse nestedResponse = client.execute(httpPostToMicroserviceA())) {
          if (resp.getStatusLine().getStatusCode() == 201) {
            LOGGER.info("Success");
          } else {
            // Microservice A could not consume data,
            logErrorResponse(client, response);
          }
  }
}

private void logErrorResponse(CloseableHttpClient client, CloseableHttpResponse response)
            final String responseString = EntityUtils.toString(resp.getEntity());
            LOGGER.debug("Error response: " + responseString);
            // Try to Post to Microservice B
            try (final CloseableHttpResponse subResponse = client.execute(httpPostToMicroserviceB())) {
              if (resp.getStatusLine().getStatusCode() == 201) {
                LOGGER.info("Success");
              } else {
                // Is this exception propagated to the caller?
                throw new RuntimeException("Very bad unrecoverable state");
              }
}

Of cause this could be optimized a bit more if you find a more generalized solution to merge postDataToMicroserviceA() and logErrorResponse(), since basically they do the same...


Rock, Paper Scissor game (console-based) in Python

It looks like you are familiar with dictionaries and maybe lists. So, let's look at how you collect and enter input. It looks like you are trying to control erroneous input with your try/except and if statement. There is some trouble though. I can send a float through your code if it has a value like 1.2 or 2.5. Your code will turn it into an int and then try to use the value, but there's another way to handle something like this:

if choice not in ['1','2','3']:
    raise ValueError
else:
    break

So, in this case, I'm using a list of the only acceptable values, checking if the choice is in there, and then moving forward.

Your control flow looks a little messy. There are a couple of ways to handle this.

If we keep the same general approach, you can make it more readable by spreading it out. I would actually make a new function for this:

def compare(x,y):
    if x == y:
        state = "It's a Draw!"
    if x == '1':
        if y == '2':
            state = "You Lose!"
        else:
            state == "You Win!"
    elif x == '2':
        if y == '1':
            state = "You Win!"
        else:
            state == "You Lose!"
    else:
        if y == '1':
            state = "You Lose!"
        elif y == '2':
            state = "You Win!"
    return state

However, depending on how comfortable you are with lists, there is another, simpler way!

You can setup a list of the possible game conditions and then do whatever you want to them:

game_result = ["tie!", "win!", "lose!"]

(Actually, that sequence in the list was coded for 1) Rock, 2)Paper, and 3)Scissors. There should be another arrangement for rock-scissors-paper though that makes things smooth).

Then define a comparison function that just looks at the modulated difference between the user and robot input (you'll need to convert them to the int data type first).

def compare(x,y):
result = game_result[ (x-y)%3 ]
return result

There's a few tricky things with how you're checking which round you should be on. So, first thing, it might be helpful/more readable if you change the variable name to something useful like round_number or matches_left.

Then, you have it set to end the while loop if the round number is not equal to n. There's another potential bug here. What if the user enters a float or something you don't want? -- Actually, you're using int() on the input, which corrects for this. So good call! But, that design pattern doesn't always carry over well and it may not be as clear to other readers ( it wasn't to me anyways).

Suppose the player enters 1.2, then your while loop goes on for ever if you aren't using int(). One way to handle this is to use try/except; another way is to use isinstance; and another way is to do something like this:

while num_of_rounds <= ngames:
        game()
        num_of_rounds += 1

In this way, you cover a broader set of what is acceptable/unacceptable and don't have your code hinging on a small window of operation (and exploitability).

Overall, your code works and was fun to play! The biggest things are style, readability, and different ideas on how to handle incorrect input. I would check out the PEP 8 Python style Guide for some general insights: https://www.python.org/dev/peps/pep-0008/


You are mixing two very different objects and tasks in your Parts class. On the one side there is the object of a Part and on the other hand there is a dictionary of parts which is your inventory system. You should separate the two:

import sys
from collections import namedtuple

class Part(namedtuple("Part", "name part_number quantity")):
    def __str__(self):
        return ", ".join(self)

class Parts(dict):
    def display (self):
        if not self:
            print('No Parts Found in List')
            return
        print()
        print('Name, Part Number, Quantity')
        for part in self.values():
            print(part)
        print()

    def add(self, *args):
        try:
            name, part_number, quantity = args
        except ValueError:
            name = input("Enter Name of Part:\n ")
            part_number = input("Enter Part Number:\n ")
            quantity = input("Enter Quantity:\n ")
        self[name] = Part(name, part_number, quantity)

    def remove(self, part=""):
        if not part:
            part = input("Enter Part Name to Remove\n")
        try:
            del self[part]
        except Keyerror:
            print("Part {} not found.".format(part))

    def edit(self, part=""):
        if not part:
            part = input("Enter Part Name to Edit\n")
        try:
            new_name = input("Enter new part name\n")
            number = input("Enter new part number\n ")
            quantity = input("Enter new quantity\n ")
            self[part] = Part(new_name, number, quantity)
        except KeyError:
            print("No such Part exists: {}".format(part))

    def save(self, filename=""):
        if not filename:
            filename = input("Filename to save: ")
        with open(filename, "wt") as out_file:
            for part in self.values():
                out_file.write("{}\n".format(part))
        print("File saved")

    def load(self, filename=""):
        if not filename:
            filename = input("Filename to load: ")
        try:
            with open(filename, "rt") as in_file:
                for line in in_file:
                    if not line:
                        break
                    part, part_number, quantity = line.strip().split(",")
                    self.add(part, part_number, quantity)
        except FileNotFoundError:
            print("File Not Found.")

def menu(inventory):
    menu_list = [("Parts", inventory.display),
                 ("Add Part", inventory.add),
                 ("Remove Part", inventory.remove),
                 ("Edit Part", inventory.edit),
                 ("Save Part List", inventory.save),
                 ("Load Part List", inventory.load),
                 ("Exit", sys.exit)]
    while True:
        for i, (name, _) in enumerate(menu_list, 1):
            print("{}. {}".format(i, name))
        try:
            user = int(input("Selection> "))
            menu_list[user-1][1]()
        except (ValueError, IndexError):
            print("Selection Not Valid.")

def main():
    print("Welcome to Sticks&Stones Inventory System")
    inventory = Parts()
    while True:
        menu(inventory)

if __name__ == '__main__':
    try:
        main()
    except (KeyboardInterrupt, SystemExit):
        print("Exiting Program...")

Here I made two classes. I also made the inventory a sub-class of dict. This way you don't have to keep an external dictionary (and could even have two different inventories at the same time, maybe for different things?).

All methods of the inventory take parameters if you want to, and ask for them if they are not supplied.

A dict has dict.values which directly gives you a list (or iterable) of all values.

The Part is just a data container, so I used collections.namedtuple here, and just added nicer printing by overriding the magic __str__ method, which is invoked when calling e.g. print(part).


Manipulating bits

One of the areas where your code may be improved is the way it handles and compares bits. You are using char* strings to represent bits while you could have used unsigned values and bitwise operations to speed up most of your operations. Actually, you should even replace every int representing bits by unsigned since the representation of unsigned values is known and they are the tool to use when representing bits.

You can replace the MANCHESTER_ONE and MANCHESTER_ZERO definitions by:

#define MANCHESTER_ONE 1u
#define MANCHESTER_ZERO 2u

1u is 0b01 in binary and 2u is 0b10.
Then you can change the following bit of code in encode:

switch (real)
{
case 0:
    bit = MANCHESTER_ZERO[0] - '0'; // Subtract 48 to work out the real value
    nbit = MANCHESTER_ZERO[1] - '0';
    break;
case 1:
    bit = MANCHESTER_ONE[0] - '0'; // Subtract 48 to work out the real value
    nbit = MANCHESTER_ONE[1] - '0';
    break;
}

By the way, the switch is useless since your are only checking for two values. You can replace it by a regular if:

if (real == 0)
{
    bit = (MANCHESTER_ZERO >> 1) & 1;
    nbit = MANCHESTER_ZERO & 1;
}
else // real == 1
{
    bit = (MANCHESTER_ONE >> 1) & 1;
    nbit = MANCHESTER_ONE & 1;
}

Since we replaced the strings MANCHESTER_* by unsigned values, we use bitwise ANDs instead of array subtracts.
A gain in efficiency may be obtained by refactoring this piece of code:

// Put the data into a stringstream for comparison
std::stringstream con;
con << bit << nbit;
const char* sbit = con.str().c_str();

int real = 0;

// Compare the data and work out the value
if (strcmp(sbit, MANCHESTER_ONE) == 0)
{
    real = 1;
} else if (strcmp(sbit, MANCHESTER_ZERO) == 0) {
    real = 0;
}

std::stringstream is known to be slow since you have to convert your integer values into strings first before performing operations on them. In a for loop, it may be a big performance loss. Here is how you can refactor this bit of code:

// Put the bits in an unsigned
unsigned sbit = (bit << 1) | nbit;

// Check only for MANCHESTER_ONE,
// assuming that it will be equal
// to MANCHESTER_ZERO if not
int real = int(sbit == MANCHESTER_ONE);

As said in the comments, I make the assumption that once computed, sbit can only be equal to MANCHESTER_ONE or MANCHESTER_ZERO and nothing else.

General advice about C++

I cannot see any hint that you are using C++11, therefore I will review your code as C++03 code:

As said in the comments, allocating memory in a function and not deallocating it is not a good idea. You should simply use a std::vector to represent your arrays of numbers.
#define is to be avoided whenever possible in C++. Consider using const variables instead.
The standard way to check whether you are debugging is #ifndef NDEBUG (the double negative is kind of ugly, but it's the standard way).
In C++, it is useless to write return 0; at the end of main. If no return statement is given, the compiler will add an implicit return 0;.
If the MANCHESTER_* constants are not used anywhere else, you can define them as private static const variables of the class Machester.

Here is your code once refactored:

#include <iostream>
#include <stdexcept>
#include <vector>

class Manchester
{
public:

    static std::vector<unsigned> encode(const std::vector<unsigned>& data, unsigned length)
    {
        std::vector<unsigned> output(length * 2);

        for (unsigned i = 0; i < length; i++)
        {

            // Work out the array indexes to use
            unsigned bid = i * 2;
            unsigned nbid = bid + 1;

            // Get the data
            unsigned real = data[i];

            unsigned bit = 0;
            unsigned nbit = 0;

            // Work out what it is
            if (real == 0)
            {
                bit = (ZERO >> 1) & 1;
                nbit = ZERO & 1;
            }
            else // real == 1
            {
                bit = (ONE >> 1) & 1;
                nbit = ONE & 1;
            }

            #ifndef NDEBUG
                std::cout << "[encode] " << real << " [" << bit << nbit << "]" << std::endl;
            #endif

            output[bid] = bit;
            output[nbid] = nbit;
        }

        return output;
    }

    static std::vector<unsigned> decode(const std::vector<unsigned>& data, unsigned length)
    {
        if ((length % 2) != 0)
        {
            throw std::range_error("length is not a multiple of 2");
        }

        std::vector<unsigned> output(length / 2);

        for (unsigned i = 0; i < (length / 2); i++)
        {
            // Work out the array indexes to use
            unsigned bid = i * 2;
            unsigned nbid = bid + 1;

            // Get the data
            unsigned bit = data[bid];
            unsigned nbit = data[nbid];

            // Put the data into an unsigned int
            unsigned sbit = (bit << 1) | nbit;

            // Check only for MANCHESTER_ONE,
            // assuming that it will be equal
            // to MANCHESTER_ZERO if not
            unsigned real = unsigned(sbit == ONE);

            #ifndef NDEBUG
                std::cout << "[decode] bit: " << bit << nbit << " [" << real << "]" << std::endl;
            #endif

            output[i] = real;
        }
        return output;
    }

private:

    static const unsigned ONE;
    static const unsigned ZERO;
};

const unsigned Manchester::ONE = 1u;
const unsigned Manchester::ZERO = 2u;

int main()
{
    typedef std::vector<unsigned> vec_t;

     // Some unencoded data
    unsigned data[] = { 1u, 1u, 0u, 0u };
    // Initialize vector with array
    vec_t vec(data, data+sizeof(data) / sizeof(unsigned));

    vec_t encoded = Manchester::encode(vec, 4);
    vec_t decoded = Manchester::decode(encoded, 8);
}

You can find a live working version here at Coliru.


I think you might be overcomplicating the whole thing.

How do you define a palindrome? No matter which direction you're reading it, it's the same word. As you mentioned already, this means that all occurences of characters have to be even, except for one, which might be odd. However, the string length doesn't matter for this (it's just a logical consequence):

All characters with even occurences don't matter and can be ignored. You only have to count the number of characters who've got an odd count.

With no odd count: abccba - this is a palindrome.
With one odd count: abcba - this is a palindrome as well.
With two odd counts: abcdba - this isn't a palindrome.

So the task boils down to one simple task: Count the number of odd character counts.

Some code things I've noticed:

Try to avoid using using namespace. It might bite you in the back once you've got ambigious code and accidently call (or pass) the wrong function and you're unable to find the reason for some bug.
Try to be more consistent with your whitespace characters. In some places you've put them there, in other cases you've omitted them. Overall this makes your code quite a bit harder to read (at least for me).
Don't use single-char variables (a, i, k, etc.) unless they're iterators. This isn't JavaScript. You usually don't have to optimize code size. Instead use talking variable names, even if it's just "index" or "offset".
I'd also try to use a constant value rather than calling specific members over and over again, if you don't expect them to change. In your case this would be the check inside your loop: while(i<s.size()-1) { You don't know what's happening inside std::string::size(). While highly unlikely, this might actually iterate over your whole string every loop to determine the current length, making your code even more inefficient. Just ensure your compiler knows it's going to be constant:

  const std::string::size_type length = s.size();
  while(i < length - 1) {
      // ...
  }

In your solution you start by sorting the whole string (which is most likely O(n²)). After this you're iterating over all elements a second time to do the actual counting (O(n)).

To me this is quite suboptimal, especially if you're able to use some memory for this.

I'd try something like the following code, which will iterate over the input string and count the occurences of every character (O(n)). In a second loop I count the number of even and odd occurences (O(1)).

#include <iostream>

int main(int argc, char **argv) {
    // Let's just assume argv[1] holds the string

    // This will hold all character counts, initialized to 0
    unsigned char counts[256] = {0};

    // Iterate over the string...
    for (unsigned char *pos = reinterpret_cast<unsigned char *>(argv[1]); *pos; ++pos)
        ++counts[*pos]; // ...and count

    // Counts for even/odd:
    // - Even -> index 0
    // - Odd -> index 1
    unsigned int eo[2] = {0};

    // Now iterate over all characters
    for (unsigned int i = 0; i < 256; ++i)
        ++eo[counts[i] % 2];

    if (eo[1] > 1) { // More than one odd count - can't be an anagram
        std::cout << "No anagram can be a palindrome, since there are multiple unique characters." << std::endl;
        return 0;
    }

    // At most one odd count; this can be an anagram
    std::cout << "There might be an anagram that is a palindrome." << std::endl;
    return 0;
}

The big advantage here in my opinion is the fact that there's no branching outside any loop construct (except that one final check).

You could however, just skip the counting of even/odd counts and use a single bool to determine whether you've got a second occurence of an odd count (which would mean that you don't have any palindrome).


Relying on the max number of thread pool threads to cap the number of concurrent downloads feels ... wrong. It may also cause problems if another component needs a thread pool while all 25 are waiting for a response from web servers.

(slight correction) Although you use semaphores to limit the number of concurrent downloads to ten, you will still have up to 25 thread pool threads in the DoWork() method (15 blocked on the semaphore).

Two alternatives:

Manage you own task list and threads (since 4k URLs per thread could take more than a few seconds).
Make your requests asynchronously and track the list of IAsyncResult objects (though this may get a little fiddly).

I'm not sure I like the idea of using a static Semaphore to protect instance data, you should store the semaphore in a local field. Even if you only ever have a single instance, I prefer to scope the lock similarly to the data to be protected. (sorry, I thought the semaphore was to protect the controls rather than used as a throttle)
You should release your semaphore in a finally block.
Only the thread that created a control should be used to update it. I recommend using ISynchronizeInvoke.Invoke() to call AddItem() (implemented implicitly on Control). This will also remove the need to use a semaphore to protect the control (though you may still need one to protect a pending URL list depending on what you do about the first point). (this is already done, sorry, missed it).
What is the purpose of the 1000 millisecond sleep? it appears before the tasks are even queued.


MVC is a concept that stems from good OOP practices. It's about seperating your application to three different parts: InputControllers, ProcessingModel and OutputView.

What you are describing is the bootstrap page, which, at least from my perspective should not be a class.

Here's my approach to this:

index.php

<?php
require "../bootstrap.php";

bootstrap.php

<?php
//Pseudo-code ahead:
require autoloader;
start router;
add router rules (either from file, or actually in the code)
$route = $router->route($uri); //$route is a Route object which tells us
                               //what controller to use, what are the parameters, etc.
$controllerClass = $route->getControllerClass();
$controllerAction = $route->getControllerAction();
$controller = new $controllerClass($request);
//Where $request is the Request object, containing the URI, GET, POST, COOKIES, etc.
$viewParams = call_user_func_array([$controller, $controllerAction], $route->getParameters());
//$route->getParameters() is an array of parameters from the route.
//call_user_func_array will transform that array into actual arguments to pass in.

$viewClass = $viewParams["class"];
$viewAction = $viewParams["action"];
$view = new $viewClass($request);
echo $view->render($viewParams);


MC_1(".----", '1'),
...

This is pretty repetitive. Unfortunately, you can't call the object simply 1, but you can do better:

MC_1(".----"),
...
Morse(String morse) {
    this.morse = morse;
    this.code = name().charAt(name().length - 1);
}

This assumes, you can use all needed chars as a part of the name, which is not the case. So let's handle it by adding another constructor (your original and using

MC_SPACE("/", ' ');

just like you did. But I'm not sure at all, if using an enum is the way to go. What about using a simple Map<String, char> and another the other way round or better a BiMap?

Encapsulate it in a class Codec and let the class do more work.

public static String morseConversion(String s) {
    String ms = s.toUpperCase().trim(); // modified string

As this is nothing but a cleanup of s, I'd simply modify it. There's a rule about never modifying arguments, but it's wrong. Ask yourself:

What harm can happen by cleaning up s directly?
What harm can happen by having both s and sm?

The answers should make it perfectly clear in this case.

for (int i = 0; i < ms.length(); i++) {
    isValid(ms.charAt(i));

According to the name, isValid is a predicate. It returns a boolean to be used elsewhere. Your method should be called checkIsValid or alike. Or make it to a predicate and use checkArgument.

Validation is fine, but not here. What you do is determining if the following loop will succeed. So you're doing all the work twice.

for (Morse c : Morse.values()) {
     if (ms.charAt(i) == ' ' && ms.charAt(i - 1) == ' ');

This test is independent of c, so it does not belong to the loop.

What's worse: if (..); else if is a really terrible way if writing conditions. It's pretty confusing. If you need something like this, write

     if (ms.charAt(i) == ' ' && ms.charAt(i - 1) == ' ') {
         // Do nothing. Ignoring consecutive spaces.
     } else if (ms.charAt(i) == c.code) {

  It seems to me that I'm potentially looping quite a while, and this may not be the best or even common practice.

That's exactly what a Map is for. Feed it with the char. and it gives you the String. No loop needed.


Simulation to find max population of R-pentominos in Game of Life

Global

Python has deprecated sets, instead use the __builtins__.set.
This allows us to add some nice sugar to your code, for creating the set.

cell_set = {(0, 1), (0, 2), (1, 0), (1, 1), (2, 1)}

Your names are good, but a few 'let you down', as I don't know what sim means, I assume simulate.
You may want to use str.format to format strings for print.
This is as it will be simpler to add strings and numbers.

print str(i + 1) + " generation population: " + str(gen_size)
print "{} generation population: {}".format(i + 1, gen_size)

You can use Python's max to find the maximum.

max([1, 2, 3]) # 3
max([(1, 3), (2, 2), (3, 1)]) # (3, 1)

As you mutate cell_set you will have to use a full-fledged generator, rather than a generator comprehension.
Where you yield (gen_size, i).

def generate_cells(cell_set, generations=1500):
    for i in range(1, generations + 1):
        cell_set = sim(cell_set)
        print "{} generation population: {}".format(i, len(cell_set))
        yield len(cell_set), i

max_size, max_gen = max(generate_cells(cell_set))

In my opinion that is much easier to understand.
Python has a dedicated style guide called PEP8, it states that constants, dx and dy, should be upper-snake case.
So DX and DY.

is_ng_alive

You should use zip, to loop through both dx and dy.

for ax, ay in zip(dx, dy):
    if (x + ax, y + ay) in original_set:
        cnt += 1

You can use sum and a generator comprehension to not have to add up cnt manually.

cnt = sum((x + ax, y + ay) in original_set for ax, ay in zip(dx, dy))

You can simplify your logic, as if cnt is 3 it will return true.
Then you can just return the boolean from the new truth statement.

if cnt == 3:
    return True

return (x, y) in original_set and cnt == 2

I mistakenly thought that zip(dx, dy) would be a line.
Instead you may want the algorithm to be 'more square', which would be:

for ax in dx:
    for ay in dy:
        (x + ax, y + ay)

sim

Using the changes from above you can change the for loop with ease.
However to make things easier to read you may want to make (x + ax, y + ay) for ax, ay in zip(dx, dy) a function.

def new_coords(x, y):
    return ((x + ax, y + ay) for ax, ay in zip(dx, dy))

for item in ((nx, ny) for (nx, ny) in new_coords(x, y)
             if is_ng_alive(nx, ny, original_set)):
    new_set.add(item)

print_cell_set

This is very bad on performance, instead you would want to build a string, and then limit prints.
You can do this with another list comprehension, a turnery and str.join.

for x in range(-x_size, x_size):
    print ''.join('*' if (x, y) in cell_set else '.' for y in range(-y_size, y_size))

Overall you have nice code, you just missed a few things to improve clarity.

And I got:

__author__ = 'Sayakiss'

DX = [0, 0, 1, -1, 1, -1, 1, -1]
DY = [1, -1, 0, 0, -1, 1, 1, -1]

def new_coords(x, y):
    return ((x + ax, y + ay) for ax, ay in zip(DX, DY))

def is_ng_alive(x, y, original_set):
    cnt = sum((nx, ny) in original_set for nx, ny in new_coords(x, y))
    if cnt == 3:
        return True

    return (x, y) in original_set and cnt == 2

def sim(original_set):
    new_set = set()
    for (x, y) in original_set:
        for item in ((nx, ny) for (nx, ny) in new_coords(x, y)
                 if is_ng_alive(nx, ny, original_set)):
            new_set.add(item)
        if is_ng_alive(x, y, original_set):
            new_set.add((x, y))
    return new_set

def print_cell_set(cell_set, x_size=10, y_size=10):
    for x in range(-x_size, x_size):
        print ''.join('*' if (x, y) in cell_set else '.' for y in range(-y_size, y_size))

def generate_cells(cell_set, generations=1500):
    for i in range(1, generations + 1):
        cell_set = sim(cell_set)
        print "{} generation population: {}".format(i, len(cell_set))
        yield len(cell_set), i

cell_set = {(0, 1), (0, 2), (1, 0), (1, 1), (2, 1)}
print "{1}-{0}".format(*max(generate_cells(cell_set)))


extract all textcontent in htmlcollection to array with javascript

Declare your variables - whenever you assign to or reference a variable without defining it first, you will either (1) implicitly create a property on the global object (which can result in weird bugs), or (2) throw an error, if you're running in strict mode. You currently aren't defining any of your variables. Fix it by putting const (or, when needed, let) in front of them when assigning to them for the first time, eg const htmlObject = $(anycasestr);.
jQuery or DOM methods? You're using jQuery to turn the string into a jQuery collection of elements, but then you're using getElementsByTagName to select children. If you're using jQuery, you can be concise and consistent to use it to select the
 children.. To find children of an element which match a particular tag name, call .find on the jQuery collection - then, you can use .map to turn the found jQuery elements into a collection of just the text of the elements:
const $parent = $(anycasestr);
const arr = $parent.find('div')
  .map((_, child) => child.textContent)
  .get(); // turn the jQuery collection of strings into an array of strings

const anycasestr = `

refinement

decent

elegant

`;
const $parent = $(anycasestr);
const arr = $parent.find('div')
  .map((_, child) => child.textContent)
  .get(); // turn the jQuery collection of strings into an array of strings
console.log(arr);

Or, you can use DOMParser instead. Using DOMParser rather than jQuery to turn the text into a collection of elements can avoid accidental execution of malicious scripts. Example exploit using jQuery:

const anycasestr = `<img src="" onerror="alert('evil')">`;
const $parent = $(anycasestr);

With DOMParser:

const anycasestr = `

refinement

decent

elegant

`;
const doc = new DOMParser().parseFromString(anycasestr, 'text/html');
const arr = [...doc.querySelectorAll('div > div')]
  .map(div => div.textContent);
console.log(arr);

The query string div > div selects
 elements which are direct children of another
. It works exactly the same way as CSS selectors. querySelectorAll is a great tool for concise selection of elements - it can be easier to write and understand at a glance than other methods (like your original htmlObject[0].getElementsByTagName("div")).
Array.prototype.slice.call is a bit verbose - on non-ancient environments, you can use spread syntax instead, like I did above. Creating an array all at once by mapping is also somewhat more elegant than declaring an array then .pushing onto it.
If you had more
 children and wanted to take only the text from the first 3 of them, it'd be more functional to .slice the array of elements instead of putting an iteration count in a for loop:

const anycasestr = `

refinement

decent

elegant

don't include me

don't include me

don't include me

`;
const doc = new DOMParser().parseFromString(anycasestr, 'text/html');
const arr = [...doc.querySelectorAll('div > div')]
  .slice(0, 3)
  .map(div => div.textContent);
console.log(arr);

in terms of computational concerns?

Unless the stuff that needs to be parsed is unreasonably large, performance for this sort of thing is not a concern; better to write clean, readable, maintainable code. If you later find that something is taking longer to run than is ideal, you can identify the bottleneck and then figure out how to fix it. (But this almost certainly won't be the bottleneck.)


Concurrent Stack with blocking and non-blocking methods

I see that you made improvements to your code since here.

Synchronizing

You decided to use internal locking what is technically ok. The way you did it is a variant that I never used. I prefer to use following pattern:

Define an object local Lock-Object:

Object lock = new Object();

And synchronize with the synchronized-block construct:

public void anyMethod() {
    synchronized (this.lock) {
        // do stuff in monitor here
    }
}

Even if your approach is comparable to this you should go with less statements as you are always have aquire the lock with locked.compareAndSet(false, true) and release the lock with locked.set(false). You have no compiler and language support for this locking mechanism. You can easily forget to release the lock or you may find yourself in situations that will compromise your locking like: If your list is empty and you call the poll-method, it aquires the lock, failing afterwards with an ArrayIndexOutOfBoundsException that causes the lock never to be released. That is also true for the take-method().

Missing maxSize constraint (?)

I do not know if there should be any other assertion in the put-method. But there you do not check for maxSize.

Handle empty list

Your take()-method and your poll-method are vulnerable if the internalList is empty. They both fail with an ArrayIndexOutOfBoundsException. Either you return null or what I think is the better way to check for emptyness and throw an "EmptyStackException". This is the standard behaviour from the Java Stack implementation:

java.util.Stack<Object> stack = new java.util.Stack<>();
stack.pop(); // throws EmptyStackException

Avoiding the ArrayIndexOutOfBoundsException has semantical reasons. This Exception is published from different abstraction layer. So using an EmptyStackException is an interpretation of the underlying state of the internalList from the stack'S point of view.

You may say that you catch the ArrayOutOfBoundsException and map it to the EmptyStackException which would be the correct semantic. But you should avoid it to be thrown as throwing exceptions is very expensive.

Busy waiting

Currently you use a while-loop to wait for new elements if no element is present.

Busy waiting should be replaced by a non cpu killing concept. I doubt that in your case busy waiting or equivalent functionality should be done as mentioned in the comments there is a possibility never to recover from it. Providing a timeout mechanism would be an approach. Your busy waiting solution could easily extended to evaluate a given timout but it keeps very cpu expensive.

On the other side a non cpu killing way is complicated. The only chance to do so is to instantiate a Timeout-thread sleeping n seconds, before put the current thread to wait and notify it if the timout is reached with a timout marker. You have to consider that a notification should also be made when new elements become available. Furthermore your timeout thread has to be killed. You have to decide what to do if a timeout happens (returning null oor throwing an exception). Equivalent Java classes return null.

A personal note: In productive environments I would not implement such a timeout mechanism by myself if there is a chance to use existing well tested solutions. For the sake of education this is something where you certainly learn a lot but it also can be very frustrating as this goal is miles away in contrast to centimeters to the implementation so far. But I encourage you at least to go some meters to experience the burden you put on your shoulders.


Check this Stack Overflow question out, which has a solution to the same problem. A simplified version would look like this

(define (insert-at pos elmt lst)
 (if (empty? lst) (list elmt)
 (if (= 1 pos)
  (cons elmt lst)
  (cons (first lst)
        (insert-at (- pos 1) elmt (rest lst))))))

(define (insert-everywhere sym los)
  (map (lambda (i)
         (insert-at i sym los)
           )
       (range 1 (+ 2 (length los)))))

There is a function written for inserting at a particular position.
Then we have our iterative function that maps over the elements in the list.

Alternatively, there is the recursive solution found in the link above. It does this by using conditions and cons (which appends to lists together). It seams a bit clunky, but map really cleans it up.


Associating a set of constants with corresponding strings is difficult in C.  One approach is to define a structure, such as

struct patterns {
    const char combination[4];
    int count;
};

Here we have space for a string and an integer to count occurrences.
Creating an array of these and initializing it gives us this:

struct patterns patterns[N_PATTERNS] = {
    {"HHH", 0}, {"HHT", 0}, {"HTH", 0}, {"HTT", 0},
    {"THH", 0}, {"THT", 0}, {"TTH", 0}, {"TTT", 0},
};

Then you can loop through the strings by accessing each array member and
incrementing the counts.  The count and string are kept together so that
indexing errors cannot happen.

Also, your main is too complicated.  Just reading the string from the
command line is easier.

Putting it together, gives me this:

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

#define N_PATTERNS 8
struct patterns {
    const char combination[4];
    int count;
};

static int increment_occurance(struct patterns *p, const char *s)
{
    for (int i = 0; i < N_PATTERNS; ++i) {
        if (!memcmp(s, p[i].combination, 3)) {
            p[i].count += 1;
            return 1;
        }
    }
    return 0;
}

static void count_occurances(struct patterns *p, const char *s)
{
    const char *end = s + strlen(s) - 2;

    for (; s < end; ++s) {
        increment_occurance(p, s);
    }
}

int main(int argc, char **argv)
{
    struct patterns patterns[N_PATTERNS] = {
        {"HHH", 0}, {"HHT", 0}, {"HTH", 0}, {"HTT", 0},
        {"THH", 0}, {"THT", 0}, {"TTH", 0}, {"TTT", 0},
    };
    if (argc < 2) {
        fprintf(stderr, "Usage: %s string\n", argv[0]);
        return EXIT_FAILURE;
    }
    count_occurances(patterns, argv[1]);

    for (int i = 0; i < N_PATTERNS; ++i) {
        printf("%s %d\n", patterns[i].combination, patterns[i].count);
    }
    return EXIT_SUCCESS;
}

EDIT: note that we can use the more efficient memcmp instead of strncmp in increment_occurance.


If Nesting

You are nesting if's too much which quickly becomes ugly. I don't know your language but if at all possible negate the the conditions and return the result for example:

do:

if not HasCompleted {

return(or equivalent) completion(false, nil)

}

instead of:

if HasCompleted {
...
}
else
{
completion(false, nil)
}


Calculate highscores based on sales data

def level(self):
    startdate = model.Order.all().filter('status =', 'PAID'
            ).filter('distributor_id =',
                     self._key.id()).get().created.date()
    last_day_nextmonth = startdate + relativedelta(months=2) \
        - timedelta(days=1)

Continuing lines with \ is generally frowned upon. Either split it onto multiple lines or wrap the expression with parenthesis

    total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)

I think writing a self.silver(start_date, end_date) function would make sense to get the sum of those two.

    if total >= 125:
        level = 5
    elif total >= 75:
        level = 4
    elif total >= 25:
        level = 3
    elif total >= 2:
        level = 2
    else:
        level = 1

I'd store all of these levels in a list like [0, 2, 25, 75, 125]. Then I'd use functions from bisect to figure out which level I was at.

    return self.levelHelp(level, last_day_nextmonth + timedelta(days=1))

def levelHelp(self, level, startdate):

    last_day_nextmonth = startdate + relativedelta(months=2) \
        - timedelta(days=1)
    total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)
    if total >= 125:
        newlevel = 5
    elif total >= 75:
        newlevel = 4
    elif total >= 25:
        newlevel = 3
    elif total >= 2:
        newlevel = 2
    else:
        newlevel = 1

Deja Vu! You've got the exact same code again, at the very least, move the common code into another function.

    maxlevel = level if level > newlevel else newlevel

Use maxlevel = max(level, newlevel)

    nextstart = last_day_nextmonth + timedelta(days=1)
    now = datetime.now().date()
    if nextstart > now: #next start in is the future
        return maxlevel
    else: return self.levelHelp(maxlevel, nextstart)

You shouldn't really be using recursion here. This is very naturally a while loop. I think if you rewrite this as a while loop, it'll be clearer and you'll be able to combine these two functions.

def non_manager_silver(self, startdate, enddate):
    silver = 0
    timeline = date(startdate.year, startdate.month, 1)

I'm not clear why you back this up to the start of the month rather then using the startdate.

    downline = User.query(User.sponsor == self._key).fetch()

This has no effect, because you throw it away as soon as you enter the loop

    distributor = self
    while distributor.has_downline():
        downline = User.query(User.sponsor
                              == distributor.key).fetch()

        for person in downline:
            orders = model.Order.all().filter('distributor_id =',
                    person.key.id()).filter('created >',
                    startdate).filter('created <',
                    enddate).filter('status =', 'PAID'
                    ).fetch(999999)

Why 999999?

            for order in orders:
                for (idx, item) in enumerate(order.items):

No need for those parens.

                    purchase = model.Item.get_by_id(long(item.id()))
                    amount = int(order.amounts[idx])

Using int and long seems a little odd. Are you converting from strings?

                    silver = silver + amount * purchase.silver \
                        / 1000.000

Use silver += amount * purchase.silver / 1000.000

            distributor = person

See, here is where you should be using recursion. I assume that you are trying to go through the downlines of all the downlines. However, as your code is written, you'll only go through the downlines of the last member of the downline.

    return silver

def personal_silver(self, startdate, enddate):
    p_silver = 0
    timeline = date(startdate.year, startdate.month, 1)  # first day of month
    orders = model.Order.all().filter('distributor_id =',
            self._key.id()).filter('created >',
            timeline).filter('created <', enddate).filter('status ='
            , 'PAID').fetch(999999)
    for order in orders:
        for (idx, item) in enumerate(order.items):
            purchase = model.Item.get_by_id(long(item.id()))
            amount = int(order.amounts[idx])
            p_silver = p_silver + amount * purchase.silver \
                / 1000.000  # remember amounts

    return p_silver

This function is pretty much exactly the same as the previous function. You should be able to move common parts into a function.

I'd approach this whole thing quite differently.

def find_downline(distributor):
    """
    Given a distributor, collect all the members of his downline into a list
    """
    downline = [distributor]
    immediate_downline = User.query(User.sponsor == distributor.key)
    for member in immediate_downline:
        downline.extend( find_downline(member) )
    return downline

def find_orders(distributor):
    return model.Order.all().filter('distributor_id =',
            self._key.id()).filter('status ='
            , 'PAID').fetch()

def silver_in_order(order):
    total = 0
    for item, amount in zip(order.items, order.amounts):
        purchase = model.Item.get_by_id(long(item.id()))
        total += amount * purchase.silver
    return total

def silver_bimonth(distributor):
    bimonths = collections.defaultdict(int)
    for member in find_downline(distributor):
         for order in find_orders(member):
             date = order.created.date
             bimonth_index = (date.year * 12 + date.month) / 2
             bimonths[bimonth_index] += silver_in_order(order)
    return = max(bimonths.value)

def level(distributor):
    silver = silver_bimonth(distributor)
    return bisect.bisect_left(LEVELS, silver) + 1

Zero testing. Probably doesn't work. But it should give an idea of an alternate approach. Basically, I figure that since you are going to fetch all the orders anyways, it makes more sense to fetch them all figure which bimonthly period they belong to, and figure out the maximum that way.


Powershell Script to remove printers and drivers

Before relying on old VBS scripts, it pays to check what native PowerShell tools you have available:

PS> help printer

Name                              Category  Module                    Synopsis
----                              --------  ------                    --------
Add-Printer                       Function  PrintManagement           Adds a printer to the specified computer.
Add-PrinterDriver                 Function  PrintManagement           Installs a printer driver on the specified computer.
Add-PrinterPort                   Function  PrintManagement           Installs a printer port on the specified computer.
Get-Printer                       Function  PrintManagement           Retrieves a list of printers installed on a computer.
Get-PrinterDriver                 Function  PrintManagement           Retrieves the list of printer drivers installed on the specified computer.
Get-PrinterPort                   Function  PrintManagement           Retrieves a list of printer ports installed on the specified computer.
Get-PrinterProperty               Function  PrintManagement           Retrieves printer properties for the specified printer.
Read-PrinterNfcTag                Function  PrintManagement           Reads information about printers from an NFC tag.
Remove-Printer                    Function  PrintManagement           Removes a printer from the specified computer.
Remove-PrinterDriver              Function  PrintManagement           Deletes printer driver from the specified computer.
Remove-PrinterPort                Function  PrintManagement           Removes the specified printer port from the specified computer.
Rename-Printer                    Function  PrintManagement           Renames the specified printer.
Set-Printer                       Function  PrintManagement           Updates the configuration of an existing printer.
Set-PrinterProperty               Function  PrintManagement           Modifies the printer properties for the specified printer.
Write-PrinterNfcTag               Function  PrintManagement           Writes printer connection data to an NFC tag.
Out-Printer                       Cmdlet    Microsoft.PowerShell.U... Sends output to a printer.

So your script reduces to something like this:

$PrintersToRemove = @("Printer1", "Printer2")
$PrintDriversToRemove = @("Manufacturer1", "Manufacturer2")

Remove-Printer -Name $PrintersToRemove -WhatIf

$drivers = Get-PrinterDriver | ? Manufacturer -in $PrintDriversToRemove

foreach ($driver in $drivers)
{
    Remove-PrinterDriver -Name $driver.Name -WhatIf
}

Note that I didn't put in the removing excess printer driver logic. I'm not exactly sure what that does.

Note also the -WhatIf parameters. They stop the commands from actually executing. You would remove those when you are satisfied that the script will do what you want it to do.

Instead of putting comments at the top of the script, you can use the PowerShell help system:

<#
.SYNOPSIS
  Remove old printers by name

.DESCRIPTION
  [Add stuff here if you like.]

.PARAMETER PrintersToRemove
  (REQUIRED) An array of printers to cycle through and
  remove. Use the exact name of the printer to have it included in the list

.PARAMETER PrintDriversToRemove - (optional) An array of printer drivers to cycle
  through and remove. You can obtain a list by running the "prndrvr.vbs -l"
  command on a computer with drivers to remove. Alternatively, you can
  leave the array empty, and the script will remove any unused (determined
  by the system) print drivers automatically.

.NOTES
  Written by Luke Barone

.EXAMPLE
  Example 1

.EXAMPLE
  Example 2
#>

That way you can do a help MyScript -detail

It's probably a good idea to use parameters to the script rather than getting people to edit it:

[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [string[]]$PrintersToRemove,

    [Parameter(Mandatory=$false)]
    [string[]]$PrintDriversToRemove
    )

That way if you update the script, you can just copy it over the old one. The users don't have to merge them. You would make another script that contains the actual parameters, and that one would call this one.

One last thing, I like to put the following near the top of my scripts. It helps to avoid some bugs.

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'


Do either of these implementation really do what you seem to say they do (ensure that all visible items that are orderable are selected?)  Perhaps it's hard to tell without understanding whether one can "select" something that is "shown" but not "orderable".  If they can, then I think your logic is wrong and you should be comparing that all three number "shown", "selected", and "orderable" are equal.

I would consider refactoring. Just as you have methods for shownNumbers() why not add methods for getting all selected items and getting all items with orderable quantity.  So, perhaps something like this:

self.allselected = function () {
    return (self.shownNumbers().length === self.filterSelected().length &&
        self.shownNubers().length === self.filterNonzeroQuantity().length);
}

self.getAllSelected = function () {
    return self.shownNumbers().filter(function (number) {
        return number.isSelected();
    }
}

self.getAllOrderable = function () {
    return self.shownNumbers().filter(function (number) {
        return number.orderableQty > 0;
    }
}

Or, if you don't want to refactor then combine the conditions in a single filter.  This may or may not work depending on the my very first comments around method logic.

self.allselected = function () {
    var shownNumbers = self.shownNumbers();
    var selectedAndOrdereable = shownNumbers.filter(function (number) {
        return (number.isSelected() && number.orderableQty > 0);
    };
    return selectedAndOrderable.length === shownNumbers.length;
}

In either case, don't call shownNumbers() repeatedly in single method.  It is unnecessary. Get the result of shownNumbers() and work with it.

Consider naming your method something like areAllOrdereablesSelected() that a) indicates to caller that return value will be boolean (similar isSelected()) and b) better hints are what the underlying logic that the boolean represents is.   I would think allSelected as a method name would do what your first comparison condition in this method does - get all selected elements.

You might be able to optimize for performance and/or memory utilization by implementing loops and counters, but you must decide if it is worth it.


Simple Java program - Coding bat sumNumbers

There are a couple things you can do here to make things simpler. The first is to make your inner loop a while loop instead of a for loop. With this idea, you  can build up each number char by char, using Character.getNumericValue() which will return 1 for '1' etc. With charVal, we can incrementally build up our number by multiplying the by 10 and adding the new digit. When we reach a non-digit, we add the current num to our sum, and set sum to 0. Since the code now only operates one char at a time, we don't need i, or j either. With these changes, your updated code is

public int sumNumbers(String str) {
    int sum = 0;
    int num = 0;
    for (char ch : exampleString.toCharArray()) {
        int digit = Character.getNumericValue(ch);
        if (digit >= 0 && digit <= 9) {
            num = num * 10 + digit;
        } else {
            sum += num;
            num = 0;
        }
    }
    return sum + num;
}


Does checking for the Core.Instance.isLocalPlayer twice in my method constitute a bad design?

If you find yourself using a lot of if (type == x) do x else do y statements you can use inheritance. The problem with using if (type == x) throughout your code is that if tomorrow you add a new Agent, you have to add an extra else case in each place you do this.

Here's an example of how to improve that:

public bool SetConnection(byte connectionID)
{
    Agent agent = agentFactory.CreateAgent(Core.Instance.IsLocalPlayer);
    return agent.TryToEnterRoom(connectionId);
}


In general, you have some problems being consisten in your coding.

1) Formatting:

In your NodeGraph class you are not consistent in your indentation. Your createMatrx (which has a typo and should be called createMatrix) you are not using any indentation.

2) Access modifiers:

In your class Node2 you set your members private, as expected.

In your class Node you don't specifically set the access modifier as private for some members, and you set them explicitly publbic for others. I would expect all members to be private.

3) Naming:

Single character variable names are not very descriptive. Name your variables according to their purpose.


Counting consecutive selections of a given number when sampling integers in a range

You can use the itertools for this.

Just groupby the value to get groups of equal values, filter for the desired value, then get the length of each streak and finally take the max of that length:

from itertools import groupby

def longest_streak(values, desired_value):
    return max(len(list(group))
               for value, group in groupby(values)
               if value == desired_value)

(I think it should be streak, 4. b: "an uninterrupted series" and not strike.)

Then your main can code become this:

from random import randint

if __name__ == "__main__":
    desired_number = int(input("Desired number: "))
    lower_range = int(input("Lower range: "))
    upper_range = int(input("Upper range: "))
    iterations = int(input("Iterations: "))

    numbers = (randint(lower_range, upper_range) for _ in range(iterations))
    print("Biggest consecutive strike: ", longest_streak(numbers, desired_number))

Here numbers is a generator, so the function can just consume the numbers as they are generated (meaning that this will occupy at most len(group) space in memory).

if __name__ == "__main__": is a guard so that the code under it is only executed when directly executing this script, but not when importing from it.


1st questions with answers within X hours

a.CreationDate <= (DATEADD(HOUR, @HoursElapsed, a.CreationDate))

This first condition of your WHERE clause either needs to be removed or needs some explanation.

For any non-negative value of @HoursElapsed, this will always return true.  Perhaps, the intent was to use q.CreationDate as the third argument of the DATEADD function?

Otherwise, this condition just says:

x <= x + y

The <= can return true for any non-negative y value.  No matter the value of x, x plus some non-negative y will always be some number larger than (or in the case of y=0, equal to) x.

I don't like your indention style.  Specifically, in your CTE, I don't like that the AND in your WHERE clause gets the same indention level as the rest of the query.  In your main query, I don't like that your INNER JOIN have the same indention level as the rest of the query (and the WHERE appears to have a space in front of it.

Importantly, any SQL query has up to eight primary clauses.  WITH, SELECT, INTO, FROM, WHERE, GROUP BY, HAVING, and ORDER BY.  Everything else is a part of one of these clauses.  These 8 clauses should have zero indentation relative to the query as a whole, and everything else should be indented by at least one level (and I personally prefer four spaces, but I know SEDE default is two spaces).

Our major offender here is the massive list of INNER JOIN subclauses (helper elves?) within the FROM clause.

Keeping in mind the comments I already made about the first part of your WHERE clause, we could simplify the entire WHERE clause into simply just this:

WHERE a.CreationDate BETWEEN q.CreationDate AND DATEADD(HOUR,@HoursElapsed,q.CreationDate)

Our FROM can be massively simplified.

First, there's no reason our CTE can't include the CreationDate.  That completely eliminates the need for us to have the Posts table we labeled q.  And that can clean up some other nastiness, like q.PostTypeId = @QuestionType (our CTE already narrows that dataset down to just questions).

Bearing in mind the recommended change to the CTE (just add CreationDate to the select list), I recommend a FROM that looks more like this:

FROM AllFirstQuestions q
    INNER JOIN Posts as a ON a.PostTypeId = @AnswerType AND a.ParentId = q.Id
    INNER JOIN Users qUser ON qUser.Id = q.OwnerUserId
    INNER JOIN Users aUser ON aUser.Id = a.OwnerUserId

I'm guessing that a.PostTypeId = @AnswerType is probably unnecessary, but I don't know enough about SEDE.

I'm going to wager though that the Id column of the Users table is an indexed, auto-incrementing, non-null primary key.  We don't have to include a AND alias.OwnerUserId IS NOT NULL on joining it.  Any post with a NULL owner user id will be eliminated by virtue of the fact that there are no NULLs in the Id column of the Users table (and even if there were, null wouldn't join to null... I don't believe).

Finally, this is SEDE specific, but it doesn't make sense to allow the user to enter a decimal number for hours elapsed.  You're saving it as an INT, so it's immediately converted to an INT and the decimal part is lost before you even do anything with it.  Moreover, SQL's DATEADD (one place you use @HoursElapsed) takes an INT, so it doesn't make sense to even think about passing anything else here, and SQL's DATEDIFF (you compare result of this to @HoursElapsed) returns an INT, so it also doesn't make a whole lot of sense to compare to a floating point number here.  I think you just need to not allow the user to enter decimal places, since they're 100% ignored no matter what.  Allowing the user to enter decimal places gives the false impression that your query is doing something it's not.


Javascript Fibonacci with dynamic programming

Your code will accomplish the task of returning the Nth Fibonacci number and will do it quite fast.   But you are not getting the point of the video, how to do Memoization.

To improve your code:

Defining your variables at the beginning of your function.
Indent your if block and surround with { }

fibonacci: function (n)  {
  var array = [1, 1]; // prevent variable  hoisting
  var i = 2;          // defining var at start of function
  if (n === 0 || n === 1) {
    return 1;  // indent if block and surround with {}
  }
  for (; i < n; i++) {
    array.push(array[0] + array[1]);
    array.shift();
  }

  return array[0] + array[1];
}

Memoization is more efficient by storing or memorizing past results to get faster future results the NEXT time you call the function.  If you call fibonacci(701) then fibonacci(700), you will calculate the results both times.  If  you memoize the function you will look up the result on the second call.  If you call fibonacci(702) you will look up the last two values to get the next result.

You have NO memoized values.

function fibonacci (n, pastResults)
{
  var memo = pastResults || [1, 1]; //if no pastResults, set default value
  var i = memo.length;
  if (i > n) { // we have result
    console.log('looking up value')
    return {  //return 2 values
        pastResults: memo,
        result: memo[n-1]
    };  // return it
  }
  for (; i < n; i++) {
    memo[i] = memo[i-1] + memo[i-2];
  }

  return {
    pastResults: memo,
    result: memo[n-1]
  };
}

var r = fibonacci(7)
console.log(r.result) //13
r = fibonacci(5, r.pastResults);  // looking up value
console.log(r.result) //5
console.log(r.pastResults) //[1, 1, 2, 3, 5, 8, 13], these will not be recalcuated
r = fibonacci(22, r.pastResults);
console.log(r.result) //17711

Here is a more eloquent, but harder to understand solution.

Note, in my 13+ years of JavaScript development, I've never used Memoization in production code.

References:

...coming soon

...Bock scope vs Function scope reference soon

https://github.com/dwyl/Javascript-the-Good-Parts-notes#memoization


One approach would be to utilize .splice() instead of .slice() and .shift().

If the input array is expected to be mutated const copy = [...arr] can be removed and the array methods can be called on input arr : data

let data = [1,2,3,4,5,6,7,8,9,0];

const interweave = arr => {
  const copy = [...arr];  // copy input
  const r = copy.splice(Math.ceil(copy.length / 2)); // splice half of input
  for (let i = 1; r.length; i += 2) // set `i` to `1` increment by `2`
    copy.splice(i, 0, r.shift()); // use `.splice()` and `.shift()`
  return copy; // return `copy`
}

console.log(interweave(data));