Generic tree data structure for flat data from a database

GenericNode<T>

I'll adopt the name Node<T>, as Henrik Hansen has done.

This class is completely publically mutable, which is probably not ideal. Does it make any sense to change the NodeInformation once you've created the node? Maybe it does, but if not, then you should work to enforce the idea by making it immutable. I'd also wager it makes no sense to have a node without this information, so I'd add a constructor to this effect:

    public T NodeInformation { get; }

    public Node(T nodeInformation)
    {
        NodeInformation = nodeInformation;
    }

The children and parent properties are more tricky, as (without some effort), you can't know who who the children are upfront, and it's even more effort to make both the Children list and Parent immutable. Instead, let's make them privatelly mutable, and add an AddChild method, so that it's more difficult for an external entity to produce an invalid tree:

public Node<T> Parent { get; private set; }

private readonly List<Node<T>> _children = new List<Node<T>>();
public IReadOnlyList<Node<T>> Children => _children;

public void AddChild(Node<T> childNode)
{
    if (childNode.Parent != null)
        throw new ArgumentException(nameof(childNode), "Child node already has a parent");

    _children.Add(childNode);
    childNode.Parent = this;
}

Note that we have a List<Node<T>> so we can add children, but we only expose an IReadOnlyList<Node<T>>, so they can only be added (without dodgy casts) by means of the AddChild method.

IDbEntityNode

