The recursive definition of Fibonacci is an elegant one, but in practice it's something you would never want to use. Let's say you want to get fibonacci(5). How often does fibonacci get called?

fibonacci(5)
 =    fibonacci(4) + fibonacci(3)
 =   (fibonacci(3) + fibonacci(2)) + (fibonacci(2) + fibonacci(1))
 =   ((fibonacci(2) + fibonacci(1)) + (fibonacci(1) + fibonacci(0)))
   + ((fibonacci(1) + fibonacci(0)) + fibonacci(1))
 =   (((fibonacci(1) + fibonacci(0)) + fibonacci(1))
        + (fibonacci(1) + fibonacci(0))
     )
   + ((fibonacci(1) + fibonacci(0)) + fibonacci(1))

That seems a lot for 0 + 1 + 1 + 2 + 3 + 5. Indeed, the recursive variant without memoization has exponential runtime. You have several options to reduce the time:

use an iterative variant (which leads to \$ \mathcal O(n)\$ instead of \$ \mathcal O(2^n)\$ per call of fibonacci),
use memoization (which, if done correctly, leads to \$ \mathcal O(n)\$ in worst case and \$ \mathcal O(1)\$ if the number was already calculated).

But that begs the question: do we actually need fibonacci? For a programming challenge, it's enough to calculate the sum in main, while you're calculating the numbers iteratively. If you're looking for performance, that would be the fastest variant (that doesn't use the closed form).


To avoid spoiling the problem for you, I'll offer some hints.

Hint 1:

   Have you read the Wikipedia article about the triangular numbers? It's always worth doing a bit of research into the mathematical background of a Project Euler problem.

Hint 2:

   There is a mathematical formula for the \$n\$th triangular number, namely \${1\over2}n(n+1)\$.

Hint 3:

   What do you know about the divisors of \${1\over2}n(n+1)\$? Try out some small examples and see if there is a pattern.

Hint 4:

   When a problem requires you to establish some facts about the divisors of all the numbers in a range, then what you need is a sieve.


Password validator using regular expressions

(Note: Python is not my main language, and this is my first answer on Code Review)

Looks alright, I can't see any obvious holes in the regex. Tried it a few times myself, worked as expected.

I don't really have a good answer for you "random string" question, but for:

Are there better regular expressions I could use to verify that password?

Well, I think you could take out the curly brackets out on them. For instance, when you're matching any lower case letter, at least once, you have:

if re.search(r"[a-z{1,9}]", password) is None:

Since you only want to know if one exists, you don't need the {1,9}. So, unless there's some strangeness with re.search that I don't know about, you could replace [a-z{1,9}] with just [a-z]. Ditto for the other validation functions.

Now, I'm not 100% certain with this, but it seems you could return either None or a number from your validation functions, and test whether it's equal to None in validate_password(). Like this:

def lower_error(password):
    return re.search(r"[a-z]", password)

def symbol_error(password):
    return re.search(r"[!@$&]", password)

def upcase_error(password):
    return re.search(r"[A-Z]", password)

def digit_error(password):
    return re.search(r"\d", password)

Now lower_error() etc return None, or a number.

def validate_password(password):
    if lower_error(password) is None or upcase_error(password) is None:
    ...
    elif digit_error(password) is None or symbol_error(password) is None:
    ...

I was a bit worried about 0  being equal to None, but typing 0 is None into the Python REPL says False.

EDIT: By the way, just noticed length_error() only checks if it's less than 8 characters, not that it's under 20.


Combining two Arrays of hashes based on a hash key

First create a hash that maps names to the hashes for one list:

people2_by_name = Hash[people2.map { |h| [h[:name], h] }]

Filter the other list

people1.select { |h| people2_by_name.has_key?(h[:name]) }
       .map { |h| [h, people2_by_name[h[:name]]] }

This will only work properly if there are no duplicate names in each, but it is \$\mathcal{O}(n)\$ in the number of hashes.


Definite Integral Approximation using the Trapezoidal Method

If you are writing mathematical code in Python, then it is worth looking at NumPy, which is a library implementing (among other things) fast arithmetic operations on arrays of floating-point numbers.

In NumPy you'd write:

import numpy as np

def calculate_area(f, a, b, n):
    """Return an approximation to the definite integral of f from a to b
    using the trapezium rule with n intervals.

    """
    w = (b - a) / n                # width of the intervals
    x = np.linspace(a, b, n + 1)   # x coords of endpoints of intervals
    y = f(x)
    return w * (y.sum() - (y[0] + y[-1]) / 2)

Here np.linspace returns an array of numbers evenly spaced between two endpoints. For example, if we are asked to integrate between 0 and 1 with 4 intervals, then the endpoints of the intervals are:

>>> np.linspace(0, 1, 5)
array([0.  , 0.25, 0.5 , 0.75, 1.  ])

Under the assumption that f is a straightforward arithmetic function of its argument, then f(x) computes an array of the corresponding y values for each x. For example, if we have

def f(x):
    return x ** 2 + x + 1

Then:

>>> x = np.linspace(0, 1, 5)
>>> f(x)
array([1.    , 1.3125, 1.75  , 2.3125, 3.    ])

However, NumPy already has a built-in function np.trapz that computes an integral using the trapezium rule. Using this function, we could write:

def calculate_area(f, a, b, n):
    """Return an approximation to the definite integral of f from a to b
    using the trapezium rule with n intervals.

    """
    x = np.linspace(a, b, n + 1)   # x coords of endpoints of intervals
    return np.trapz(f(x), x)


Trying to write an equals method for a class containing array of objects

It depends on what is exactly possible in your class - can you override class, can some fields be null at any point? For example retrofit creates classes using reflection and some classes can be very unexpectedly null unless set in constructor without parameters.
Many IDEs have generators, they do this really well.
If you override equals, you really should override hashCode too:
https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java

I included equals generated by Android Studio - 2 possibilities, depending on if you are okay with subclasses too (hashcodes both same).

    @Override
    public boolean equalsV1(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        College college = (College) o;
        return Arrays.equals(student, college.student) &&
                Arrays.equals(teacher, college.teacher);
    }

    @Override
    public boolean equalsV2(Object o) {
        if (this == o) return true;
        if (!(o instanceof College)) return false;
        College college = (College) o;
        return Arrays.equals(student, college.student) &&
                Arrays.equals(teacher, college.teacher);
    }

    @Override
    public int hashCode() {
        int result = Arrays.hashCode(student);
        result = 31 * result + Arrays.hashCode(teacher);
        return result;
    }

You can notice, that there are static methods for arrays in Array class.
Code is trying to exit as soon as it is sure, that equality isn't there rather than your approach, where code runs till the end and maybe it will set equals to true along the way, which has to run longer.
You don't need to use getters, you can use fields directly since it's accessing fields of different instance, but same class.
In College class it's fine, but in Student your class would crash if name is null. It shouldn't happen as even if your empty constructor you set it to something. But sadly in java I can still create Student class and pass null myself (would be good to do null check there). So just to be safe, equals should be able to handle that. There's method for that to make it easier - Objects.equals(name, other.name) rather than name.equals(other.name). First one will work fine and return false when name is null. Second one will raise NullPointerException.
equals shouldn't ever throw Exception. If you aren't sure to guarantee that, it might be better to just surround code in try-catch and return false on exception.
Unless it's exercise, try to rely on these generators. They are pretty good and worked well for me.
Now I switched to kotlin, that has data classes, which automatically have equals and hashCode based on all class properties already saves work and lines of code!


I've noted a few things you could consider:

Your class should probably be VendingMachine, note the capital M.
The value 50 is a magic number and should probably be defined as a const at the top of your class.
The use of coins and tokens is confusing as they appear to refer to the same thing. Pick one term and use it everywhere.
getCans() changes the value of cans. This is a side-effect, which is generally considered a no-no, especially in a getter.
The Java idiom for decrementing is -=, so I'd change cans = cans - tokens; to cans -= tokens;
Both constructors contain similar code. I'd change the first to use the second, thus:

public Vendingmachine() {
    this(50);
}


This looks fine, the only thing I would say is @location is being declared as nvarchar(max). I can only assume that u.Location is also nvarchar(max). If it isn't then set it to be the same size. nvarchar max will have a slight performance hit to it.


Some performance-related nitpicking:

Instead of string concatenation keep an array of string lengths;
Use a running window of current concatenated length: when advancing to the next string simply subtract the first window's element and add the current string length.

Thus the array will be iterated just once, no extra strings interned in the JS engine.

const longestConsec = (strings, count) => {
    let n = strings.length;
    if (!n || count <= 0 || count > strings.length)
        return '';

    let lengths = Array(n);

    // fill the running window
    let windowLen = 0;
    for (let i = 0; i < count - 1; i++) {
        let stringLen = strings[i].length;
        windowLen += stringLen;
        // fill the cache with items 0..count-1, the rest will be filled in the main loop
        lengths[i] = stringLen;
    }

    let maxLen = 0;
    let maxLenAt = 0;
    for (let i = count - 1, windowStart = 0; i < n; i++, windowStart++) {
        let stringLen = strings[i].length;
        lengths[i] = stringLen;

        let thisLen = windowLen + stringLen;
        if (thisLen > maxLen) {
            maxLen = thisLen;
            maxLenAt = windowStart;
        }
        windowLen += stringLen - lengths[windowStart];
    }

    return strings.slice(maxLenAt, maxLenAt + count).join('');
}


For-loop for mixing audio (left channel, stereo to mono)

Provide a complete sample

For future reference, it's much easier to review code if it's complete.  That is, instead of just writing a loop, you could instead wrap in a small but complete program.  Your code refers to SampleSize, bufferSize, and micBuffer but none of those are defined in the sample you've posted.

Establish and use consistent naming

Some of your variable names, such as SampleSize are capitalized, while others, such as bufferSize are not.  One common C++ convention is to use lowercase names for variables (as with bufferSize) and capitalized names for classes and structure types such as Vector.  There is no significance to these conventions to the compiler, but a consistently applied convention makes it easier for others to read and understand your code.

Avoid the use of hard-coded "magic numbers"

There are numbers, such as 960 and 32768.0f in your code that don't have an obvious meaning.  Better would be to declare them as constants with a meaningful name, or at least to have more explanatory comments.

Eliminate unused variables

This code declares a variable Test at the top of the sample, and then redefines it within the scope of the if statement.  The second declaration of Test is never used within the code.  TestChannels and TestSize are also unused within this code. You can (and should) eliminate unused variables like this.Your compiler is smart enough to help you find this kind of problem if you know how to ask it to do so.

Remove loop invariants from the loop

A loop invariant is a value used within a loop construct that doesn't change.  Right now your code checks the value of MixMono and left for every iteration through the loop. Since they don't change within the loop, it's better to check them just once and then select a loop, since you're looking for performance.

As an example of this, here's what your MixMono loop would look like when extracted:

