Trying to implement cross-class functionality that needs a field to operate in C#

I think the rule you should follow here is "favor composition over inheritance".

What that means in your case is that you create a separate class, something like ReapplyDelay and make both classes own an instance of that class.

The code could look something like this:

class ReapplyDelay
{
    private Queue<KeyValuePair<int, float>> reapplyDelay = new Queue<KeyValuePair<int, float>>();

    public void RemoveOld(float delay, float duration)
    {
        while (reapplyDelay.Count > 0)
        {
            if (reapplyDelay.Peek().Value - delay > duration)
            {
                reapplyDelay.Dequeue();
            }
            else
            {
                break;
            }
        }
    }

    public bool AddNew(EntityInfoServer collidedInfo, float duration)
    {
        if (!reapplyDelay.Any(id => id.Key == collidedInfo.entityId))
        {
            reapplyDelay.Enqueue(new KeyValuePair<int, float>(collidedInfo.entityId, duration));
            return true;
        }

        return false;
    }
}

And your two original classes would then look like this:

BlazingAura_Server:

private BlazingAuraC_Server conditionInstance;
private ReapplyDelay reapplyDelay = new ReapplyDelay();

void Update()
{
    reapplyDelay.RemoveOld(BlazingAuraC_Server.BURNING_REAPPLY_DELAY, conditionInstance.duration);
}

void OnTriggerEnter(Collider collider)
{
    if (collider.tag != "Spell")
    {
        EntityInfoServer collidedInfo = collider.transform.GetComponentInChildren<EntityInfoServer>();
        collidedInfo.QueueDamageRaw(conditionInstance, BlazingAuraC_Server.TICK_FREQ * BlazingAuraC_Server.BASE_DPS, ValueModDamageSubtype.Elemental);

        if (reapplyDelay.AddNew(collidedInfo, conditionInstance.duration))
        {
            collider.transform.GetComponentInChildren<EntityInfoServer>().AddConditionServer(Condition.Burning, conditionInstance);
        }
    }
}

Storm_Server:

private float duration;
private ReapplyDelay reapplyDelay = new ReapplyDelay();

void Update()
{
    duration += Time.deltaTime;

    if (Mathf.CeilToInt((duration + Time.deltaTime) / TICK_FREQ) > Mathf.CeilToInt(duration / TICK_FREQ))
    {
        Activate(stormCollider);
    }

    reapplyDelay.RemoveOld(STORM_DRENCH_DELAY, duration);
}

public void OnTriggerEnter(Collider collider)
{
    if (collider.tag == "Player")
    {
        //Debug.Log("IN STORM");
        EntityInfoServer collidedInfo = collider.transform.GetComponentInChildren<EntityInfoServer>();

        if (reapplyDelay.AddNew(collidedInfo, duration))
        {
            collider.transform.GetComponentInChildren<EntityInfoServer>().AddConditionServer(Condition.Drenched, stormInfo);
        }
    }
}

You know your code better than I do, so the details might be different, but the general idea should be clear: extract common independent pieces of functionality into a separate class and then use that.

I have also changed your fields from public to private: if you really need to expose them, you should use public properties, not fields.


Searching a string for any permutation of words

OK, first of all, exceptions are slow. Any code that uses exceptions in the normal flow of the application will be slow. Only use exceptions for something that has gone terribly wrong in your application, never for the normal execution of your code.

Having said that, I approached the problem from a different angle. You have two tasks in essence: the first task is to generate all the permutations of the input array of words. The second task is, for every permutation of the words you calculate, concatenate them into a pattern string, and try to find that pattern in your input string wherever it may occur. Since these are two entirely separate tasks, isolate them in separate functions. The great thing about doing this is that you can test them separately and only use them in the overall solution when you know they work properly.

The second task is actually way simpler than the code you have, where you are continually chopping up the input string through substr(). You are missing the indexOf() function which just returns the index of the pattern in the string, or -1 if it was not found. Even better, the second parameter to indexOf() is the starting index for the search (with a default of 0).

Here's one way of doing that second task.

var findPermutation = function (permutation, s, result) {
  "use strict";
  var i, index,
      pattern = permutation.join("");

  for (i = 0; i < s.length - pattern.length; i += 1) {
    index = s.indexOf(pattern, i);
    if (index >= 0) {
      result.push(index);
      i = index;
    }
  }
};

var result = [];
findPermutation(['a', 'b', 'c'], "abcabc", result);
console.log(result); // should be [0, 3]
findPermutation(['c', 'a', 'b'], "abcabc", result);
console.log(result); // should now be [0, 3, 2]