Again, everything here is publically mutable: I do not think it makes much sense to change the Id of something! As a general rule, immutable is good if you can have it. It's very easy to add a public setter back in, but it's potentially nightmarish to take it out.
You mentioned wanted more generic IDs: I'd be inclined to make this type generic, with both generic Ids and generic Data. You can always provide a 'convenience' concrete version which has int and string baked in. If you have generic Ids, you either need to make the type comparable, or you'll want to pass CreateGenericTree an IEqualityComparer<TId> to handle it (or you could assume the default comparer, but that's much less fun, and you can again provide a 'convenience' overload which uses it by default).

CreateGenericTree

Conceptually, this appears to create multiple trees, as oppose to one tree (as there can be many roots); should it be called CreateTrees?
You are repeatedly indexing into flatDataObject: much better to loop over something like i, which everyone knows is an index, and set element = flatDataObject[i] (or use a foreach as Henrik Hansen has said).
I think I'm in a minority, but I'd be strongly inclined to use a dedicated delegate type rather than Func<T, bool>. What question does Func<T, bool> answer? It is a horse? Is it lazily loaded? I don't know. You might consider then something like, but a lot of people dislike nominal delegates, for various reasons.

public delegate bool RootDetector<in T>(T node) where T : IDbEntityNode

You are returning a List<T>, and there is a good chance that you could just as well return a more abstract type, such as IList<T> or IReadOnlyList<T>. This give you freedom to change the actual returned type later (e.g. if you change the implementation) without having to change the return type, and if it turns out later that you need some members of a less abstract type, then you can more easily change an abstract return type to less abstract return type than you can the other way round.
You are also taking List<T> as a parameter. As someone consuming your API, this would concern me, as List<T> is openly mutable, and I would unsure whether your code is going to modify what I pass it. Much better to use an abstract type like IReadOnlyList<T>, which gives the caller more freedom, and communicates immediately that you are not going to modify the parameter.
Your code will currently heave oddly if the flatDataObject contains nodes with the same Id. Unfortunately, checking for this would be ugly.

Below is my take (you'll note it's pretty similar to Henrik Hansen's code).

public static IReadOnlyList<Node<T>> CreateTrees<T>(IEnumerable<T> flatDataObjects, RootDetector<T> isRoot) where T : IDbEntityNode
{
    if (flatDataObjects == null)
        throw new ArgumentNullException(nameof(flatDataObjects));
    if (isRoot == null)
        throw new ArgumentNullException(nameof(isRoot));

    var nodes = flatDataObjects.ToDictionary(fdo => fdo.Id, fdo => new Node<T>(fdo));

    List<Node<T>> roots = new List<Node<T>>();

    foreach (var node in nodes.Values)
    {
        if (isRoot(node.NodeInformation))
        {
            roots.Add(node);
        }
        else
        {
            if (nodes.TryGetValue(node.NodeInformation.ParentId, out var parentNode))
            {
                parentNode.AddChild(node);
            }
            else
            {
                throw new InvalidOperationException($"Non-root node {node.NodeInformation.Id} has ParentId {node.NodeInformation.ParentId}, but no node exists with that id");
            }
        }
    }

    return roots;
}

Note that I've added dedicated checks for null parameters, and that upon detecting an invalid input (a node with no parent) I throw a helpful error message. Note also that ToDictionary will throw if two elements have the same key (Which is good), though the message will be less helpful: you could actively trap this exception and throw your own explanation, or otherwise you could manually detected duplicates and throw first/write your own version of ToDictionary to achieve the same.

I would argue that these LINQy versions are much more readable, because each bit of logic is mostly self contained. Even clearer would be to select the roots only at the very end, but there is a good case to be made that calling isRoot as few times as possible is desirable, as we don't know what it does, and partitioning the dictionary would introduce complexity.

Boring things

IsRootNode is a method parameter, and usually these are in lowerCamelCase (e.g. isRootNode). Note that it has the same name currently as the method you are passing to it, which means if you change it to isRootNode you might forget to change the usage if the method is in scope, and then you have a problem (C# warns about unused variables, but not unused parameters).
Pay attention to your white-space: inconsistent white-space can make perfectly good code terribly untidy-looking, and a few more line-breaks here-and-there really help to break up the logic and make the code easier to scan.


Advice on approach to organizing my business logic & data access?

By reviewing this I have two general comments to your code:

Transaction

Is there any reason to use explicit transaction scope? When you call SaveChanges on the context it already uses transaction. It either uses ambient transaction or create a new one database transaction. So unless you are using multiple transactional resources (multiple database connections, MSMQ, etc.) or calling SaveChanges multiple times you don't need to create transaction explicitly. It is point of unit of work to save changes as one atomic unit. Also one side note: Default transaction used in SaveChanges uses default (or current) isolation level configured on database connection. Default for SQL Server is ReadCommitted. Default isolation level for TransactionScope is Serializable.

Testing

You mentioned that you want to make this abstraction to be able to replace context for testing. If you mean unit testing you can stop and go back to redesign your interfaces. You cannot unit test your business layer code if it uses IQueryable (Linq-to-entities) exposed by your data access layer. There is currently no provider which can simulate linq-to-entities behaviour for your unit tests. Once you use same in memory collection to mock IQueryable you will use linq-to-objects in your unit tests instead. That means you will test different code.

The only correct way is either:

Not expose IQueryable from your DAL. Keep all linq-to-entities queries as internal implementation of your repositories (= you must materialize result in repositories by for example calling .ToList).
Use integration tests against real test database instead of using unit tests with mocked data access layer

I wrote several answers about this problematic on Stack Overflow:

Unit testing DbContext
Using the repository pattern to support multiple providers

Check also linked answers in those questions.


Parsing URL query and appending it at end of the other URL

I'd write it like this

function concatQueryVars($first, $second) {
    $url = strtok($first, '?');
    $first = parse_url($first, PHP_URL_QUERY);
    $second = parse_url($second, PHP_URL_QUERY);
    return !empty($url) &&
           !empty($first) &&
           !empty($second)
           ? $url . '?' . $first. '&' . $second : false;
}

echo concatQueryVars('http://example.com/?a=b', 'http://example.com/?c=d&e=f');

Result:

  http://example.com/?a=b&c=d&e=f


Text Analyzer - Properly implementing Java coding style

Single responsibility principle

The main method does most of the job.
It would be better to split that up to smaller methods,
in a way that each method has a single responsibility.
You will end up with something more modular, reusable, testable.

Make variables local when possible

stringBuffer is only used within the main method,
so doesn't need to be a member variable.
Declare it right before you need it,
in fact, it's best at the time of initialization:

StringBuffer stringBuffer = new StringBuffer();

Avoid static variables when possible

None of the static variables were needed.
In general, avoid static variables as much as possible,
especially if they are mutable.

wordCount is not as simple to eliminate as stringBuffer,
but still easy enough:
make getWordsCount return a Map<String, Integer>.

Use the enhanced for-each loop

Instead of this:

for (int i = 0;  i < l.size(); i++) {
    s2 = s2 + l.get(i) + "\n";
}

Since you don't need the index values and it's just clutter,
the recommended writing style is this:

for (String word : l) {
    s2 = s2 + word + "\n";
}

This has another advantage that in this form the loop can work efficiently not only with an ArrayList, but with a LinkedList too,
because elements are no longer accessed by index.

Use boolean expressions directly

Instead of this:

    while (scanner.hasNext() == true) {

You can and should write this:

    while (scanner.hasNext()) {

Refer to types by interfaces

Instead of this:

private static HashMap<String, Integer> wordCount = new HashMap<String, Integer>();

This would be better:

private static Map<String, Integer> wordCount = new HashMap<String, Integer>();

Use Java 7

I'm guessing you're using an older version because of things like this:

List<String> l = new ArrayList<String>(s);

Starting from Java 7 you don't need to specify the type parameters at the right hand side of expressions, the compiler can figure them out most of the time, and you can use the diamond operator <> like this:

List<String> l = new ArrayList<>(s);

Unused imports

You have some unused imports:

import java.io.FileNotFoundException;
import java.util.Map;

I'm surprised your IDE doesn't warn about them.
In fact it probably does.
Strive to keep warnings to minimum, ideally down to zero.

Extremely poor names

In this code,
the variable names s, l, s2 are bordering obfuscation.

Set<String> s = wordCount.keySet();
List<String> l = new ArrayList<>(s);
Collections.sort(l);
String s2 = "";
for (int i = 0;  i < l.size(); i++) {
    s2 = s2 + l.get(i) + "\n";
}

Sure you can come up with better names for these,
which will make the code so much more readable.

Prefer StringBuilder over StringBuffer

StringBuffer synchronizes internally to make it thread safe.
This is rarely needed in practice,
and in this example it's completely unnecessary.
Use StringBuilder instead.

Btw, is there a benefit to accumulating the output in memory before producing the output? Probably not.
You could just write the output directly,
without building up a long string.

Put braces consistently

In this code, you put braces for the if, but not for the else

if (tokenCount == null) {
    wordCount.put(token, 1);
} else
    wordCount.put(token, tokenCount + 1);

At the minimum, be consistent.
The recommendation is to put braces always.


I'm not going to address what else you could test, since it really depends what you're expecting your Polynomial class to do.  However, looking at your test, there's several things that could be improved.
Test One Thing
Having all of your assertions in the same test means that the test can fail for multiple different reasons, some of which are unrelated.  Consider modifying your tests so that they contain the complete AAA for what they are testing.  This makes it much clearer what the relationship between the data setup in the Arrange phase is, to the Assertions made.
As an example, your code current does this:

int [] c1 = {0, 0, 0, 1};
Polynomial p1 = new Polynomial(c1);
c1[2] = 1;
assertEquals("Degree error", 3, p1.getDegree());
assertEquals("Polynomial must compute coefficients out of range", 0, p1.getCoefficient(-1));
assertEquals("Polynomial must compute coefficients out of range", 0, p1.getCoefficient(4));
assertEquals("Array is not immutable", 0, p1.getCoefficient(2));

There's three unrelated assertions between the point where you modify your array (c1[2] = 1) and the assertion that it impacts 'Array it not immutable'.  This make far less obvious what the 'c1[2] = 1' is doing there.
Having multiple tests, where each one tests only a single thing also means that you don't need to put a message in each of your assertEquals calls.  The test name itself tells you what you're testing.
Duplicate tests
Sometimes you want to test the same thing in different scenarios.  Other times, it doesn't make as much sense.  I'm pretty sure that if the array is immutable for c1, it will also be immutable for c2, testing it again doesn't seem like it's really adding value.  If you do want to test the same thing, with different values, consider using parameterised tests.  Something like this:
@ParameterizedTest
@MethodSource("coefficients_outOfRangeCoefficient")
void getCoefficient_outOfRange_computesZero(int[] coefficients, int outOfRangeCoefficient) {
    Polynomial polynomial = new Polynomial(coefficients);
    assertEquals(0, polynomial.getCoefficient(outOfRangeCoefficient));
}

static Stream<Arguments> coefficients_outOfRangeCoefficient() {
    return Stream.of(
            arguments(new int[] {0,0,0,1}, -1),
            arguments(new int[] {0,0,0,1}, -4),
            arguments(new int[] {-1,0,0,0}, -1),
            arguments(new int[] {-1,0,0,0}, 4)
    );
}

Would allow the same test to be used across four different combinations of coefficients and get indexes.


Design

I'm guessing you're coming from some sort of Object-Oriented Programming Language (OOPL), like Java. Python is an interpreted language, and while treating it like an OOPL isn't bad in many large scale scenarios, something small like this doesn't need that design. If this is for some kind of scholastic exercise or you're just training OOPL design in Python, you can stick to it, but personally I'd avoid it here.

Printing & Strings

Pasting out each array index isn't necessary. Instead of using the modulo operator to format strings, you can either use .format() or f-strings. For the board prompt I'd personally use .format(), like so:

print(' {} | {} | {} \n===+===+===\n {} | {} | {} \n===+===+===\n {} | {} | {} \n'.format(*list(n for n in self.board)))

You use variadic assignment in three_in_row, so I'm assuming you know the four use cases of the asterisk.

I notice you use double quotes a lot in your main code but not in the actual main function, so maybe that was pregenerated by an editor like VSCode? Regardless, you can use single quotes more throughout your code.

Game & Logic

None checks and usage seem to be quite frequent throughout this program. Again, this indicates to me some beginner OOP ideology. We all start somewhere, but as it is in good OOP design to not explicitly use null where possible, the same can apply to None here.

In your eval_board function, you prioritize the fourth, or central, spot for the AI.  Why not just check this outside of the loop, and then start it if it fails? This function appears to be used exclusively by the AI as well, so why isn't it named something like ai_move or ai_eval to reflect this? Other functions could benefit from this naming as well. Also, using while loops and checking for a None spot seems like a bad substitution for Boolean functions and checks in my mind.

Conveniently, I've also put up a Tic Tac Toe question, which is here: Back to Basics - Tic Tac Toe

Any comments I'd have on optimizing your game logic would just be incorporating some of the techniques used in my implementation. Granted, I don't have an "AI," but the imagination shouldn't need to flex over the available possibilities.


Is it advisable to integrate SQL statements in the JSP pages that are not displayed to the user but handled at the back?

General advice

  I know that it is not advisable to include the database interaction in
  the JSP page but as this page would be handled in the backend without
  any direct interaction from the user I'm very tempted to use
  check_email.jsp as above.

It's a good thing when you know that something is wrong to search for a better way to do it. This is an important part of having good code in my opinion.

What you must not do, is code something that you know is not right, but look like having no impact of security or side effects. There is a chance that you won't be the last programmer on this code. What will happen if he decide that the view is more publicly accessible ? (In this case not much since from my understanding, JSP tag are interpreted server-side)

There is one thing you know for sure, that if this code is in the server/controller/service, it will be where he belong!

Re-usability

This SQL request looks to me like a request that could be re-use in different in an application. Will paste it everywhere you need it or would ratter call a service that will return the result of the query ? The second option look better to me.

I can't provide a good example of a service without knowing what framework you use. There is plenty of resource on the internet that could help you, I could point you some tutorials if I could know what your set-up is.

Quick note

In your JavaScript you have var url = "../ajaxPages/check_email.jsp?email="+email;. Are those pages suppose to be responses to AJAX request ? If so, you should know that you can probably create a controller that do respond to AJAX request. In my opinion, this will help you keep all the important logic in the controller and remove some JSP pages that I guess are not doing what they should be doing.


Compute and Display Engineering Information

This is a pretty incomplete code example, but let me give you some initial thoughts:

Use meaningful class and variable names. Spec seems very indeterminate as to what the class does. $sg, $q, and $n also convey little value (though perhaps that is because these are common scientific formula names that I am not fully familiar with.
Don't have the class output directly to standard output (which is what I assume the dump() function does.  Consider actually logging to server logs, or have it returned as part of the method return value so that caller can determine how to display it.
I almost question the need for this to be a class at all if this is only going to have a single method. It is very unclear how class properties are set. If all you are going to do is instantiate an object, use several methods to set properties (or directly set since these are public), and then call a single method, I don't see why this could not just be a function, or just static class method, as I do not understand what value you get by instantiating the class.  Perhaps if you had a constructor where you passed in and validated the variable values or, better yet, interacted with the DB to set these values, there would be value in having a class.
Do you really want to directly json_encode the object?  If you do, you might consider implementing the JSONSerializable interface, which would allow you to implement a jsonSerialize() method where you could specifically control the data structure that is sent to json_encode() for serialization. For example, if you wanted to make properties protected/private but still be able to see them in JSON output, you could build a stdClass object or associative array with key-value pairs describing the object, which would then be serialized.
If your code needs to be compatible with potentially older versions of PHP (i.e. < 5.4), you should probably not use short echo tag syntax (i.e. <?=$json?>)

Since you know have complete class information, I have updated my answer to give more specific review comments on your code below.  My comments are within multi-line comments.

/*
Class name seems non-specific
*/
class Spec
{
/*
Typical style guides would have class properties defined before class methods.
All methods should have visibility (i.e. public, protected, private) explicitly
defined.
Consider using a constructor such that you could do something like:
$spec = new Spec($id);
Where the constructor could call the load method. This would allow you to make
load method private, meaning calling code couldn't destructively reload
the object.  This will also allow you to validate the id input as integer
value greater than zero before trying to do any further work in instantiating
the class.
If you are going to use PHPDoc, use it on every method and property as well as
class itself. Don't partially use documentation.
*/
    function load()
    {
/*
Consider working with DB in an object-oriented fashion, with database object
dependency being passed to this class on instantiation.
Consider using parametrized prepared statements here rather than string
interpolation.  String interpolation raises question as to whether you might
be opening up an SQL injection vulnerability.
Don't use 'SELECT *'. It makes expected return results unclear to the code
reader and also potentially negatively impacts performance if you end up
retrieving more fields than necessary.
This DB interaction only considers happy path. What if query fails for some
reason?  What if an empty result set is returned?
*/
         $result = db_query("SELECT * from spec where id = {$this->id}");
         $row = db_fetch_array($result);
         $this->n = $row['n'];
         $this->sg = $row['sg'];
         $this->q = $row['q'];
    }

    /**
     * Computes and returns Pressure
     * Outputs debug info
     * Assigns internal parameter
     *
/*
"number" is not a valid @return type. It looks like you should be using "float".
*/
     * @return number
     */

/*
I really don't understand why you would need to make this method publicly
available. If you had a constructor, you could pass that constructor the id
(as well as a valid DB object if you choose to work with DB in OO fashion)
and then execute private load and calcPressure methods, setting up the object
for its intended use directly upon instantiation.
*/
    function calcPressure()
    {
        $res = abs($this->n * sqrt($this->q) / 15164.93 * $this->sg);
/*
Don't output from this class.
*/
        dump("  *** <u>Pressure</u> = $res");
        $this->pressure = $res;
/*
You would probably not need a return if you made this private method called
from constructor.
*/
        return $res;
    }
/*
Consider whether these should be public.  My guess is that they shouldn't be
unless you REALLY want the object to be mutable since you are reading this
information from a database and haven't shown an update method.
If you do intend to make the object mutable, then it still probably makes sense to make these private so that you can have proper setters that can trigger
methods to update the database and recalculate pressure.
If you make them private, you would obviously need to implement getters or
__get() magic method to allow caller to get to the information.
As you begin to work more with OOP, you will likely find that the use cases
for truly public properties are fairly limited.
*/
    public $pressure;

    public $sg;

    public $q;

    public $n;

    public $id;
}


Recreate Mario's half-pyramids using hashes (#) from CS50

Your code is quite nice. Your use of functions seem quite reasonable. And your style is nice too. Good job!

Calling print is expensive. To improve performance we can build the strings without using the for loop. For example to build \$n-(i + 1)\$ spaces we can use:
>>> n = 12; i = 1
>>> " " * (n - (i + 1))
'          '

To build the pyramid you can delegate the creation of the spaces to Python by using str.ljust and str.rjust.
These functions allow an easy to use way to build the pyramid.
>>> 'abc'.ljust(10)
'abc       '
>>> 'abc'.rjust(10)
'       abc'

Using print_spaces(l, n) is harder to understand than print("  ").

Your use of comments are not great. Most of them can be understood by just reading the code.
I only found one of your comments to help.
Because it explains something that isn't particuarly clear in clear English.
# there's two spaces between two pyramid. at the print_spaces function range(n - i+1)
# so initialize l = 1 and n = 4, would always give (4-(1+1)) = 2

However this is a sign that your code is complicated.
Which if you fix will make your comment redundent.

If we put these together we can greatly simplify your code.
from sys import exit
from cs50 import get_int

def main():
    while True:
        num = get_int("Height: ")
        if num >= 1 and num <= 8:
            break

    print_pyramid(num)
    exit(0)

def print_pyramid(n):
    for i in range(n):
        hashes = "#" * (i + 1)
        print(hashes.rjust(n) + "  " + hashes)

main()

There are still some more improvements that can be made.

Using sys.exit(0) is abnormal. It is normally best to just let Python handle that for you.

We can add an if __name__ == "__main__" guard to prevent your code from running if you import it accidentally.
This is because if you use import filename you can import this program by accident and we don't want to run the main function if that happens.

I personally am a fan of always using the < operator.
It just feels natural to see numbers ordered from smallest to largest, left to right.

We can Pythonify the print in print_pyramid by using the Format Specification Mini-Language.
There are three parts to this.

By using a format string we can enter values where we want them in a formatted string.
>>> a = 1; b = 2; c = 3
>>> f"{b}:{a} -> {c}"
'2:1 -> 3'
>>> "{b}:{a} -> {c}"  # Not a format string
'{b}:{a} -> {c}'
>>> "{b}:{a} -> {c}".format(a=a, b=b, c=c)  # Old style format strings
'2:1 -> 3'

We can use the alignment option to align the values where we want them to.
>>> a = 1; b = 2; c = 3
>>> f"{b:>3}:{a:<3} -> {c:^3}"
'  2:1   ->  3 '

We can enter the width using the same {} syntax as the values.
>>> a = 1; b = 2; c = 3; width = 3
>>> f"{b:>{width}}:{a:<{width}} -> {c:^{width}}"
'  2:1   ->  3 '

from sys import exit
from cs50 import get_int

def main():
    while True:
        num = get_int("Height: ")
        if 1 <= num and num <= 8:
            break
    print_pyramid(num)

def print_pyramid(n):
    for i in range(n):
        hashes = "#" * (i + 1)
        print(f"{hashes:>{n}}  {hashes}")

if __name__ == "__main__":
    main()


Check the validity of a South African ID number using the Luhn Algorithm

Let's work through some of the simpler issues, like code redundancy, and some helper-functions in the core library that help a lot, and will make your code simpler.

Double-checking else

When you have an either-or check in an if-condition, there's no need to double-check the else side of things.

you check for odd-positioned digits, which implies every other digit is even-positioned... This code:

if(x % 2 == 0 ){
    .....
}else if(x % 2 != 0){
    .....
}

can be just:

if(x % 2 == 0 ){
    .....
} else {
    .....
}

Try-Catch

There's no code in your function that throws an explicit exception - why do you have a try/catch? All integer parsing comes from digits in a BigInteger, so there can be no illegal characters, etc.

Character-to-digit-value

Your code has a lot of this type of logic:

String numString = String.valueOf(chars[x]);
int numbers = Integer.valueOf(numString);

but that can be simplified to just:

int numbers = Character.getNumericValue(chars[x]);

Separated sums

You have both sumOdd and sumEven, but there's no need for both. You can have one sum accumulator and use it in each side.

Simplifying the doubled digits

The algorithm requires doubles that are larger than 9 to be reduced by 9. Your code is:

int doubled = numbers * 2;
if(doubled > 9){
    _doubled = doubled - 9;
}else{
    _doubled = doubled;
}
sumEven += _doubled;

Using a "ternary" expression, and a little bit of manipulation on the math, you can reduce that to just:

sum += digit < 5 ? digit * 2 : digit * 2 - 9;

Autoboxing and conditionals

Java will "autobox" primitive variables like boolean to their full class types Boolean when needed, without any explicit handling. Let's take this exit segment:

if((summation * 9) % 10 == checksum)
    return Boolean.TRUE;
else
    return Boolean.FALSE;

This should have braces on the 1-liners, to be:

if((summation * 9) % 10 == checksum) {
    return Boolean.TRUE;
} else {
    return Boolean.FALSE;
}

but really, that's all unnecessary, because autoboxing comes to the rescue:

return (summation * 9) % 10 == checksum

That's all you need.

Conclusion

Putting all these suggestions together, you can significantly reduce the complexity of the code, to something like:

public static Boolean getIdentitySummationRL(BigInteger identities){
    char[] idchars = identities.toString().toCharArray();
    int sum = 0;
    // loop over each digit, except the check-digit
    for (int i = 0; i < idchars.length - 1; i++) {
        int digit = Character.getNumericValue(idchars[i]);
        if ((i % 2) == 0) {
            sum += digit;
        } else {
            sum += digit < 5 ? digit * 2 : digit * 2 - 9;
        }
    }
    int checkdigit = Character.getNumericValue(idchars[idchars.length - 1]);
    int compdigit = (sum * 9) % 10;

    return checkdigit == compdigit;
}

(I have checked that using my ID number, and it's OK)

Update

Note I have been doing a little more reading on Luhn's algorithm because of @Molvalio's comment and also I remember doing it a couple of decades ago for other numbers (not ID numbers) and I remember the checking algorithm to be different to this implementation. I was right that checking the number is simpler than your code. See the algorithm here: Luhn's Algorithm Verification

The point is that your code is computing a check-digit and comparing it with the existing digit, but you're missing the fact that the digit is designed to be incorporated in to the same calculations as the checksum, and a valid number has a resulting digit of 0.

Additionally, the Luhn's algorithm is computed right-to-left. In your case, because the length of SA ID numbers is 13, you're OK (both left and right digits are odd) but you should implement the algorithm more closely....

So, the code can be simplified further:

public static Boolean checkLuhn(BigInteger identities){
    char[] idchars = identities.toString().toCharArray();
    int sum = 0;
    // loop over each digit right-to-left, including the check-digit
    for (int i = 1; i <= idchars.length; i++) {
        int digit = Character.getNumericValue(idchars[idchars.length - i]);
        if ((i % 2) != 0) {
            sum += digit;
        } else {
            sum += digit < 5 ? digit * 2 : digit * 2 - 9;
        }
    }
    return (sum % 10) == 0;
}


Input Validation

You aren’t completely validating input

X: a1
O: b2
X: a2
O: a3 (block)
X: a3 For the Win!?

Invalid Win/Draw Detection Logic:

X  O  X
O     O
X  O  X

Last move in centre: “Aw, it’s a draw!”???

exit()

This is a bad function to use.   It exits the Python interpreter.   Unconditionally.  Period.

When you want to change your code to play repeated games, run unit tests, etc., you won’t be able to.  Nothing will execute after exit().

Better would be to move the code into a function, and simply return to force an exit of the current local context, instead of an exit of the entire interpreter.

f-strings

You are using {} and .format() in print_board, and using %s and %d in "..." % (...) expressions.  Usually, you should try to avoid mixing formatting methods.  Both are awkward to use, as the value and the place the value goes are far apart in the code.  Avoid using the % style.

Additionally, instead of:

print('%s won in %d turns! Congratulations!' % (user, turn))

using an f-string moves the variables inside the format string:

print(f'{user} won in {turn} turns! Congratulations!')

(I’d leave the print_board function alone, but in other print formatting, f-strings are a win.  )


In terms of you where to put the eval function, both are fine really. I have seen bits of both in libraries likes cats or scalaz. And given how easily you get one from the other, it does not make a massive difference architecturally.

However, I see a few issues on the side of validating your expressions, that I am honestly acking to improve :)

1) Both sides of an expression can result in an error, but you will show only one of them to the user.

2) These nested match-case expressions can be massively simplified by using one of the many functional validation libraries.

Let me attempt to solve both of these by using Scalactic's validation:

import org.scalactic._
import Accumulation._

object Arithmetics extends App {

  sealed trait Expression {
    def eval: Double Or Every[String] = this match {
      case Addition(l, r) => withGood(l.eval, r.eval)(_ + _)
      case Subtraction(l, r) => withGood(l.eval, r.eval)(_ - _)
      case Division(l, r) =>
        def isNonZero(i: Double) = if (i != 0) Pass else Fail(s"divisor evaluated to zero: $r")
        withGood(l.eval, r.eval.when(isNonZero))(_ / _)
      case SquareRoot(v) =>
        def isGreaterThanZero(i: Double) = if (i >= 0) Pass else Fail(s"Expression under square root evaluated to $i (<0): $v")
        v.eval.when(isGreaterThanZero).map(Math.sqrt)
      case Number(v) => Good(v)
    }
  }
  final case class Addition(left: Expression, right: Expression) extends Expression
  final case class Subtraction(left: Expression, right: Expression) extends Expression
  final case class Division(left: Expression, right: Expression) extends Expression
  final case class SquareRoot(value: Expression) extends Expression
  final case class Number(value: Int) extends Expression

  val failing = Addition(SquareRoot(Number(-5)), Division(Number(1), Subtraction(Number(1), Number(1))))
  println(failing.eval)
  // Bad(Many(Expression under square root evaluated to -5.0 (<0): Number(-5), divisor evaluated to zero: Subtraction(Number(1),Number(1))))

  val valid = Addition(SquareRoot(Number(25)), Division(Number(1), Number(2)))
  println(valid.eval)
  //Good(5.5)
}

You can see that you can get multiple errors at once, and much fewer lines of code, plus a human readable syntax.

In case you want to stick with your custom Calculation, it could look like this:

object Arithmetics2 extends App {

  sealed trait Calculation[A] {
    def map[B](f: A => B): Calculation[B] = this match {
      case Success(value) => Success(f(value))
      case Failure(errors) => Failure(errors)
    }
    def zip[B](other: Calculation[B]): Calculation[(A, B)] = (this, other) match {
      case (Success(valueA), Success(valueB)) => Success((valueA,valueB))
      case (Failure(errorsA), Failure(errorsB)) => Failure(errorsA ++ errorsB)
      case (_, Failure(errors)) => Failure(errors)
      case (Failure(errors), _) => Failure(errors)
    }
    def filter(f: A => Boolean, msg: A => String): Calculation[A] = this match {
      case Success(value) if f(value) => Success(value)
      case Success(value) => Failure(List(msg(value)))
      case Failure(errors) => Failure(errors)
    }
  }
  case class Success[A](value: A) extends Calculation[A]
  case class Failure[A](errors: List[String]) extends Calculation[A]

  sealed trait Expression {
    def eval: Calculation[Double] = this match {
      case Addition(l, r) => l.eval.zip(r.eval).map{ case (a,b) => a + b}
      case Subtraction(l, r) => l.eval.zip(r.eval).map{ case (a,b) => a - b}
      case Division(l, r) =>
        l.eval.zip(r.eval.filter(_ != 0, _ => s"divisor evaluated to zero: $r")).map{ case (a,b) => a / b}
      case SquareRoot(v) =>
        v.eval.filter(_ >= 0, i => s"Expression under square root evaluated to $i (<0): $v").map(Math.sqrt)
      case Number(v) => Success(v)
    }
  }
  final case class Addition(left: Expression, right: Expression) extends Expression
  final case class Subtraction(left: Expression, right: Expression) extends Expression
  final case class Division(left: Expression, right: Expression) extends Expression
  final case class SquareRoot(value: Expression) extends Expression
  final case class Number(value: Int) extends Expression

  val failing = Addition(SquareRoot(Number(-5)), Division(Number(1), Subtraction(Number(1), Number(1))))
  println(failing.eval)
  // Failure(List(Expression under square root evaluated to -5.0 (<0): Number(-5), divisor evaluated to zero: Subtraction(Number(1),Number(1))))

  val valid = Addition(SquareRoot(Number(25)), Division(Number(1), Number(2)))
  println(valid.eval)
  //Success(5.5)
}

Notice that it actually is not that lengthy/hard to make some decent validation mechanism.
Once you get a bit more into functional programming, you will see that functions like map, filter or zip can be found in many places. You will find them for example on most collections, like List.


Instead of doing SELECT TOP 10 * FROM ... you should only retrieve the columns needed which in your case is LineName.
var name = "" doesn't need to be there, if you just return firstOrDefault.LineName and for no result/exception return string.Empty.
While we are at var firstOrDefault I would like to say that using var here is just wrong because it isn't clear from the right side of the assignment what the type is. The variable name firstOrDefault isn't descriptive enough so you should consider using maybe geographyLine or foundGeographyLine.
You are selecting the TOP 10 but using FirstOrDefault. This just doesn't seem right. Using SELECT TOP 1 would be much better and faster.


I think display() and userInput() would be clearer if you did it like this:

def display(self):
    """
    Display the menu alongside the navigation elements
    """
    response = None
    while response is None:
        # Display menu buttons
        for button in self.menu:
            print "   ", button.nav, button.name

        # Wait for user input
        response = self.userInput()

def userInput(self):
    """
    Method to check and act upon user's input
    """
    inputSel = raw_input("Enter selection> ")
    for button in self.menu:
        # If input equals to button's navigation element
        if inputSel == str(button.nav):
            button.do()
            return inputSel

    return None

So display() keeps showing the menu as long as userInput() returns None. userInput() returns None if the user's input doesn't match a button, or the inputSel value if it does match.

I think the way the Controller loops is fine. The program will always stop when it gets to raw_input() and read stdin until the user hits ENTER or RETURN. That's what raw_input() does.

You're managing your buttons as a list, which means you have to scan the whole list until you find the navigation element the user selected. If you put them in a dict, you can simply use the user's input to index directly into the structure and select the correct button (or determine that the user's selection is invalid). However, you still want them as a list for display because you can't control the order in which entries are pulled from a dictionary and I think you want your menu to display in the same order every time. That needs a list.

I would suggest the following for the constructor for the Display class. We're going to pass in a list so it's easy to define, and we'll keep the list, but we'll also have the class internally turn that list into a dict so it can more easily find the user's input on each selection.

class Display
    def __init__(self, menu):
        self.menu_list = menu
        self.menu_dict = {}
        # Initialise values
        for button in menu:
            self.menu_dict[button.nav] = button

With the simplification in userInput() and display() above, the shouldCycle member goes away. Now, with the menu defined internally as a dictionary (self.menu_dict) and as a list (self.menu_list), display() and userInput() will look like this:

def display(self):
    """
    Display the menu alongside the navigation elements
    """
    response = None
    while response is None:
        # Display menu buttons -- use the list so we get the same
        # order every time.
        for button in self.menu_list:
            print "   ", button.nav, button.name

        # Wait for user input
        response = self.userInput()

def userInput(self):
    """
    Method to check and act upon user's input
    """
    inputSel = raw_input("Enter selection> ")
    try:
        # Here we use the dictionary for ease of lookup
        button = self.menu_dict[int(inputSel)]
    except KeyError:
        # The user's selection didn't match any of the button.nav
        # values, so we got a KeyError exception on the dictionary
        return None

    button.do()
    return inputSel


Logging conditionally repetitively in code

There are a few remarks that come to my mind.
Simplifying the logic
In your sample code, the two different log strings for success and failure don't differ too much. So I guess the following strings might be acceptable to you as well:
"Setting read callback hook: successful"
"Setting read callback hook: FAILED with status nnn"

Then you can create a static method statusText(int status) e.g. in a Utils class that returns "successful" for status==0 and "FAILED with status nnn" in all other cases. If I understood correctly, such a statusText() method should be re-usable all over your application, assuming that 0 always means success.
And then you can do the logging like:
LOGGER.info("Setting read callback hook: " + Utils.statusText(status));

But there are a few other issues:
Log Levels
Log4J has different log levels, and you shouldn't ignore that aspect. Depending on the consequences, a failure should typically get the ERROR level, at least the WARN level. So, in case of a non-zero status, LOGGER.error() seems to be a better choice.
INFO is meant for messages useful to the system administrator running the site. Messages targetting the developer should get a lower level, typically DEBUG or TRACE. I guess, the success of setting some callback isn't important to the system admin. The admin typically only wants to see things needing his/her special attention. So, I'd change the success case to LOGGER.debug().
Of course, then my statusText() solution no longer fits, as that doesn't support different log levels.
Why not Exceptions?
Your code sticks to the 1970s status code pattern to communicate failure (return an integer where some values mean success and others mean failure). By the 1990s, the software industry had learned that error handling can be done in a better way using exceptions.
So, instead of returning int values and forcing each and every layer of your software to check for the success results, throw an exception if something like setting a callback failed. By embracing exceptions as the signal of failure, your code typically becomes

cleaner,
more readable,
more compact,
more focussed on the main task instead of the failures
and more robust.

The simple guidelines for exceptions are:

If a method can't fulfill its job (whatever you defined that job to be), it throws an exception.
If a method returns normally, the caller can rely on the fact it has successfully done its job.
You catch an exception only if you know a way how to continue successfully even after an internal failure, e.g. by retrying.


Laravel time-punching database structure

I'm assuming what you want, ultimately, is show a list of all tuples (user, punch_in_time, punch_out_time). If so, the schema you showed does work, though the query would be ugly. One answer might be to have two tables:

ActivePunches(user_id, punch_in_time)

and

CompletedPunches(user_id, punch_in_time, punch_out_time)

When a user who isn't in the active list punches in, you add them to ActivePunches. When an active user punches out, you delete their active record and move it to completed. All other state transitions are illegal. You could also collapse these two into a single table (with an extra state column), but the nature of the problem indicates you might want to keep records for a long time, in which case you want to avoid reading a huge index, so this separation gives you a bit of a performance gain.


Simplify an if else construct with assignment before if and else

def find_eulerian_tour(graph):
    available_edges, path = initial_state(graph)
    while incomplete(available_edges):
        edge = propose_extension_edge(available_edges, path)
        if extension_is_possible(edge):
            extend_path(available_edges, path, edge)
        else:
            node = propose_node_for_reorder(available_edges, path)
            if reorder_is_sensible(node):
                path = reorder_path(available_edges, path, node)
            else:
                return None
    return path

Since you are inside a while block, an if-else can be turned into if->continue. The inner if-else can be turned into if not->return:

def find_eulerian_tour(graph):
    available_edges, path = initial_state(graph)
    while incomplete(available_edges):
        edge = propose_extension_edge(available_edges, path)
        if extension_is_possible(edge):
            extend_path(available_edges, path, edge)
            continue
        node = propose_node_for_reorder(available_edges, path)
        if not reorder_is_sensible(node):
            return None
        path = reorder_path(available_edges, path, node)
    return path

Now it reads like a checklist:

Extension possible? Do that and continue.
Reordering not sensible? Quit.
Reorder.

Is it an improvement? On the original: I think so. Nested logic is generally more difficult to follow. On the if-elif-else? Not really, but that's the price to pay for caching the intermediary values.


Search Array of Strings in Array of String, receive Int-Array of indexes

If you use pSearchStrings[] for all pArray[], you can transform pSearchStrings in a Pattern and use matcher method to avoid to load each time ArrayUtils.contains(..)

EDIT

private static int[] getIndexArray(String[] pArray, String[] pSearchStrings) {
    StringBuilder sb = new StringBuilder((int) estimateSizeOfSearchStrings +16);
    for (String searh : pSearchStrings) {
         sb.append(".*");
         sb.append(search)
         sb.append(".*|");
    }
    Pattern patt = Pattern.compile(sb.toString().subString(0,sb.length() -1);
    // If pSearchStrings are always the same, you can put static 'patt' outside this method
    // Or pass pre-compiled 'patt' as a parameter.
    int [] indexes = new int [pSearchStrings.length];
    int i = 0;
    for (String str : pArray) {
            if (patt.matcher(str).find())
            indexes[i++] = ArrayUtils.indexOf(pArray, str);
    }
    return indexes;
}


Using Templates to add virtual tables to non-virtual classes

I don't know what framework you are using for your tests but gtest has type parametrised tests that you can use to test all the implementations with the same tests.

By using this feature you wouldn't even need the code to begin with, which in my book is the best code: the code you never wrote :)


Python code to run a C program that calculates whether points are in the mandelbrot set

In my opinion, Popen is simply the wrong approach to this problem. Everything else follows from that. Python provides an API to directly expose C functions to Python. Boost.Python is a fantastic library to make it easy to expose C++ classes without having to deal with the messy direct Python API. Boost.Numpy makes it easy to return numpy arrays directly.

Regardless of which one you choose, you should choose one and use it to create something to the effect of mandelbrot.so which will have one function that returns a list of lists. You can then just use that function directly. Rather than write getcounts() to do some work doing string processing, just call mandelbrot.getcounts() with all the same args. Something like:

import numpy as np
import matplotlib.pyplot as plt
import mandelbrot

xmin = -2
xmax = 2
ymin = -2
ymax = 2
depth = 60
dim = 600
counts = mandelbrot.getcounts(xmin, xmax, ymin, ymax, dim, depth)
plt.imshow(counts, extent = [xmin, xmax, ymax, ymin], interpolation = 'nearest')
plt.show()

There are several huge advantages to doing it this way:

The ability to actually do any sort of error checking.
Not having to do any output processing converting between one program's output and another program's desired input.
Not having to start a new process and do input handling on that one will make the code perform dramatically better.
It'll read more Pythonic on one end (just call a function that returns a value) and more C/C++-ic on the other end (have a function that returns a value there too, instead of printing output). This has the added benefit of being able to actually write tests for your C/C++ code.


Simplest quick sort using one 19-line function

Rather than creating new Lists, your method could sort the list in place. The method you call recursively could take the list and index values; the methods would look something like this:

/**
 * sorts the {@code list} in place
 */
public static void sort(ArrayList<Integer> list) {
    sort(list, 0, list.size());
}

/**
 * Sorts the {@code list} from {@code fromIndex} to {@code toIndex} - 1.
 */
private static void sort(List<Integer> list, int fromIndex, int toIndex) {

    if (fromIndex == toIndex - 1) {
        return;
    } else {
        // find the pivot, Collections.swap elements, etc...
        // recursively call self.
    }

}

Sorting the list in place reduces the amount of memory on the stack.

Also, to make the code more generic, perhaps you could sort lists of Comparable instead of Integer.


name = "First Page": you retrieve the content of this variable from an other function. Functions returns values vary so from a design principle, we can not assign them to class variables which are supposed to be constant/static.
When you instantiate MainWidget, you need to inject 3 arguments into it because of the way you defined its __init__(). Arguments are a different level of abstraction, so you must use them with parsimony. In your case, there is a better way to get rid of sidebarWidget and customModulesLen described in the next bullet.
You must keep the __init__() clean and outsource the creation of the widegets to an other function that you can call from __init__(). In that function, you can refer to the previous __init__()'s argument which are sidebarWidget and customModulesLen.
You forgot to attach the widget to its parent in lay = QVBoxLayout(self). I mean you must code it this way instead: lay = QVBoxLayout(self.parent). Because objects must own their data members, you should write self.lay = QVBoxLayout(self.master)


Strategic themes

Prefer comprehensions to loops: List comprehensions and dict comprehensions let you compress loops into one-liners.  It's also a nice feeling to initialize an object "all at once" rather than building it little by little.
Avoid special cases: if n in valMap is annoying.  If valMap were a defaultdict, then a failed lookup would naturally have a value of 0.
Use built-in functions: To compute a sum, use sum().  Converting the valMap to a defaultdict enables this further simplification.
Obey the single-responsibility principle: The isDollarWord() function does too much, and should be split up.  A word_value() function would be more useful than isDollarWord() — at the least, it allows for more interesting unit tests.  Once word_value() has been defined, comparison with 100 is trivial.

Localized issues

valMap is not descriptive enough for my taste.  I suggest LETTER_VALUES, in all caps to identify it as a constant.
isDollarWord() should be named is_dollar_word().  (You named remove_marks() correctly, though.)

File handling

You have a file descriptor leak.  Opening files using a with block is almost always preferable to a regular open() call.
Better yet, avoid hard-coding filenames, and let the input be specified on the command line or through standard input.  fileinput.input() is useful for this.

Internationalization and Python 3 compatibility

string.lowercase is locale-dependent, which, according to your specification, you don't want.  Furthermore, it has been removed in Python 3.  You want string.ascii_lowercase instead.
If you want to interpret the input as CP1252, specify an encoding when opening the file, so that it is decoded correctly even before your application even has a chance to get to the data.  If using fileinput.input(), use an openhook parameter (but beware of a bug in Python 2).
For Python 3 compatibility, remove_marks() should also call .decode('ascii') on its return value, to convert the byte string back into a text string.
Alternate ways to handle the internationalization problem include transliteration using transliterate or Unidecode.  German convention, for example, treats ö as oe and ß as ss.

Suggested implementation

from collections import defaultdict
import fileinput
from string import ascii_lowercase
from unicodedata import normalize

LETTER_VALUES = defaultdict(int,
    ((letter, index + 1) for index, letter in enumerate(ascii_lowercase))
)

def remove_marks(word):
    return normalize('NFKD', word).encode('ascii', 'ignore').decode('ascii')

def word_value(word):
    return sum(LETTER_VALUES[c] for c in remove_marks(word.lower()))

for line in fileinput.input(openhook=fileinput.hook_encoded('cp1252')):
    if word_value(line) == 100:
        print(line.strip())


Prime number sieve using ranges::view::ints

It may well be more efficient to compute std::sqrt(max) once upfront than to multiply n * n every time around the loop.

Removing an element by value from the set is O(log n), where n is the set size at the time.  This will likely make this method slower than writing to elements in a fixed-size storage (such as a std::vector that's never resized), and creating the return set from that.  Also, find() is much slower than vector lookup.

I think we can probably test m * n <= max instead of the more expensive m <= max / n, if we can arrange that the multiplication doesn't overflow.  It will be fine if 2 * n < std::numeric_limits<number_t>::max() - max.  Also, no need to start at 2 * n when removing - we can start at n * n instead, as all the lower multiples have already been removed due to their smaller factor(s).

And a tiny improvement to the test code - we can stream a single character '\n' to output rather than the string "\n".


I'd probably verify the correct amount of checkboxes by iterating over them when verifying. This can get tricky in case your layout is complex, but you should usually be able to find a solution to this.

Since I liked the initial idea (I always try to avoid doing such checks or just do them server side), here's a fiddle I came up with. Just keep in mind that this code is barely optimized, complete or clean. It's just some quick example put together.

This works pretty straightforward and without any source code modifications in case anyone adds more checkboxes. You could even just modify the plain HTML template and everything would work  again.

Here's the magic:

All check box groups are grouped inside some HTML tag/container. In my case it's a <div>. These containers are marked with the class checkgroup.

<div class="checkgroup">
    <!-- Other content and checkboxes -->
</div>

Once verifying, I first determine all such containers in the current document.

var groups = document.getElementsByClassName('checkgroup');

Then I try to read custom attributes to get custom limits as well as a possible error message (stored in minimum, maximum, and message).

// Get the limits
if (group.hasAttribute('minchecked'))
    minimum = parseInt(group.getAttribute('minchecked'));
if (group.hasAttribute('maxchecked'))
    maximum = parseInt(group.getAttribute('maxchecked'));
// Get the actual error message
if (group.hasAttribute('errchecked'))
    message = group.getAttribute('errchecked');

I then iterate over all checkboxes included in the current group and count the number of checked instances.

var checkboxes = group.getElementsByTagName('input');
for (var j = 0; j < checkboxes.length; ++j) {
    // Here I should check whether that's indeed a checkbox...
    if (checkboxes[j].checked)
        ++ticked;
}

Once this is done, there's a simple comparison on the limits and an error message is shown just in case.

// Show an error message and highlight the background
if (ticked < minimum || ticked > maximum) {
    group.style.backgroundColor = '#fcc';
    alert(message);
    group.style.backgroundColor = '';
}


[can't finish now--work in progress]

In create_node:

static struct slist_node *create_node(void *value)
{
    struct slist_node *node = calloc(1, sizeof(*node));
    if (!node) { return NULL; }
    node->data = value;
    return node;
}

...I see a few things I don't like. Personally, I'd prefer an explicit comparison to NULL rather than !node. I'd also rather avoid doubled-up return statements, so I'd probably write the code more like this:

static struct slist_node *create_node(void *value)
{
    struct slist_node *node = calloc(1, sizeof(*node));
    if (node != NULL)
        node->data = value;
    return node;
}

I'm also a bit less than enthused about using calloc here. You're assuming that the zero-bytes used to initialize the memory will turn into null pointers when the right number of them are treated as a pointer. That's pretty common, but not actually required. It also means that node->data gets initialized to zero bytes, only to be immediately overwritten with some other value. As a rule, I'd prefer to explicitly set the pointers:

static struct slist_node *create_node(void *value)
{
    struct slist_node *node = malloc(sizeof(*node));
    if (node != NULL) {
        node->next = NULL;
        node->data = value;
    }
    return node;
}

I'd at least consider keeping track of the current list size in the slist structure. When you insert a node, increment it. When you remove a node, decrement it. This lets you get the size for essentially zero cost with extremely minimal overhead.

I'd write slist_find_ahead using a for loop, something like:

struct slist_node *p;
for (p=list->head; p!=NULL; p=p->next)
    if (list->compare(p->data, value))
        return p;
return NULL;

As it is, slist_find_ahead will attempt to dereference copy->next->data, even when copy->next == NULL.


Retrieving data from files in the folder

There is a few things I would fix:

find a better way to grab the path - don't let the user type the path manually as he can easily make a typo and you procedure would fail as you're not currently really checking if the path provided is correct/(exist). Remember not to ever trust user with their input in your programs.

For example, consider this code which shows a box to select the folder (note you can even pass the initial path to it by providing a parameter)

Additionally: If you wanted to point to "My Computer" by default see this workaround on my blog.

Sub Main()

    Dim path As String
    path = GetFolder("") & "\"

    Debug.Print path
End Sub

' strPath is the initial path
Private Function GetFolder(strPath As String) As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = strPath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

Early vs. late binding

I see you are late binding your objects. There are tons of discussions what is better and why so I am not going to judge here all I can see is that all it takes to get intelli-sense and a better performance is adding references to Microsoft Scripting Runtime via the Tools -> References in VBE (Visual Basic Editor).

Now, if you combine the tips from above you could get a little bit revised but better version of you code

Sub Copydata()

    Dim path As String
    path = GetFolder("") & "\"

    Dim script As FileSystemObject
    Set script = New FileSystemObject

    Dim catalogue As Folder
    Set catalogue = script.GetFolder(path)

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.AskToUpdateLinks = False

    Dim textfile As File
    Dim column_index As Integer
    Dim loadedfile As Workbook

    Dim actualfile As Workbook
    Set actualfile = ActiveWorkbook

    For Each textfile In catalogue.Files

        Workbooks.Open textfile
        Set loadedfile = ActiveWorkbook
        loadedfile.Worksheets(1).Range("D1:D15").Copy
        column_index = actualfile.Worksheets(1).Range("A5").CurrentRegion.Columns.Count
        actualfile.Worksheets(1).Range("A5").Offset(0, column_index).PasteSpecial
        loadedfile.Close Savechanges:=False

    Next textfile

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.AskToUpdateLinks = True

End Sub

' strPath is the initial path
Private Function GetFolder(strPath As String) As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = strPath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

Great, so now you probably want to eliminate opening each workbook just to copy data. There are various ways to pull data from opened and closed workbooks (without actually opening them) and I am going to use the ADODB way in your example.

Note, you need to add references to Microsoft ActiveX Data Objects 6.1 Library for this to work but the efficiency should increase a lot because you do not open the files just to get 15 rows out of them.

Let's start with a very simple example:

Assuming there is a folder temp on you C:\ drive and there is a file1.xlsm in it

Sub Pull_Data_from_Excel_with_ADODB()

    Dim cnStr As String
    Dim rs As ADODB.Recordset
    Dim query As String

    Dim fileName As String
    fileName = "C:\temp\file1.xlsm"

    cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
               "Data Source=" & fileName & ";" & _
               "Extended Properties=Excel 12.0"

    query = "SELECT * FROM [Sheet1$D1:D15]"

    Set rs = New ADODB.Recordset
    rs.Open query, cnStr, adOpenUnspecified, adLockUnspecified

    Cells.Clear
    Range("A2").CopyFromRecordset rs
    Dim cell As Range, i As Long
    'headers
    With Range("A1").CurrentRegion
        For i = 0 To rs.Fields.Count - 1
            .Cells(1, i + 1).Value = rs.Fields(i).Name
        Next i
        .EntireColumn.AutoFit
    End With
End Sub

See, this does not open the file and allows you to pull the D1:D15 from it.

Now if you slightly modify the code to suit your example you get a fully working and efficient code

Option Explicit

Sub Copydata()

    Dim path As String
    ' retrieve the path to the folder with the files to pull data from
    path = GetFolder("") & "\"

    Dim script As FileSystemObject
    Set script = New FileSystemObject

    Dim catalogue As Folder
    Set catalogue = script.GetFolder(path)

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.AskToUpdateLinks = False

    Dim cnStr As String
    Dim rs As ADODB.Recordset

    Dim query As String
    ' SQL query to pull D1:D15 from Sheet1 in each file
    query = "SELECT * FROM [Sheet1$D1:D15]"

    Dim wbFile As Variant

    ' iterate through the files in the folder user selected
    For Each wbFile In catalogue.Files

        ' upate the connection string with path to each file
        cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
               "Data Source=" & wbFile & ";" & _
               "Extended Properties=Excel 12.0"

        ' populate a recordset with D1:D15 from each file
        Set rs = New ADODB.Recordset
        rs.Open query, cnStr, adOpenUnspecified, adLockUnspecified

        ' Copy data from recordset to range in one go
        Range("A5").Offset(0, Range("A5").CurrentRegion.Columns.Count).CopyFromRecordset rs

        ' close the recordset and free memory
        rs.Close
        Set rs = Nothing
    Next wbFile

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.AskToUpdateLinks = True

End Sub

' strPath is the initial path
Private Function GetFolder(strPath As String) As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = strPath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function


Very good.

Couple of points:

I would remove the set() method, and allow its work to be done by the operator[]. To do this you need return the value you want by reference.

double &  operator[](unsigned int i);
  //  ^^^  Return double by reference.

This allows you to do;

V4 x;
x[1] = 12;

When you pass objects as parameters it is usally best to pass by const reference. This means that no copy will be made and the original object can not be modified by the method using it:

V4 operator +(V4 const & rhs);
                      ^^^

Note I always put the const on the right of the type (rather than the left). Admittedly this is a religious war so choose a side and stick to it (there is only one minor side instance were it makes difference). But I find it makes reading the type name easier (as types are read from right to left with const always binding to the left (except where it is the leftmost lexeme in the type then it binds right).

Methods that do not change the state of the object should be declared const:

V4 operator -(V4 const & rhs) const;
                        //    ^^^^^  indicates that calling this method will not
                        //           change the state of the object.

Note: This means you should provide two versions of operator[] a normal one that allows mutation and a const version that can be used in contexts where it is read only.

double&        operator[](unsigned int i)        { return coord[i];}
double const&  operator[](unsigned int i) const  { return coord[i];}

Note: array access is not validated against the array bounds. Normally you don't check as we do not want to impose an extra burden on the responsible just because there are bad developers. But it is traditional to add at() method that does the same work as operator[] but also validates the bounds of the array access.

double&        at(unsigned int i)        { if (i > 3) {throw std::range_error("BLA");} return coord[i];}
double const&  at(unsigned int i) const  { if (i > 3) {throw std::range_error("BLA");} return coord[i];}

Implementing operator + - * / is easily done if you implement them in terms of += -= *= /=. This also provides the user of your object the opportunity to use your class more efficiently when a new object is not required (though this should be a secondary though).

V4 operator *(V4 const & rhs) const;
V4 operator *=(V4 const & rhs);       // This does change the sate of the object

V4 V4::operator*(V4 const& rhs) const { V4 result(*this); result *= rhs; return result;}

Using a for loop is easy. But sometimes it can be simpler to use the standard algorithms to accomplish simple tasks over short containers:

double sum = 0;
for(int i= 0; i<4; i++){
    sum += coords[i]*coords[i];
}

This can be replaced with:

sum = std::accumulate(coords, coords + 4, 0);

You can find good documentation here: http://www.sgi.com/tech/stl/table_of_contents.html (look for section: 5 Algorithms)

In the moto of not doing extra work. Don't write methods that do nothing:

V4::~V4(){}//nothing to destroy?

Remove this. The class automatically provides a desttructor that will correctly destroy nothing.

I actually like using void as the return type of assignment (I think it has no down side). But traditionally assignment should return a reference to self. This then allows the object to be part of an assignment chain.

V4  a;
V4  b;
V4  c;

a = b = c; // assignment chaining.
// It also allows you to pass the object as a parameter to a mehtod:

doStuff( a = b); // Assign a to b. Then call doStuff using a.

It is also a good idea to define the streaming operators for most classes. This allowsd you to serialize and de-serialize the class to a stream (file/string etc).

So now the class looks like this.

class V4
{
    double coords[4];
 public:
    V4();
    V4(double x, double y, double z, double w);

    double module() const;
    double&       operator[](unsigned int i)       {return coords[i];}
    double const& operator[](unsigned int i) const {return coords[i];}

    V4&  operator = (V4 const& rhs);
    V4&  operator +=(V4 const& rhs);
    V4&  operator -=(V4 const& rhs);
    V4&  operator *=(double k); //moltiplication of vector by a scalar k

    V4   operator +(V4 const& rhs)  const {V4 result(*this); result += rhs; return result;}
    V4   operator -(V4 const& rhs)  const {V4 result(*this); result -= rhs; return result;}
    V4   operator *(double rhs)     const {V4 result(*this); result *= rhs; return result;}

    double dot4(V4 const& rhs) const; //the dot product

    V4 cross(V4 const& u, V4 const& v,V4 const& w) const; //the cross product
};

Then rest of the interesting ones:

double V4::module() const
{
    return std::sqrt(std::accumulate(coords, coords + 4, 0.0);
}

V4&   V4::operator +=(V4 const& rhs)
{
    std::transform(coord, coord+4, rhs.coord, coord, std::plus);
    return *this;
}
V4&   V4::operator -=(V4 const& rhs)
{
    std::transform(coord, coord+4, rhs.coord, coord, std::minus);
    return *this;
}
V4&   V4::operator *=(double k)
{
    std::transform(coord, coord+4, coord, std::bind1st(std::multiplies, k));
    return *this;
}


How would I unit test a method that gets data from an RSS feed?

Separate the concerns of fetching the feed XML from parsing it by extracting a class (e.g. FeedReader) to do the reading. Your IFeedReader would be generically reusable and look something like:

public interface IFeedReader
{
    XElement Load(string url);
}

with implementation

public class FeedReader : IFeedReader
{
    public XElement Load(string url)
    {
        return XElement.Load(url);
    }
}

You then inject an IFeedReader through the constructor and use it to fetch the data in your method. This lets you use a Fake or a Mock of the IFeedReader, depending on your preference, to return appropriate results for your unit test.

consider reading up on: inversion of control (IoC) and dependency injection (DI), and mock object frameworks.


Python search for array in large text file

Performance

It should be possible to accomplish this task in seconds rather than minutes, with the right data structure.  This is your main mistake:

paid = list(set(t))

The problem is, for a list with n items, it takes O(n) time to check whether the list contains a particular item.  It's particularly bad if the vast majority of the entries that you are seeking do not appear in the list — then it really does need to look at every single member of the list before concluding that an item is not in the list.

On the other hand, testing whether a particular element is a member of a set is O(1) — extremely efficient!

Miscellaneous

Please avoid cryptic filenames such as x and t.  Calling the file handle f is OK, since f is a typical name for a file handle, but since you have two files in this program, more distinctive names would help readability.  I would also avoid renaming the patent data file to f.txt, which is too cryptic.

It's a good habit to always call open() in the context of a with block, so that the file handle will be automatically closed for sure.  The 'r' mode is implied, and can be omitted.

Suggested solution

with open('data.txt') as paid_file:
    paid = set(line.rstrip() for line in paid_file)

with open('MaintFeeEvents_20160711.txt') as patent_events_file:
    for line in patent_events_file:
        if line.split(' ', 1)[0] in paid:
            print(line, end='')


How to reduce load when fading in multiple elements in jQuery

for optimizing this function - will be better if you'll give an example of working code. Just upload some sample to http://jsfiddle.net/.

Anyway, to reduce the load on any animations, use default CSS transitions.

-moz-transition: all 0.5s ease-out;
-o-transition: all 0.5s ease-out;
-webkit-transition: all 0.5s ease-out;
transition: all 0.5s ease-out;

And then change the opacity from 1 to 0 or change class. Here is an working example http://jsfiddle.net/x6fxx/ , works much faster then jquery's script, this one is css based solution which is using hardware acceleration ( modern browsers ).


Built-ins and generality

It is a good first try, but I discourage explicit recursion and suggest a larger use of built-ins, Haskell provides you with incredibly powerful and general functions. Also writing something a bit more general will make you familiar with first class functions (the core of the Haskell experience).

Decomposition

As always, I am going to divide the task in smaller, more manageable parts:

Find out how to apply a function to each second item of list.
Give multiply_by_two as argument to the function above.

mapSecond

mapSecond :: (a -> a) -> [a] -> [a]
mapSecond f = zipWith ($) (cycle [id, f])

Given a function and a list, apply the function to each second item of the list.

This function is quite advanced, let me explain it:

zipWith: given a function and two list applies the function to each pair. If you are familiar with Python, zip = zipWith (,)

Prelude> zipWith (++) ["Hello", "Foo"] ["World", "Bar"]
["HelloWorld","FooBar"]

$: given a function and two arguments, applies it to the arguments.

Prelude> ($) (*) 2 5
10

cycle: given a list repeats it forever.

Prelude> take 10 $ cycle [1,2,3]
[1,2,3,1,2,3,1,2,3,1]

The second argument is omitted, as it can be 'currried' (simplified) away.

The main function is now:

main = print $ ( mapSecond (* 2) ) [1,2,3,4,5,6]


Since the entire app will have multiple modules I would like to split
  the code into standalone modules that can be loaded as required (any
  suggestions how to do this?)

Use a dynamic module loader such as requireJS. You can use it to load modules dynamically using AJAX, and it features an optimization tool to combine your scripts into a single file to reduce the number of HTTP requests on production server.

  How can it be improved?

Stick to shared conventions for the naming of variables. Do not use all-uppercase for regular variables, only when you wish to indicate a constant value.

Use a name specific to your appliation/website, organization or company instead of GLOBAL for the global variable referencing the root of your library, if any: it is no longer needed using Asynchronous Module Definition with requireJS.

  Are there any mistakes/issues I should be aware of?

You should think about the way you wish to handle the communication between modules. The latest trend is to abstract and decouple the communication using publish/subscribe pattern.

You can find more details in The Scalable JavaScript Application Architecture presentation by Nicholas C. Zakas, and you may be interested in the open-source framework that I developed based on this approach, which I presented recently in Paris JavaScript user group.


This is an addition to Caridorc's answer.

The usual reason for using itertools is that you don't want to construct lists when you don't need to. For example, in Python 2, you'd write for i in xrange(100) instead of for i in range(100) so that you don't have to construct a whole list of 100 numbers when you don't need it. If this doesn't make sense to you, familiarize yourself with the difference between generator expressions (genexprs) and list types.

In your case, however, there's a much more serious problem. You've got a Shlemiel the painter's algorithm!

When you write reduce(list.__add__, list_of_lists), you're essentially writing list_1 + ... + list_n. Python will evaluate this as follows:

Take list_1 and list_2. Create a new list object of the proper size, and copy the elements from lists 1 and 2 into this new list. Call it intermediate_1.
Take intermediate_1 and list_3. Create a new list of the proper size, and copy the elements from these two lists into the new list. Call it intermediate_2.
…
Take intermediate_(n-1) and list_n. Create a new list of the proper size, and copy the elements from these two lists into the new list. This is the final result.

Do you see the problem? This code is quadratic in both runtime and memory usage.

Here's some hard data. Consider the following function:

def fn(n):
    lists = [[0] * 10000 for i in xrange(n)]
    combined = reduce(list.__add__, lists)

I ran this for values of n of 1, 10, 100, 200, 250, 300, 400, and 500 (using IPython's %timeit fn(100), which does proper timing), and got the following results:

This definitely looks quadratic, and the coefficient of determination is R2 = 0.99655, which indicates an extremely strong correlation.

When we instead use

def fast(n):
    combined = list(itertools.chain.from_iterable(
        [0] * 10000 for i in xrange(n)))

the time for fast(500) is just 65.8 ms instead of 7.42 s. (This shows that it is indeed the Shlemiel factor and not just large lists that's causing the slowdown.)

So, tl;dr, yes, use iterators—but make sure you know why!

So when use reduce?

Just a review of what reduce does for binary operators:

reduce(int.__add__, [x1, x2, x3], x0) = (((x0 + x1) + x2) + x3)

This is extended to general functions as follows:

reduce(f, [x1, x2, x3], x0) = f(f(f(x0, x1), x2), x3)

You should use reduce when you want to write code that looks like either of the above examples. Basically, reduce just saves you a loop.

Conceptually, you use reduce when you want to collapse a bunch of things into one value.

It may help to think of reduce in comparison with its other core functional operations:

Use map when you want to transform a bunch of values to other things (like "reverse all these strings"). You use map in list comprehensions when you write [s[::-1] for s in strings].
Use filter when you want to take a bunch of values and keep just some of them (like "take just the strings that are palindromes"). You use reduce in list comprehensions when you write [s for s in strings if s == s[::-1]].
Use reduce when you want to collapse a bunch of things into one value (like "concatenate all these strings"). You can't use reduce in list comprehensions, because you're not creating a new list (just a value).

Notes:

The problem in your case is that the version with list_1 + ... + list_n is just as bad in terms of efficiency. reduce wasn't your problem; it was what reduce expanded to.
With reduce, you can omit the third argument x0, and reduce will use the first element of the sequence, or raise a TypeError if the sequence is empty.

Before noting some examples, it may be helpful to realize that some operations from __builtins__ are just reduce under the hood. For example:

sum(ints) = reduce(int.__add__, ints, 0);
all(bools) = reduce(lambda x, y: x and y, bools, True), and, similarly;
any(bools) = reduce(lambda x, y: x or y, bools, False);
min(ints) is like reduce(lambda x, y: x if x < y else y, ints) (it's actually a bit smarter), and, similarly;
max(ints) is like reduce(lambda x, y: x if x > y else y, ints).

A few quick examples:

def factorial(n):
    return reduce(int.__mul__, xrange(1, n + 1), 1)

def replay_chess_game(moves):
    return reduce(lambda board, move: board.then(move),
                  moves,
                  INITIAL_BOARD)

def perform_git_rebase(commits):
    return reduce(lambda head, commit: head.cherry_pick(commit),
                  commits,
                  git_globals.refs.HEAD)

I don't use reduce all that much in Python, but you should definitely know when to use it.


Duplicate method call or add logic to set local variables as parameters?

I think this would be even better, in this case.

private static void Invoke<T>(string[] args, MethodInfo method) where T : new()
{
    T target = new T();
    target.InvokeMethod(
        "Initialize", errorIfMethodDoesNotExist: false, accessNonPublic: true);
    string[] methodArgs = args.Skip(1).ToArray();
    method.Invoke(target, methodArgs);
}

Skip() on an empty collection returns an empty collection.


Using a function to find the average for number of letters and words

First of all, be careful with types: to compute an average something, you will need a floating point number. However, the number of letters and words are countable and can therefore use the type unsigned int which are generally faster than floating point numbers.

Moreover, to detect a "space" character, you can use the standard function isspace from the header ctype.h.

Also, the variable answer is useless. You can get rid of it and simply return the answer the same line you're computing it.

Therefore, your function average_of_let_wor can be reduced to:

double average_of_let_wor()
{
    unsigned int numberOfLetters = 0;
    unsigned int numberOfWords = 0;
    int userInput;

    printf("please enter your input:\n");
    while ((userInput = getchar()) != EOF)
    {
        if (isspace(userInput))
        {
            numberOfWords++;
        }
        else
        {
            numberOfLetters++;
        }
    }

    return (double)numberOfLetters / (double)numberOfWords;
}


I have the following ideas for improvement of your code:

Separate different concepts like timers and UI rendering to make them easy to understand and change.
Use milliseconds for consistency with browser API.
Separate formatting and calculation for dates and durations.
Incapsulate mutable state in objects so it won't leak in your main application logic (let interval).
Don't use the substr function to format time because this solution is not robust. Write custom formatter or use a library like momentjs instead.

Here is my solution:
class Timer {
    constructor(duration, delay = 1000) {
        this._remaining = duration;
        this._delay = delay;
        this._callbacks = [];
    }

    start() {
        this._intervalId = setInterval(this._tick.bind(this), this._delay);
    }

    stop() {
        clearInterval(this._intervalId);
    }

    onTick(callback) {
        this._callbacks.push(callback);
    }

    _tick() {
        this._remaining -= this._delay;
        if (this._remaining <= 0) this.stop();
        this._callbacks.forEach((cb) => cb(this._remaining));
    }
}

class Timers {
    makeActive(timer) {
        this._activeTimer = timer;
    }

    stopActive() {
        if (this._activeTimer) this._activeTimer.stop();
    }
}

// I didn't change formatting implementation here because I am lazy
const formatHMS = (date) => date.toISOString().substr(11, 8);
const formatLocaleHMS = (date) => date.toLocaleTimeString().substr(0, 8);

const dateIn = (duration) => {
    const date = new Date(0);
    date.setMilliseconds(Date.now() + duration);
    return date;
}

const durationToDate = (duration) => {
    const date = new Date(0);
    date.setMilliseconds(duration);
    return date;
}

const timeControls = document.querySelector('.timer__controls');
const timeLeft = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');

const displayRemaining = (duration) => {
    timeLeft.textContent = formatHMS(durationToDate(duration));
}

const displayEnd = (duration) => {
    endTime.textContent = `Be back at ${formatLocaleHMS(dateIn(duration))}`;
}

const timers = new Timers();

const startAndUpdate = (duration) => {
    displayRemaining(duration);
    displayEnd(duration);

    const timer = new Timer(duration);
    timer.start();
    timer.onTick(displayRemaining);

    timers.stopActive();
    timers.makeActive(timer);
};

const secondsToMs = (seconds) => seconds * 1000;
timeControls.addEventListener('click', (e) => {
    const button = e.target.closest('button');
    if (button) startAndUpdate(secondsToMs(parseInt(button.dataset.time)));
});

const minutesToMs = (minutes) => secondsToMs(minutes * 60);
document.customForm.addEventListener('submit', function (e) {
    e.preventDefault();
    const value = this.minutes.value;
    if (value !== '') startAndUpdate(minutesToMs(parseInt(value)));
});


Looping over files in C++ and changing their names to store data into a single file

As you're new to C++, you should be aware that implementing an entire program in main() can make things difficult, especially when the code is already complex.

As it appears, you have declare and initialize variables at the top, open the file, perform the operations, then output things.  Even with these comments in place, you should still split this up into functions.

Do not maintain a list of variables as it could make maintenance more difficult, such as if variables are no longer being used.  Instead. you should only declare or initialize variables as close to their intended use as possible.  That way, if you no longer use that variable, you won't have to search for it at the top.  This will also make your code easier to follow.
Consider just having main() do two things: attempt to open the file and call all the necessary functions afterwards.  You can also open the file in an other function, but if you do it in main(), then you can easily return from there if the file cannot be opened.
Everything else, especially the file operations, should be in separate functions.  Also keep in mind that a function should just have one primary purpose, in order to maintain the Single Responsible Principle (SRP).  If a function needs to do something else that another function already does, then it should call that function.  You should also name functions, in the verb form, based on what they're supposed to do.  This will make the function's intent very clear to others.

Example:

void openFile() {}

Miscellaneous:

Try not to use using namespace std in global scope as it could cause name-clashing bugs, especially in larger programs.  See this post for more info on this.
This variable appears to be a constant:

int tmax = 80000;

If so, initialize it with const so that it cannot be modified:

const int tmax = 80000;

For this approach at checking the file:

infile.open("File_1.prn");

if(infile.fail())
{
    cout << "error reading file" << endl;
    return 1;
}

you should use std::ifstream, check for !infile(), print the error message to std::cerr, and then return EXIT_FAILURE:

std::ifstream infile("File_1.prn");

if (!infile)
{
    std::cerr << "error reading file";
    return EXIT_FAILURE;
}


Print a string of characters with their occurrences

Big \$O\$
Time complexity is a ratio of some input metric (e.g. the number of character in the string) to the number of instructions required to complete the function.
In this case the metric \$n\$ is the string length. The first loop that uses String.match must for each character check all characters to find a count. That means at least \$n * n\$ steps need to be performed to do the operation.
Thus the complexity of the function is said to be \$O(n^2)\$
If you think about how you would solve it on paper. You would go over each character once with a list of characters found adding 1 to each count as you find them. This would have a time complexity of \$O(n)\$
Maps use a hash function to locate an item \$O(1)\$. So the time complexity to find out if you have counted a character before is \$O(1)\$, rather than your regExp \$O(n)\$
function countLetters(str) {
    const charCounts = {};
    var result = "";
    for (const c of str) {
        if (charCounts[c]) { charCounts[c] += 1 }
        else { charCounts[c] = 1 }
    }
    for (const [char, count] of Object.entries(charCounts)) {
        result += char + " has " + count + " ";
    }
    return result;
}

The second loop to create the result, will count in the worst case each character again. Thus the number of instructions is \$2n\$ In big \$O\$ notation the scale \$2\$ is insignificant compared to powers, even if it was \$1000000n\$ we ignore the scale and make it just \$n\$
It can not be done with less complexity as you need to check every character at least once. Because you do not know what the characters are before you check them.
Style Notes.

Use ; or not, never use them sometimes.
Careful with indentation. You indent 4 and sometime 2 spaces, use either not both.
Use Function declarations in favor of arrow functions when in global scope.
Variables that do not change should be declared as constants const
Use for of rather than  for in


Updating an item's status in MS SQL Server using ODBC

Security

$itemstatus

$itemstatus will either be 1 or 2. It cannot possibly be anything else, so it is not an attack vector.

doQuery

I don't know doQuery so I cannot say if it is secure. If it is this: MongoCursor::doQuery, I wouldn't use it. The documentation says this: Warning Please do not use me. It doesn't say why, but security concerns could be one reason.

SanitizeIt

I wouldn't use your SanitizeIt function. For yesorno you don't need it, and for username it is quite limiting.

htmlentities and htmlspecialchars are generally used to prevent XSS attacks when outputting data to the user, not to prevent SQL injection.

Limiting the input to alphanumeric characters is not only very limiting, it might also not be sufficient for multi-byte encodings. If you can ensure that usernames only ever contain alphanumeric characters[*] - and that this will never change - then you can leave it in (as part of a defense in depth strategy it's not bad)

The recommended approach to SQL injection is to use parametrized queries (see here for corner cases). If you post your doQuery function we could tell you if it does this correctly.

[*] This basically means that you have to use the exact same function when registering users and when writing the username to the database.

Other

Style

Your indentation is off, which makes you code hard to read
you can either use under_score or camelCase for variables, but if you use neither, variable names are hard to read (see yesorno, itemstatus).


Encapsulating common Try-Catch code. Is this a known pattern? Is it good or bad?

This looks like the Execute Around pattern in its static syntax. A thunk is passed around, and then invoked at the appropriate moment.

The intent is however a bit different. In true execute around, the is something done before and something done after a certain action/function/block. Catching exceptions "feels" a bit different.


There's really not much to say about this code, so I'll quote a comment posted on this question:

  [...] a basic game engine is a loop and a redraw/update system. So yes you are good. You should explore other game engines in javascript and see what they do. – Steven

Just one thing that's itching: you're declaring var frameLength = 500; - I think this is going to bite you later, when you want to adjust frame rate (FPS).


Finding unpaired number in an odd length Array of integers

Sorting of the array will take O(n (log n)) in the average case. You can do it in linear time using bitwise operation

public class Test {
    public static void main(){
        int a = 0;
        int[] arr = {9,3,9,3,9,7,9};

        for (int i = 0; i < arr.length; i++ ){
            a = a ^ arr[i];
        }

        System.out.println(a);
    }
}

Any number which will XOR with 0 will be the number itself. But if it will XOR with itself, it will be 0. In the end, we'll get the non paired number.


Have you actually tested your code (with numbers other than 6)? Because I doubt that can work.

Firstly you have lowX = highX + 1; where it most likely should be lowX = midX + 1; (dito with Y).

And more importantly, your code only adds or subtracts one from X and Y at the same time. There is no case where X and Y are changed independently from each other, thus making it impossible to navigate the whole matrix.

I would suggest two alternative solutions:

A) Run the binary search recursivly. First search the outer array for the inner element (array) that includes the sought number, then search that array.

B) Logically map the two dimensional array to a simple array and search that, e.g. an index i on a simple array maps to the indexes x = i/4 and y = x%4 of the matrix.

Questions: What is the use case for this? If the arrays are sorted like this, why use a matrix instead of a simple array? What is the logic behind using sub-arrays like this? Do you need the location of an element, or just if it's present or not?


Updating a textarea label with the number of characters inside the field itself

Just a few things I notice, prolly not warranting a "mark as answer" but may help:

Cache $(this): var $this = $(this); So that you don't keep inefficiently re-wrapping this
$(this).attr('id') - really? You can just use this.id, you know.
hasDigit === digit, so why do you have both? Scrap one of those regexes, the other one is redundant.
Cache label.html() so that you don't keep grabbing it (which is quite inefficient). Instead: var labelHtml = label.html() and then reuse labelHtml


Print limited previous lines from a file

private int size;

I would find this more consistent with other Java classes if it called this capacity rather than size.

    private int capacity;

The size is typically the number of elements currently in the data structure.

        this.innerStore = new ArrayList<>();

This could be

        innerStore = new ArrayList<>(capacity);

While you can use the this. there (perhaps to make it obvious that it is a field), you don't need to do so as it is not ambiguous as to which innerStore is involved.

Passing the capacity (or size) initially tells it how big the structure will grow.  This saves having to do multiple allocations.

You could also do some extra work and use an array here.  Of course, with an array, you have to manually keep track of where you are in the array.  For a queue, you would normally use the array in circular fashion, overwriting the oldest entry and returning to the beginning after reaching the end.

    boolean add(String s){
        if(innerStore.size() == size){
            innerStore.remove(0);
            innerStore.add(s);
            return true;
        }
        innerStore.add(s);
        return true;
    }

This could be just

    boolean add(String s) {
        while (innerStore.size() >= capacity) {
            innerStore.remove(0);
        }

        return innerStore.add(s);
    }

The other way, if you passed the maximum capacity, it would stop enforcing it.

You don't need to add and return twice.  Once is plenty.

You shouldn't always return true.  If the internal add fails, you should return false.  Returning the result of the internal add accomplishes this exactly.


find if one string is a valid anagram of another , in scala

Short circuit!

Check the lengths first. In the case that they aren't the same, you don't need to incur a linear pass for an equality check.

Don't check the hashmap for an entry!

It's good that you know m(c) can throw if there's a missing key; luckily,
 you can use Map#getOrElse and provide a default -- in this case, it makes sense to provide a 0 default since you haven't seen the character.

Compare the counts from each string directly!

I find the subtracting of the counts to be very confusing. You'll need to remove keys from the counter if any of the values go to 0, which lowers the signal to noise ratio of the code. It's better to just build a second counter.

If you decide to build two counters and compare them, you'll need to do the same fold logic twice. This is really messy to write, so you won't want to do this twice. You may want to pimp out the String class. You can do this in the following way:

implicit class Counter(s: String) {
  def countCharacters: Map[Char, Int] =
    s.foldLeft(Map.empty[Char, Int])({ case (acc, c) =>
      acc + (c -> (acc.getOrElse(c, 0) + 1))
    })
}

You can see it in action here:

scala> "hello".countCharacters
res0: Map[Char,Int] = Map(h -> 1, e -> 1, l -> 2, o -> 1)

So now you can compare the counts with a clean, non-repeated API.

Pulling this all together, you can write:

object ValidAnagram extends App {

  // when I see a string, implicitly construct a `Counter` instance
  implicit class Counter(s: String) {
    // this will be "added" to the String API via an implicit class construction
    def countCharacters: Map[Char, Int] =
      s.foldLeft(Map.empty[Char, Int])({ case (acc, c) =>
        acc + (c -> (acc.getOrElse(c, 0) + 1))
      })
  }

  def validAnagram(s1: String, s2: String): Boolean =
    if (s1.length != s2.length) false
    else if (s1 == s2) true
    else s1.countCharacters == s2.countCharacters

  println(validAnagram(args(0), args(1)))
}