if (MixMono)
{
    for (int i = 0; i < bufferSize; ++i)
    {
        int s = micBuffer[i] * scaleFactor; //32bit Float to 16Bit Int
        ChannelCheck++;
        copy += s;
        if (ChannelCheck == 2)
        {
            Test[Tindex] = copy / 2;
            copy = 0;
            Tindex++;
            ChannelCheck = 0;
        }
    }
}

Now that it's extracted, it's easier to see what's happening and to identify inefficiencies.  One thing to note is that we're doing two multiplies, an add and a division for each mono sample.  The math is currently (left * 32768 + right * 32768)/2 with each channel being a float and the result being an int16_t.  Mathematically, this is the same as (left+right)*16384 so as long as you can assure that the samples are within range and that you always have an even number of samples, you can simplify this loop to this:

const float scaleFactor = 32768;
const float halfScaleFactor = scaleFactor/2;
if (MixMono)
{
    for (int i = 0; i < bufferSize; i+=2)
    {
        Test[Tindex++] = (micBuffer[i] + micBuffer[i+1]) * halfScaleFactor;
    }
}

The other loops can be similarly compressed and the s, ChannelCheck and copy variables completely eliminated:

else if (left)
{
    for (int i = 0; i < bufferSize; i+=2)
    {
        Test[Tindex++] = micBuffer[i] * scaleFactor;
    }
}
else
{
    for (int i = 0; i < bufferSize; ++i)
    {
        Test[Tindex++] = micBuffer[i] * scaleFactor;
    }
}

Consider using pointers

Depending on the architecture and compiler, using pointers instead of array indexing may be faster.  If your application requires more speed than indexing can provide, you might want to test using pointers and see if that will allow your code to meet its performance requirements.  As always, you should prefer clearly written code and only attempt such speedups if you have measured the performance of the code and found it insufficient.

Consider using a struct

Another possibility is to define a struct like this:

struct Sample
{
    float left;
    float right;
};

and then processing your micBuffer data by casting it as an array of such structures.  Your code might be easier to read and understand this way and may be faster.  An example is this:

Sample *micBufferEnd = (Sample *)&micBuffer[bufferSize];
if (MixMono)
{
    for (Sample *s = (Sample *)micBuffer; s < micBufferEnd; ++s)
    {
        Test[Tindex++] = (s->left + s->right) * halfScaleFactor;
    }
}

This works by treating the samples a pair at a time.  When the ++s is executed at the end of each loop, it advances the pointer by the size of the structure which happens to be the size of two floats.

Note that as @JerryCoffin noted in his comment, that this is not guaranteed to work because the compiler is free to insert padding between values.  For instance, on a 64-bit machine, the compiler may decide to align each member on a 64-bit boundary, possibly resulting in a gap between member items.  Compilers often implement something like a #pragma pack to force the behavior used here, but that's not portable, and it's even possible that it could change from version to version of an individual compiler.  An alternative, also noted in the comments, was to define the structure differently.  One way to do it might be this:

class Sample
{
private:
    float chan[2];
public:
    float left() const { return chan[0]; }
    float right() const { return chan[1]; }
};

Using it would be almost identical except that left and right are now member functions rather than data items.

Sample *micBufferEnd = (Sample *)&micBuffer[bufferSize];
if (MixMono)
{
    for (Sample *s = (Sample *)micBuffer; s < micBufferEnd; ++s)
    {
        Test[Tindex++] = (s->left() + s->right()) * halfScaleFactor;
    }
}


Code to initialize a .NET object from a CSV file

Here is another answer, using Reflection, Expression and Attribute to create a more automated solution.

First you create a couple of custom Attributes to mark fields or properties with the CSV Header Name when it doesn't match the class member name, or to indicate a class member isn't initialized from the CSV:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class CSVColumnName : Attribute {
    public string ColumnName { get; }
    public CSVColumnName(string name) => ColumnName = name;
}

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class CSVNoColumnName : Attribute {
}

Then you can create a static method to build the PropertySetters Dictionary for you by Reflection. You need a couple of extension methods to make MemberInfo easier to work with:

public static Type GetMemberType(this MemberInfo member) {
    switch (member.MemberType) {
        case MemberTypes.Field:
            return ((FieldInfo)member).FieldType;
        case MemberTypes.Property:
            return ((PropertyInfo)member).PropertyType;
        case MemberTypes.Event:
            return ((EventInfo)member).EventHandlerType;
        default:
            throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", "member");
    }
}

public static bool GetCanWrite(this MemberInfo member) {
    switch (member.MemberType) {
        case MemberTypes.Field:
            return true;
        case MemberTypes.Property:
            return ((PropertyInfo)member).CanWrite;
        default:
            throw new ArgumentException("MemberInfo must be if type FieldInfo or PropertyInfo", "member");
    }
}

Then you can create the setter lambdas for each field and put them in a Dictionary:

public static class CSVMapping<T> {
    public static Dictionary<string, Action<T, object>> PropertySetters() {
        var t = typeof(T);
        var propsOrFields = t.GetMembers(BindingFlags.Instance | BindingFlags.Public).Where(m => m.MemberType == MemberTypes.Property || m.MemberType == MemberTypes.Field);

        var ans = new Dictionary<string, Action<T, object>>(StringComparer.OrginalIgnoreCase);
        foreach (var m in propsOrFields) {
            if (!Attribute.IsDefined(m, typeof(CSVNoColumnName)) && m.GetCanWrite()) {
                var ca = (CSVColumnName)Attribute.GetCustomAttribute(m, typeof(CSVColumnName));
                var csvname = (ca != null) ? ca.ColumnName : m.Name;
                // (T p1, object p2) => p1.{m.Name} = ({m.Type})p2;
                var paramobj = Expression.Parameter(t);
                var paramval = Expression.Parameter(typeof(object));
                var body = Expression.Assign(Expression.PropertyOrField(paramobj, m.Name), Expression.Convert(paramval, m.GetMemberType()));
                var setter = Expression.Lambda<Action<T, object>>(body, new[] { paramobj, paramval });
                ans.Add(csvname, setter.Compile());
            }
        }
        return ans;
    }
}

Note: You could use reflection to assign values as well, but I figure it is worth the effort to build the lambdas since you presumably will be assigning to the fields often (once per CSV file row).

Now you can annotate the class with CSV information:

private class MassUploadUser {
    public string email { get; set; }

    [CSVColumnName("First Name")]
    public string firstName { get; set; }

    [CSVColumnName("Last Name")]
    public string lastName { get; set; }

    public string role { get; set; }

    [CSVNoColumnName]
    public bool active { get { return true; } }
}

Note: Since active is a read-only property, the PropertySetters method would skip it even if it didn't have the attribute.

Finally, you can convert the CSV file to class members just like my previous answer, using the setters Dictionary to assign read-in values:

var fieldMap = CSVMapping<MassUploadUser>.PropertySetters();

using (var parser = new TextFieldParser(csvFilename)) {
    parser.SetDelimiters(",");

    string[] header = parser.ReadFields();
    var headerMap = header.Select((h, i) => new { h, i }).ToDictionary(hi => hi.h, hi => hi.i);

    while (!parser.EndOfData) {
        string[] fields = parser.ReadFields();

        var massUploadUser = new MassUploadUser();
        foreach (var field in fieldMap.Keys)
            fieldMap[field](massUploadUser, fields[headerMap[field]]);
    }
}


This can be simplified down to a single query :-)

You calculate COUNTs using different WHERE-conditions and aggregation levels, but the base tables are always the same:

CountByYear: Edits per user & year
TotalCount: All actions of a user
CountAllEdits: All Edits of all users (including UserId NULL)

In a case like this you can utilize conditional counts (COUNT(CASE...)) and Windowed Aggregate Functions (SUM() OVER).

To be able to calculate both Edits only and All actions I use a LEFT JOIN PostHistoryTypes ON Name like 'Edit%' which returns NULL for non-edit-actions. This enables both counts using:

count(PostHistory.PostHistoryTypeId) = all actions
count(PostHistoryTypes.id)           = edits only

Aggregation starts with the lowest level, GROUP BY UserId, YEAR. And because OVER is processed after  aggregation you get the higher aggregation levels using:

sum(count(...)) over (partition by UserId) = -- count by user
sum(count(...)) over ()                    = -- count all

This results in this base query:

   select
      [Year Rank] = row_number()
                    over (partition by datepart(year, CreationDate)
                                         -- (excluding NULL UserId)
                          order by count(case when UserId is not null then PHT.Id end) desc),
      [Year] = datepart(year, CreationDate),
      UserId,
      CountByYear = count(pht.id), -- Edits per user & year
      TotalCount = sum(count(UserId)) over (partition by UserId), -- All actions of a user
      CountAllEdits = sum(count(pht.Id)) over () -- All Edits (including NULL UserId)
   from
       PostHistory as ph
   left join PostHistoryTypes as pht
     on ph.PostHistoryTypeId = pht.Id
    and pht.Name like 'Edit%'
   where PostId in (select Id from Posts where DeletionDate is null)
   group by
       [UserId],
       datepart(year, CreationDate)

And then you just have to filter for the top 10 and do the percentage calculations:

/*
  Aggregate the top 10 users with the most post edits
  for each year, along with relevant statistics.
*/

with cte as
 (
   select
      [Year Rank] = row_number()
                    over (partition by datepart(year, CreationDate)
                                         -- (excluding NULL UserId)
                          order by count(case when UserId is not null then PHT.Id end) desc),
      [Year] = datepart(year, CreationDate),
      UserId,
      CountByYear = count(pht.id), -- Edits per user & year
      TotalCount = sum(count(UserId)) over (partition by UserId), -- All actions of a user
      CountAllEdits = sum(count(pht.Id)) over () -- All Edits (including NULL UserId)
   from
       PostHistory as ph
   left join PostHistoryTypes as pht
     on ph.PostHistoryTypeId = pht.Id
    and pht.Name like 'Edit%'
   where PostId in (select Id from Posts where DeletionDate is null)
   group by
       [UserId],
       datepart(year, CreationDate)
 )
select
   [Year Rank],
   [Year],
   [User Link] = UserId,

   -- number of edits by user & year
   -- [Edits by User & Year]?
   [Annual Total] = CountByYear,

   -- % of edits vs. all actions by user & year
   [% Year/User]  = cast(100.00 * CountByYear / TotalCount    as decimal(5,2)),

   -- % of edits by user & year vs. all edits
   [% Year/Site]  = cast(100.00 * CountByYear / CountAllEdits as decimal(5,2)),

   -- % of actions by user vs. all edits
   [% Total/Site] = cast(100.00 * TotalCount  / CountAllEdits as decimal(5,2)),

   -- number of all actions by user
   [Grand Total] = TotalCount

from cte
where [Year Rank] <= 10
  and CountByYear > 0
order by
    [Year Rank] asc,
    [Year] asc;