A few things to note here: permutation is some permutation of an array of words and so is itself an array. s is the string to search through, and result is an array of indexes that have been found. The for loop is cut short when the remaining bit of the string to search through is smaller than the pattern length. The code at the end is testing this simple routine (and if I'd written it properly, the test code would itself check that result has the right values. So, BOOM, we have the second part done; now all we have to do is generate the complete set of permutations from an array.

Here, I did it in a functional style: rather than have the routine generate, say, a huge array of all the permutations, I wrote the routine to accept a callback function and this will be called for every permutation that was generated (after which the permutation can be thrown away). In other words, the permutation generator would generate the next permutation, execute the callback function with this value, and then go back and calculate the next permutation. It would stop this merry-go-round once all the permutations had been generated.

For the permutation generator I went with Heap's Algorithm. It's the fastest, you can read up about it on wikipedia, and I'd already written about the algorithm and written a JavaScript version on my blog. Here's that code:

var generatePermutations = function (items, process) {
  "use strict";
  var generate = function (last, items, process) {
    var
      i,
      swap = function (x, y) {
        //console.log(x + " <=> " + y);
        var temp = items[x];
        items[x] = items[y];
        items[y] = temp;
      };

    //console.log(last);
    if (last === 0) {
      process(items);
    }
    else {
      // if last is even
      if ((last & 1) !== 1) {
        for (i = 0; i < last; i += 1) {
          generate(last - 1, items, process);
          swap(0, last);
        }
      }
      // else last is odd
      else {
        for (i = 0; i < last; i += 1) {
          generate(last - 1, items, process);
          swap(i, last);
        }
      }
      generate(last - 1, items, process);
    }
  };

  generate(items.length - 1, items, process);
};

generatePermutations(['a', 'b', 'c', 'd'], function (items) {
  console.log(items.join(""));
});

The last bit of the code shows how it is called: an array of items to be permuted and then a callback function that will be called for every permutation generated (all this one does is to merely output the items joined into a string).

If you are not familiar with this style of writing callback functions you can separate them out like this:

var callbackFunction = function (items) {
  console.log(items.join(""));
};
generatePermutations(['a', 'b', 'c', 'd'], callbackFunction);

So now we have it all: a permutation-of-words generator and a pattern matcher for each permutation of words. Since the callback function is so simple -- it only requires one parameter, yet the matcher requires three, I wrapped things up in another function:

var findPermutations = function (s, words) {
  "use strict";
  var result = [];

  generatePermutations(words, function (permutation) {
    var i, index,
        pattern = permutation.join("");

    for (i = 0; i < s.length - pattern.length; i += 1) {
      index = s.indexOf(pattern, i);
      if (index >= 0) {
        result.push(index);
        i = index;
      }
    }
  });

  return result;
};

console.log(findPermutations("abcdabcd", ['a', 'b', 'c', 'd']));

Again I threw in a small test case at the end to check that everything worked. If you run it, it'll output [0, 4, 3, 2, 1] (with the matching patterns being abcd, abcd, dabc, cdab, bcda).

Aside: things that still aren't great.

The permutation generator is a bit long-winded and can be rewritten to use some helper functions.
The permutation generator modifies the input array of words. It should make a copy, so that the original array is not changed.
I ignored the case where the length of the concatenated words is longer than the search string and hence nothing needs to be done. Easy exercise for the reader.


I would think that this might be a problem best solved via recursion.

For example:

function flattenArray(arr) {
    var result = [];

    arr.forEach(function($val) {
        if(Array.isArray($val)) {
            result = result.concat(flattenArray($val));
        } else {
            result.push($val);
        }
    });

    return result;
}

Also consider a more meaningful name for your function like flattenArray vs. steamrollArray.  This better conveys what the function does.  Look at your question title for example. You used Flattening array to describe your code not Steamrolling array.


Use of getters and setters with a car information example

JavaScript provides a analogy to private properties, but you should think of them as hidden as they do not behave as private properties. Protoptyped methods do not have access to hidden properties.

Properties defined with the "this" token are public and can be accessed anywhere the object can be accessed. Private properties are declared with the var token or as the objects passed parameters and should never require direct getting and setting

function MyObject (id, name) {
    this.id = id;                     // create public property
    var displayVal = "Hi I am "+name; // create Hidden property
    this.display = function () {      // create public function
         console.log(displayVal);     // this function closes over displayVal
    }
    // closure closes over all currently scoped variables thus
    this.displayName = function () {
         console.log(name)     // the argument passed to this object is also
                               // available as a hidden property
    }
}
MyObject.prototype.test = function () { // this prototype does not close over
                                        // the property displayVal
      // the next line will display undefined
      console.log(displayVal);  // undefined
}
var myObj = new MyObject(0, "OBJECT"); // creates a new object
console.log("Public id = " + myObj.id);  // accessing public property
myObj.display();                         // display private property

// hidden properties are not enumerable
for(var i in myObj){
    console.log(i + " as " + (typeof myObj[i]) );    // will report
                       // id as number
                       // display as function
                       // displayName as function
                       // test as function
}
// Note no hidden variables are displayed

JavaScript is a classless language and attempting to transfer class like concepts to it from other languages is bad practice. Use closure to define private (hidden) properties.

Object factories in my view are bad design, they slow down an already slow language and provide no extra benefit to the code.


How can this async url response checker be cleaner/faster?

Overall, your code looks pretty decent. The functions are doing what they should be (create_task shouldn't be running the tasks as well), coroutines are gathered after aggregation.
I'd suggest a few things to make it more readable (and maintainable)
if __name__ block
Put script execution content inside the if __name__ == "__main__" block. Read more about why on stack overflow.
Variable naming
While you follow the PEP-8 convention on variable naming, the names still could use a rework, for eg. session instead of just s.
URL or path
URL refers to "Uniform Resource Locator", which is of the form:
scheme:[//authority]path[?query][#fragment]

You are dealing with only the path here, scheme and authority sections have been fixed as https://example.com/. This is again naming convenience.
Gather vs create
You are creating as well as gathering tasks in create_tasks function.
Type hinting
New in python-3.x is the type hinting feature. I suggest using it whenever possible.

Rewrite
import asyncio
import aiohttp

HOST = "https://example.com"
THINGS_FILE = "things.txt"

def validate_path(path: str) -> bool:
    return 5 <= len(path) < 16 and path.isalnum()

async def check_404(session: aiohttp.ClientSession, path: str):
    async with session.head(f"{HOST}/{path}") as response:
        if response.status == 404:
            print("hello i am working")

async def execute_requests(paths: list[str]):
    async with aiohttp.ClientSession() as session:
        tasks = []
        for path in paths:
            if validate_path(path):
                task = asyncio.create_task(check_404(session, path))
                tasks.append(task)
        return await asyncio.gather(*tasks)

def main():
    with open(THINGS_FILE) as things:
        paths = [line.strip().lower() for line in things]
    while True:
        asyncio.get_event_loop().run_until_complete(execute_requests(paths))

if __name__ == "__main__":
    main()

This can be further rewritten depending on the data being read from file, using a map/filter to only iterate over validated paths in file etc. The above is mostly a suggestion.


Generic classes with inheritance/equals/comparison operators

This code looks very Java-like in its style and implementation. Maybe C#1.0 at its best. There are a number of stylistic and idiomatic changes I'd make to make these two classes "play well" in the C# / .NET world of 2015. Without going into exhaustive detail, I employed object immutability, parameterized constructors, implementing IClonaeble, utilizing properties, correctly implementing Equals and ==.

With regards to the two things that  you'd like to do, sorry, neither are possible (nor really desirable) with C# for various reasons that you can find on MSDN.

The code:

public class MaterialParam<TValue> where TValue : IEquatable<TValue>, ICloneable
{
    public readonly string name = string.Empty;

    public readonly string shaderValueName = string.Empty;

    public readonly TValue value; // = Value();

    public MaterialParam()
    {
    }

    public MaterialParam(string name, string shaderValueName, TValue value)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }

        if (shaderValueName == null)
        {
            throw new ArgumentNullException("shaderValueName");
        }

        if (value == null)
        {
            throw new ArgumentNullException("value");
        }

        this.name = name;
        this.shaderValueName = shaderValueName;
        this.value = value;
    }

    public MaterialParam(MaterialParam<TValue> other)
    {
        if (other == null)
        {
            throw new ArgumentNullException("other");
        }

        this.name = other.name;
        this.shaderValueName = other.shaderValueName;
        this.value = other.value;
    }

    public string Name
    {
        get
        {
            return this.name;
        }
    }

    public string ShaderValueName
    {
        get
        {
            return this.shaderValueName;
        }
    }

    public TValue Value
    {
        get
        {
            return this.value;
        }
    }

    public static bool operator ==(MaterialParam<TValue> a, MaterialParam<TValue> b)
    {
        if (ReferenceEquals(a, b))
        {
            return true;
        }

        if (((object)a == null) || ((object)b == null))
        {
            return false;
        }

        return a.Equals(b);
    }

    public static bool operator !=(MaterialParam<TValue> a, MaterialParam<TValue> b)
    {
        return !(a == b);
    }

    public MaterialParam<TValue> Clone()
    {
       return new MaterialParam<TValue>(this);
    }

    public override bool Equals(object obj)
    {
        if (!(obj is MaterialParam<TValue>))
        {
            return false;
        }

        var other = (MaterialParam<TValue>)obj;

        return (this.name == other.Name)
            && (this.shaderValueName == other.ShaderValueName)
            && this.value.Equals(other.Value);
    }

    public override int GetHashCode()
    {
        return this.name.GetHashCode()
            ^ this.shaderValueName.GetHashCode()
            ^ this.value.GetHashCode();
    }
}

public class MaterialRangedParam<TValue> : MaterialParam<TValue> where TValue : IEquatable<TValue>, ICloneable
{
    public readonly TValue minValue; // = Value();

    public readonly TValue maxValue; // = Value();

    public MaterialRangedParam(TValue minValue, TValue maxValue)
    {
        if (minValue == null)
        {
            throw new ArgumentNullException("minValue");
        }

        if (maxValue == null)
        {
            throw new ArgumentNullException("maxValue");
        }

        this.minValue = minValue;
        this.maxValue = maxValue;
    }

    public MaterialRangedParam(MaterialRangedParam<TValue> other) : base(other)
    {
        if (other == null)
        {
            throw new ArgumentNullException("other");
        }

        this.minValue = other.MinValue;
        this.maxValue = other.MaxValue;
    }

    public TValue MinValue
    {
        get
        {
            return this.minValue;
        }
    }

    public TValue MaxValue
    {
        get
        {
            return this.maxValue;
        }
    }

    public static bool operator ==(MaterialRangedParam<TValue> a, MaterialRangedParam<TValue> b)
    {
        if (ReferenceEquals(a, b))
        {
            return true;
        }

        if (((object)a == null) || ((object)b == null))
        {
            return false;
        }

        return a.Equals(b);
    }

    public static bool operator !=(MaterialRangedParam<TValue> a, MaterialRangedParam<TValue> b)
    {
        return !(a == b);
    }

    public new MaterialRangedParam<TValue> Clone()
    {
        return new MaterialRangedParam<TValue>(this);
    }

    public override bool Equals(object obj)
    {
        if (!(obj is MaterialRangedParam<TValue>))
        {
            return false;
        }

        var other = (MaterialRangedParam<TValue>)obj;

        return base.Equals(other) && this.minValue.Equals(other.MinValue) && this.maxValue.Equals(other.MaxValue);
    }

    public override int GetHashCode()
    {
        return base.GetHashCode() ^ this.minValue.GetHashCode() ^ this.maxValue.GetHashCode();
    }
}


React props children with List and Spinner Loader

The way I do it is to have both the Spinner and the components in the render and pass it the loading prop and inside the Spinner component it will render the spinner if loading is set to true and return null if its set to false. That way you're not re-rendering the whole listview when you toggle it on and off.

this.state = {
  loading: false,
} //in the contructor

componentDidMount() {
this.setState({ loading: true }, () => this.fetchData());
}

// Simulate fetchData
fetchData = () => {
  //const self = this; you don't need this line
  setTimeout(() => {
     this.setState({
        loading: false
     });
  }, 4000);        //after you receive the response, you set it back to false
}

render() {

  return (
    <Content>
      <Spinner visible={this.state.loading} />
      <ListView
        style={styles.container}
        dataSource={this.state.dataSource}
        renderRow={data => <Row {...data} />} />
    </Content>
  );
}


Instead of calling update_pos at the end of a heap operation, update it as you go along. For example, percUp becomes:

cur_pos = len(self.list) - 1
parent_pos = cur_pos // 2
while parent_pos:
    cur = self.list[cur_pos]
    parent = self.list[parent_pos]
    if self.G[parent][2] > self.G[cur][2]:
        self.list[parent_pos] = cur
        self.pos[cur] = parent_pos
        self.list[cur_pos] = parent
        self.pos[parent] = cur_pos
    cur_pos = parent_pos
    parent_pos //= 2

And similarly for percDown.
Having written that, a simpler approach to deletion from a heap is simply to leave the object in the heap but mark it somehow as deleted. Then when you extract the minimum you check to see if it was marked as deleted, and if it was, you throw it away and extract another one.
If you use the "mark object as deleted" method, then you would be able to use Python's built-in heapq module (see in particular the "Priority Queue Implementation Notes"). See this answer for an example implementation.
It looks (from the name "G" for the scores) as though you are using this to implement the priority queue of unvisited nodes in the A* search algorithm. But then it is not clear why you need to delete items from the middle of the heap—in the A* algorithm this never happens (an item is only deleted when it is popped as the minimum item). So you could just not implement deletion, and since the pos dictionary is only used by the deletion method, you wouldn't have to maintain it, and so you could just use Python's built-in heaps directly. See this answer for an example.


Implementing "Pierre the Tight-rope" Walker from LYAH

I don't see glaring flaws. A couple notes though:

-You could combine the addLeft/Right functions and pass in a tuple representing how many birds you want to add ( (0,2) for 2 right ); the functions are almost identical.

-I've found where bindings to read neater if I have more then 2 (personal choice).

-AFAIK, the Error Monad /= the Either Monad.


Reusing StringBuilder or creating a new one?

Reusing doesn't need memory allocation, so it could be faster as @Mike Nakis mentioned. On the other hand it leads to ugly code: you use the same variable for two (or more) different purposes which could confuse readers, make maintenance harder. Unless you have a good reason to do that avoid it. I mean, you have a good reason if a profiling shows that creating new StringBuilder instances is a bottleneck in the application.

If you really have to reuse StringBuilders, try accessing them with different names with a helper method:

public static StringBuilder reuseForBetterPerformance(final StringBuilder sb) {
    sb.delete(0, sb.length());
    return sb;
}

Client code:

final StringBuilder b = new StringBuilder();
//build up a string
final StringBuilder c = reuseForBetterPerformance(b);
//reuse it
c.append(...)

It makes the code a little bit more readable, since the method name says why you're reusing the StringBuilder.


.hasScroll function, checking if a scrollbar is visible in an element

=== > == (Not that it really matters in this case, but it's still better.)

Also, IIRC clientHeight etc are not cross-browser, this is why jQuery provides .position(), .offset(), .scrollTop() and .height() (whichever one best suits your needs).


I recommend putting your functions into a namespace.

for (auto i = begin + 1; i != end; ++i) {

By doing begin + 1, you require that Iterator is a RandomAccessIterator, whereas you only need an ForwardIterator. Use std::next instead:

for (auto i = std::next(begin); i != end; ++i) {

You could also use std::next(begin, 1) to be explicit.

Similarly, when you do *(i - 1), you require that Iterator is a RandomAccessIterator. Replacing it with std::prev still requires that Iterator is a BidirectionalIterator. Unless you think that is a reasonable requirement (for some versions of bubblesort, it would allow it to be more efficient), don't do this.

Rewrite the for loop as so (or any variant where you keep track of the two):

for (auto i = begin, inext = std::next(begin); inext != end; ++i, ++inext) {
    auto& val0 = *inext;
    auto& val1 = *i;
    // ...

While we are discussing iterator categories, it's useful to name Iterator after the iterator category you require, so FwdIter or ForwardIterator would be better names.

template<typename Iterator>
void bubble_sort(Iterator begin, Iterator end) {
    bubble_sort(begin, end, [] (const typename Iterator::value_type& v0,
                const typename Iterator::value_type& v1) { return v0 < v1; });
}

Rather than manually writing out the comparator, use std::less. I would use std::less<>, but you could use std::less<typename std::iterator_traits<Iterator>::value_type> if you wanted to.

template<typename Iterator>
void bubble_sort(Iterator begin, Iterator end) {
    bubble_sort(begin, end, std::less<>{});
}

Actually, instead of doing this, you could put a default argument on the other overload of bubble_sort:

template<typename Iterator, typename Comparator = std::less<>>
void bubble_sort(Iterator begin, Iterator end, Comparator cmp = {})

There are two advantages I can think of by doing it this way:

Less code (only one function definition)
You avoid ADL problems

One problem with

template<typename Iterator>
void bubble_sort(Iterator begin, Iterator end) {
    bubble_sort(begin, end, std::less<>{});
}

is that the bubble_sort(begin, end, ...) can activate ADL. If Iterator was, let's say, mylibrary::vector<int>::iterator, and if I wrote a bubble_sort in the namespace mylibrary, this bubble_sort call might call the one from the mylibrary namespace instead of the one we intended.

This is not good. As a rule of thumb, when writing generic code, avoid unqualified function calls like bubble_sort(begin, end, ...); instead qualify it with the namespace: ::bubble_sort(begin, end, ...).


Python OOP - Web App (Flask) - User registration class?

In general, your code seems to be in pretty good shape if you're hoping to move towards domain driven design, notably seen from your "entity-like" User object and the UserService.

Does it make sense to have2 separate classes? I am actually thinking to move all of my User methods to the UserService class and just have a UserService class with setters and getters.

First off, if you're anticipating your application to grow, a clear separation of concerns is what you'd want to achieve and to further achieve this, the two objects you have are fine. That is, one to represent a definition of what a user is and another to determine what you can do with a user object or related objects which in this case is the UserService. This naturally means that the methods on the User class should now be part of the UserService, considering them business logic of the application. I would use the words model to describe the User class and service to describe the UserService to define the types of components for the application.

I am confused about is where and when to interact with the database. Should I do it directly on my route.py vs create a new class?

One thing that you can also consider from domain driven design is also to include a repository object when your application becomes large enough. Repositories typically carry operations that might interact with a database, replacing what may be seen like an ORM that you have mentioned. Otherwise, if you're still small and nimble and don't have too many complex relationships in your database, you can keep it simple and keep the database queries in your model for simplicity for the time being. Both allows the user to be created from anywhere if needed and enables code re-use more than including them in the route. Designing from an interface perspective consider the following.
user_repository = UserRepository(db_conn)
user_service = UserService()
foo_user = user_service.register_user(...)

// using the repository
repository.save(foo_user)

// using the model
foo_user.save()

I'll end this with, it depends how large your application is growing, the larger it is, the more you want to re-evaluate your design so to better organize groups of functionality to better extend from and if possible re-use code. That said, what you may have could be good in the long run if your application doesn't really grow beyond those needs.


writeln() and format() with variadic templates

The biggest thing that sticks out at me is that you're passing all of your Args... parameters by value, thus pretty much making std::forward useless here. To make use of std::forward, the reference type needs to be deduced from the calling context. By itself, std::forward really doesn't do anything except a static_cast to the deduced reference type.
Basically, everywhere you have Args should be passed by Args&&:
template<typename T, typename ...Args>
void writeln(T firstArg, Args&&... extraArgs)

template<typename T, typename ...Args>
std::string format(T firstArg, Args&&... extraArgs)

As a cut down example of the difference this makes, try this example:
#include <memory>
#include <iostream>

struct s
{
    s()
    { }

    s(s&& )
    {
        std::cout << "Move\n";
    }

    s(const s& )
    {
        std::cout << "Copy\n";
    }
};

template <typename T>
void do_forward(T&& v)
{
    sink(std::forward<T>(v));
}

template <typename U>
void sink(U&& u)
{
    std::cout << "In sink\n";
}

int main()
{
    s something;
    do_forward(something);
}

If I run this, the output is:

In sink

If I change the signature of do_foward and sink to:
template <typename T>
void do_forward(T v)

template <typename U>
void sink(U u)

The output is:

Copy
Move
In sink

If we change main to just pass an actual rvalue reference instead of an lvalue:
int main()
{
    do_forward(s{});
}

We remove the first copy operation (from do_forward) but still have a move operation (in sink).


Phone Number and Email Address Extractor - Is there any way to simplify this code?

There are a couple of pointers. I possibly got too ahead of myself with the solution, but hopefully, a step-by-step walkthrough clarifies everything.
I am happy to answer any questions you have.

The overall suggestion is:

"""Email and number extractor - finds phone and email addresses on the clipboard.
Python 3 - 30/04/2020
"""
import re
from io import StringIO

import pyperclip

class PastingIO(StringIO):
    def write_items_to_string(self, items, items_name: str):
        self.write(f"{items_name} found:\n\n".upper())

        if items:
            for item in items:
                self.write(f"\t{item}\n")
        else:
            self.write(f"\n\tSorry, there are no {items_name}")

        self.write("\n")  # padding newline

def main():
    email_regex = re.compile(
        r"""(
            [a-zA-Z0-9._%+-]+           # username
            @                           # @ symbol
            [a-zA-Z0-9.-]+              # domain name
            (\.[a-zA-Z]{2,4})           # dot something
        )""",
        re.VERBOSE,
    )

    phone_regex = re.compile(
        r"""(
            (\d{3}|\(\d{3}\))?          # area code
            (\s|-|\.)?                  # separator
            \d{3}                       # first 3 digits
            (\s|-|\.)                   # separator
            \d{4}                       # last 4 digits
            (\s*(ext|x|ext.)\s*\d{2,5})?# extension
        )""",
        re.VERBOSE,
    )

    # get copied text and paste it to text var
    # text = str(pyperclip.paste())
    text = """
        This is sample text.
        hello@you.com
        There is nothing here.
        rofl@mao.org
        234-654-1234 is a telephone number.
        So is 123-456-7890!
        However, 1234-32-342 is invalid.
        Hello World!
        invalid@email.world should be invalid all-together.
        Check out this email: a@b.c
    """

    output = PastingIO()

    print("Working on:", text, sep="\n")

    matching_targets = {
        "numbers": {"regex": phone_regex,},
        "emails": {"regex": email_regex,},
    }

    for target_name, target_dict in matching_targets.items():
        regex = target_dict["regex"]
        target_dict["results"] = [match[0] for match in regex.finditer(text)]
        output.write_items_to_string(target_dict["results"], target_name)

    match_summary = output.getvalue()

    pyperclip.copy(match_summary)
    print("Copied to clipboard:", match_summary, sep="\n")

if __name__ == "__main__":
    main()

Walkthrough

"""Email and number extractor - finds phone and email addresses on the clipboard.
Python 3 - 30/04/2020
"""

is a module docstring.
It basically supersedes the comments of the same content that you had in your code.
The module docstring is more powerful.
For example, other people can invoke it with help():

~$ python -c "import emailAndNumberExtractor; help(emailAndNumberExtractor)"
Help on module emailAndNumberExtractor:

NAME
    emailAndNumberExtractor

DESCRIPTION
    Email and number extractor - finds phone and email addresses on the clipboard.
    Python 3 - 30/04/2020

FUNCTIONS
    main()

FILE
    ~\emailandnumberextractor.py

import re
from io import StringIO

import pyperclip

I did not touch either the re import or your re.compile statements.
You will have to decide for yourself if these are correct.
I did however include a sample text to match against.

StringIO is used here as a sort of temporary file.
When you look for and find matches, these matches should be collected, ideally in a mutable sequence like a list.
This is your data.
In your code, you irretrievably intertwine that data with its display, here the print of a str.
You did this through string concatenation.
But what if you would like to forward the list of found matches somehow, i.e. use it a second time, in another context?
You cannot, because the data is mingled with the string.

As such, StringIO will be a virtual, in-memory file for us to write to.
It will hold the formatting, i.e. indentations and newlines.
The data will come from somewhere else and be kept separate.
Since we do not need a real file, this will do.
I chose this over multi-line string formatting, since that is not straightforward to do and has many caveats.

class PastingIO(StringIO):
    def write_items_to_string(self, items, items_name: str):
        self.write(f"{items_name} found:\n\n".upper())

        if items:
            for item in items:
                self.write(f"\t{item}\n")
        else:
            self.write(f"\n\tSorry, there are no {items_name}")

        self.write("\n")  # padding newline

This class definition might be the trickiest part.
Don't worry if you haven't learned about classes yet.
It can be understood this way:

PastingIO, our new custom class, is inheriting from StringIO.
This means that PastingIO will have all the functionalities of its parent, StringIO.
I explained the latter earlier.
The reason I did this was to extend StringIO by a simple functionality.
This functionality is the function write_items_to_string.
If function definitions occur in classes, they are called methods.

Methods are much like normal functions, but since they are methods of a class, they usually do something with their class.

Now, doing something with the class itself, PastingIO, is not getting us far.
See, a class is like a blueprint.
It contains all the instructions of how something should look like and behave.
But it is not yet something substantial.
A class is like a construction plan, but we are interested in the house that will be built based on that plan.
The plan itself is a (to us, useless) piece of paper.

To build the "house", instantiation is needed.
This is done in the code when we call PastingIO().
The parantheses are important.
It is the instruction to actually build an object from the class definition.
Lastly, we give this thing a name, by just assinging it to a variable (output).
More on that later.

The object we get is like StringIO, but with the added functionality.
You will note that this functionality is much like the loops you defined to concatenate to the string.
I created this method since those loops do identical things.
Now, you won't have to repeat yourself anymore.
This is in adherence to the DRY principle: don't repeat yourself.

As such, I hope write_items_to_string is self-explanatory.
The self just refers to the object instance we created, output.
It means that we act on output.
In this case, imagine the write method to just write to a file, like you do with real files using with open("file.txt", "w") as f: f.write("Hello"), only virtually.
It builds and holds our output string, including all the formatting.

Here, a class is important to hold the string.
A function alone cannot (rather: should not) hold onto anything (referred to as a state).

Skipping the re.compile() statements, they are unchanged.
The text statement is just a sample text to work on.

output = PastingIO()

This is the line mentioned above.
output is now an instance of our custom PastingIO class.
It has all the capabilities of a StringIO (much like a virtual text file), with the added write_items_to_string method, capable of modifying the content of output.

    matching_targets = {
        "numbers": {"regex": phone_regex,},
        "emails": {"regex": email_regex,},
    }

This is a nested dictionary. matching_targets is a dictionary, but each of its values is also a dictionary.
This affords us a neat and organized way to store all related data and functionalities, without repeating ourselves.

    for target_name, target_dict in matching_targets.items():
        regex = target_dict["regex"]
        target_dict["results"] = [match[0] for match in regex.finditer(text)]
        output.write_items_to_string(target_dict["results"], target_name)

This is where, finally, the business happens.
One key aspect I found in your code was that findall was called twice.
You compiled the regex outside the loops, only once, which is great.
But even findall only needs to be called once for each regex.
Note that I replaced it with finditer, a simple iterator that does the same thing here.
It returns matches only if you ask it to (lazy stuff), which we do in a loop.

(List) comprehensions are faster than the "manual" equivalent using for or while loops.
The list at target_dict["results"] will hold all the found strings (well, only the first found capture group).
Note that we iterate over matching_targets, and thus do both emails and numbers in one sweep.
The results are then found in for example matching_targets["emails"]["results"], so two keys are required.

Note that this data would not strictly have to be stored in the dict, since we do nothing with it later on.

The last line calls the write_items_to_string method of output.
At first, output is empty.
We write to it, and it retains its contents across those loops, building up a virtual text file.

String concatenation in loops is usually a bad idea.
Strings are immutable, that means even just appending a single letter will lead to the creation of an entirely new object.
Lists are mutable.
So a good alternative approach to what was done here would be to collect string components in a mutable sequence, like a list, and then joining them together once afterwards, using join.

match_summary = output.getvalue()

just gets the text contents of the output object.
match_summary is now a string, printed to the specifications in write_items_to_string.
If you want different newlines, indentations etc., look there.

Note that if you did not want each item on a newline, and would be happy with printing the "raw" output, that is suddenly much, much easier:

emails = ["hello@world.org", "a@b.c"]
result = f"Emails found: {emails}"
print(result)

is all that is needed:

Emails found: ['hello@world.org', 'a@b.c']

pyperclip.copy(match_summary)
print("Copied to clipboard:", match_summary, sep="\n")

Note that I saved a print call here by just separating the arguments with a comma.
They are separated according to the sep argument.

if __name__ == "__main__":
    main()

This is a common pattern used to prevent the file from running when being imported.
If a Python file, i.e. module, is run directly as a script, as is the case here, its __name__ attribute will be set to "__main__".
As such, the main() function is executed, as desired.

However, notice how in the docstring explanation above, I imported your module to call help on it.
In such a case, without the __name__ == "__main__" safeguard, the module would also run, which would then of course be undesired.
As such, it is a good idea to keep modules importable.


Computing sum on column + sum on row + sum on each diagonal

For every element, you currently sum \$n\$ elements for the row, column, diagonal and anti-diagonal, so \$4*n\$ elements.
That's a total of \$4*n^3\$ adds.

That can be improved on easily by pre-processing:

Build an array of the sums for all rows, columns, diagonals and anti-diagonals. You need \$4*n\$ space and \$4*n^2\$ adds.
Add the proper sums for each element, that's \$4\$ adds per element, for a total of \$4*n^2\$ adds.
Together, that's \$8*n^2\$ adds.

In conclusion, you can trade \$4*n\$ extra space for a speed-up by a factor of \$n/2\$.

Regarding your current code:

I cannot find anyplace you use something from <set>. So, why include it?
You should avoid using namespace std; It's a plague and just biding its time to bite you later.
Why is “using namespace std;” considered bad practice?

You can import selected identifiers with using std::cout;, and qualify others with std::cin.
You know you can introduce a variable in the initializer-part of the for-loop?
There's no need for a separate step to open a fstream. User the right ctor.
You noticed an error, you wrote to stderr about it, so why do you try to muddle on instead of aborting?
You never check whether input failed. Are you completely sure the input is well-formed?
Consider merging your allocations where possible. new and delete are quite costly after all.
return 0; is implicit in main().
You never free the memory you allocated. That's actually a good thing as cleaning up just for the OS to take everything down is wasted effort. Beware false positives in leak-detectors though.
I suggest a comment // m and m[0] to m[n - 1] intentionally left allocated though, in case anyone (else) later pokes around and might conceivably adopt it into a greater whole. Also shows you considered it.
You might consider investing into a class for square matrices. It's quite easy to build one.


Callback pattern for handling socket response

I am using a callback pattern and am wondering if this is frowned upon in the Go community.

"callback pattern" shouldn't be frowned upon (they are used in "first-class functions" for instance: https://blog.golang.org/first-class-functions-in-go-and-new-go https://dave.cheney.net/2016/11/13/do-not-fear-first-class-functions)

However regarding your code, I don't think that it looks like idiomatic go code.

Don't just check errors, handle them gracefully

sc.conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil)

if err != nil {
    cb(nil, err)
}

You pass the err to your callback, but you then continue inside the Connect function: if you couldn't dial, why do you continue?

Never start a goroutine without knowing how it will stop

go func() {
    defer sc.conn.Close()
    defer close(done)
    for {
        _, message, err := sc.conn.ReadMessage()
        if err != nil {
            cb(nil, err)
        }
        cb(message, nil)
    }
}()

The inner for loop will never stop (so will your goroutine).

One possibility would be to change it like this:

// SocketResponse function callback for data from socket
type SocketResponse func(res []byte)

// Connect create the connection with the host
func (sc SocketClient) Connect(cb SocketResponse) error {
    u := url.URL{Scheme: "wss", Host: sc.Host, Path: sc.Path}

    var err error
    sc.conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil)

    if err != nil {
        return err
    }

    defer sc.conn.Close()
    for {
        _, message, err := sc.conn.ReadMessage()
        if err != nil {
            return err
        }
        cb(message)
    }
}

Some properties of this code :

on dial error, it stops
it reads all the messages until one error is encountered
it blocks (but go sc.Connect() is easy to write)

Some possible evolutions:

to continue even in case of errors, you could return a channel of errors (and send all errors encountered)
also use a channel to report the received messages
to control when the Connect method should stop, you could use a context or split your method in 3 parts: Connect, ReadMessage & Close


Is there another way / proper way of  parsing this JSON array ?

This can be argued, but I think you can write directly i < array.length(); without noticeable slowdown (if length() does the right thing and is just a getter of a field). Makes the loop slightly more readable, IMHO. Or at least add spaces: int i = 0, length = array.length();

I had a glance at the Jettison site, and couldn't find a JavaDoc page. But if JSONArray implements the Iterable interface, you can use the foreach syntax, even more readable.

I agree with the comment of RoToRa, too.

Otherwise, code looks OK.


Looking for performance suggestions in Noise algorithm

I'm not sure if Cos and Sin are efficient here, they might be a ferformance killer. Consider making a table of sin/cos values for come range of angles.


Converting tcpdump output to text2pcap acceptable input

Regex
The time regular expression can be simplified to
regexp_time = re.compile(r'\d{10}\.\d{6}')

which is a bit more readable. The second one does not acount for letters in hexadecimal numbers so a line starting with 0x00a0: won't be parsed… Since you are using a file that is extremely regularly formatted, I suggest you drop this regular expression and rely on the fact that, if regexp_time does not match, then you have a line of data. (At least on my tcpdump output, I only get a single line.) But if you want to use a second regular expression to filter out lines that may be between the timestamp and the first line of data, I'd suggest simply using
regexp_hex = re.compile(r'\t0[xX][\da-fA-F]+:')

and not worry about the rest of the line.
Matches
When using the match method on a compiled regular expression, you receive a match object or None. This match object let you easily extract out the matched bits using its group method. So there is little use of splitting a line to parse stuff:
timestamp = regexp_time.match(line):
if timestamp:
    output.write("%s\n" % timestamp.group())

In fact, you can so easily extract out the groups that I would use a second regex for the hexadecimal data anyway:
regexp_hex = re.compile(r'\t0x([\da-fA-F]+):  ([\da-fA-F ]+?)\s{2,}(.*)')

So that, the first group is the hexadecimal address, the second one is the hexadecimal payload and the third one is the ASCII payload. You then just need to format the output:
payload = regexp_hex.match(line)
if payload:
    address = payload.group(1)
    hex_data = payload.group(2).replace(' ', '')
    ascii_data = payload.group(3)
    output.write('\t{0>6}:  {:<47}  {}\n'.format(address, hex_data, ascii_data))

The only thing left is to split the hex_data in groups of 2 digits. This can be done using the itertools recipe grouper.
Proposed improvements
import re
import itertools

TIMESTAMP = re.compile(r'\d{10}\.\d{6}')
PAYLOAD = re.compile(r'\t0x([\da-fA-F]+):  ([\da-fA-F ]+?)\s{2,}(.*)')

def grouper(iterable, count, fillvalue=None):
    args = [iter(iterable)] * count
    return itertools.zip_longest(*args, fillvalue=fillvalue)

def convert_tcpdump_to_text2pcap(in_filename, out_filename):
    with open(in_filename) as input, open(out_filename, 'w') as output:
        for line in input:
            time = TIMESTAMP.match(line)
            if time:
                output.write('{}\n'.format(time.group()))
                continue
            payload = PAYLOAD.match(line)
            if payload:
                address = payload.group(1)
                hex_data = payload.group(2).replace(' ', '')
                ascii_data = payload.group(3)

                hex_data = ' '.join(''.join(part) for part in grouper(hex_data, 2, ' '))
                output.write('\t{:0>6}:  {:<47}  {}\n'.format(address, hex_data, ascii_data))

if __name__ == '__main__':
    convert_tcpdump_to_text2pcap('../Traffic/traffic1.txt', '../Traffic/txt2.txt')


Using range minimal query for lowest common ancestor (LCA)

This review describes my thoughts as a fellow competitive programmer.

About your questions

In-order traversal is a must here. Otherwise the RMQ-based algorithm won't work - it requires that for each vertexes A and B their LCA occurs between any occurrences of A and B.
You will need some kind of maps to map tree node to their position in the RMQ array. So, at least one of them should stay. However, you can get rid of index_node_map if you make RMQ store node's "value" (which is actually node's id, as far as I understood from your code).

Major problems

Your code does not satisfy PEP 8 at least in terms of whitespaces (it's easy to check and fix with tools like pep8, flake8, autopep8), that significantly reduces readability.
You have God object in the solution, which, well, "solves the problem". Meaning, it mixes together all of the following:

In-order traversal of a tree.
Mapping between tree nodes and their indexes in the traversal.
Calculating depths of vertexes.
Reducing LCA to RMQ with
Solution of RMQ problem with sparse table.

Moreover, all these are highly tied together and you cannot, say, debug RMQ separately. It is a very common problem among competitive programmers (especially beginners). Though, some do not consider it to be a problem, but you're posting on codereview.
You initialize object outside of constructor, in the build_depth_index function. It may lead to a false conclusion that one may re-use the object with different inputs by calling build_depth_index with new tree. Despite "work in the constructor" being a kind of anti-pattern, I feel it's OK to move all initialization to the constructor in this case:

You won't be able to reuse or not initialize the object.
You will have less mutable state to care about (as opposed to the "initialize everything in build_depth_index and make the object reusable" approach), which is generally helpful for debugging.

There are a bunch of implicit invariants, e.g.:

You assume that all values in the tree are different. It's not enforced with asserts, so it's possible to accidentally apply your algorithm to "wrong" tree and get "almost correct" results.
In the in_order function you assume that each vertex occurs in the in-order traversal only once (because you "reenumerate" vertexes), but it's not the case for non-binary trees. Algorithm is more general than that. I'd suggest to avoid writing general algorithms for some "specific" cases because that is prone to copy-pasting and makes the algorithm harder to debug.

There is some debug output in the middle, which cannot be switched off.
No need in defaultdicts. I'd suggest to avoid defaultdicts when implementing data structures (esp. RMQ) because typically you should initialize the structure first and use it afterwards.

  self.rmp_map = defaultdict(tuple) # key: (index, step), value: (min value, index)

you represent two-dimensional array with dict. Please don't do that, use arrays.
Use namedtuple instead of regular tuples to improve readability.

My suggestions

Get rid of God object

I'd suggest the following objects and functions:

class Rmq:
    def __init__(self, array, key):
        """Initializes RMQ structure for 'array', assuming that the value
        being minimized is returned by the 'key' function, if applied to
        array element"""

    def get_minimal_element(self, l, r):
        """Returns minimal element of array from position l to r (inclusive)"""

def get_in_order_traverse(tree):
    """Traverses tree in-order and returns a list of nodes."""

def get_depths(tree):
    """Calculates depths of all vertexes in the tree and returns mapping
    from vertex's value to its depth (root's depth is 0)."""

class Lca:
    def __init__(self, tree):
        """Initializes LCA solver for the given tree."""

    def get_lca(self, a, b):
        """Given two vertexes a and b returns their LCA as a TreeNode."""

Of course, that design can be de-coupled even further. Say, Lca.__init__ can take an optional argument specifying Rmq's factory so we can plug different implementations of Rmq for debugging.

Other suggestions

Rename TreeNode.value to TreeNode.id, because LCA does care about node "values", it cares about their ids only.
Even better approach is to make TreeNodes hashable by overloading __hash__ and __eq__ so functions do not depend anymore on "what is node's id and how to find it".
Replace TreeNode.left and TreeNode.right with a list called TreeNode.children. For the sake of generality - algorithm does not care.
Use logging module for debug output so it can be switched on/off dynamically.
Use namedtuple instead of tuples.
In your sparse table implementation you can ignore all those segments which extend beyond array's length and get rid of if. You never need to access them, as all requests to RMQ lie inside the original array.


Functional Javascript Practice with AJAX

Move your APPID and API url from your code an into constants. That way, they're readily visible and easily configurable.
Move the creation of your API url into a function, that way it's easily modifiable. In addition, use $.param to construct the query portion of your URL. jQuery encodes the params for you. If you can do ES6, you can simplify using shorthand literal notation and template strings

function getApiUrl(lat, lon){
  return `${API_URL}?${$.param({lat, lon, APPID})}`;
}

Not entirely sure why you need to stringify data.main.temp when the logic comes after it expects a number.
data.main.temp appears to be in Kelvin. It would be better if you name the variable appropriately to show that it is in Kelvin.
Move your temperature calculations into functions, like convertFromKelvinToCelsius and convertKelvinToFahrenheit.
It appears that you only get the data once, but your conversions to Celsius and Fahrenheit happen on click. Why not convert them just once, and on click, just display the pre-calculated values?
In the same spirit, why not render the HTML in advance and just show/hide depending on the click. This avoids you from putting the values in html all the time.
Construct your data first, then do the HTML. Makes it easier to have all your logic up top, and rendering down below. That way, your data is prepared and all in one place.
The <i> part, you're repeating code. Why not determine the class name only and addClass to the <i> once instead of repeating the addClass for each condition.

I'll leave the code to you. Feel free to open up another review for a followup.


Profile It!
As suggested in the comments, you should profile the code to see where the slowdown is.
Algebra Is Your Friend
One small suggestion I can offer is some algebraic improvements.
A linear interpolation between a and b can be formulated like this:
result = a * interp + b * (1 - interp);

That's 2 adds and 2 multiplies. You can use some algebra to reduce that to:
result = interp * (a - b) + b;

which is 2 adds and 1 multiply. Doing that also removes the need to calculate x1mf and y1mf. So your inner loop would become:
T xf = x - (int64_t)(x);   // get decimal portion
T yf = y - (int64_t)(y);

T a = *line;
T b = *(line + 1);
T top = xf * (a - b) + b;
T c = *(line + n);
T d = *(line + n + 1);
T bottom = xf * (c - d) + d;
val = yf * (top - bottom) + bottom;

That takes you from 8 multiplies to 3, but from 9 adds to 10. So that's likely from 17 instructions to 13.
There are a few more optimizations you can do:
You're subtracting 1 from x and y every time through the loop. You could calculate the values with the 1 already subtracted out in interp2() rather than in interp2_mx():
for (int m = 0; m < mi; ++m)
{
    T* line_zi = zi + m * ni;
    const T* x = xi + m * ni - 1; // <- Do this here instead of on every loop iteration!
    const T* y = yi + m * ni - 1; // <- Same here

You might also have luck by keeping track of a pointer to the next input pixel just incrementing it instead of calculating line every time through the loop, too.
Naming
It would be nice if you could pick more easily understandable names for your functions and variables. Why is this called interp2()? What is interp1()? You should name it bilinearInterp() or something obvious like that. And what does interp2_mx() mean?
Using x and y to represent horizontal and vertical offsets is fine. Those are well-established traditions. But you're naming the start of your image z which is really weird. z is usually reserved for depth, at least when used with x and y. That makes your code very confusing to read.
Likewise, mz and nz are confusing, too. And even worse in iterp2_mx(), mm2 and nm2 are not only confusing but easy to mix up! mz and nz should be something like imageWidth and imageHeight (or matrixWidth and matrixHeight, or inputWidth and inputHeight), and the other variables and arguments should be appropriately named as well.
Why do xi and yi have an i in their names? That makes them look like integers, but they're declared as type T, which you say will likely be float or double.
Errors
Looking at your error handling, I'm not convinced it's sufficient. You check if xp is less than 0 or greater than nm2, and the same for yp. But what happens when xp exactly equals nm2? line ends up pointing to the last pixel in a line. But then you calculate line + 1. That gets you the first element of the next row. And for yp, it means reading a row that doesn't exist when yp equals mm2.


Here is a sort that I put together after some research:

private void sort(PlayingCard[] hand)
{
    int i, j;
    PlayingCard temp;
    for (i = 1; i < hand.length; i++) {
        temp = hand[i];
        j = i;
        while (j > 0 && hand[j - 1].getRank().compareTo(temp.getRank()) > 0) {
            hand[j] = hand[j - 1];
            j--;
        }
        hand[j] = temp;
    }
}


Breaking a line segment into two where it encounters a rectangle

General points

Use const when a variable does not change.

Avoid using underscore in JavaScript names

Making names too long makes code hard to read, especial when the relevant part of the name is tiny. eg nIntersection, eIntersection, sIntersection, wIntersection when in busy lines the n,e,w,s can easily be overlooked.

The function getLineIntersection returns a point or false. Rather than return a point return the value t.
This value represents the unit distance along the line of the intersection. It is easier to work with this value (finding closest point to start of line). See example

In the same function you calculate the cross product of the two lines as vectors. There is room for improvement.

You calculate this value twice. You need do it only once.

When the line are parallel the cross of the vectors will be zero. Lines will not intercept when parallel. Also it means you will be dividing by zero.

You calculate the unit distance along each line then you check if the intercept point is on both lines. You can improve the performance by checking each line as you go. No need to find the unit distance on the second line if it does not cross the first.

Rendering
When drawing paths that all have the same style move the ctx.beginPath outside the loop. ctx.beginPath forces a GPU state change and on many systems this can slow the whole device down, not just your page. (see Rewrite)
Vector Math
Consider creating or using a vector library to reduce long messy lines like let t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y);
Expressions like that are very prone to typos and errors. Using a vector library gives readable abstraction to the operation. eg the above line may becomes t = s2.cross(line1.p1.sub(line2.p1)) / s1.cross(s2)
Even using a very basic library to define points and lines will help reduce the amount of code. see Rewrite.
Problems?
Hard to know if these are problems or if there are constraints that mean the following will not be of issue.

A line segment may start, end, or be completely inside a box. There is no code that take this into account

You stop clipping line segments on the first line clipped. This means that is more than one segment crosses the box the second etc will not get clipped.

Assuming that the code is working, then there is no need to clip when the line segment ends on the box's  edge. Thus the test if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {  can be if (s > 0 && s < 1 && t > 0 && t < 1) {

You only clip lines is they cross the box, If lines  cross the corner of a box you do not clip it?

Rewrite
I have added 4 very basic objects, Point2, Vector2, Line2, and  Rectangle2 (2 stands for 2D) and use these to store and do the calculations.
getLineIntersection returns the unit distance along the line segment rather than a point. The unit distance is push to an array. If 2 units are in that array then the segment will be clipped. The units distances are sorted to get the first and second intercepts.
The behavior remains the same as your original code apart from clipping only crossing opposite sides of the box. The rewrite will clip if line crosses adjoining box edges. The data includes this as a 3rd box.

const ctx = canvas.getContext("2d");

const Point2 = (x = 0, y = 0) => ({x, y});
const Vector2 = Point2;
const Line2 = (p1, p2) => ({p1, p2});
const Rectangle2 = (x, y, w, h) => ({p1: Point2(x, y), size: Vector2(w, h)});

function drawSegments(segments) {
    ctx.beginPath();
    for (const seg of segments) {
        ctx.moveTo(seg.p1.x, seg.p1.y);
        ctx.lineTo(seg.p2.x, seg.p2.y);
    }
    ctx.stroke();
}

function drawRectangles(rectangles) {
    ctx.beginPath();
    for (const r of rectangles) {
        ctx.rect(r.p1.x, r.p1.y, r.size.x, r.size.y);
    }
    ctx.stroke();
}

function getLineIntersection(l1, l2) {
    const s1 = Vector2(l1.p2.x - l1.p1.x, l1.p2.y - l1.p1.y);
    const s2 = Vector2(l2.p2.x - l2.p1.x, l2.p2.y - l2.p1.y);
    const df = Vector2(l1.p1.x - l2.p1.x, l1.p1.y - l2.p1.y);
    const cross = s1.x * s2.y - s1.y * s2.x;
    if (cross !== 0) {
        const u = (s1.x * df.y - s1.y * df.x) / cross;
        if (u > 0 && u < 1) {
            const u = (s2.x * df.y - s2.y * df.x) / cross;
            if (u > 0 && u < 1) { return u }
        }
    }
    return false;
}

function breakSegments(segments, rect) {
    const r1 = rect.p1;
    const r2 = Point2(r1.x + rect.size.x, r1.y);
    const r3 = Point2(r2.x, r2.y + rect.size.y);
    const r4 = Point2(r1.x, r3.y);

    const boxLines = [
        Line2(r1, r2),
        Line2(r2, r3),
        Line2(r3, r4),
        Line2(r4, r1),
    ];
    const units = [];
    var i = 0;
    while (i < segments.length) {
        units.length = 0;
        const line = segments[i++];
        for (const bLine of boxLines) {
            const u = getLineIntersection(line, bLine);
            u && units.push(u);
        }

        if (units.length === 2) {
            units[0] > units[1] && ([units[0], units[1]] = [units[1], units[0]]);
            const [u1, u2] = units;
            const p1 = line.p1, p2 = line.p2;
            const vx = p2.x - p1.x;
            const vy = p2.y - p1.y;
            line.p2.x = line.p1.x + vx * u1;
            line.p2.y = line.p1.y + vy * u1;
            segments.splice(i - 1, 0, Line2(
                Point2(line.p1.x + vx * u2, line.p1.y + vy * u2),
                Point2(line.p1.x + vx, line.p1.y + vy)
            ));
            break;
        }
    }
}

const lineSegments = [
    Line2(Point2(10,   60),  Point2(500, 60)),
    Line2(Point2(100, 10), Point2(100, 120)),
    Line2(Point2(220, 170), Point2(300, 110)), // cross corner segment
    //Line2(Point2(256, 0), Point2(256, 120)),  // these lines do not get clipped
    //Line2(Point2(263, 120), Point2(263, 0)),
];

const rects = [
    Rectangle2(250, 50, 16, 16),
    Rectangle2(90, 80, 16, 16),
    Rectangle2(250, 140, 36, 36)  // cross corner box
];
breakSegments(lineSegments, rects[0]);
breakSegments(lineSegments, rects[1]);
breakSegments(lineSegments, rects[2]);
drawSegments(lineSegments);
drawRectangles(rects);
<canvas id="canvas" width="500" height="500"></canvas>


Abstract it away!

Not sure exactly which instruction means to throw error 7 (which is normally an out of memory error code), but I think something like this should work - basically the idea is to extract the piece of logic into its own self-contained function, so that the calling code doesn't need to worry about an expected error and can use a simple Boolean value instead:

Private Function IsLoginEnabled(Optional ByRef outNoteElement As WebElement) As Boolean
    On Error Resume Next
        Set outNoteElement = this.Driver.FindElementByClass("note")
        IsLoginEnabled = outNoteElement Is Nothing And Err.Number = 7
        Err.Clear
    On Error GoTo 0
End Function

The calling code's logic can now leverage a simple Boolean result:

this.IsLoggedIn = IsLoginEnabled(noteElement)

It can also see that noteElement only ever contanis a valid object reference when the function returns False, so you don't need to be dealing with a run-time error in order to determine whether you need to inspect that noteElement object give your AP department a call.


I prefer

import tkinter as tk

and I can see that tk.Button, tk.INSERT, tk.FALSE are not my local variables/classes.

You can use string.ascii_lowercase instead of letters list, and string.ascii_uppercase instead of capital.

You don't have to convert string.ascii_lowercase and string.ascii_uppercase into list.

https://docs.python.org/3/library/string.html

password1 and password2 are local variables so you can use one name password in both functions.

for loop put in two lines - to make it more readable.

for child in frame.winfo_children():
    child.grid_configure(padx=5, pady=10)

In comments you can put one space after #  - to make it more readable.
You can put one space after every , .

You can use "" directly with join

"".join(password1)

You don't need ()

around text_frame in

tk.Text((text_frame), ...

# OK
tk.Text(text_frame, ...

around capitol in

choice((capital))

# OK
choice(capital)

around letters in

choice((letters))

# OK
choice(letters)

You can add empty lines in functions to separate some part of functions

In complex_password you can randint(1, 2) instead randint(1, 4) because it gives the same probability - 50% for letter and 50% for number.

In complex_password you can use for loop instead while and don't need variable count.

In complex_password you don't need if count == 12 because this part can be outside while/for loop.

You can organize code this way

import tkinter as tk
from tkinter import ttk
import random
import string

# === constants === (UPPER_CASE names)

    # empty

# === classes === (CamelCase names)

    # empty

# === functions === (lower_case names)

def complex_password(): #complex password function
    password = []

    password.append(random.choice(capital))

    for __ in range(12):
        roll = random.randint(1, 2)

        if roll == 1:
            password.append(random.choice(letters))
        else:
            number = random.randint(0, 9)
            number = str(number)
            password.append(number)

    password = "".join(password)

    text.insert(tk.INSERT, password)
    text.insert(tk.INSERT, "\n")

def simple_password(): #simple password function
    password = []

    password.append(random.choice(words))
    password.append(random.choice(words))

    number = random.randint(1, 99)
    password.append(str(number))

    password = "".join(password)

    text.insert(tk.INSERT, password)
    text.insert(tk.INSERT, "\n")

def clear_text(): #clear txt box function
    text.delete(1.0, tk.END)

# === main ===

# --- some variables ---

words = [
    'Dog', 'Cat', 'Mouse', 'Fire', 'Ice', 'Basket', 'Tree', 'Tiger',
     'Lion', 'Flash','Super', 'Light', 'Zoom','Speed', 'Pants', 'Shirt',
     'Hat', 'Suit', 'Berry', 'Yogurt', 'Epic', 'Keyboard', 'Toe', 'Car',
     'Truck', 'Bike', 'Motor', 'Hammer', 'Pizza', 'Heart', 'Arm','Joint',
     'Saw', 'New', 'Carrots', 'Baby', 'Kiss', 'Backspace',  'Enter', 'Alt',
     'Print', "Down", 'Up', 'Question', 'Rain', 'Forest','Red', 'Orange',
     'Yellow', 'Green', 'Blue', 'Purple', 'Brown', 'Black', 'Indigo', 'Grey',
     'Shadow', 'Eye', 'Brick', 'Twig', 'Gangster', 'Thug', 'Chains', 'Gold',
     'Silver', 'Bronze', 'Platinum', 'Titanium', 'Exploding', 'Ladybug', 'Grass',
     'Monkey', 'Rhino', 'Comma', 'Hair', 'Shark', 'Fish'
]

letters = string.ascii_lowercase
capital = string.ascii_uppercase

# --- init ---

main = tk.Tk()

main.title("Password Gen")
main.resizable(width=tk.FALSE, height=tk.FALSE)
main.geometry("238x230")

# --- objects ---

frame = ttk.Frame(main)
button_frame = ttk.Frame(frame)
text_frame = ttk.Frame(frame)
text = tk.Text(text_frame, borderwidth=10, height=8, width=20, relief="sunken")

# buttons
simple = ttk.Button(button_frame, text="Simple", command=simple_password)
complex = ttk.Button(button_frame, text="Complex", command=complex_password)
clear = ttk.Button(button_frame, text="Clear", command=clear_text)

# buttons grids
simple.grid(column=2, row=1)
complex.grid(column=1, row=1)
clear.grid(column=3, row=1)
text.grid()

# frame grids
frame.grid(column=1, row=2)
text_frame.grid(column=1, row=2)
button_frame.grid(column=1, row=1)

# misc settings
for child in frame.winfo_children():
    child.grid_configure(padx=5, pady=10)

# --- start the engine ---

main.mainloop()


In no particular order:

That hashing method is terrible and insecure. Hashes must be costly (slow) most of all, and they must contain a unique salt. Use password_hash, don't invent your own.

If that is the required hashing method: move away from it ASAP. But at the very least, utf8_encode is entirely superfluous, since you're only allowing ASCII characters to begin with and it won't do anything in that case.

Don't validate strings you have already altered (here: after mysqli_real_escape_string).
You're already using mysqli, use prepared statements rather than tedious and error prone escaping.
Disallowing "special characters" in passwords makes them weaker, not stronger. Unless you have strong business reasons for this restriction (which legitimately may exist), don't limit the allowed character set.
Use more functions to make your code more readable.
Name your SQL columns, don't rely on the implicit order.
Use DEFAULT values in your database table definitions instead of passing default values through the query, if possible.
Check whether your SQL query succeeded (and/or use mysqli's exception error mode); presumably you have a UNIQUE constraint on the username, so the query may legitimately fail, and your code doesn't even know it.

function validateUsername($name) {
    return ctype_alnum($name) && strlen($name) >= 6;
}

function validatePassword($str) {
    return ctype_alnum($str)
        && strlen($str) >= 8
        && preg_match('/[A-Z]/', $str)
        && preg_match('/[a-z]/', $str)
        && preg_match('/[0-9]/', $str);
}

function createUser(mysqli $db, $name, $password) {
    $stmt = $db->prepare('INSERT INTO `accounts` (`name`, `password`) VALUES (?, ?)');
    $stmt->bind_param('ss', $name, password_hash($password, PASSWORD_DEFAULT));
    return $stmt->execute();
}

if (!validateUsername($_POST['name'])) {
    echo 'Invalid name';
} else if (!validatePassword($_POST['password'])) {
    echo 'Invalid password';
} else if ($_POST['password'] !== $_POST['repeat_password']) {
    echo "Passwords don't match";
} else if (!createUser($db_link, $_POST['name'], $_POST['password'])) {
    echo 'Something went wrong';  // add better error handling here
} else {
    echo 'Account created';
}

Of course, you'll probably want to collect all the errors and output them next to the actual <input> elements when you inform the user about errors, instead of just failing on the first error that is produced. That's a bit too broad to tackle here though. And this could all be further improved with OOP or other larger architectural choices of course…


Find non duplicate Triangle Triplets from a list of given numbers- version 3

I have followed your previous implementations and I don't think there is much else you can change, code-wise. The next step is probably optimizing the algorithm, just like you've said.

Some nitpicking:

I personally didn't like your in-place lambda. It looks basically like a raw conditional, but with more boilerplate around it. Either make it a proper function or just leave the conditional as it was in the first iteration. Your hybrid approach does not appeal to me.
If you use push_back() instead of emplace_back(), you'll be able to omit repeating the type Triplet. Effectively, the results will be the same, since we are dealing with plain integers, so there's no way to avoid copying them. Use the DRYer version:

triplets.push_back( { first, second, third } );

unsigned int is likely smaller than vector::size_type on 64bit platforms. Realistically speaking, you probably don't need 64bit indexing, but a safer approach would be to use std::size_t or vector::size_type itself.
You can sprinkle a few consts here and there, such as for size, first, second and third. Right now the function is small, so it is easy to track the variables and see that they are never changed. However, if it were to be expanded in the future, it would aid the reader a lot to have an immutability guarantee when first spotting the variable declaration. Very important though, vec_input, as the name suggests, is input/read-only. So it must not be changed. Definitely make it const!
Any chance you can "guesstimate" the size of triplets when entering the function to reserve() some memory? If you could, that would potentially save a lot of time wasted with reallocations and copies done by [push|emplace]_back.


VBA Automatic insert in a Excel Spreadsheet

The comments I have fall into three categories that relate to general programming practices that would be applicable to any language, not just VBA.

Raw Strings
Don't Repeat Yourself (DRY)
Single Responsibility Principle (SRP)

Raw Strings:
There are a lot of raw strings (examples: "CODICI", "Z12", "fine") in the code.  I'm guessing that the ease of Copy-Paste made it simple to paste Worksheet("CODICI") in the 10 places where a reference to sheet "CODICI" is needed.  However, should you ever change the name of this sheet someday (and chances are excellent that you will want to), by then there will be at least 10 places to get wrong - and the compiler/interpreter will not help you find them.  By adding a module level variable for the worksheet and assigning it once, you avoid this maintenance issue and reduce the volume of text in your subroutine.  There is a performance improvement here as well, but it will not be noticeable - performance is not the motivation for the change.  Raw strings like "CODICI" are generally to be avoided within your code for the above reasons.  Strings that never change for you subroutine are excellent candidates to be declared as module level constants.  And, when you want to change the name of the worksheet "CODICI", you only need to change your code in a single place (easy to get right!).

DRY:
DRY is important from both readability and maintenance of your code.  Eliminating repeated blocks of code by writing small, focused, methods to eliminate the repeated code is the typical example of DRY.  However, repeatedly writing raw strings or copy-pasting multiple line expressions falls under this principle as well.

SRP:
A simple search will provide you a better definition of SRP better than I can/will provide here.  As the name implies, SRP encourages that each  subroutine, function you write (in VBA or anything else) only does one thing.  A good criteria for SRP is this: a subroutine (or function) has a single responsibility if it has only one reason to change.  Your code has as single subroutine.  Consequently, it contains many reasons to change because it does everything.  Some of the reasons to change have been mentioned above within the DRY section.  Full disclosure: I regularly fail to achieve SRP my own code, but it is certainly a good principle to aspire to.

Sub inserisciAutomatico() is the macro entry point for the code - I would suggest that it's  responsibility is to declare constants, initialize the necessary module level variables and call a sequence of operations to accomplish the task.  The rewrite provided below does not accomplish this goal completely, but hopefully does so to a degree that is useful as an example.

By consolidating these tasks/responsibilities to smaller, single responsibility methods - you will make your code far easier to understand and maintain.  As you have already done, declaring Option Explicit at the top of your module is a good practice.  It forces the explicit declaration of all variables used.  A good indicator that Sub inserisciAutomatico() is doing 'too much' is the long list of variables it has declared.  Creating smaller focused subroutines and functions to accomplish the macro's goal will make many of these disappear.

The rewrite below removes many of raw strings by declaring them as constants.  It also reduces the number of local variable declarations needed by calling subroutines focused on the tasks associated with the original variable.  It also moves the remaining local variable declarations closer to their usage (generally a good practice).  I'll apologize in advance for my lack of any skills in Italian.  Some of the subroutines are named a bit strangely.  The names were chosen to identify the principle that motivated their creation.

Option Explicit

Private Const TheMainWorksheetName As String = "CODICI"
Private Const DefaultFont As String = "Calibri"
Private Const DefaultFontSize As Long = 10
Private Const Appoggio As String = "fine"
Private Const ProvaFormulaRange As String = "B7:B250"
Private Const ValoreRange As String = "D4:D250"
Private Const DWG As String = ".dwg"
Private Const ASM As String = ".asm"
Private Const XLS As String = ".xls"
Private Const JPG As String = ".jpg"
Private Const ProvaFormulasAddress As String = "Z1"
Private Const PrimoValoreT0 = "T0"

'DRY - use a variable (needs a better name) to avoid
'repeating the expression 'Worksheets("CODICI")'
Private theMainWorksheet As Worksheet

Sub inserisciAutomatico()

    Application.ScreenUpdating = False
    Application.EnableEvents = False

    Set theMainWorksheet = Worksheets(TheMainWorksheetName)

    Dim risultati As Range
    Set risultati = theMainWorksheet.Range(ValoreRange)

    'Dim valore As String
    'ComboBox1 needs a meaningful name to indicate what
    'value it is providing - for this example, it has been named 'valoreComboBox'
    'valore = theMainWorksheet .ComboBox1.value

    'Renaming ComboBox1 eliminates variable 'valore' and there is no longer
    'any uncertainty what is provided by the control
    Dim cell As Range
    Set cell = risultati.Find(theMainWorksheet .valoreComboBox.value)

    Dim risultato As Range
    Set risultato = risultati.Find(Appoggio, LookIn:=xlValues, After:=cell)

    Dim risultatoAppoggio As Range
    Set risultatoAppoggio = risultati.Find(theMainWorksheet .valoreComboBox.value, LookIn:=xlValues)

    Dim kitNrSecondoAppoggio As String
    kitNrSecondoAppoggio = risultatoAppoggio.Offset(-1, -3)

    Dim provaFormula As Range
    Set provaFormula = theMainWorksheet.Range(ProvaFormulasAddress)
    provaFormula.FormulaArray = "=MAX(IF(LEFT(" & ProvaFormulaRange & ",1)=""" & kitNrSecondoAppoggio & """, " & ProvaFormulaRange & "))"

    Range(risultato.Address).EntireRow.Insert

    SRP_SetupPrimoValore risultato.Offset(-1, -3).Address, PrimoValoreT0

    'KitNR was originally declared as a String, so the original KitNr + 1 operation below acted like integer addition
    'because VBA implicitly converts KitNr to a number.  Declare KitNr as an actual number type and eliminate any confusion
    Dim KitNr As Long
    KitNr = CLng(theMainWorksheet.Range(ProvaFormulasAddress).value)
    'The subrouting wants a string...so explicitly provide it...again to eliminate any confusion
    SRP_SetupNumeroID risultato.Offset(-1, -2).Address, CStr(KitNr + 1)

    'TextBox1 needs a meaningful name to indicate what it is providing
    SRP_SetupDescrizione risultato.Offset(-1, 0).Address, wksht.TextBox1.value

    'ComboBox2 needs a meaningful name to indicate what it is providing
     SRP_SetupGruppo risultato.Offset(-1, 1).Address, wksht.ComboBox2.value

    SRP_SetupTheFormula risultato.Offset(-1, 2).Address, risultato.Offset(-2, 2).Address

    Range(risultato.Offset(-1, 3).Address).value = DWG
    Range(risultato.Offset(-1, 4).Address).value = ASM
    Range(risultato.Offset(-1, 5).Address).value = XLS
    Range(risultato.Offset(-1, 6).Address).value = JPG

End Sub

Private Sub SRP_SetupPrimoValore(ByVal addr As String, ByVal value As String)
    Range(addr).value = value
End Sub

Private Sub SRP_SetupNumeroID(ByVal addr As String, ByVal kitNrAppoggio As String)
    Range(addr).value = kitNrAppoggio
    DRY_AvoidRepeatingTheFormattingOfNumeroIDAndDescrizione Range(addr)
End Sub

Private Sub SRP_SetupDescrizione(ByVal addr As String, ByVal value As String)
    Range(addr).value = value
    DRY_AvoidRepeatingTheFormattingOfNumeroIDAndDescrizione Range(addr)
End Sub

Private Sub SRP_SetupGruppo(ByVal addr As String, ByVal comboBox2Value As String)
    Range(addr).value = comboBox2Value
    Range(addr).NumberFormat = "@"
End Sub

Private Sub SRP_SetupTheFormula(ByVal addr As String, ByVal formulaAddress As String)
    Range(formulaAddress).Select
    Selection.Copy
    Range(addr).PasteSpecial xlPasteFormulas
End Sub

Private Sub DRY_AvoidRepeatingTheFormattingOfNumeroIDAndDescrizione(ByRef theCell As Range)
    theCell.Font.Bold = False
    theCell.Font.Name = DefaultFont
    theCell.Font.Size = DefaultFontSize
    theCell.Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous
End Sub

The 'raw' numbers within the Offset(...) statements are still a maintence issue waiting to happen.  I would consider creating a small ClassModule or UserDefinedType (UDT) to host the rowOffset and columnOffset values.  After creating the Class or UDT, create module level variables with names for each Offset pair to identify what the offsets mean (for example, "risultatoToNumerIDOffset").  The result is that risultato.Offset(-1, -2) becomes something like risultato.Offset(risultatoToNumerIDOffset.Columns, risultatoToNumerIDOffset.Rows) and the offset values are no longer spread throughout the code.


dynamic programming solution for a string ending with 0, 1 or 2

Your recurrence is very fine, so I've just minor adjustments to propose:

In this kind of bottom-up DP, you only need to access the previous row. No need to keep the whole history.
There is a copy/paste bug in dp[i][0] computation.
No need to use a dict, each level (row) is fully filled out.

I would thus write:

def total_with_length(n):
    if n <= 0:
        return 0
    n0, n1, n2 = 1, 1, 1
    for _ in range(n-1):
        n0, n1, n2 = n1+n2, n0+n2, n0+n1+n2
    return n0 + n1 + n2


What happens if I enter only + surrounded by spaces?
The program should not abort if I enter 0 / 0, but continue with the next line.
I'd like to omit the spaces around the operator.
In the regular expression, the operator part can be written as [+\\-*/].


The algorithm is purely combinatorial: it doesn't depend on the actual values of the elements. That can be made explicit by using more general types. Compare these signatures:

ansatzEtas :: Integer -> Forest String
ansatzEtas :: Integer -> [a] -> Forest (a, a)
-- takes the alphabet as a parameter (length must be >= the first argument n)

The output is guaranteed to be a forest of pairs.
Now that a is a type parameter, we are guaranteed that the pairs contain only elements from the original list.

We can easily get back a forest of strings using the fact that trees are functors:

pairToList :: Forest (a, a) -> Forest [a]
pairToList = (fmap . fmap) (\(x, y) -> [x, y])

More precise types make mistakes much less likely, and can even help us know what to write. For example, imagine we're still trying to write innerEtas, and we want to know what to put in place of the underscore:

innerEtas :: String -> [(String, String)]
innerEtas (x:xs) = map (\a -> (_, filter (/=a) xs)) xs

We can try to compile this code as it is, with the underscore, and GHC will report that this hole is of expected type String.

• Found hole: _ :: String

It also helpfully tells us that xs :: [Char] is in scope. On a tired day, one might then mistakenly interpret that as advice to put xs in:

innerEtas (x:xs) = map (\a -> (xs, filter (/=a) xs)) xs
                               -- Bug!

Looking back, before we even start writing innerEtas, we know that it's supposed to give us pairs, and we can say it in the type.

innerEtas :: [a] -> [((a, a), [a])]
innerEtas (x:xs) = map (\a -> (_, filter (/=a) xs)) xs

Here we would be told the following expected type:

• Found hole: _ :: (a, a)

Which is hopefully much more helpful to determine what goes where.

This generalization may introduce a bit of a challenge, because innerEtas uses (/=), which requires an Eq constraint. Two options:

Just add the Eq a constraint everywhere, this is an easy solution, we still get most of the benefits of the generalization anyway.
Rewrite innerEtas to not use (/=), instead write a custom recursive function or use other combinators than filter. This can help avoid mistakes when making heavy use of Eq, but arguably this is not the case here.

Still, in this case there's a cute one-liner to extract an element from a list and keep the rest, nondeterministically, without using Eq:

pick :: [a] -> [(a, [a])]
pick xs = [(y, ys ++ ys') | (ys, y : ys') <- liftA2 zip inits tails xs]
-- inits, tails from Data.List

-- Example
pick [1,2,3] = [(1,[2,3]),(2,[1,3]),(3,[1,2])]

Some refactoring is possible between innerEtas and buildEtas. There is redundancy because both are checking whether the list is empty. In fact, x is quite a bit more special than the other elements, and we can take it apart in buildEtas already. Then innerEtas could take x separately from the tail as an argument, but it becomes a one-liner that we might as well inline:

buildEtas :: [a] -> Forest (a, a)
buildEtas [] = []
buildEtas (x : []) = undefined   -- I think this is unnecessary, but kept it to remain close to the original code
buildEtas (x : xs) = let ys = map (\(y, zs) -> ((x, y), zs) (pick xs)
                     in map (\(node, list) -> Node node $ buildEtas list) ys


Approach to string split by character in Haskell

Well, sorry, but it is really tempting to note that there is in fact a library routine that can do that, and it is even called the same as your function:

groupBy (\a b -> b /= '/') "/hejsan/asdas"

This code with groupBy from Data.List will give you ["/hejsan","/asdas"]. Even though it should probably be noted that this is taking advantage of how groupBy is implemented internally, which might not be the best idea.

But let's look at your implementation - two things jump out:

You are clearly using the first element in the rs list differently from the rest. Why not make it an additional parameter so you can skip de- and recomposing the list all the time?
Why do you even need an accumulation parameter for your groups? Once you append something to rs, you already know that it will be reversed in the end and end up at the start of the return value. So you can simply prepend the group to the result of the recursive function call.

With the two changes and a bit of refactoring (replacing your if by pattern matches), we get the following version:

groupBy :: String -> Char -> String -> [String]
groupBy ""     _ "" = []
groupBy ""     _ r  = [r]
groupBy (x:xs) c ""
    | x == c        = groupBy xs c ""
    | otherwise     = groupBy xs c [x]
groupBy (x:xs) c r
    | x == c        = r : groupBy xs c ""
    | otherwise     = groupBy xs c (r ++ [x])

This can be improved further:

This has clearly two modes of operation depending on r == "". When calling you always know whether that is the case, so you could easily split it into two functions. One of them can get rid of the r parameter completely, so you end up with a nice function to call from outside.
Building a list using ++ is inefficient, as it creates a copy of the list each time you append an element, leading O(n²) complexity. It's better to use x:r and then reverse once in the end, which is a more efficient O(n). A bit more involved refactoring enables you to construct the string in the right form right away (see span).

That's really all the difference to the "perfect" library-level implementation (see the library code). Note that generally, initialization of accumulation parameters is simply done by defining a wrapper function, even though we can easily put this function without even needing it.

Hope this helps.


Merging records from one spreadsheet into another

The unique data could be appended, using a Scripting Dictionary and arrays in less than a second.  Alternatively, you could use an ADO Query to append records from sheet1, not in sheet2.

The easiest method would be to add all the records to the second worksheet then record a macro that:

Convert the range to a table
Select a cell in the range then click Ribbon >  Table Tools > Remove Duplicates

All that is left to do is refactor the Macro to make the code dynamic.

Watch:
 - Excel VBA Introduction Part 25 - Arrays
 - Excel VBA Introduction Part 39 - Dictionaries
 - Excel VBA Introduction Part 32 - ADO (ActiveX Data Objects) SQL Statements (INSERT, UPDATE, DELETE)

Here is how I would rewrite the OP's code using a Scripting Dictionary and arrays.

Function UpdateNEW2() As Long
    Const Delimiter As String = "|"
    Dim dic As Object
    Set dic = CreateObject("Scripting.Dictionary")
    Dim newRows As Range
    Dim vSteps, key
    With Sheets("Steps")
        vSteps = .Range("A2:O2", .Cells(.Rows.Count, 2).End(xlUp)).Value
    End With

    Dim r As Long, c As Long, n As Long
    For r = 1 To UBound(vSteps)
        key = vSteps(r, 3) & Delimiter & vSteps(r, 4)
        Debug.Print key
        If Not dic.Exists(key) Then dic.Add key, 0
    Next

    Dim vInterface, results
    With Sheets("Interface")
        vInterface = .Range("A7:O7", .Cells(.Rows.Count, "C").End(xlUp)).Value
    End With

    ReDim results(1 To UBound(vInterface), 1 To 15)
    For r = 1 To UBound(vInterface)
        key = vInterface(r, 4) & Delimiter & vInterface(r, 5)
        Debug.Print key
        If Not dic.Exists(key) Then
            n = n + 1
            For c = 3 To 15
                results(n, c - 2) = vInterface(r, c)
            Next
        End If
    Next
    If n > 0 Then
        With Sheets("Steps")
            With .Cells(.Rows.Count, 2).End(xlUp).Offset(1)
               .Resize(n, 15).Value = results
            End With
        End With
    End If
    UpdateNEW2 = n
End Function

(Sample Data)


I would store the result of mSelectedData.getTime() into a variable. It will save one method call and remove duplicate code.
The line that resets the data range seems a tad out of place; however, I am not sure about the rest of your implementation, so this might be the best place for it.
Also, I would check your first if-statement:

if (twoWeeksAgo.getTime() >= mSelectedDate.getTime())

Currently it will evaluate true (which is not expected) if the Dates are the same. From your description, it sounds like you want the date range to be inclusive not exclusive. Change the >= to simply > to get the result you expect:

if (twoWeeksAgo.getTime() > mSelectedDate.getTime())

Other than that, the code looks fine; though I personally would capitalize the first word of each comment and put a space between it and the double slashes. So, // Some comment instead of //some comment. Just a personal preference.