;

I noticed you didn't use exactly the same WHERE-conditions all the time, in your TotalCount calculation you didn't check for DeletionDate is null, but in fact there's no NULL at all in that column (thus it could be removed from the query).

It was hard for me to infer the actual meaning from the column names.
And the calculation of [% Total/Site] doesn't make sense for me, you compare all actions of a user to all edit-actions.

First I would expect indicators like:

edit count of this user (per year & globally)
% edits of this user vs all edits (per year & globally)

And additionally maybe:

all actions count of this user (per year & globally)
% edits vs all actions of this user (per year & globally)


You will need to settle on the variable name containing $request[ 'ID' ];. At the moment, you are using $publisher_id and $publisher ...which of course is a script fouling typo. I'd probably avoid declaring the variable, because I don't find a declarative coding style to be very beneficial in this case.
You could use a different syntax to declare your array to be less verbose. For example:

 $response['status'] = 404;
 $response['data']['errors']['general'] = 'Sorry, no record was found.';

By writing an if-else, you can avoid rewriting json_encode().

..I don't WP so I cannot say if there any native techniques to leverage.

The first function could look like this:

function get_publisher(\WP_REST_Request $request) {
    $request = json_decode($request);
    if (empty($request['ID'])) {
        $response['status'] = 404;
        $response['data']['errors']['general'] = 'Sorry, no record was found.';
    } else {
        $response['status'] = 200;
        $response['data']['publisher'] = $request['ID'];
    }
    return json_encode($response);
}


Interesting question,

this code pass JSHint, it is readable, well organized and except for return definitions; (where did you declare definitions?) holds few mysteries to me.

Still, when I take a step back, why not simple use a bog standard Object? It seems as if you just re-invented the Object with few added benefits.


Sorting a list of numbers in increasing order

What you've written is called "selection sort", and it works fine. It's not the best sort, but it's not bad, either.  It's one of a class called "n^2" sorts, because it generally runs in time proportional to the square of the length of the list.

Selection sort is a somewhat painful sort to write in a recursive style, because removing an element from a list is not so natural.

You can make it look a smidgen more natural if you rebuild the list on the way back out after removing it. However, the second pass over the list (as you've written it) does not change the asymptotic running time; it's still "order n-squared".

One note: you gain nothing by mutating "b" in the body of "find-shortest." Instead, replace

(set! b (car tl)) (find-shortest (cdr tl) b)

with

(find-shortest (cdr tl) (car tl))

... to make your code shorter and cleaner.

Also, If you were in my class, I would ask you for purpose statements and test cases. :)


Basic string compression counting repeated characters

As @vnp said, don't print the result for "testing". Convert each statement in the main method to proper unit tests, for example:

@Test
public void test_aabcccccaaa() {
    assertEquals("a2b1c5a3", compress("aabcccccaaa"));
}

@Test
public void test_a5() {
    assertEquals("a5", compress("aaaaa"));
}

Once this is done, you can go ahead and safely refactor the rest of the code,
having an easy way to repeat the tests.

Being aware of, and working knowledge of unit testing should definitely score you extra points in a job interview, or might be even required.

Bug

For single letter inputs, the method seems to return an empty string. That looks incorrect. Judging by that for "abc" it returns "a1b1c1", it would seem that for "a" it should return "a1" instead of an empty string

Simplify

The algorithm can be simplified to these steps:

Loop over the characters, from the 2nd till the end
If the current character is the same as the previous, increment the count
If different, append the count and append the previous character
After the end of the loop, append the count

The implementation can be something like this:

public String compress(String str) {
    if (str.isEmpty()) {
        return "";
    }

    char[] chars = str.toCharArray();
    StringBuilder builder = new StringBuilder();

    int count = 1;
    char prev = chars[0];
    for (int i = 1; i < chars.length; i++) {
        char current = chars[i];
        if (current == prev) {
            count++;
        } else {
            builder.append(prev).append(count);
            count = 1;
        }
        prev = current;
    }
    return builder.append(prev).append(count).toString();
}


Implementing a thread-safe factory with caching

If you are on Java 8, you can use a cool new feature of ConcurrentMap: computeIfAbsent.

It lets you defer the actual construction of the Connection until it becomes necessary and makes your code more concise:

private static ConcurrentMap<ConnectionSettings, Connector> connectorCache =
    new ConcurrentHashMap<ConnectionSettings, Connector>();

public static Connector newConnection(String url, String user, String psswd)
        throws ConfigurationException {

    ConnectionSettings settings = new ConnectionSettings(url, user, psswd);
    return connectorCache.computeIfAbsent(settings, Connector::new);
}

Note the two arguments to computeIfAbsent:

The first is your ConnectionSettings instance, which is used as a key.
The second is an instance of the interface Function. If called, it gets the settings as an argument and must return an instance of Connector. The function is defined by using a lambda expression, in this case a constructor reference. This is possible because the constructor of Connector does exactly that: it takes the settings as an argument and returns a Connector instance.

The call tells your connectorCache to check for the specified settings. If they exist the corresponding connector is returned. If not (and only then!) is the function executed, which creates a new Connector. (Of course in that case the new instance is put into the map.)

So you see the constructor is only invoked if needed. All necessary locking for concurrency is done by the map and you don't have to worry about it.


Table class to fill array structure with values

Refactored Code

This is a possible way to refactor the code to meet the style guidelines of Ruby using Rubocop.

# frozen_string_literal: true

# A simple table with rows and cols
class Table
  attr_reader :grid

  def initialize(rows:, columns:)
    @grid = construct(rows, columns)
  end

  def construct(rows, columns)
    unless rows.is_a?(Array) && columns.is_a?(Array)
      raise 'arguments must be arrays'
    end

    table = []
    rows = [] if rows.nil?
    rows.each do |_row|
      table << columns.map { |c| c }
    end
    table
  end
end

Style Considerations

A guard clause should be appended wih an empty line. Also, since the line is over 80 characters, split it up in multi-line.

raise 'arguments must be arrays' unless rows.is_a?(Array) && columns.is_a?(Array)
table = []

unless rows.is_a?(Array) && columns.is_a?(Array)
  raise 'arguments must be arrays'
end

table = []

You have an unused block argument row and the map should be rewritten using {..}.

rows.each do |row|
  table << columns.map do |c| c end
end

rows.each do |_row|
  table << columns.map { |c| c }
end

General Guidelines and Conventions

The tool also complained about the following guidelines.

use 2 instead of 4 white spaces for indentation
remove any trailing white space
remove space before comma
add a frozen string literal comment justification
add top level class documentation comment


Multi-digit number is what is throwing it off. I typically fix this by opting to find the highest number and then offset the rest of them appropriately.  I did this back when I was messing around with polynomial triangles.

Fixing the spacing issue

I started by getting the longest possible number and then prepending the space before it to make it line up properly.

Nextly, you have to fix the preappend so it looks better over size 2.  This is accomplished over a fairly odd algorithm.

As for the rest of the code, I did not have time to look at it, but will in a bit.

Fixing structure

Overall, your code looked pretty good.  Here are just some suggestions.

I went ahead and moved the pascal array generation to another function.  The idea of a function is that it performs a task.  Logically breaking up these tasks into multiple functions limits the size of each function and increases readability.  From there, we can assign it to a variable inside the pascal function.  I used the intuitive name generatePascalArrays, so you can get the gist of what the function does from the variable assignment.

Secondly, I noticed you split the 1 and 0 exception cases, I combined that into one if and console.log(num).

Additionally, I did use some arrow functions.  In other languages, you may have heard of them as lambda functions.  If you are not familiar with them, here is a link.

function generatePascalArrays(num) {
  var result = [[1],[1,1]];
  for (var i = 2; i < num; i++) {
    result[i] = [];
    result[i][0] = 1;
    for (var j = 1; j < i; j++) {
      result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
    }
    result[i][j] = 1;
  }
  return result;
}

function pascals(num) {
  if (num <= 1) {
    console.log(num);
  }
  var result = generatePascalArrays(num),
      width = Math.max(...result[result.length-1]).toString().length;
  for (var i = 0; i < result.length; i++) {
 let preOffsetter = result[result.length-i-1].length * Math.floor(width/3) + result.length - i
 console.log(' '.repeat(preOffsetter) + result[i].map((x) => ' '.repeat(width - x.toString().length) + x));
  }
}

pascals(5)
pascals(6)
pascals(10)


App for a tabletop RP that generates hits and misses for weapons

The way you normally emulate switches in Python is with a dictionary. That's a bit of a funny solution when you have to evaluate all these conditions though. If they were regular values then you could mathematically determine them and save lines that way, but since you have the odd variations those changes would only obfuscate your code for the sake of a cleverer seeming solution. I would suggest you gather the printed values into a result at least. You could access them with a value key and return that value the same way.

hit_strings = {
                5: "CRIT! HEADSHOT!"
                3: "Lethal!",
                2: "Severe!",
                1: "Ouch!",
                0.5: "Grazed!",
                0: "Miss!",
              }

def hitCheck(rng, acc):
    hitTotal = acc + rng
    if hitTotal > 190:
        result = 5
    if 160 < hitTotal < 191:
        result = 4
    if 120 < hitTotal < 161:
        result = 2
    if 80 < hitTotal < 121:
        result = 1
    if 40 < hitTotal < 81:
        result = 0.5
    if 0 < hitTotal < 41:
        result = 0

    print (hit_strings[result])
    return result

It's still long, but this does make it more modular and easier to expand with more values.

The luck generator isn't particular different no, just have one call. You should also remove your defunct comments that you used as print tests.

Your big problem in getReady is that you try to cram everything into one function. You could separate them out easily with functions like get_attempts

def get_attempts():
    while True:
        print("\n")
        total = input('Max attempts: ')
        print("\n")
        if total == '' or int(total) < 0:
            print("Value must be higher than 0!")
        else:
            total = int(total)
            return total

#Here's the main part of the app.
def getReady():
    running = False
    while not running:
        i = downed = total = 0
        total = get_attempts()

Though going back to get_attempts, you should just put newline characters in your input string instead of on separate lines. Also it's better to validate that input is actually a number. The most Pythonic way to do this is to attempt to turn it into an integer and catch it if that's not possible.

def get_attempts():
    while True:
        total = input('\n\nMax attempts:\n\n')
        try:
            total = int(total)
        except ValueError:
            print("Value must be a number!")

Then you can test if it's greater than 0 and print the other message if it's not.

        if total > 0:
            return total
        print("Value must be higher than 0!")

Splitting up your functions like this will make your code much neater and easier to change.


Support static typing / analysis with dependency injection

As far as I can tell, the use case you are targeting is already supported by the completion callback, even when you are using promises.  I have had good luck using the following pattern to ensure that asynchronously initialized, promise based libraries are fully initialized before testing begins:

let client;

// Note the function now accepts argument `done`
before(function(done){
    client = new Client({port: 7033}).ensure().then(done)
                                     .catch(function (reason) {
                                         console.error(reason);
                                     });
});

it('tests client', function(){
    assert(client.isConnected);   // we know client is initialized
});

As you correctly pointed out this is similar to returning the promise.

let client;

before(function(){
    client = new Client({port: 7033}).ensure()
                                     .catch(function (reason) {
                                         console.error(reason);
                                         throw reason;
                                     });
    return client;
});

it('tests client', function(){
    assert(client.isConnected);   // we know client is initialized
});

In either case, the initialization should be guaranteed complete before testing continues.  So unless I am missing something, there should not be any ambiguity about the initialization state.

If you wish to initialize before each test, it works just as well with beforeEach(...).  Also, note that there is a timeout that will cause test failure if done is not called quickly enough.  Reference the docs if you need to extend the timeout as there are a variety of patterns.

While I think the existing pattern fully addresses your use case, you might prefer the argument injection for stylistic reasons.  In that case I propose you can create a wrapper that calls the test function in the context of the client's then handler.

function provide_client(testFunc) {
    return function (done) {
        // Here I assume that the initialized client is passed through `then`.
        // If not fetch it from where ever appropriate.
        new Client({port: 7033}).ensure().then(function (client) {
            testFunc(client);
            done();
        }).catch(function (reason) {
            console.error(reason);
        });
    };
}

// Application
it('tests client', provide_client(function (client) {
    assert(client.isConnected);
}));


PEP 8 implementation is great, now to focus on being concise -

While you have started writing immaculate programs, as in here and your current question, I believe you should start making your programs more concise. This decreases memory space and sometimes, makes your program faster. Also, I'm glad to see you've started implementing the if __name__ == '__main__' guard.

Here's one approach you could use to make your program really concise and fast -

def zigzag(word: str, num_rows: int) -> str:

    ans = [''] * num_rows
    x = 0
    direction = 1
    for i in word:
        ans[x] += i
        if 0 <= x + direction < num_rows:
             x += direction
        else:
             direction *= -1
             x += direction
    return ''.join(ans)

if __name__ == "__main__":
    print(zigzag("PAYPALISHIRING", 3))

Here, I believe that it would be better if you don't declare word and num_rows before calling the function. This -

print(zigzag("PAYPALISHIRING", 3))

looks much shorter (and better) than -

word = "PAYPALISHIRING"
num_rows = 3
print("".join(line for array in zigzag() for line in array))

Also, (hey, I'm kind of like a beginner, so please correct me if I'm wrong) I feel that you should perform the .join() function, or any other function really, in the principal function, as I have done above -

# rest of the principal function
return ''.join(ans)

Just use the if __name__ == __main__ guard to (simply) call the principal function and execute the entire program (you shouldn't really perform any other function(s) in it except calling the principal function to execute it) -

if __name__ == "__main__":
    print(zigzag("PAYPALISHIRING", 3))

Also, I would rename increasing to direction as it suits this task better ("the value of "direction" changes only when we have moved up to the topmost row or moved down to the bottommost row" (taken from Leetcode). If you're wondering what *= means, it's just another way of doing x = x * 5, which is specified here.

Also, you could make -

array = []
for _ in range(num_rows):
    array.append([])

num_rows = 3
print(array)
# [[], [], []]

more concise by just simply initializing it -

array = [[] for _ in range(num_rows)]  # Thanks to Maarten Fabré

num_rows = 3
print(array)
# [[], [], []]

See how concise you can get by doing this? This removes the need to use .append(), which, in this case, is unnecessary (this will also take up less memory space).

  I know the final line is a bit messy, and I could unpack it into a
  two-line for loop but I really like single-line for loops.

Nah, don't worry. As far as I know,

print("".join(line for array in zigzag() for line in array))

is so much more concise than unpacking it into a two-line for loop. I'm glad you like single-line for loops :)

Here are the times taken for each function -

Your function -

%timeit "".join(line for array in zigzag() for line in array)
8.34 µs ± 834 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

My function -

%timeit zigzag("PAYPALISHIRING", 3)
4.19 µs ± 134 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

As you can see above, the time taken for execution has been approximately halved, which also shows that making your function concise, down to what I have done in my function, can make your program much faster.

Here is the Leetcode result for my program (if need be) -

Hope this helps!


Explicit visibility

I don't like relying on standard visibility; explicit declaring takes away all doubts. Instead have this:

private int[] queue;
private int front;
private int rear;
private int currentSize;
private int size;

Implicit this

Contrary to the above having explicit this is unneeded and takes away from the readability. You should only use it when there is ambiguity with a parameter name. This results in this:

queue = new int[size];
front = 0;
rear = 0;
this.size = size;
currentSize = 0;

Naming

What is currentSize and how does it differ from size? At first glance I would think they're the same. Some alternative names

size:

size
maxSize

currentSize:

index
offset

Iterator

If you want your class to be able to be used in a foreach loop, you could implement Iterator<T>.

Generics

Your datastructure is not generic so you're losing out on a lot of possibilities.

Kaput

Your code isn't working as it is. I'm not entirely sure why (it's 3:30 AM so I'm not going to debug it deeply anymore) but I followed a hunch and this small example demonstrates it:

public static void main(String[] args) {
    CircularQueue cq = new CircularQueue(3);
    cq.add(5);
    cq.add(10);
    System.out.println(cq.poll());
    cq.add(15);
    System.out.println(cq.poll());
}

You'll notice that the last call to poll() will throw you your self defined exception (aka front > rear evaluates to true).


Compute conditional median of PANDAS dataframe

So, you want to get the medians of the groups by removing each value from the group in turn:

        group  =>  individual removal of values

          NaN      [  ]   NaN   NaN   NaN
         25.0  =>  25.0  [  ]  25.0  25.0
         15.0      15.0  15.0  [  ]  15.0
         19.0      19.0  19.0  19.0  [  ]

median   19.0      19.0  17.0  22.0  20.0

An other way of doing, beside manually reconstructing the group without the current value for each value, is to build the above intermediate matrix and ask for the median on each column. This will return a Series of length the length of the group, which is supported by SeriesGroupBy.transform.

The steps to get the desired result are:

build the matrix by repeating the input group as many time as its length;
fill the diagonal of the matrix with NaNs;
ask for the median by row/column depending on how you built the matrix.

The function that can be fed to transform may look like:

def median_without_element(group):
    matrix = pd.DataFrame([group] * len(group))
    np.fill_diagonal(matrix.values, np.NaN)
    return matrix.median(axis=1)

An other advantage of this approach is that you are able to reuse the same groups of elements and so cut on the need to recompute them again and again:

import numpy as np
import pandas as pd

def median_without_element(group):
    matrix = pd.DataFrame([group] * len(group))
    np.fill_diagonal(matrix.values, np.NaN)
    return matrix.median(axis=1)

def compute_medians(dataframe, groups_column='Time', values_column='A'):
    groups = dataframe.groupby(groups_column)[values_column]
    dataframe['Feature_1'] = groups.transform(np.median)
    dataframe['Feature_2'] = groups.transform(median_without_element)

if __name__ == '__main__':
    df = pd.DataFrame({
            'Time': [0.0, 1.0, 2.0, 0.0, 1.0, 2.0, 0.0, 2.0, 0.0, 1.0, 2.0],
            'Id': [1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4],
            'A': [10, 15, np.NaN, 11, 16, 25, 10, 15, 9, 14, 19],
    })
    compute_medians(df)
    print(df)


Style guide

You should code your Python to follow PEP (Python Enhancement Proposal) documents, and in particular, PEP8.

PEP8

Comparing your code to PEP8's standards shows quite a few violations.

You should have whitespace between your binary operators.

factors=[]
number=int(n)

Two blank lines after a declaration

from operator import mul
from math import sqrt, ceil

def next_prime_factor(n):

Comparison to None: instead of != None it should be is not None

x=filter(None, numbers) + [2] if filter(None, numbers) != None else [2]

Line too long: PEP8 has a maximum character count of 79 characters per line, this line has 82:

print 'The smallest number with more divisors than the inputted number is',ans,'.'

while 1 should be denoted as while True instead:

while 1:

Whitespace and naming

You have double indentation here:

while number > 1:
            f=next_prime_factor(number)
            factors.append(f)
            number /= float(f)
            number=int(number)
            if number==1:break

You should avoid names like this:

numbers = range(3, max_n+1, 2)
half = (max_n)/2

Their purpose is a little confusing. Try to use more descriptive names that better describe what they are.

You should name your variables like snake_case:

primecounts

Unnecessary logic

div_count=reduce(mul,div_exps(pcount),1)
return div_count

You're defining a variable right before returning it, just return it directly.

for i in primes_list:
    primecounts.append(factors.count(i))
return v

You can use the list comprehension notation instead:

primecounts = [factors.count(i) for i in primes_list]

if div_count(end_num)<=div_count(last_num):
    end_num*=min(div_count_factors)
else:
    break

When you have a block that looks like this:

if condition == true/false:
    doSomething()
else:
    endBlock #return, break, continue

When the block terminates in the else loop, you can reverse the conditions and reduce a layer of logic:

if condition != true/false:
    endBlock

doSomething()

So, you can simplify that above block down:

if div_count(end_num) > div_count(last_num):
    break

end_num *= min(div_count_factors)

The code after the if is not needed: filter always returns a list, which is empty, if no elements remain. This results in identical behavior to the current code.

x=filter(None, numbers) + [2] if filter(None, numbers) != None else [2]


How can this this URL Checker be made cleaner?

one line functions make your logic hard to follow, I would advise strongly against them.
Especially if you only call that function only once, which is the case in most of your code.

As a very minor comment, I would put

curl_setopt($this->curl, CURLOPT_NOBODY, true);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);

inside __construct(), it should be a tiny bit more efficient.

One more minor comment, $url could easily be passed as a parameter, why make it a property?

All that taken into account, I would rather maintain something like this:

class URLChecker
{
private $curl;

public function __construct()
{
    $this->curl = curl_init();
    curl_setopt($this->curl, CURLOPT_NOBODY, true);
    curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
}

public function __destruct()
{
    curl_close( $this->curl );
}

public function URLisValid( $url )
{
    $httpcode = $this->getHttpCodeForURL( $url );
    return  $httpcode == 200; //HTTP_RESPONSE_OK
}

private function getHttpCodeForURL( $url )
{
    curl_setopt($this->curl, CURLOPT_URL, $url);
    curl_exec( $this->curl );
    return curl_getinfo( $this->curl, CURLINFO_HTTP_CODE );
}
}


Extract left text outside the parenthesis if any

Assuming the text on the left cannot contain opening parenthesis, splitting by the first opening parenthesis might work as well:

>>> clean_title = 'Alone in the Dark (The Cincinnati Series Book 2)'
>>> clean_title.split('(', 1)[0].lower().rstrip()
'alone in the dark'

Note that it will not fail even if there are no parenthesis:

>>> clean_title = 'Test'
>>> clean_title.split('(', 1)[0].lower().rstrip()
'test'

As far as the regular expression approach, you might also use re.sub() which would not require checking if there is a match or not. And, as a bonus, let's account for the extra space before the parenthesis:

>>> re.sub(r"(.*?)\s?\(.*?\)", r"\1", clean_title).lower()
'alone in the dark'

Or:

>>> re.sub(r"\s?\(.*?\)", r"", clean_title).lower()
'alone in the dark'

You can also do the lowering part in a replacement function:

>>> re.sub(r"(.*?)\s?\(.*?\)", lambda m: m.group(1).lower(), clean_title)
'alone in the dark'

Also note that I'm using non-greedy regular expressions.


I think you should take a look at std::chrono and std::thread.

If you want to replicate, say, a VB timer or whatever (something that calls a function every second), you can do this:

template<typename Func>
void timer(Func func, unsigned interval)
{
    while(true)
    {
        std::this_thread

        std::this_thread::sleep_for(;
            std::chrono::milliseconds(interval));
        func();
    }
}

Of course, you can change that into a functor and give it a bool for start and stop.

if you just want to measure the elapsed time then just use chrono

std::chrono::system_clock::time_point start=std::chrono::system_clock::now();
//start timer
//do stuff
std::chrono::duration<double> time_taken=std::chrono::system_clock::now() - start;

Don't reinvent the wheel.  If you don't have access to C++11, then all of this functionality can be used from Boost.


You don't use ExeConfigurationFileMap configMap in any of your methods just get rid of it. If you do copy&pasta you should always check if some cleaning needs to be done.
You are calling this

Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
ConfigurationSectionGroup userSettingsGroup = config.SectionGroups["UserSettingsGroup"];

in every GetXXX method. Extract it to a separate method.
Something like

table = GetConfigurationPrinterSection();
return table;

doesn't buy you anything. Just return directly which makes it possible to reduce the scope of table to only the first case.
The GetConfigurationConnectionStringsSection() method already returns a ConnectionStringsSection so there is no need to read it as ConfigurationSection only to cast it to a ConnectionStringsSection. Changing this would also make the ConnectionStringSettingsCollection col superfluous.
To make your life a little bit easier you could use the var type at places where it is obvious from the right hand side of an assignment which type is meant.
The lines where you read the e.g printerSettings are a little bit long.

If we would change the GetXXX methods like mentioned we would get

private static ConfigurationSectionGroup FetchConfigurationSectionGroup(string groupName)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
    return config.SectionGroups[groupName];
}
private static string FetchSectionName(ConfigurationSectionGroup group, string sectionName)
{
    return group.Sections.Get(sectionName).SectionInformation.SectionName;
}
private static Hashtable GetConfigurationPrinterSection()
{
    ConfigurationSectionGroup userSettingsGroup = FetchConfigurationSectionGroup("UserSettingsGroup");
    Hashtable sectionSettings = ConfigurationManager.GetSection(FetchSectionName(userSettingsGroup,"printerSettings")) as Hashtable;
    return sectionSettings;
}

private static Hashtable GetConfigurationReportsFolderSection()
{
    ConfigurationSectionGroup userSettingsGroup = FetchConfigurationSectionGroup("UserSettingsGroup");
    Hashtable sectionSettings = ConfigurationManager.GetSection(FetchSectionName(userSettingsGroup, "reportsFolderSettings")) as Hashtable;
    return sectionSettings;
}

but as you see we still have some code duplication here, so a method FetchSetting(string groupName, string sectionName) would help us to remove that duplication like so

private static Hashtable FetchSetting(string groupName, string sectionName)
{
    ConfigurationSectionGroup userSettingsGroup = FetchConfigurationSectionGroup(groupName);
    return ConfigurationManager.GetSection(FetchSectionName(userSettingsGroup, sectionName)) as Hashtable;
}
private static ConfigurationSectionGroup FetchConfigurationSectionGroup(string groupName)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
    return config.SectionGroups[groupName];
}
private static string FetchSectionName(ConfigurationSectionGroup sectionGroup, string sectionName)
{
    return sectionGroup.Sections.Get(sectionName).SectionInformation.SectionName;
}
private static Hashtable GetConfigurationPrinterSection()
{
    return FetchSetting("UserSettingsGroup", "printerSettings");
}

private static Hashtable GetConfigurationReportsFolderSection()
{
    return FetchSetting("UserSettingsGroup", "reportsFolderSettings");
}

which looks quite nice and tidy.

But wait, what about the ConnectionStringsSection ? If we remove everything which isn't necessary we will end with

private static ConnectionStringsSection GetConfigurationConnectionStringsSection()
{
    return (ConnectionStringsSection)FetchConfigurationSectionGroup("UserSettingsGroup")
        .SectionGroups.Get("StoredConnectionSettings")
        .Sections.Get("defaultConnectionString");
}

but because the HashTable table will only be used for that value we should generate the HashTable there which will lead to

private static Hashtable GetConfigurationConnectionStringsSection()
{
    var section= (ConnectionStringsSection)FetchConfigurationSectionGroup("UserSettingsGroup")
        .SectionGroups.Get("StoredConnectionSettings")
        .Sections.Get("defaultConnectionString");

    Hashtable table = new Hashtable();
    ConnectionStringSettingsCollection col = section.ConnectionStrings;

    foreach (ConnectionStringSettings settings in section.ConnectionStrings)
    {
        table.Add(settings.Name, settings.ConnectionString);
    }

    return table;
}

leaving the former GetStoredSettings() like this

public static Hashtable GetStoredSettings(StoredSettingsType sectionType)
{

    switch (sectionType)
    {
        case StoredSettingsType.DBConnection:
            {
                return GetConfigurationConnectionStringsSection();
            }

        case StoredSettingsType.Printer:
            {
                return GetConfigurationPrinterSection();
            }

        case StoredSettingsType.ReportsFolder:
            {
                return GetConfigurationReportsFolderSection(); ;
            }
        default:
            {
                return null;
            }
    }
}

which looks strange with the given name, so let us rename the GetXXX methods which will lead to this

private static Hashtable FetchConnectionStringsSetting()
{
    var section= (ConnectionStringsSection)FetchConfigurationSectionGroup("UserSettingsGroup")
        .SectionGroups.Get("StoredConnectionSettings")
        .Sections.Get("defaultConnectionString");

    Hashtable table = new Hashtable();
    ConnectionStringSettingsCollection col = section.ConnectionStrings;

    foreach (ConnectionStringSettings settings in section.ConnectionStrings)
    {
        table.Add(settings.Name, settings.ConnectionString);
    }

    return table;
}
private static Hashtable FetchPrinterSetting()
{
    return FetchSetting("UserSettingsGroup", "printerSettings");
}

private static Hashtable FetchReportsFolderSetting()
{
    return FetchSetting("UserSettingsGroup", "reportsFolderSettings");
}
private static Hashtable FetchSetting(string groupName, string sectionName)
{
    ConfigurationSectionGroup userSettingsGroup = FetchConfigurationSectionGroup(groupName);
    return ConfigurationManager.GetSection(FetchSectionName(userSettingsGroup, sectionName)) as Hashtable;
}
private static ConfigurationSectionGroup FetchConfigurationSectionGroup(string groupName)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
    return config.SectionGroups[groupName];
}
private static string FetchSectionName(ConfigurationSectionGroup group, string sectionName)
{
    return group.Sections.Get(sectionName).SectionInformation.SectionName;
}
public static Hashtable GetStoredSettings(StoredSettingsType sectionType)
{

    switch (sectionType)
    {
        case StoredSettingsType.DBConnection:
            {
                return FetchConnectionStringsSetting();
            }

        case StoredSettingsType.Printer:
            {
                return FetchPrinterSetting();
            }

        case StoredSettingsType.ReportsFolder:
            {
                return FetchReportsFolderSetting(); ;
            }
        default:
            {
                return null;
            }
    }
}


Hash function for a key of type structure

"Is this a good hash function?" is not a question that can be answered in isolation.  It depends greatly on the expected distribution of the inputs and on the desired distribution of its output.  Do you want each bit of the output to be equally likely to be 0 or 1, for example?

Here, I'm going to assume that you want the minimal requirements for a hash function - maximum likelihood of different outputs for different inputs, and no requirements for cryptographic-strength collision resistance.

It's interesting that you're combining the content pointed to by k2 and k3 but that value of the pointer k1 - a comment is needed to explain why this is what you want.

I assume that you are constrained to the signature unsigned long (*)(void*) by some library.  A pointer to const void would be better as the argument, as your hash function really mustn't modify its argument.  Failing that, you can declare k as pointer-to-const:

    hash_key_t const *const k = key;

(It's C, so void* will promote to any other pointer).

The repeated code to hash the two strings can be extracted into a function:

static unsigned long hash_string(const char *s, unsigned long h)
{
    if (!s) return h;
    while (*s)
        h = h * 31 + *s++;
    return h;
}

unsigned long hash_func (void *key)
{
    const hash_key_t *const k = key;
    unsigned long h = 0;

    h = hash_string(k->k2, h);
    h = hash_string(k->k3, h);

    h = h*31 + (unsigned long)k->k1;
    return h*110351524UL;
}

I removed the right-shift of k1 in the above - that doesn't add any extra entropy to the hash, and may (on some platforms) reduce it.  But I have left your magic constant untouched - see next section.

An aspect of your algorithm that's a little suspect is the final constant. It is an even number - worse, it's a multiple of 4; this is throwing away two bits from your result.  I'm not convinced there's a good reason to multiply the final result - you'll need to justify it given the expected inputs and desired distribution of result.

Because you effectively concatenate the two strings, you'll get collisions between "ab", "c" and "a", "bc".  That may or may not be a problem for your inputs, but it's worth noting in a comment in case you want to repurpose this in future.  If it's undesirable, you could either perform another multiplication between the strings or you could provide a different per-character constant to each invocation.

Rather than reinventing the wheel, you may be able to re-use (or at least copy) an existing algorithm.  For example, if your code is GNU GPL compatible, here's the glibc implementation:

/* We assume to have `unsigned long int' value with at least 32 bits.  */
#define HASHWORDBITS 32

/* Defines the so called `hashpjw' function by P.J. Weinberger
   [see Aho/Sethi/Ullman, COMPILERS: Principles, Techniques and Tools,
   1986, 1987 Bell Telephone Laboratories, Inc.]  */
static inline
unsigned long int
hash_string(const char *str_param)
{
    unsigned long int hval, g;
    const char *str = str_param;

    /* Compute the hash value for the given string.  */
    hval = 0;
    while (*str != '\0') {
        hval <<= 4;
        hval += (unsigned long int) *str++;
        g = hval & ((unsigned long int) 0xf << (HASHWORDBITS - 4));
        if (g != 0) {
            hval ^= g >> (HASHWORDBITS - 8);
            hval ^= g;
        }
    }
    return hval;
}


Make Simultaneous HTTP Requests That Resolve Into a Single Return

Compatibility aside, you can skip jQuery. Everything you need is present in vanilla JS. jQuery AJAX can be replaced by fetch and deferreds can be replaced by native Promise. As an added bonus, use template literals to easily construct strings.

// Work on the very basic data, the IDs
const ids = [
  '275cd1b76574497327761b33fb08ad4d',
  '275cd1b76574497327761b33fb08ad4d'
];

// Map IDs into urls
const urls = ids.map(id => `/gh/gist/response.html/${id}/`);

// Construct a function that transforms the Response object into an img
const responseToImage = res => `<img src="data:image/png;base64,${res.text()}"/>`;

// For each, send request, convert response to img, and store promise in array
const promises = urls.map(url => fetch(url).then(responseToImage));

// Wait until all promises resolve, then append image
Promise.all(promises).then(images => {
  const container = $('#myDiv').show();
  images.forEach(image => container.append(image));
});

As for your code, a few things

var gistID = '275cd1b76574497327761b33fb08ad4d';

function Source(url){
 this.url = url;
};

var source = new Source("/gh/gist/response.html/" + gistID + "/");
var sources = [source,source];

This code doesn't look scalable. If say I wanted to add more images, different images, there is no way for this code to do that without having to modify several lines of code. In this case, gistId has to be abandoned, you'd have to write new Source(...) for each item, and update the sources array.

Also, insider tip: It's a bad sign if a really simple code update results in modification of several lines. Also, writing code this way results to bad habits which can hurt in the long run.

function asyncGroup() {

 var promises = [];

 sources.forEach(function(source,index,sources){

  var deferred = jQuery.Deferred();

  promises.push(deferred.promise());

  $.ajax({url: source.url, processData: false}).always(function(data){
   sources[index].element = '<img src="data:image/png;base64,' + data + '"/>';
   deferred.resolve();
  });
 });
 return promises;
}

The $.ajax function already returns a Deferred-like, jqXHR object. You don't need to "wrap" it in a Deferred, this is already redundant. You can simply push its return value to the array. Additionally, when doing 1:1 conversion from one array to another, array.map is the function you want. With these, you can remove all that boilerplate code to transform source.url to an array of deferreds.

$.when.apply(null, asyncGroup() ).done(function( status ) {
 sources.forEach(function(source){$("#myDiv").append($(source.element));});
 $("#myDiv").show();
});

You can cache the result of $('#myDiv') in a variable so that you don't have to call it repeatedly. Additionally, jquery.append accepts HTML strings as argument. No need to convert it first.


API request, conversion from 12-hour to 24-hour format and conversion from UTC to MET time

Welcome to CodeReview! This is a great first question.

Do not do your own time math

...nor your own formatting when possible. Tell Python to do it for you. Some example code:

from dataclasses import dataclass
from datetime import timedelta, datetime, timezone
import requests, pytz

@dataclass(frozen=True)
class DayInfo:
    day_length: timedelta
    sunrise: datetime
    sunset: datetime
    solar_noon: datetime
    civil_twilight_begin: datetime
    civil_twilight_end: datetime
    nautical_twilight_begin: datetime
    nautical_twilight_end: datetime
    astronomical_twilight_begin: datetime
    astronomical_twilight_end: datetime

    @classmethod
    def get(cls, lat: float, long: float, tz: timezone) -> 'DayInfo':
        """ Function twilightApiGetList(key):
            Calls the sunrise-sunset api to return the value of a given key
            All times returned are in the provided timezone.
        """
        with requests.get(
            'https://api.sunrise-sunset.org/json',
            params={
                'lat': lat,
                'lng': long,
                'date': 'today',  # technically this can be omitted
                'formatted': 0,   # we want ISO8601 ("machine-readable")
            },
        ) as response:
            response.raise_for_status()
            data = response.json()

        if data['status'] != 'OK':
            raise requests.HTTPError(data['status'], response=response)
        results = data['results']

        return cls(
            day_length=timedelta(seconds=int(results['day_length'])),
            **{
                k: datetime.fromisoformat(results[k]).astimezone(tz)
                for k in (
                    'sunrise',
                    'sunset',
                    'solar_noon',
                    'civil_twilight_begin',
                    'civil_twilight_end',
                    'nautical_twilight_begin',
                    'nautical_twilight_end',
                    'astronomical_twilight_begin',
                    'astronomical_twilight_end',
                )
            },
        )

if __name__ == "__main__":
    day_info = DayInfo.get(44.244622, -7.768863, pytz.timezone('MET'))
    print(f'{day_info.civil_twilight_begin:%H:%m}')
    print(f'{day_info.civil_twilight_end:%H:%m}')

Notes:

You didn't parameterize the right things. Parameters should be coordinates and timezone.
Ask the API for machine-readable (ISO) dates.
Might as well parse everything from the API.
Do not use string manipulation to get your desired format. What is shown is string interpolation with standard Python time fields.
Use requests - it has a lot of niceties that make this easier.
Only issue one call to the API, returning an object that has both of the keys you care about. If you're never, ever going to use the other keys, you can delete them from this class, but they're inexpensive to generate - compared to a second HTTP call, which is much more expensive.


import unittest

#helpers
def Count(dice, number):

The python style guide recommends lowercase_with_underscores for global functions.

    return len([y for y in dice if y == number])

This can be written as

    return dice.count(number)

def HighestRepeated(dice, minRepeats):
    unique = set(dice)
    repeats = [x for x in unique if Count(dice, x) >= minRepeats]
    return max(repeats) if repeats else 0

This will be somewhat clearer if you find the highest repeated count and then check it against minRepeats. You can also use the counter class:

counts = collections.Counter(dice)
element, count = counts.most_common()[0]
return count if minRepeats <= count else 0

def OfAKind(dice, n):
    return HighestRepeated(dice,n) * n

def SumOfSingle(dice, selected):
    return sum([x for x in dice if x == selected])

Could be written as

    return collections.Counter(dice)[selected]

#strategies
def Chance(dice):
    return sum(dice)

def Pair(dice):
    return OfAKind(dice, 2)

def ThreeOfAKind(dice):
    return OfAKind(dice, 3)

def FourOfAKind(dice):
    return OfAKind(dice, 4)

def SmallStraight(dice):
    return 15 if tuple(sorted(dice)) == (1,2,3,4,5) else 0

Shouldn't a small straight consist of 4 elements in a row?

def LargeStraight(dice):
    return 20 if tuple(sorted(dice)) == (2,3,4,5,6) else 0

Can't a large straight start with 1?

def Ones(dice):
    return SumOfSingle(dice,1)

def Twos(dice):
    return SumOfSingle(dice,2)

def Threes(dice):
    return SumOfSingle(dice,3)

def Fours(dice):
    return SumOfSingle(dice,4)

def Fives(dice):
    return SumOfSingle(dice,5)

def Sixes(dice):
    return SumOfSingle(dice,6)

Writing so many functions that differ only in a parameter they pass to another function is odd.

def Yahtzee(dice):
    return 50 if len(dice) == 5 and len(set(dice)) == 1 else 0

Can't you assume that there are always 5 dice? Also, why don't you use OfAKind?

class YahtzeeTest(unittest.TestCase):
    testCases = (
        ((1,2,3,4,5), 1, Ones),
        ((1,2,3,4,5), 2, Twos),
        ((3,2,3,4,3), 9, Threes),
        ((3,2,3,4,3), 0, Sixes),
        ((1,2,3,4,5), 0, Pair), # no pairs found
        ((1,5,3,4,5), 10, Pair), # one pair found
        ((2,2,6,6,4), 12, Pair), # picks highest
        ((2,3,1,3,3), 6, Pair), # only counts two
        ((2,2,6,6,6), 18, ThreeOfAKind),
        ((2,2,4,6,6), 0, ThreeOfAKind), # no threes found
        ((5,5,5,5,5), 15, ThreeOfAKind), # only counts three
        ((6,2,6,6,6), 24, FourOfAKind),
        ((2,6,4,6,6), 0, FourOfAKind), # no fours found
        ((5,5,5,5,5), 20, FourOfAKind), # only counts four
        ((1,2,5,4,3), 15, SmallStraight),
        ((1,2,5,1,3), 0, SmallStraight),
        ((6,2,5,4,3), 20, LargeStraight),
        ((1,2,5,1,3), 0, LargeStraight),
        ((5,5,5,5,5), 50, Yahtzee),
        ((1,5,5,5,5), 0, Yahtzee),
        ((1,2,3,4,5), 15, Chance),
        )

    def testRunAll(self):
        for (dice, expected, strategy) in self.testCases:
            score = strategy(dice)
            self.assertEquals(expected, score, "got {0} expected {1}, testing with {2} on {3}".format(score, expected, strategy.__name__, dice))
        print 'ran {0} test cases'.format(len(self.testCases))

You are duplicating some of the logic of the unit test system here. I recommend using nose tests which would allow this one function to generate a number of tests each of which is considered an independent test by the unit testing system. Then you wouldn't need to spend so much effort.

I'd also consider writing functions for each of your tests rather then putting them in a huge list. The list technique is really nice but its best used for calling the same function. Using it to test so many different functions is odd.

if __name__ == '__main__':
    unittest.main()


Calculating longest increasing sub-sequence recursively

Time complexity

Your recursive solution works, but the time complexity is not optimal.  In the worst case where the array is sorted in increasing order, the time complexity appears to be \$O(n!)\$, because for each length you recurse on every length less than it.

What you need to do is to avoid recomputing solutions you've already found.  If you used some kind of memoization (i.e storing answers you've already found), you should be able to reduce the problem to time complexity \$O(n^2)\$.  For example, if you already computed _lis(arr, 5), then the next time you need to compute it, you should be able to just reuse the previous answer instead of recomputing it the recursive way.  All you would need to do is have an array of size n to store your results as you compute them.


)

My first comment is you should start looking at smart pointers.
They will definitely simplify your code.

The second comment: look at the STL containers.
Containers in C++ follow a specific pattern. The idea is that we want to use algorithms on containers interchangeably and thus containers follow these conventions to make them easy to use with the standard algorithms.

Third comment: you fail to follow the rule of three.
Basically. If you define one of 'Destructor'/'Copy-Constructor'/'Assignment-Operator' (rather than using the compiler generated defaults) then you probably need to define all three. In this case your code is going to crash if you make a copy of the list. The problem arises from having an owned pointer in your code.

Fourth comment: Prefer to be pass parameters by const reference. For simple objects like integers it will not make any difference. But you have templatised the code and T can be any type. Thus passing by value is going to cause a copy (which may be expensive).

Reviewing the above code:
The complexity of adding a node is O(n). By maintaining a head and a tail pointer you can change this to have a complexity of O(1). ie. this loop becomes unnecessary.

Node<T> * tmp = head;
while (tmp->next !=  head)
{
  tmp = tmp->next;
}

You have an output operator std::ostream & operator<<(std::ostream & os, const CircularLinkedList<U> & cll) It would be nice if you had a symmetric input operator. In this situation you need to worry about the size of the list (or adding a special terminating character). So the creation of the input operator will affect your design of the output operator.


Mapping a textual method name to a function

std::call_once is an interesting tool, but there are alternatives built into the language: namely, you can use the Immediately-Invoked Function Expression (IIFE) borrowed straight from JavaScript and made usable thanks to C++11 lambda functions.

Here is how you can use it to initialize handlerMap:

std::unordered_map<
    Glib::ustring,
    std::function<void(Minecraftd1*, const Glib::RefPtr<Gio::DBus::MethodInvocation>&)>
> handlerMap = []{
    using namespace std::placeholders;
    std::unordered_map<
        Glib::ustring,
        std::function<void(Minecraftd1*, const Glib::RefPtr<Gio::DBus::MethodInvocation>&)>
    > initMap;
    initMap.emplace("SaveAll", std::bind(&Minecraftd1::handleSimpleCommand, _1, _2, "save-all"));
    initMap.emplace("Stop", std::bind(&Minecraftd1::handleSimpleCommand, _1, _2, "stop"));
    return initMap;
}();

Agreed, it looks a bit messy with the big std::unordered_map type, but you could probably create a type alias to get rid of the syntactic mess. Even if you dont typedef the whole thing, I guess that exposing the type of std::function<void(Minecraftd1*, const Glib::RefPtr<Gio::DBus::MethodInvocation>&)> could be an interesting idea.

Alterntively, there is even better than IIFE: in your can, you can use initializer lists to achieve what you're trying to do:

std::unordered_map<
    Glib::ustring,
    std::function<void(Minecraftd1*, const Glib::RefPtr<Gio::DBus::MethodInvocation>&)>
> handlerMap = {
    { "SaveAll", std::bind(&Minecraftd1::handleSimpleCommand, std::placeholders::_1, std::placeholders::_2, "save-all") },
    { "Stop",    std::bind(&Minecraftd1::handleSimpleCommand, std::placeholders::_1, std::placeholders::_2, "stop") }
};

But it means that you have to explicitly write std::placeholders:: everywhere if you don't want using std::placeholders; to leak into the outer namespace. In other words, you have to choose which solutions seems to best convey your idea while not bearing too much syntactic noise.


Don't use the macro NULL.  Use the specific keyword nullptr now.
Your struct can be more simply written using immediate inline initializers.
struct ListNode {
    int val = 0;
    ListNode* next = nullptr;
    ListNode() = default;
    ListNode(int x) : val{x} {}
    ListNode(int x, ListNode* next) : val{x}, next{next} {}
};

Also note that the * goes with the type in C++, not with the name being declared.
Regarding
void reverse(ListNode** subHead, ListNode** subTail)
It appears that the names subHead and subTail are never modified by the code, so this would be easier if you passed references to the pointers, rather than having an extra explicit dereference operation when you use it.
ListNode* itHead = *subHead;
//...
while (itHead != end) {
    //...
    itHead = next;
}

This is just a for loop that's spread out for no reason.  The value of next you want is lost during the body of the loop, so I can see why you don't put that inside a for construct.  But you can put the declaration of subHead there... put the parts you can into a for loop, even if it's not all three of them.
Re:
if (*subHead==NULL) return;
Don't make explicit comparisons against null.  Use the truth predicates that are part of the (possibly smart!) pointer.
Combining this with the tip of using references (...ListNode*& subHead,) you get simply:  if (!subHead)  return;.
Re:
std::swap(*subHead, *subTail);
This works because you know that these are raw pointers.  But generally you write code like this as a template, or at least you code mostly as if you are writing a template, to ease future maintenance.  If the type of something changes, the code should at best still work; second but still OK is cause a compile-time error that you must fix; but bad is to silently fail.  Consider what would happen if these were not raw pointers but iterators of some type, including something supplied by your program or another library (not in std).
You need to use the so-called "std two-step" to use swap and a few others.  Or, if using C++20 you can use std::ranges::swap instead.  Always use swap etc. properly without relying on knowledge that the overload you want is indeed found in std.


if arr[mid] is value:

You don't want to compare two integers with is, which compares identity. Use == instead. is will break your code when using large or small numbers (\$<-5\$, \$>256\$).

For example, using is with this "test" function:

def test1():
    arr = list(range(257, 270))
    value = 260
    print_binary_search(arr, value)

Results with an infinite loop.

Using == works as expected and returns 3.

The reason is that Python uses integer caching for the range \$[-5, 256]\$.

And some PEP8 nitpicking:

while(left <= right):

The parenthesis around the condition are useless in this case, you should prefer a whitespace:

while left <= right:

You are missing some whitespaces after commas in function definition, function calls, list literals and around operators.

For example, your code should look like this (relevant lines only):

def print_binary_search(arr, value):

#######

pos = binary_search(arr, value)

#######

arr = [2, 5, 8, 9, 11, 15, 17, 19, 22, 26, 29, 33, 56]

#######

print("Element found in the position " + str(pos))


Transform a Binary Search Tree into a Greater Sum Tree

Compiler Warnings

  Iterable is a raw type. References to generic type Iterable should be parameterized

This is very easy to fix. It's horrible that you haven't fixed it already. I'm sure that you know what generics is by now so I don't need to explain it to you. Whenever you see this warning, add generics!

Iterable --> Iterable<Integer>

Problem solved!

Then you can get rid of the (Integer) cast next to itr.next();

Why Binary Search Tree?

My first thought, once I understood the problem your solving was: Why on earth do you have the data as a Binary Search Tree? What does the tree have to do with anything?

If this was a question given to me at an interview, I would ask them this. Why a Binary Search Tree? The operations you're doing is totally unrelated to a tree. You could just as well perform this on a regular int[]. If there is a good reason for why it has to be a Binary Search Tree then please explain it to me.

Here's a simple implementation of how to perform this on a regular int[], without using a Binary Tree:

public static void main(String[] args) {
    int[] input = new int[] { 1, 2, 7, 11, 15, 29, 35, 40  };
    int[] expected = new int[] { 139, 137, 130, 119, 104, 75, 40, 0 };
    transformToGreaterSum(input);
    System.out.println(Arrays.toString(input));
    System.out.println(Arrays.toString(expected));
}

private static void transformToGreaterSum(int[] input) {
    int sum = 0;
    for (int i = input.length - 1; i >= 0; i--) {
        int prevSum = sum;
        sum += input[i];
        input[i] = prevSum;
    }
}

Note that this is also \$O(n)\$ without using any extra space.

Broken Tree

I'd also like to point out that your actual search tree does not match your image. I found out by debugging your code that your actual search tree looks like this:

The fact that it looks like this, and the fact that your algorithm works at all, is just because your input is sorted: {1, 2, 7, 11, 15, 29, 35}.

Your tree is in fact not a correct Binary Search Tree. A correct tree could look like this:

Yes, that's still a tree. It just doesn't have any left nodes (it does have seven nodes left though, I didn't remove any). A child node that is bigger than its parent should be on the right, which makes this tree right. (I love the English language)

As if that was not enough, your int[] expected says:

int[] expected = {71, 87, 89, 72, 35, 42, 0};

But your image says:

119, 137, 75, 139, 130, 104, 0, 40

Given your description:

  Given a BST, transform it into greater sum tree where each node contains sum of all nodes greater than that node. Diagram is here.

I would expect the node for 11 to get the value 15 + 29 + 35 + 40 = 119. I don't see 119 anywhere in your expected or actual result though...

Verifying a Binary Search Tree

As your question contains an incorrect tree and one of your comments below has an incorrect tree, I'd like to provide you with a method to verify a correct tree:

private static void verifyNode(TreeNode node) {
    if (node.left != null) {
        if (node.left.item >= node.item) {
            throw new IllegalStateException("node.left >= node: " + node.left.item + " >= " + node.item);
        }
        verifyNode(node.left);
    }
    if (node.right != null) {
        if (node.right.item <= node.item) {
            throw new IllegalStateException("node.right <= node: " + node.right.item + " <= " + node.item);
        }
        verifyNode(node.right);
    }
}

Just pass it your root node and it will verify your tree recursively. Note that there are two things this method does not verify, that are also a requirement for a Binary Search Tree:

There must be no duplicate nodes.
A unique path exists from the root to every other node.

Arrays and Lists

Speaking of int[] I wonder why your constructor takes a List<Integer> instead of an array: int[]. I don't think you gain anything by using a list.

The only thing you gain at the moment by using Integer rather than int is the possibility for this:

if (items.get(i) != null) {

As your input never contains null (and I see no reason why it should), I don't get the point of using that non-null check. I modified your code to use int[] instead and removed the non-null checks and all worked well still. It even got rid of some indentation steps and felt like a cleanup overall.

Iterate over what?

If you would have your Iterator as Iterator<TreeNode> instead of Iterator<Integer> you could use your iterator in your computeSum method as well as in your test method to fetch the results. This would make you have to modify your iterator implementation though (but as your tree is not a real binary search tree, it's quite broken already).

Or you could just ignore the tree structure and use arrays....

Summary

Given how many trees I've seen you implement, I really thought your code would be better than this. Your current code doesn't live up to your requirements, or your requirements are messed up. Additionally, the "raw type" mistake is a mistake one just should not make after having written just a few Java classes.


When writing any kind of event method, I always try to minimize the code that executes because you don't want the user to be aware of processing that is happening between the keystrokes. In your case, your code is firing each time ANY cell on ANY sheet is changed. So in the spirit of keeping things streamlined, don't create, initialize, or perform any logic that you don't really need (until you need it). Using this philosophy, the beginning of my example method would look like this:

If Sh.Name = "Response" Then Exit Sub

Dim checkCells As Range
Set checkCells = Union(Sh.Range("B3"), Sh.Range("B5"))
If Intersect(Target, checkCells) Is Nothing Then Exit Sub
If Target.Address = vbNullString Then Exit Sub

Notice that if the changed sheet is "Response", then initializing any other variable is meaningless. Once we get past that, a checkCells range is established using the Union function. It may be a bit overkill sometimes, but clearly illustrates the idea that you're looking at multiple, non-contiguous cells/ranges.

Also, from your OP code, if either cell is empty, you are immediately exiting. So you can check the target address after the other checks right away.

But then I get into an issue where you check if the cell value is null, but right away you're checking that it has a value:

If Range("B3").Value = vbNullString Then Exit Sub
Application.EnableEvents = False
If Sh.Range("B3").Value <> vbNullString Then ...

This is redundant. And -- by the way -- you'll never get to your Else statement because you've already exited if B3 is a null string.

The statement in both parts of your If statement is confusing:

Columns.ClearColumns

Columns is a property of a Range or Worksheet, and ClearColumns is not a method of Range at all that I know of. So I'm assuming it's a part of the add-in. But if Columns is the name of one of your code modules, then change it. Using Columns is not a good name to use because it is the same as an existing property and is confusing. If you are clearing columns on a worksheet, then specify which worksheet always. I'm also assuming the Transactions is a code module in your VBA project as well.

Here is all of the code:

Option Explicit

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    If Sh.Name = "Response" Then Exit Sub

    Dim checkCells As Range
    Set checkCells = Union(Sh.Range("B3"), Sh.Range("B5"))
    If Intersect(Target, checkCells) Is Nothing Then Exit Sub
    If Target.Address = vbNullString Then Exit Sub

    Dim wsMyList As Worksheet
    Set wsMyList = ThisWorkbook.Sheets(2)

    Application.EnableEvents = False
    With Sh
        Dim lookupArea As Range
        If Target.Row = 3 Then
            Set lookupArea = wsMyList.Range("A:B")
            .Range("B4").Value = Application.WorksheetFunction.VLookup(Target.Value, _
                                                                       lookupArea, _
                                                                       2, False)
            .Range("B6").Value = "Type or Select a transaction"
            Columns.ClearColumns
            Transactions.FetchTransactions
        ElseIf Target.Row = 5 Then
            Set lookupArea = wsMyList.Range("D:E")
            .Range("B6").Value = Application.WorksheetFunction.VLookup(Target.Value, _
                                                                       lookupArea, _
                                                                       2, False)
            Columns.ClearColumns
            Columns.PopulateFields
        End If
    End With
    Application.EnableEvents = True
End Sub


Your code is correct as far as I can see. However, there are some
things which can be improved or simplified.

Let's start with the class Node definition:

Strictly speaking, data and prev are properties.
prev is – as I understand it – a pointer to the node that was added after this one, so I would call it next instead.
The class should be private because it is not indented to be
used outside of Queue.
data should be a constant because it is not mutated after the
creation of a node (attributions go to @Feldur who noticed that in
a comment).
Minor note: There should be a space before curly braces.

Then we have:

private class Node {
    // properties
    let data: String
    var next: Node?

    init(data: String) {
        self.data = data
    }
}

Consequently, head and tail are private properties as well:

// properties
private var head: Node?
private var tail: Node?

The enqueue() method can be simplified. head and tail are both
nil or not, so there is no need to check both. Here it makes sense
to check the tail via optional binding, so that a new node can be
appended if the list was non-empty, or a single-node list created
otherwise:

func enqueue(e: String) {
    let node = Node(data: e)
    if let lastNode = tail {
        lastNode.next = node
    } else {
        head = node
    }
    tail = node
}

The dequeue() method returns the string "empty" if the queue is
empty. This is a "magic string" and makes it impossible to store the
string "empty" itself in the queue. Swift optionals were make
for this very purpose: The method should return an optional String?
which is nil if the queue is empty.

The method can be simplified in a similar manner as enqueue().
Now we check the initial node via optional binding. Note that there
is no forced unwrapping (!)  anymore, which should generally be
avoided:

func dequeue() -> String? {
    if let firstNode = head {
        head = firstNode.next
        if head == nil {
            tail = nil
        }
        return firstNode.data
    } else {
        return nil
    }
}

In your test code, the queue variable can be defined and initialized in
a single statement:

var q = Queue()

Since dequeue() now returns an optional, we can remove elements in
a loop like this:

q.enqueue("One")
q.enqueue("Two")
q.enqueue("Three")

while let s = q.dequeue() {
    print(s)
}

Finally: There is nothing in the implementation which is particular
to strings. You can make the class generic so that it can be used
with other data types as well. Only minor modifications are
necessary:

Replace Node by Node<T> (and move it outside of Queue, as
Swift currently does not allow nested types in generic classes).
Replace Queue by Queue<T>.
Replace String by T.

Then it looks like this:

private class Node<T> {
    let data: T
    var next: Node?

    init(data: T) {
        self.data = data
    }
}

class Queue<T> {

    private var head: Node<T>?
    private var tail: Node<T>?

    func enqueue(e: T) {
        let node = Node(data: e)
        if let lastNode = tail {
            lastNode.next = node
        } else {
            head = node
        }
        tail = node
    }

    func dequeue() -> T? {
        if let firstNode = head {
            head = firstNode.next
            if head == nil {
                tail = nil
            }
            return firstNode.data
        } else {
            return nil
        }
    }
}

Test code:

var q = Queue<Int>()

q.enqueue(1)
q.enqueue(2)
q.enqueue(3)

while let i = q.dequeue() {
    print(i)
}


Constants in UPPERCASE

@username = 'user'
@password =  nil
@host     = 'server_to_run_command_on'

should be constants, as well as:

LOGFILE = "path/to/log.txt"

Marking a variable as constant in Ruby just needs upper-casing its name.

Return value simplification

res = check.exec!(cmd)
data = res
write_data(data)

Is unnecessarily long just write:

write_data( check.exec!(cmd) )

Other then this minor remarks, the code looks as straightforward and readable as it can get.


Forward values from JSON file as class attributes

Pathlib

Use it. It makes stuff like this:

os.path.join(os.getcwd(), "..", "data", "log.log"),

much nicer. It can also avoid this kind of thing:

"D:\dir"

namely, OS-specific directory separators. If you ever hope to have this be cross-platform, you'll want to remove your backslashes and use the libraries for path manipulation.


Search a file system for files that match a given pattern

Looks quite pythonic. However:

_ stands for don't care, akin to famous hunoz. It is not expected to be used in expressions later on; it is a placeholder.

Fot instance, I am totally lost in what

        for _ in [join(root, _) for _ in files if fnmatch.fnmatch(_, patt)]:
            yield _

does actually yield.

os.walk() works perfectly well on Windows
I don't see how do you want to break search into two functions. What would those functions do?
Any usable file matcher should have an option to specify file type (plain vs directory vs link vs etc), attributes, etc.


One role

Be careful to do only what the functions should.

The function is called compareVersions however what it does is validate and compare versions.

The potential throw is the result of validation and has nothing to do with comparing the values.

As you have not called the function validateAndCompareVersions you have over stepped its role.

How to throw

If (and try to avoid throwing exceptions), if you must throw, throw correctly.

In this case the first throw should be a RangeError and the message should make sense.

You have very poor error message  "Problem comparing versions: not a valid number"; The first part is redundant, exception contains a trace that will locate the "problem" and the "Problem" is implied in the fact that this is an exception.

"not a valid number" The arguments are version strings, "1.0.0" is not a number. The error should indicate the problem explicitly.

 throw new RangeError("Invalid version string: '" + (isNaN(v1) ? v1 : v2) + "'");

The second exception is a little better, but could be improved

 throw new RangeError("Invalid operator: " + o);

How to catch

Only catch what is thrown for you. Higher level catchers will handle the rest.

Having the throws in the function means you must add additional support code outside the function. Try catches break the flow of the code, not having a try catch means that a input error will halt the app.

try {
    compareVersions(a,b,type);
} catch(e) {
    if (e.name === "RangeError") {
        // do what is needed to prevent app from stopping
    } else {
        throw e; // rethrow for development cycle or high level catchers
    }
}

You may need to be a little more specific, you can either extend an existing error or define a new error. Extending is the JS way so using the name property

// in function
const error = new RangeError("Invalid version string: '" + (isNaN(v1) ? v1 : v2) + "'");
error.name = "InvalidVersionStr";
throw error;

// outside function
try {
    compareVersions(a,b,type);
} catch(e) {
    if (e.name === "InvalidVersionStr") {
        // do what is needed to prevent app from stopping
    } else {
        throw e; // rethrow for development cycle or high level catchers
    }
}

Validate or normalize

It is best to avoid exceptions.

In JavaScript we can pretend we have a 3 state Boolean, true, false, and undefined. We can use the 3rd state to signal an error without needing to break flow or halt execution. You can return undefined with return;

Then you calling function need only handle the undefined

 const versionResult = compareVersions(a, b, type);
 if (versionResult === undefined) { /* put the spanner here */ }

Better yet the function should assume all is good and just return true or false.

Validate the version strings at the source and deal with it when you get it (that is where the problem actually is)

You can either validate the version string or normalize the string

function normaliseVersionStr(ver) {
    return /^\d*\.\d*\.\d*$|^\d*$/.test(ver) ? ver : "0";
}
function validateVersionStr(ver) {  // returns false if string not valid, else true
    return /^\d*\.\d*\.\d*$|^\d*$/.test(ver);
}

// Good strings returned as they are
normaliseVersionStr("1.0.0")
normaliseVersionStr("1")
normaliseVersionStr("1.000.0")

// Bad string returned as version 0
normaliseVersionStr("1.0.0A")
normaliseVersionStr("1.")
normaliseVersionStr("1.0")
normaliseVersionStr("")

Alternative solution

Now that you can trust the arguments you get you can write a better function as you dont need to bother with all the possible edge cases.

There are many ways to do this, and they depend on what you define as same, greater, less. I will assume the following

 01 == 1 == 1.0.0 == 01.0.0 == 1.00.00
 0.01.0 == 0.1.0
 0.0.1 < 0.1.0
 2.0.1 < 2.1.0
 1.9.0 < 2

If we then pad the strings to match (each version str) parts sizes, and remove leading zeros.

 1 and 1.0.0 become 100 and 100
 1 and 2 become 1 and 2
 1 and 0.0.1 become 100 and 1
 1.99.0 and 1 become 1990 and 1000

Then use eval to do the final operation. If you don't like eval, you can use new Function

Example

It is assumed that the operator is defined in the source (not as an user input). If the operator is a user input string then you should validate or normalize that string before calling the function.

An invalid operator will throw an exception.

// logical operator optional. Default "=="
// "==", "<", ">", "<=", ">="
// "=" is considered to be "=="
// can also use "!=", "!==", "==="
// strA, strB must be valid version strings
function compareVersionStrings(strA, strB, operator = "==") {
    const a = strA.split("."), b = strB.split(".");
    const len = Math.max(a.length, b.length);
    var valA = a.shift(), valB = b.shift(), i = 1;
    while (i < len) {
        const vA = a[i] !== undefined ? a[i] : "";
        const vB = b[i] !== undefined ? b[i] : "";
        const digits = Math.max(vA.length, vB.length);
        valA += vA.padStart(digits, "0");
        valB += vB.padStart(digits, "0");
        i++;
    }
    valA = valA.replace(/0*\d$/,"");
    valB = valB.replace(/0*\d$/,"");
    operator = operator === "=" ? "==" : operator;
    return eval(`${valA} ${operator} ${valB}`);
    // or
    return (new Function(`return ${valA} ${operator} ${valB})`)();
}