JavaScript (multiple) inheritance / mixins

Q1: I wouldn't say it was good or particularly bad practice for some of the reasons I will go into below.

Q2: It's not memory efficient if you compare the code you have to a class / prototype based solution.

Q3: Take a look below, i've tried to keep it to as skeletal structure as possible to demonstrate how prototypes can be very useful.

xtend

xtend is great for smaller, intricate pieces of code and it has helped me loads recently. The caveat: In larger code bases you want to avoid the level of blind inheritance that xtend provides. Potentially in the future you may create a class that uses an object that has many layers of inheritance as an array of options for example. When that object squares up to the media and asked it's name and occupation, how does it know where all its components came from and what they do? In your code, how does the boy know he's a boy as well as a human for example.

Public / Private Methods

OOP in JS : Public / Private Variables will explain alot, if you are used to OOP in other languages this will probably click straight away.

Your first function is a class constructor with two private methods declared. I prefer to only set information in a constructor and then use public methods (prototypes) to deal with the workload.

Prototypes

Many objects can use prototypes and they're never duplicated within each object that is created.

Take this piece of code for example, first the class structure:

function CreateHuman(params) {
    // We create a new human object using params as initial data
    this.human = {
        name : params.name,
        age : params.age,
        gender : 'unknown'
    }
}

// first prototype, updates the gender with the one specified in the call
CreateHuman.prototype.setGender = function (gender) {
    this.human.gender = gender;
}

CreateHuman.prototype.setName = function (name) {
    this.human.name = name;
}

CreateHuman.prototype.setAge = function (age) {
    this.human.age = age;
}

// this method does more work than any of the others
CreateHuman.prototype.setHobby = function() {

    // If the gender has been set, the hobby will be applied
    // You could use functions here as well

    switch(this.gender) {
        case('male') :
            this.person.hobby = 'football';
            this.person.hobbyActive = (this.age >= 6) ? true : false;
            break;
        case('female') :
            this.person.hobby = 'singing';
            this.person.hobbyActive = (this.age >= 4) ? true : false;
            break;
        deafult :
            this.person.hobby = 'no hobby';
            this.person.hobbyActive = true;
    }
}

// And a return method to get the object from the class
CreateHuman.prototype.getPerson = function() {
    return this.person;  // We return the object with all collected data
}

We could then use the class very easily to create a number of humans with different names, ages and genders.

var params =
{
    name : "Dave",
    age : 30
};

I've included the params in this example as you may just need one object created and feeding it params is an easy way to make sure your code is useable by anyone else that might use your class.

var human = new CreateHuman(params);
var people = {}; // Make people an object to hold all the humans created

// Call our first prototype function
human.setGender('male');
// 2nd prototype
human.setHobby();

people.human1 = human.getPerson();

people.human1 if logged in the console would be:

Object {name : 'dave',
        age : 30,
        gender : 'male',
        hobby : 'football',
        hobbyActive : true
       }

Start again:

human.setName('Alexa');
human.setAge(28);
human.setGender('female');
human.setHobby();

people.human2 = human.getPerson()

// And so on

I hope that gives you an insight into prototypes, they will be far more useful to you than object inheritance (though I admit it does have its uses).


Here's the first thing I came up with. Wrote it in Notepad, so it might not compile exactly as is.

private static int GetClicks(AppContext context, Period period, bool unique)
{
    int Clicks = 0;
    switch (period)
    {
        var query = context.EmailLinkClicks.AsQueryable();
        case Period.Today:
            query = query.Where(c => c.CreatedOn == DateTime.Today);
            break;
        case Period.Week:
            query = query.Where(c => c.CreatedOn > System.Data.Entity.DbFunctions.AddDays(c.CreatedOn, -7));
            break;
        case Period.Month:
            query = query.Where(c => c.CreatedOn.Month == DateTime.Today.Month);
            break;
    }

    var ipAddresses = query.Select(c => c.IpAddress);

    if (unique)
    {
        query = query.Distinct();
    }

    return query.Count();
}

enum Period
{
    Today,
    Week,
    Month
}

Update: As to where to store these queries... Doing it in your controller isn't the worst thing in the world. There are a ton of different places you could put that code though. The Repository pattern seems to be popular. I'm not strict about that kind of thing though.

Update: if you wanted to get both the total and unique stats in the same call, you could do something like this: https://gist.github.com/alexdresko/8059762/bcf233b86869042c4b6f360f6b461999b2bf4899

Update: But what you probably want, assuming you want to create some kind of report, is this: https://gist.github.com/alexdresko/8059762/c4afa948f020e8395bb27d565269c914aad926a7

That one will allow you to simply iterate over the collections of stats in your view, display all relevant information.


Accessing elements of a linked list with .get(i) is expensive, because it's an \$O(N)\$ operation compared to \$O(1)\$ of array backed structures. You should avoid doing this, and use an enhanced for-each loop instead, for example:

for (Long currentTimeStamp : timestamps) {
    if (currentTimeStamp  >= oldestTime) {
        newTimestamps.add(currentTimeStamp);
    } else {
        break;
    }
}

If you need the element index, you can add a counting variable "manually" (declared before the loop, and increments in the loop body).


Your code can be improved in few lines:

        String fileName = file.getName();
        if (fileName.indexOf(".") > 0)
            fileName = fileName.substring(0, fileName.lastIndexOf("."));
        return fileName;

As far as catching the exception, an advice, always catch the specific exception, not the generic, so you should be catching IOException or IndexOutOfBoundException instead of Exception. Also, it's always a good idea to log exception somehow.


Move struct Listener into class GameMessenger
The struct Listener is just an implementation detail of GameMessenger, you can move it into class GameMessenger like so:
class GameMessenger: ...
{
    struct Listener: ...
    {
         ...
    };

    ...
};

Now that it is private, I would also keep Listener very simple, and just have it hold the two member variables, without adding any member functions.
Pass messages as const references
The actual message handler functions take a const reference to the message, but your GameMessenger::broadcast() takes it by value, making an unnecessary copy. Change it to:
void broadcast(const GameMessage &gameMessage) {...}

Naming things
Some names could be improved. For example, struct Listener has a member variable m_listener. Combined with the std::vector<Listener>, you get the word listener repeated a lot, like in GameMessenger::broadcast(), where there's even a listener.m_listener. Consider renaming m_listener to m_handler or m_callback.
Some names are a bit longer than necessary. I suggest these changes:
- `typename GameMessage` -> `typename Message`
- `isOwnerAlreadyRegistered()` -> `isRegistered()`

Make class GameMessenger a template
With void pointers you throw type-safety overboard, and requires you to reinterpret_cast<>() things. I can't say much about m_ownerAddress, however
the main problem here is that you have a non-templated class GameMessenger. Apart from the constructor, all the public member functions are template <typename GameMessage>. Instead of having one GameMessenger object being responsible for all possible message types, consider making the class templated itself, and only be responsible for one specific message type.
If you implement it this way, there will be one GameMessenger object per message type. That means there is no longer a need to have a std::array for each of the possible message types, and in fact enum eGameMessageType is no longer necessary.
Here is an example of how it might look:
template <typename Message>
class GameMessenger: private NonCopyable, private NonMovable
{
    struct Listener {
        const std::function<void(const Message &)> m_handler;
        const void *m_ownerAddress;
    };

public:
    static GameMessenger& getInstance()
    {
        static GameMessenger instance;
        return instance;
    }

    void subscribe(const std::function<void(const Message&)>& handler, const void* ownerAddress)
    {
        assert(!isRegistered(ownerAddress));
        listeners.emplace_back(handler, ownerAddress);
    }

    template <typename Message>
    void unsubscribe(const void* ownerAddress)
    {
        auto iter = std::find_if(m_listeners.begin(), m_listeners.end(), [ownerAddress](const auto& listener)
        {
            return listener.m_ownerAddress == ownerAddress;
        });

        assert(iter != listeners.end());
        listeners.erase(iter);
    }

    void broadcast(const Message &message)
    {
        for (const auto& listener: m_listeners)
        {
            listener.m_handler(message);
        }
    }

private:
    std::vector<Listener> m_listeners;

    bool isRegistered(const void* ownerAddress) const
    {
        assert(ownerAddress != nullptr);

        auto result = std::find_if(listeners.cbegin(), listeners.cend(), [ownerAddress](const auto& listener)
        {
            return listener.m_ownerAddress == ownerAddress;
        });

        return result != listeners.cend();
    }
};

So how do you use it? Instead of writing:
void handleSpawnPickup(const SpawnPickupMessage &message) {...}
void *ownerAddress = ...;

auto messenger = GameMessenger.getInstance();
messenger.subscribe(handleSpawnPickup, ownerAddress);

You replace the last two lines with:
auto messenger = GameMessenger<SpawnPickupMessage>.getInstance();
messenger.subscribe(handleSpawnPickup, ownerAddress);

If you want to avoid having to explicitly mention the type when getting the messenger instance, consider writing an out-of-class function that subscribes to the right instance for you:
template<typename Message>
void subscribeToMessenger(const std::function<void(const Message&)>& handler, const void* ownerAddress)
{
    GameMessenger<Message>::getInstance().subscribe(handler, ownerAddress);
}

So that you can just write:
subscribeToMessenger(handleSpawnPickup, ownerAddress);


You can indeed simplify this quite a bit using a generator and the itertools module.

I would separate out the generating of the pushups to be done from the total pushups. For this you can use two range objects and the yield from (Python 3.3+) keyword combination:

def pushups(n):
    yield from range(1, n)
    yield from range(n, 0, -1)

The accumulation can be done using itertools.accumulate and itertools.tee to duplicate the generator:

from itertools import accumulate, tee

def leader_step(n):
    gen1, gen2 = tee(pushups(n))
    return list(gen1), list(accumulate(gen2))

if __name__ == "__main__":
    print(leader_step(5))
# ([1, 2, 3, 4, 5, 4, 3, 2, 1], [1, 3, 6, 10, 15, 19, 22, 24, 25])

As noted in the comments by @Peilonrayz, it is not actually necessary to split the generator (as long as it fits into memory, which is very likely, given that presumably a human will try to do this training):

def leader_step(n):
    training = list(pushups(n))
    return training, list(accumulate(training))


Reduced Docker Image size for Docker file


Python Cartesian Product in a constrained dictonary

Instead of itertools.product(*[markers  for i in xrange(n)]) use itertools.product(markers, repeat=n)
Instead of creating three random values and replace it with nan use List Comprehensions.
dict([(key, value) for key, value in ...]) creates dict object.
[bool and [a] or [b]][0] - safer version of bool and a or b - one-linear version of:

if bool:
    a
else:
    b

And final version:

import itertools
import numpy as np

def create_constrained_dict(n, markers):
    d = dict([(element, np.array([(i == 0 and [np.random.uniform(0, 1)] or [np.nan])[0]
                                  for i in element]))
              for element in itertools.product(markers, repeat=n)])
    return d

EDIT

Version without np.array - 2 times faster (thanks @JoeWallis):

import itertools
import numpy as np

def create_constrained_dict(n, markers):
    d = dict([(element, [(i == 0 and [np.random.uniform(0, 1)] or [np.nan])[0]
                         for i in element]))
              for element in itertools.product(markers, repeat=n)])
    return d


Security

Use prepared statements. Classes are reusable, so even if the id is not user provided right now, this may very well change in the future, making your code vulnerable to SQL injection.

Naming

getDetails is rather vague. What details? Additionally, getX usually signals that the method returns X, which isn't the case here.

Your comment is a bit better, something like assignProperties might work. I would prefer something like loadById, populateById, or more explicit populateFieldsById.

General Structur

getDetails should be private, right?

As for the general structure, it's fine.

I would probably separate the Foo object from the code retrieving it from the database like this (pseudo code):

// just setters, getters, and business logic
class Foo {

    constructor(...) {...}
    getPropertyX() {...}
    setPropertyX(...) {...}
    getPropertyY() {...}
    setPropertyY(...) {...}
    performSomeBusinesslogicOnObject() {...}

}

// performing database interactions and populating Foo objects
class FooDAO {

    Foo getById(id) {...}
    Foo getByPropertyZ(z) {...}
    save(Foo foo) {...}

}

My main reason for doing it this way is that it separates the database operation from the model.

Now, you can use the model without being forced to have a database interaction (maybe one isn't needed right now, maybe you want to run tests, maybe the current instance of the object comes from somewhere else than the database, etc).

On the other hand, if most of your business logic happens directly on the database, not the object, this might get confusing. So it really also depends on what Foo is exactly. But for simple objects which are mainly retrieved, updated, saved, etc, this is the way I would go.


djpth('/parent/subsite/../../global/css/file.css')

returns

/parent/../file.css

I guess that is not what you want.
If the file exists I'd use the built-in realpath function. I guess it handles corner case like this and another ones better.

(See also: Effective Java, 2nd edition, Item 47: Know and use the libraries)
$pth is used for multiple purposes. It would be easier to read a $path and a $path_array.
Abbreviations are hard to read, like $pth. Longer names would make the code more readable since readers don't have to decode the abbreviations every time and when they write/maintain the code don't have to guess which abbreviation the author uses.

Furthermore, it's hard to pronounce (as well as djpth).

  If you can’t pronounce it, you can’t discuss it without sounding like an idiot. “Well,
  over here on the bee cee arr three cee enn tee we have a pee ess zee kyew int, see?” This
  matters because programming is a social activity.

Source: Clean Code by Robert C. Martin, Use Pronounceable Names, p21
Comments like this are just noise:

// Iterate through the new array

It's obvious from the code itself. (Clean Code by Robert C. Martin: Chapter 4: Comments, Noise Comments)

$pth = implode('/',$pth);
// Then we return the resolved path
return $pth;

The comment above could be eliminated with a better variable name:

$resolved_path = implode('/', $path_array);
return $resolved_path;


Converting dataframe columns to binary columns

model.matrix already does most of what you want:

company <- c("IBM", "Microsoft", "Google");
model.matrix( ~ company - 1)


Not sure if I should review it as a programming challenge, or if I should include design remarks, I'll just say what comes to mind.

I'll first note that I would make the Meeting fields private final, and add accessor methods. Them being immutable makes sense I would say, and methods help for using them as method references with the streaming API and others, as I will show in a second.

For mergeMeetings, I would really refrain from using set and remove, at least when you do not know the implementation. Depending on the List implementation, the performance of these could turn out to be quite horrible (e.g. set could traverse the list up to the index each time in case of a LinkedList). Also looping and mutating a collection at the same time is a lot of times error-prone or worse. Finally, you mutate the collection passed in, which is also a point to think about twice (though not necessarily bad).

For mergeMeetings2, I like this implementation better. It is a smarter implementation for given problem. First, I would like to note that since Java 8, Collection has a default method implementation for sort. Next, with the Comparator#comparing method, you can specify which property of the type to use to compare with. If you add accessor methods like stated before, this would make the sort look like (with a static import of Comparator):

meetings.sort(comparingInt(Meeting::startTime));

Perhaps instead of using a List to keep track of the merged meetings, you could use a stack (though do not use Stack, rather something like ArrayDeque, refer to the docs why). Instead of getting the last element from the list, you just peek the top, and pop if you have to merge again. I am not sure how I feel about

if (merged.isEmpty()) {
    merged.add(current);
    continue;
}

I think it makes the loop implementation a bit confusing, because this is only called once to add the first element to the merged elements. I wonder if using List#subList and iterating over that would be better, or a manual iterator... Also, should the Meetings become immutable, it would change the implementation a bit. Note that you are now changeing objects which are coming from the outside.

Your merge method assumes that the start time of first is always the smallest start time, and that the end time of second is always the greatest start time. This would be wrong for e.g. first = [8, 12], second = [9, 10]. It will return [8, 10], when it should be [8, 12].

The overlaps method also is a bit incorrect, because multiple meetings starting at the same point in time will not be merged. Also (first.endTime == second.startTime || second.startTime < first.endTime) is the same as second.startTime <= first.endTime.

Finally, your show method ends each line with a comma. Should you want to simply delimit each meeting with a comma, but not one at the end of the line, you could solve it for example as:

System.out.println(meetings.stream().map(Meeting::toString).collect(joining(",")));


I don't think I understand the point of declaring a class if you aren't going to write any methods in it. I mean why go the expense of declaring a class just to store some variables outside of the global scope.  Assuming this class can never populate its properties without parsing a document, so it make sense to have its constructor initiate the file reading and generate values for the properties.

I haven't personally used SPLFileObject before, but the manual says that:

the 2nd parameter $open_mode defaults to r and
the 3rd parameter $use_include_path expects a boolean value.  I expect that that 10 is not doing what you intend.

Reading a limited number of lines from the file with fgets() is a professional decision that shows real care and deliberate scripting.  Removing all debate regarding micro-optimization or if reading the whole file is an "affordable" cost, I love that you are endeavoring to ONLY "read what you need".

By my count, there are 3 factors which should halt the loop of reading of lines:

there are no more lines in the file
a line is encountered that does not contain a colon
you have extracted all relevant details from the file up to your self-imposed "magic counter" 10

The first two logical break points should be baked into the loop's breaking syntax.  The third is probably something that you don't want to get into the habit of.  Another developer may look at the code (without seeing a sample input file) and think: "Why is this operation limited to 10? Why not 20?  Why not 5?"  It is best to avoid magic numbers, or if you need to have them, write a comment explaining why it is implemented.

That battery of if conditions is considerably less wise.  Think about it.  If the first if is satisfied -- why would you want to bother executing the other four checks?  They should never be satisfied if the first one is.  While I am going to suggest a different technique in my snippet to follow, your snippet at the very least would be improved by using subsequent elseif conditions.

Because I'm rather familiar with regex, I find using regex with a lookup array to be a very convenient technique to extract your targeted values from the remote file.  Not only does regex afford a more compact script, it maintains the flexibility of your original script by allowing the targeted lines to exist in any order.
A code suggestion:
class Pilot
{
    public $name;
    public $gliderType;
    public $competitionId;
    public $gpsDatuml;
    public $competitionClass;
    public $startPoint;  // I don't know where/how this gets populated
    public $endPoint;  // I don't know where/how this gets populated

    private $keywords = [
        'PILOT' => 'name',
        'GLIDERTYPE' => 'gliderType',
        'COMPETITIONID' => 'competitionId',
        'GPSDATUM' => 'gpsDatuml',
        'CLASS' => 'competitionClass',
    ];

    public function __construct(string $url)
    {
        $this->populatePropertiesFromUrl($url);
    }

    public function populatePropertiesFromUrl(string $url): void
    {
        $pattern = '~(' . implode('|', array_keys($this->keywords)) . '): (.*)~';

        $file = new SplFileObject($url);
        while (!$file->eof()
            && ($line = $file->fgets())
            && strpos($line, ':') !== false
        ) {
            if (preg_match($pattern, $line, $match)) {
                $this->{$this->keywords[$match[1]]} = $match[2];
            }
        }
    }
}
$pilot = new Pilot('https://xcportal.pl/sites/default/files/tracks/2020-06-09/069daro396091568.igc');
var_export(get_object_vars($pilot));

Output (should be):
array (
  'name' => 'DARIUSZ KISZKO',
  'gliderType' => 'ADVANCE IOTA 2',
  'competitionId' => '0000',
  'gpsDatuml' => 'WGS-84',
  'competitionClass' => 'Paraglider (Standard)',
  'startPoint' => NULL,
  'endPoint' => NULL,
)

*Disclaimer: I am making some assumptions about the text in the remote file.  I don't actually know how the text may vary.  I don't know if my suggested code will hold up against other files.  You may wish to adjust my loop breaking algorithm.


Python program for converting scientific notation to fixed point

from re import compile

exp_regex = compile(r"(\d+(\.\d+)?)[Ee](\+|-)(\d+)")

Python style guide recommends that global constants be in ALL_CAPS. And what about numbers like "1e99"? They won't match this regex.

def to_fixed_point(match):
    """Return the fixed point form of the matched number.

    Parameters:
        match is a MatchObject that matches exp_regex or similar.

    If you wish to make match using your own regex, keep the following in mind:
        group 1 should be the coefficient
        group 3 should be the sign
        group 4 should be the exponent

    """

I'd suggest breaking the groups out of the match into local variables

coefficient, decimals, sign, exponent = match.groups()

And then use those names instead of match.group(1). That way your code will be easier to follow.

    sign = -1 if match.group(3) == "-" else 1
    coefficient = float(match.group(1))
    exponent = sign * float(match.group(4))
    return "%.16f" % (coefficient * 10**exponent)

Here's the thing. Python already support scientific notation, so you should just ask python to do conversion for you:

 value = float(match.group(0))

Less bugs, more efficient, better all around.

def main():
    """Read lines from stdin and print them with scientific notation removed.

    """
    try:
        while True:
            line = raw_input('')
            print exp_regex.sub(to_fixed_point, line)
    except EOFError:
        pass

I'd suggest using for line in sys.stdin:. It'll automatically get you the lines, stop when the file ends. That'll make this piece of code simpler.

if __name__ == "__main__":
    main()


As JohnMark13 stated in the comments above, if the exceptions you want to catch share a common supertype (possibly besides the basic Exception class), then you could catch the supertype instead of all the subtypes. If you have created the SomeException and AnotherException classes yourself, then I strongly suggest that you make them extend a common custom exception type.

Also, I think that since you rethrow the exceptions (or at least most of them), then catching the general Exception is OK. Or, you could first catch all RuntimeExceptions, rethrow them directly, and then check the rest and possibly throw your WrappingException. Consider this:

public void myMethod() {
    try {
        // do something
    }
    catch (RuntimeException e) {
        // We don't need to wrap these, so we just throw the same exception again
        throw e;
    }
    catch (YourCommonSuperException e) {
        throw new WrappingException("issue when doing something " + e.getMessage(), e);
    }
    catch (Exception e) {
        // All other excpetions, such as `IOException` and stuff will be caught and wrapped and throwed here.
        throw new WrappingException("issue when doing something " + e.getMessage(), e);
    }
    // No need for any other Exceptions
}

Perhaps you get some extra cyclomatic complexity from the // do something part. If so, then you could split that part into multiple methods and possibly declaring to throw the exception from the method if needed so that it will get caught in this myMethod() (or catch within the method and throw some kind of YourCommonSuperException.

Depending on the specific // do something part, you might want to overlook which kind of exceptions that are thrown there. If you throw them yourself, it might be possible to change to IllegalArgumentException, IllegalStateException (which both extend RuntimeException) or some exception that extends YourCommonSuperException.


Log the diff of a Apache httpd config file and reload the service with Python and systemd

As a whole your approach looks good, except for a couple of issues I'd suggest to fix:

__init__ method
Avoid repetitive indexing of nested structures like self.config['httpd-conf'].Instead use assigned instance variable with f-string formatting:

def __init__(self, config_file):
    self.config_file = config_file
    self.config = self.load_config()
    self.httpd_conf = self.config['httpd-conf']
    self.backup_file = f'{self.httpd_conf}.bak'
    self.syntax_check_cmd = self.config['syntax-check-cmd'].split()
    self.reload_cmd = self.config['reload-cmd'].split()

find_diff method
No need to convert a generator returned by difflib.unified_diff function into list with diffs = list(...) - the subsequent ''.join(diffs) itself will take care of consuming generator.
call_httpd_commands method
This method is redundant as its main effect is reloading httpd server, but you already have the appropriate method for that purpose - reload_httpd. Thus call_httpd_commands method's statements are just moved there and the old method is eliminated:

def reload_httpd(self):
    try:
        subprocess.run(self.syntax_check_cmd, check=True)
        subprocess.run(self.reload_cmd, check=True)
    except subprocess.CalledProcessError as e:
        logging.exception("Reloading failed: %s", e)


Adding fruits to a basket, allowing selection from ID and name

Creating a mapping from input to output can be very useful here. A dictionary is the ideal data structure for this

VALID_INPUTS = {
    '1': 'Apple',
    'apple': 'Apple',
    '2': 'Orange',
    'orange': 'Orange',
    '3': 'Kiwi',
    'kiwi': 'Kiwi',
}
EXIT_INPUTS = ['4', 'exit']

Then you can loop over this mapping and append the matching inputs

if my_fruits in EXIT_INPUTS:
    break
for valid_input, fruit in VALID_INPUTS.items():
    if valid_input in my_fruits:
         fruits_ls.append(fruit)


There does not seem to be a great way of solving this.

The best I can propose is to capture the style that you will re-set to into a function and use that function both during initialization and mouseout, this makes the code DRY'er, but not necessarily nicer:

this.drawPerson = function () {

  function style( svg ){
    return svg.style("fill", "steelblue")
              .attr("transform", "translate(100,100)scale(0.1)");
  }

   style( self.svg.append("path")
        .attr("d", personPath)
        .attr("class", "member") )
        .on("mouseover", function(){
            d3.select(this).transition()
                .style("fill", "red")
                .attr("transform", "translate(100,100)scale(0.2)")
        })
        .on("mouseout", function() {
            style( d3.select(this).transition() )
        });
}


You haven't implemented the observer pattern as your subject, Observable, doesn't contain a list of observers.

Whilst this may seem like some small petty point it is the core problem that the pattern hopes to solve.
You have failed to make the subject relay to its observers. As you have moved the code, run, that should be in the observer into the subject.

This makes the observer interface neigh on useless, because if you want to change this functionality then you're screwed.

An example of the observer pattern is in Python's logging library.
In this you have events like a logger.info(message).
The logger, the subject, goes on to call the underlying handlers, observers, with the event.
This causes the handler to handle the event how it's been designed to.

It's common to have a StreamHandler and sometimes a FileHandler.
The former that just prints the message, and the latter that writes the message to a file.


Simple JavaScript (sub) class [properties, getters, methods]

These are the general rules I follow:

If using actual private variables in my class, create get/set properties for those I want accessible to the outside world:

function Point(x, y) {
    var _x = x || 0,
        _y = y || 0,
        _foo = "bar";

    Object.defineProperty(this, "x", {
        enumerable: true,
        get: function() {
            return _x;
        },
        set: function(value) {
            _x = value;
        }
    });

    Object.defineProperty(this, "y", {
        enumerable: true,
        get: function() {
            return _y;
        },
        set: function(value) {
            _y = value;
        }
    });
}

var p = new Point(2, 10);
p.x; // is 2
p.y; // is 10;
p.foo; // is undefined
p._foo; // is undefined

If private variables aren't all that beneficial, or the property is meant to be public, I'll just declare that as part of the prototype:

function Point(x, y) {
    this.x = x || 0;
    this.y = y || 0;
}

Point.prototype = {
    x: 0,
    y: 0,

    constructor: Point
};

Or if I want something to be read only, I'll use a combo of private variables and public getters (Example: Viewport on GitHub):

function Foo(bar) {
    var _bar = bar || "baz";

    Object.defineProperty("bar", {
        enumerable: true,
        get: function() { return _bar; }
    });
}

var foo = new Foo("foo");
foo.bar = "abc";
alert(foo.bar); // alerts "foo"

I tend to gravitate towards making everything public, and part of the prototype. As a personal convention properties and methods prefixed with an underscore are not meant to be called publically. Some people force encapsulation by using private variables, but this always feels like I'm trying to fit a square peg into a round hole. Unless you jump through hoops, everything in JavaScript is public. Embrace it. It makes unit testing your JavaScript code easier as well.

As an added benefit, most browsers have optimized the Constructor Function + Prototype code by generated classes behind the scenes for your JavaScript "classes", making property access in JavaScript almost as efficient as native code. Browsers haven't done much to optimize Constructor Functions that use private variables --- which is not to say that kind of code won't ever be optimized. It just isn't optimized very much right now.

Edit #1:

From OP's comment below:

  The point I've got at is that adding a property to each object might result in "larger" objects. If the property is defined in the object's prototype (same for all) it is only defined once.

This is not necessarily the case. Consider this code:

Using Object.defineProperty

function Point(x, y) {
    this._x = x;
    this._y = y;
}

Object.defineProperty(Point.prototype, "x", {
    get: function() {
        return this._x;
    },
    set: function(value) {
        this._x = value;
    }
});

Object.defineProperty(Point.prototype, "y", {
    get: function() {
        return this._y;
    },
    set: function(value) {
        this._y = value;
    }
});

var p = new Point(3, 0);

There is absolutely no difference between p.x = 5; and p._x = 5;. The x and y properties created using Object.defineProperty are superfluous, and only serve to add weight to your JavaScript code. There is no logic behind the getting and setting of those values.

On the contrary, consider a case where you do want some special logic around setting a value. In the code below, the element property is a reference to a DOM node. When setting the DOM node we also want to set properties for the document and window to which the DOM node belongs:

function Foo(element) {
    this.element = element;
}

Foo.prototype._element = null;
Foo.prototype.document = null;
Foo.prototype.window = null;

Object.defineProperty(Foo.prototype, "element", {
    get: function() {
        return this._element;
    },
    set: function(value) {
        this._element = value;
        this.document = value.ownerDocument;
        this.window = this.document.defaultView;
    }
};

Now we perform special logic in the set function for element. Defining the element property via Object.defineProperty is now beneficial.

You might find Inheritance and the prototype chain a worthwhile read, as well as Introduction to Object-Oriented JavaScript.

Edit #2:

Defining a property using Object.defineProperty is useful for creating delegate properties. I'm going to build on the Foo class from my previous edit.

The element belongs to a document and a window. In the previous example, there is nothing preventing you from running this code:

var foo = new Foo(document.body);
foo.document = someOtherDocumentObjectFromAnIFRAME;

This breaks the relationship between element and document because we assume foo.document is the document object that contains foo.element. Instead, we want to create delegate properties for document and window so we can maintain that relationship:

function Foo(element) {
    this.element = element;
}

Foo.prototype.element = null;

Object.defineProperty(Foo.prototype, "document", {
    get: function() {
        return this.element.ownerDocument;
    }
});

Object.defineProperty(Foo.prototype, "window", {
    get: function() {
        return this.element.ownerDocument.defaultView;
    }
});

Notice in this variation that the element property is now defined as part of the prototype since it has no special logic around getting or setting its value.

Now the document and window properties are read-only, maintaining the relationship that document is the Document object that contains element, and window is the Window object that contains both document and element.


Return product ID, if it is specified in a form

It looks like your code would benefit from a few well-chosen utility methods. It also looks a bit 'stringly typed': things would be much easier if you could store that product ID in an integer field or property in the first place. But it's difficult to tell whether that is possible without more context.

A reusable method that can fetch a specific value from a filter string would have the biggest impact. A method that makes it easier to fetch specific fields from a form might also be useful. And don't forget about the ?. operator. With those, your code can be rewritten as following:

public int? GetProductIdFromFormIfAny(JObject form)
{
    // Returns null if no matching field is found:
    var productsField = GetFieldForTable(form, "Products");

    // Returns null if the given filter is null, or if it does not contain the specified key.
    // Note that the 'magic' index 1 is replaced by a more descriptive key name:
    var productIDValue = GetFilterValue(productsField?.DataLookupFilter, "Product_ID");

    // Returns null if the given string is null or not a valid integer:
    return int.TryParse(productIDValue, out var productID) ? productID : null;
}

I can't tell whether this is exactly what you need - maybe you'll want an exception to be thrown if a filter is malformed, for example - but it should give you some ideas.


pyclbr

The standard library includes the pyclbr module, which provides functions for building a module browser.  pyclbr.readmodule_ex() returns a tree of nested dicts with the functions (defstatements) and classes (class statements) in a module.  So you just need to check the top level dict for items of class pyclbr.Function.

Note that readmodule_ex takes the name of the module (a str), not the actual module.

Just tested this, and it prints out imported functions and dunder functions as well, so those need to be filtered out.

import pyclbr

module = 'tutils'

for k,v in pyclbr.readmodule_ex(module).items():
    if (    isinstance(v, pyclbr.Function)
        and v.module==module
        and not v.name.startswith('__')):
        print(f"{v.name} -- {v.file} at {v.lineno}")


Hangman implementation for teaching a Python course

I could come up with a laundry list of improvements.  However, I would like to focus on just one issue, which makes your code an unforgivably bad example for your students: you are misusing functions as goto labels.

Note that game() can call play_again(), which in turn may call game().  This mutual recursion is inappropriate.  If you play many games, then hit CtrlC, you will see that the deepening stack is keeping track of all the previous calls, uselessly preparing for resuming execution after a return.

If you want to do something repeatedly in Python, use a loop.  A reasonable outline would look like this:

def play_again():
    """
    Ask the player whether to play again.
    """
    return 'n' != input("\nPlay again? Y/n ").lower()

def game():
    """
    Play a single game of Hangman.  Return True if the player wins,
    or False if the player loses.
    """
    secret_word = get_secret_word()
    good_guesses = []
    bad_guesses = []

    while True:
        board(bad_guesses, good_guesses, secret_word)
        guess = get_guess(bad_guesses, good_guesses, secret_word)
        if guess in secret_word:
            good_guesses.append(guess)
            if all(letter in good_guesses for letter in secret_word):
                print("\nYou win!\n")
                print("The secret word was {}.".format(secret_word.upper()))
                return True
        else:
            bad_guesses.append(guess)
            if len(bad_guesses) == 8:
                clear()
                print("\n **  ENGHH!  ** ")
                print("\nStrike ! You lost!")
                print("\nThe secret word was {}".format(secret_word.upper()))
                return False

def main():
    """
    Play games of Hangman until the user decides to quit.
    """
    while True:
        game()
        if not play_again():
            print("\n\n\n\nCatch ya later!\n\n\n\n")
            break
        clear()

Additional remarks:

Flag variables, like game_done and found, are almost always a bad idea.  Here, game_done can be eliminated by using proper looping technique, and found can be determined using the all() function.
if guess not in secret_word is redundant.  You can just say else.

Oh, and one more thing, since you should be setting a good example for your students: write a docstring for every function.


To-do list with counting of checked items

Adding to the DOM
There is no one right or wrong way to add to the DOM, each has its pros and cons.
Some options

Markup direct to the page via element.innerHTML (as you have done).
Using the document API to create a node tree, assign properties and then add to the DOM using any of the various node insert functions like node.appendChild.
Cloning the content of a template element that defines the nodes you want to add. Then use the document API to make the needed change and append to the page

So which to use?
Its a rather subjective question and it would be best that you try them all.

was it right to use innerHTML to add li items?

Yes and no.
The method of adding was not wrong (element.innerHTML), but the design of the function and overall approch to procedural generated content is wrong.
You are re-creating the whole displayed todo list whenever you add to it. That's like building a wall one brick at a time, but before you add the next brick you smash down the wall and rebuild it to the point where you add the next brick.
You need only add the new todo item to the end (or top) of the list of items. The rest of them can stay where you put them before.
Event listeners

adding event listener to all checkboxes in my case takes 4 line (in end drawTodoList). How can I short this?

You are referring to the lines...

checkboxes = document.querySelectorAll('input[type=checkbox]')
checkboxArray = Array.from(checkboxes)
checkboxArray.forEach(function(checkbox) {
   checkbox.addEventListener('change', confirmCheck)
})

...which could be shortened to
document.geteElementById("#"+toDo.id).addEventListener('change', confirmCheck );

But the question can not be  directly answered as the function drawTodoList is flawed, as I described in Adding to the DOM.
The click function can be added to the un-ordered list element once, at the start of the app, thus one event covers all todo items.
The checkbox that is clicked on can be found in event.target. Adding a property to the checkbox that holds the todo item id lets you apply the changes to the todolist via the todo id.
Information, data, and the display

how can I improve my function countItem()?

The count is a behavior of the information not the display, get it by stepping over the items in the todo list.
The rewrite.
I started from your HTML and CSS.
It is a bit over kill but I got lost in the writing of it. The code contains how I have implemented the 3 questions you ask. Adding to the DOM, creating event listener for new items, and counting the number of unchecked items.

const todoDataJSON = `[{ "id" : 1, "checked" : false, "text" : "Click Something todo" },{ "id" : 2, "checked" : false, "text" : "Check Click Something todo as done" }]`;

// the todo information and behaviours
const todoList = (() => {
    var UId = 1;                // NOTE must start above 0 to be truthy true
    const items = [];
    const indexed = new Map();  // For quick lookups by id
    const vetRecord = record => true; // This stub Make sure incoming data is valid and safe
    const vetText = text => typeof text === "string" && text !== "";
    const create = (text, checked = false, id = UId++) => ({id, text, checked});
    const reset = () => (items.length = 0, indexed.clear(), UId = 1);

    const toDoList = Object.freeze({
        get length() { return items.length },
        get uncheckedCount() { return items.reduce((uc, record) => uc += record.checked ? 0 : 1, 0) },
        set data(jsonText) {
            var maxId = UId;
            try {
                const data = JSON.parse(jsonText);
                reset();
                data.forEach(item => {
                    if (!vetRecord(item)) { throw new Error(); }
                    maxId = Math.max(item.id, maxId);
                    const record = create(item.text, item.checked, Number(item.id));
                    items.push(record);
                    indexed.set(record.id, record);
                });
                UId = maxId + 1;
            } catch(e) { reset() } // make data safe again
        },
        get data() { return JSON.stringify(items) },
        each(callback) { for (const record of items) { callback({...record}) } },
        toggleCheck(id) {
            const record = indexed.get(id);
            if (record) { record.checked = !record.checked }
        },
        add(text) {
            if(vetText(text)) {
                const record = create(text);
                items.push(record);
                indexed.set(record.id, record);
                return {...record};  // returns a copy not the original
            }
        }
    });
    return toDoList;
})();

/* Display an UI */
;(()=>{
    const elements = {
        list : query('#todo-list'),
        count : query('#item-count'),
        uncheckedCount : query('#unchecked-count'),
        template : query('#todo-item'),
    };

    elements.list.addEventListener("click", listItemClick);
    query("#add-button").addEventListener("click", promptForNew);

    function query(query, el = document) { return el.querySelector(query) }
    const assign = (el, props) => Object.assign(el, props);
    const append = (node, ...items) => {
        items.forEach(el => node.appendChild(el));
        return node;
    }

    function listItemClick(event) {
        if(event.target.todoId) {
            todoList.toggleCheck(event.target.todoId)
            updatePage();
        }
    }
    function displayToDoItem(todo) {
        const listItem = document.importNode(elements.template.content, true);
        assign(query("li", listItem), {id : "todoItem" + todo.id });
        assign(query("input", listItem), {
            checked : todo.checked,
            name : "todo" + todo.id,
            todoId : todo.id,   // added but will not be vissible in markup
        });
        assign(query("label", listItem), {
            "for" : "todo" + todo.id,
            textContent : todo.text
        });
        append(elements.list, listItem);
    }
    function promptForNew() {
        const todo = todoList.add(prompt("What is it you want to do", ""));
        if (todo) {  displayToDoItem(todo) }
        updatePage();
    }
    function updatePage() {
        elements.count.textContent = todoList.length;
        elements.uncheckedCount.textContent = todoList.uncheckedCount;
    }

    // source data and give to todolist
    todoList.data = todoDataJSON;
    todoList.each(displayToDoItem); // display existing
    updatePage();

})();
.center {
  align-self: center;
}

.flow-right {
  display: flex;
  justify-content: space-around;
}
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 10px;
  display: flex;
  flex-direction: column;
  background-color: white;
  height: 100vh;
}

.title, .controls, .button {
  flex: none;
}

.button {
  padding: 10px 20px;
}
<template id="todo-item">

     <input type="checkbox" class="todo-checkbox">

</template>

Things to do

    All things done & to do: 0
    Things left to do: 0

  <button class="button center" id="add-button">I Have Something To Do</button>


Repository pattern best practices using EF 6

The Interface

The idea of a generic repository interface is that it should be applicable to all entity types. So GetUsers shouldn't be there, because it's only relevant for a particular type of entity. If you want members specific to an entity type, you should have a second interface which extends the generic one:

IUserRepository : IRepository<User>
{
    IEnumerable<User> GetUsers();
}

One of the debates you may well have seen is whether it's good practice to have IQueryable members, or to take Expression parameters.

The pro is that it's much more flexible. Rather than having to have, for example, FilterByStartDate(DateTime date), FilterByEndDate(DateTime date), FilterByUserGroup(int groupId), etc., I can just have FilterBy<T>(Predicate<T> condition). Likewise, by exposing IQueryable, you can call additional LINQ methods and it will all get translated into SQL, which can reduce the amount of work your database has to do, and the amount of data you have to transfer.

The con is that what you have is a leaky abstraction. It looks like I should be able to feed in any reasonable predicate, but in fact, many of them will throw exceptions at runtime because EF doesn't know how to translate them into SQL. So now the details of how exactly EF- which is supposed to be an abstraction over your database- can turn LINQ queries into SQL leak out of your repository, and every consumer of the repository has to worry about them.

On balance, my suggestion would be: at first, do NOT expose IQueryable or allow arbitrary Expressions to be passed in. Add specific methods for specific queries. If you ultimately find this isn't adequate, you can refactor by adding methods in.
Save is a confusing method. Does it mean insert or update? Generally with Entity Framework, you want an Add(TEntity entity) method and a Save() method. Add should be what inserts a record, and Save should commit any updates you've made to existing items. So, as a toy example, I could do:

var user = userRepository.GetById(userId);
DoThing(user);
user.ThingLastDoneTime = DateTime.Now;
userRepository.Save();

Note that I don't have to pass the user to Save, because it's actually just calling the DbContext's Save() method.

HostViewModel

This is where I start to get a bit more confused. Why is something called ViewModel being treated as an entity, or stored in a database?

Without knowing more it's hard to comment on what's going on here exactly, but EF is supposed to let you handle Entities- these are essentially domain objects. So a User is a good candidate for an entity. A Host might be, depending on what "host" actually means in this context. But a ViewModel? That seems like extreme mixing of concerns between your UI and your core domain.

Or, possibly what's going on is that your actual entity is a Host, and the repository is not only doing its usual repository business, but also in charge of mapping from an entity to a view model. This is also a problematic mixing of concerns. You may, for example, have a view model which does not have sufficient information to create a new entity from. So how would you handle the Add method for that type? Transformation between entities and view models is a UI concern and should be kept away from the repository pattern, which is a data access/persistence pattern.

HostRepository

As already mentioned, it's very weird that GetUsers should be returning a collection of HostViewModels.

The bulk of that method can be simplified with LINQ, too:

return db.Hosts.Select(user => new HostViewModel() { Id = user.Id,  FirstName = user.FirstName });

The Controller

I assume your comment about IoC containers is for us and not really in the code. If it's in the code, it shouldn't be!
hostRepository should also be private. Other classes don't need to get it, and shouldn't be allowed to set it except through the constructor.
You've shortened hostRepository to hostRepo in the constructor. Generally you shouldn't shorten variable names, especially if- as in this case- they're going to be exposed publically to consumers. To deal with class-level vs method level variables, all of the following are popular:

For public class members, use PascalCase (first letter capital) rather than camelCase
For private class fields and properties use _camelCase, with a leading underscore.
As an alternative to the previous, for private class fields and properties, use camelCase. Then inside methods, prefix them with this.


segment tree for adding a array with single index updates

I'd implement next_power_2 like this, using int.bit_length:

def next_power_2(n):
    "If n > 0, return smallest power of 2 greater than or equal to n."
    return 1 << (n - 1).bit_length()

This is more than twice as fast as than the version in the post, and it works for arbitrarily large integers.


Enum conversion to Enumeration class with small Business Logic inside

Shouldn't the 'IsValid' method be static? I suppose you use it like Rule.IsValid(calculatedCompensation, 0, Rule.CompensationIsZero.Id), (as general idea, obviously it can be simplified).

Anyway PERSONALLY I would not do this, because Rule is no more an Enum, you gave it logic, that usually Enum don't have. I would have keep the Enum as original and built on top of that a Class with the required logic. (Maybe called RuleValidator with a static method public static bool IsValid(Rule rule, decimal compensation, decimal demand) {...}.

If this does not concern you, than another way could be to write an extension method:

static class RuleExtensions
{
  public static bool Validate(this Rule rule, decimal compensation, decimal demand)
  {
    switch (rule)
    {
      case None: return true;
      case CompensationIsZero: return compensation == 0;
      case CompensationLessThanDemand : return compensation < demand;
      // ecc...
    }
  }
}


Partitioning array elements into two subsets

Unless it is a homework for sort algorithm study :

Manage ArrayList and load your list of number,
put all number<=x in a new ArrayList,
delete them from the original ArrayList,
finish with .addAll(..), to concatenate if needed.

Knowing that VM is optmized, it would be interesting to compare performance of this approach with your one.


This is going to be a short answer, but did you know Python has such a feature in-built?

text = "I'm a stringy!"
print(text[::-1])

Above would replace your reverse method and is the most Pythonic way to solve this.

This is called extended slicing and has been added since Python 2.3. Slicing is a very easy to use method when handling array-like data.

The following illustrates how slicing and extended slicing can be used, executed in the interactive Python IDE:

In [1]: text = "I'm a stringy!"

In [2]: print(text)
I'm a stringy!

In [3]: print(text[:-1])
I'm a stringy

In [4]: print(text[::-1])
!ygnirts a m'I

In [5]: print(text[:4:-1])

In [6]: print((text:4:-1] + text[:3:5])[::-1])
I stringy!

In [7]: print(text[::-1][::-1][::-1])
!ygnirts a m'I

As picture.


"Block a website" script with vanilla JavaScript

The main suggestion I have is to take the values from sitesToBlock and put them in the @match metadata key instead of detecting when to update the document content. There is an extensive guide about match patterns here. With this approach there should not be any need to wait for the DOM to be loaded and check if the URL contains elements in sitesToBlock, though maybe that “news_website_1” loads slower than the one I tested with and that won’t work.

Other review points:

default to using const instead of let when declaring variables unless re-assignment is mandatory. This helps avoid accidental re-assignment.
use for...of loops when possible- e.g. for iterating through sitesToBlock and there is no need for a counter variable (e.g. i) other than accessing the current element


Merging two arrays of objects with different keys/properties

When you merge two arrays, where the one array contains a key value, you can save a lot of time by indexing the keys. Consider an index on the array2 name column.

It is really easy to index the data using an Object with named properties:

var indexed = {};

_.each(array2, function(data) {
  indexed[data["name"]] = data;
});

Now, we have a fast way to find any data record in array2 for a given name.

Using that structure becomes easy again, by looping for each of the array1 values, and updating them based on the value that was indexed, if any. Loop for each record, search in the index, use the default if the index value was not found.

To make the code a bit more flexible, and because the "column" names change from id to new_id, it helps to have a structure containing this column mapping:

var mapCols = {
  key1: "key1",
  key2: "key2",
  key3: "key3",
  id: "new_id"
}

The mapCol indicates that key1 should become key1, and so on, but id should become new_id.

This allows us to then make the "simple" nested loops:

_.each(array1, function(person){
  var use = indexed[person["id"]] || defaultOptions;
  _.each(mapCols, function(key) {
    person[mapCols[key]] = use[key];
  });
});

You can see this running here in your forked code.

In theory, this will turn your code from an \$O(n \times m)\$ operation to become an \$O(n + m)\$ one, where \$n\$ and \$m\$ are the sizes of the two arrays.


Attach list of files and email using secure connection

In general, the code looks good.  I just have a few miscellaneous remarks.

Code organization

Function names should be named lower_case_with_underscores by PEP 8.
I would split the message composition and sending into separate functions.
It is good practice to avoid embedding passwords into your source code.  I suggest storing the account information in a YAML file, or at least as constants in a separate Python module.
The parameters are hard-coded, so the function is of limited utility.  The function could accept parameters with defaults:

def compose_email(from='sender@example.com',
                  to=['recipient_1@example.com','recipient_2@example.com'],
                  attachments=[])
    …

def send_email(msg, username, password)
    …

Mail content

The MIME type for .xlsx files is application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.
Concatenating file paths using os.path.join(lpath, item) would let you not have to worry about the path component separator.  Personally, I would choose to pass full paths to the function instead, to avoid assuming that they are all in some hard-coded directory:

def EMAIL_FILES(attachments):
    …
    for path in attachments:
        with open(path, 'rb') as f:
            part = MIMEBase('application', 'vnd.openxmlformats-officedocument.spreadsheetml.sheet')
            part.set_payload(f.read())
            part.add_header('Content-Disposition',
                'attachment; filename="%s"' % os.path.basename(path))
            Encoders.encode_base64(part)
            msg.attach(part)
    …

EMAIL_FILES([os.path.join('C:/Path/to/my/excel/files/', f) for f in
    ['excelfile_1.xlsx', 'excelfile_2.xlsx']
])

I'm puzzled by why you defined body as a list of strings, only to join them all into one long string.  If the body contains non-trivial content, consider writing it as a """longstring""".  Also, you may need to encode the MIMEText using Encoders.encode_quopri().


You should change your algorithm. First note that triangle numbers can be written as:
\$
T_n = \frac{n(n+1)}{2}
\$
then notice that \$n\$ and \$n+1\$ cannot share a common divisor. So you can find all the divisors of \$T_n\$ just by finding the divisors of \$n\$ and \$n+1\$ (and removing a factor 2) and multiplying them together. This alone should greatly improve your algorithm turning it (the part inside the main loop) from \$O(n^2)\$ to \$O(n)\$.

Then you could make a table of prime number to quickly find the factorization of \$n\$ and \$n+1\$. Once you know the prime factors of \$n\$ you can find the number of all divisors of \$n\$. See, for example, here: http://www.marksmath.com/math/problems/count-div.html

addendum

First advice is actually enough. Here is the code (I don't know C#, hope it compiles):

static int count_divisors(int n) {
  int count = 0;
  for (int k=1;k<=n;++k) {
    // this loop can be reduced further by noticing that
    // apart from n itself there is no divisor with k*2>n
    if (n % k == 0) count++;
  }
  return count;
}

static void Main(string[] args) {
  int last_d = 0; // cache the computation for previous n
  for (int n=0;;++n) {
    int triangular = n*(n+1)/2; // only used for debugging and clarity
    int d; // number of divisors of (n+1) (or (n+1)/2 if (n+1) is even)
    if (n%2==0)
      d = count_divisors(n+1);
    else
      d = count_divisors((n+1)/2); // n+1 is even
    // # of divisors of n * (n+1)/2 is the product of divisors
    // since two consecutive numbers do not share any divisor (apart from 1)
    int total = d*last_d;
    if (total>500) {
      Console.WriteLine("found: " + triangular);
      break;
    }
    last_d = d; // cache the computation
  }
}


Parsing huge xml file with lxml.etree.iterparse in python

The name fast_iter2 seems to lack much of a connection with the function is actually doing.

Rather then having your two sets be local variables, I suggest putting them as global constants.

Calling them elements and childElements is kinda generic. I suggest something more specific

Your loop is a bit awkward. Rather then collecting them in that iterative format, just grab everything when looking at the element tags. This makes the code filling up paper/authors more straightforward.

Rather then having an empty if block and using the else block, invert the logic.

I suggest moving the element clearing code into its own function. This helps make the function actual task clearer avoiding the question of how to clear.

The del context line is useless. Del doesn't destory the object, it merely removes the object from the current context. If this was the only context in which object was refereed to then its reference count would drop to zero. However, that's not the case here as the calling function will keep it alive anyways. Even if it did, the memory savings aren't worth worrying about since the whole script is about to end anyways.

My reworking of your code, no testing has been done on it:

    CATEGORIES = set(['article', 'inproceedings', 'proceedings', 'book', 'incollection', 'phdthesis', "mastersthesis", "www"])
    SKIP_CATEGORIES = set(['phdthesis','mastersthesis', 'www'])
    DATA_ITEMS = ["title", "booktitle", "year", "journal", "ee"]

    def clear_element(element):
        element.clear()
        while element.getprevious() is not None:
            del element.getparent()[0]

    def fast_iter2(context, cursor):
        # Available elements are:   article|inproceedings|proceedings|book|incollection|phdthesis|mastersthesis|www
        # Available tags are:       author|editor|title|booktitle|pages|year|address|journal|volume|number|month|url|ee|cdrom|cite|
        #                           publisher|note|crossref|isbn|series|school|chapter

        paperCounter = 0
        for event, element in context:
            if element.tag in CATEGORIES:
                authors = [author.text for author in element.findall("author")]
                paper = {
                    'element' : element.tag,
                    'mdate' : element.get("mdate"),
                    'dblpkey' : element.get('key')
                }
                for data_item in DATA_ITEMS:
                    data = element.find(data_item)
                    if data is not None:
                        paper[data_item] = data

                if paper['element'] not in SKIP_CATEGORIES:
                    populate_database(paper, authors, cursor)

                paperCounter += 1
                print paperCounter

                clear_element(element)

EDIT

How to avoid an explicit counter:

    CATEGORIES = set(['article', 'inproceedings', 'proceedings', 'book', 'incollection', 'phdthesis', "mastersthesis", "www"])
    SKIP_CATEGORIES = set(['phdthesis','mastersthesis', 'www'])
    DATA_ITEMS = ["title", "booktitle", "year", "journal", "ee"]

    def clear_element(element):
        element.clear()
        while element.getprevious() is not None:
            del element.getparent()[0]

    def extract_paper_elements(context):
        for event, element in context:
             if element.tag in CATEGORIES:
                   yield element
                   clear_element(element)

    def fast_iter2(context, cursor):
        for paperCounter, element in enumerate(extract_paper_elements(context)):
                authors = [author.text for author in element.findall("author")]
                paper = {
                    'element' : element.tag,
                    'mdate' : element.get("mdate"),
                    'dblpkey' : element.get('key')
                }
                for data_item in DATA_ITEMS:
                    data = element.find(data_item)
                    if data is not None:
                        paper[data_item] = data

                if paper['element'] not in SKIP_CATEGORIES:
                    populate_database(paper, authors, cursor)

                print paperCounter


Extract multiple attributes values in XML tags

There are many issues with your posted example that prevent it from being sanely parsed by XML, including lack of closing tags and lack of a starting xml tag. You say that the content is generated: if you generated it, you should try to fix this. Anyway.

import re

pat = re.compile('name="(.*?)".*'
                 'line-rate="([0-9.]*)"')

with open('test.xml') as f:
    for line in f:
        match = pat.search(line)
        if match:
            print(match.expand(r'\1 \2'))

This makes many assumptions:

The attributes actually are in the same order every time (in your example, they aren't, despite you saying that they should be)
The file is guaranteed to have at most one line-rate/name pair per line
Those two attributes are always on the same line as each other

If all of those conditions are satisfied, the above works.

Actual XML

If (as it seems you suggested in a now-rolled-back edit) your input can actually be valid XML, then a method that will perform more validation is

from xml.sax import parse, ContentHandler

class Handler(ContentHandler):
    def startElement(self, name, attrs):
        name, rate = attrs.get('name'), attrs.get('line-rate')
        if name and rate:
            print(f'{name} {rate}')

parse('test.xml', Handler())

I do not know if it is faster, but it's probably a better idea to do this and halt-and-catch-fire if the XML is malformed, which SAX will do for you.


The floating point scale factor could control both magnitude and direction without the need for your $direction parameter.  If you want to double the size the $scale = 2.0, if you want to halve it the $scale = 0.5

and this is just personal preference if you were to stick with your $direction parameter in your scaling functions.  Create a static class constant so you don't have to hardcode 'up' and 'down' all over the place.

<?
    $circle = new Circle(5);
    $circle->scale(Circle::UP, 2);

    Class Cirlce {
        const UP = 'up';
        const DOWN = 'down';
    .
    .
    .
    }


Unless you confirm the speed is a problem in the code profiler, there's no need to optimize it.

And if you want to make js code run fast, just avoid using one of the most expensive operations: invocation of a callback/function (you had 6 of them), maximize the workload inside the engine by using existing native functions and minimizing amount of time spent in interpreted code.

In this case switching to string manipulation makes the code 2.5 times faster as measured here on 10k repetitions.

let getNums = length => {
    var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var result = letters.substr(0, length).split('');
    for (var i = 1, numberedCount = Math.floor((length - 1)/26); i <= numberedCount; i++) {
        length -= letters.length;
        result.push.apply(result,
            letters.substr(0, length).replace(/./g, '$&' + i + ' ').trim().split(' '));
    }
    return result;
}


Recursively insert a node in an ordered Linked List

The assumptions your code makes are... odd. Why do you have to use recursion. In reality, your code will overflow the stack for long lists, unless you ramp up the compiler optimization, and your compiler performs tail-call optimization on the recursion.

So, yes, you can do a recursive insert, and, assuming this is some sort of educational process, your implementation appears to be reasonable, with some caveats:

I don't like the "create if the list does not exist" logic in the first block. Using the head as an "output-parameter" is ugly. head should not be modified. The new head is returned anyway. The calling code should be able to tell if the head is null before it calls the insert method, and instead call a 'create' method of some sort. Additionally, that check is only ever needed once for the entire list, so it is a waste of time to check it for each level of recursion.
you cannot insert at the beginning of the list. If you are intending to insert the values {4, 3, 2, 1} and your first node starts as 4 at the 'head', well, you can't insert before that..... Your code requires that the first node is always the minimum value in order for the sort-order to be maintained.

Bottom line, is your code only works for limited use-cases.

I would much rather your code had a 'sentinel' head node, which was never null, and then your actual data follows from that head position. That would reduce your code, and make the insertion process simpler, and also fix both issues above. Note that the 'head' node would be kept as part of the class fields somewhere, not passed in as an argument to the (recursive) method... in fact, the method should not be recursive


How to avoid echoing JavaScript from PHP?

One way is to keep the constants in a database table and have a script that automatically generates both JS and PHP code by looking through it.  The advantages of this are that you can store other bits of information if you want, and the code is all generated beforehand so there is no extra overhead with each page load.  The only disadvantage is that you have to run the script every time you change the constants.  The simplest table structure you could use would store just the name and the value, but as an example mine looks like this:

mysql> explain codes;
+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| type        | char(3)          | YES  |     | NULL    |                |
| code        | char(3)          | YES  |     | NULL    |                |
| parent      | char(3)          | YES  |     | NULL    |                |
| long_code   | char(64)         | YES  |     | NULL    |                |
| description | char(64)         | YES  |     | NULL    |                |
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
+-------------+------------------+------+-----+---------+----------------+

The "type" field is a reference to another table, which organises the constants according to which part of the program they're relevant to.

mysql> explain codetypes;
+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| code        | char(3)          | YES  | UNI | NULL    |                |
| long_code   | char(64)         | YES  | UNI | NULL    |                |
| description | char(64)         | YES  |     | NULL    |                |
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
+-------------+------------------+------+-----+---------+----------------+

Here is a sample from the database behind a chess server:

mysql> select * from codetypes where code='GST';
+------+------------+-------------+----+
| code | long_code  | description | id |
+------+------------+-------------+----+
| GST  | GAME_STATE | Game state  |  1 |
+------+------------+-------------+----+
1 row in set (0.00 sec)

mysql> select * from codes where type='GST';
+------+------+--------+-------------+-------------+----+
| type | code | parent | long_code   | description | id |
+------+------+--------+-------------+-------------+----+
| GST  | PRE  | NULL   | PREGAME     | Pregame     |  1 |
| GST  | IPR  | NULL   | IN_PROGRESS | In progress |  2 |
| GST  | FIN  | NULL   | FINISHED    | Finished    |  3 |
| GST  | CAN  | NULL   | CANCELED    | Cancelled   |  4 |
+------+------+--------+-------------+-------------+----+
4 rows in set (0.00 sec)

Which generates the following PHP code:

define("GAME_STATE", "GST");

define("GAME_STATE_IN_PROGRESS", "IPR");
define("GAME_STATE_FINISHED", "FIN");
define("GAME_STATE_CANCELED", "CAN");
define("GAME_STATE_PREGAME", "PRE");

Using the extra information you can generate other useful bits of code, for example Javascript objects for looping through the constants of each type and accessing the descriptions as well as the values:

var DbEnums={};

DbEnums["GST"]={};

DbEnums["GST"]["IPR"]={Type: "GST", Code: "IPR", Parent: null, Description: "In progress"};
DbEnums["GST"]["FIN"]={Type: "GST", Code: "FIN", Parent: null, Description: "Finished"};
DbEnums["GST"]["CAN"]={Type: "GST", Code: "CAN", Parent: null, Description: "Cancelled"};
DbEnums["GST"]["PRE"]={Type: "GST", Code: "PRE", Parent: null, Description: "Pregame"};


Synchronous logging of asynchronous retrieved folder info

I decided to go with the solution below.
By using Tasks I don't need to put all the logic right there, I can just pass the Task anywhere and map/chain over it to add extra functionality. I can even just fork it after I have all the data and get the List inside which I can also map and more.
Also with the function "getsubfolders" from the questions I can use to get the array of the paths and just wrap it in a List as I am doing in readDir.
So what I mean is that, although the structure is different, this way is way more flexible and readable (I can still derive all the above objects from the result).
I am noew trying to convert the getsubfolders to async and functional as well, for the sake of learning.
/* eslint-disable import/extensions */
/*
taken from
https://mostly-adequate.gitbooks.io/mostly-adequate-guide/content/ch08.html#asynchronous-tasks
 */
import fs from 'fs'
import {Task, traverse,concat,compose,chain,map, prop, List, } from './shared/functional.js';

// readDir :: String -> Task Error (List String)
const readDir = path => new Task((reject, result) => {
  fs.readdir(path, (err, data) => (err ? reject(err) : result(new List(data))));
});

// readDir :: String -> Task Error (Stat)
const readStat = filename => new Task((reject, result) => {
  fs.stat(filename, (err, data) => (err ? reject(err) : result(data)));
});

const dirList = dir =>
chain(
  traverse(Task.of, compose(readStat, concat(dir))),
  readDir(dir),
);

dirList('./shared/').fork(console.error, map(compose(console.log, prop('mtimeMs'))));


private static List<String> substrings(String s) {

Concerning speed, this is the first bug. There are too many substrings O(n**2) and generating all of them is wasting O(n**3) time (as the copying has linear complexity). You're using it in a loop, so it may be O(n**4), really slow.
It'd be slightly better to generate a Set rather than a List. Given the input aabaacaba, there are quite some substrings repeated. I see, you're using a Set later. You could avoid any intermediate collection when you implemented
private static void addSubstringsTo(Collection<String> result, String s)`

instead.
But this is a minor optimization. A much bigger one would be to observe, that all substrings are already there, except for those ending on the current position.
But even this is by far not the fastest way.

 if (len == 0) {

This seems to be superfluous. Sure, you can only append, but the reason is that there are no usable substrings. So you can save this test and proceed in the usual way.
} // end for

Please don't. Keep your method short enough so that such garbage is unnecessary. While IIRC the style guide requires indentantion of 2 spaces, I use 4, so that the code structure is easier to see.

int length = text.length();
...
int len  = 0;

That's crazy. len is a pretty common abbreviation for length, many dislike it, I find it acceptable. But using both in the same method is perverted.

int end = (sum > length) ? length : sum;

You surely mean
int end = Math.min(sum, length);

It's the same, but it doesn't make me think.

} // end if
    else {
      if (lookAhead.length() == 1) {

You're repeating yourself in the code below this. Something like
if (lookAhead.length() == 1 || set.contains(lookAhead)) {
    ... append, update the set, break
}

should work.

You could get some speed by not generating the strings. While the HashSet lookup is very fast, you're putting therein much more strings than you can ever use... so you're wasting time. Something like
 text.substring(0, i).lastIndexOf(lookAhead)

should be faster. But still not perfect.

Concerning the cost optimization, you're making at least two mistakes.
It's possible that appending a substring costs more than appending a character twice, so you probably should look at A * lookAhead.length() compared to C (which is called B in the linked challenge).
You're using a greedy strategy. Appending some string may be advantageous at a moment, but it may prevent appending a much longer string later. I guess, you should always explore every possibility, except when one is clearly worse than some other. By "clearly worse" I actually mean "the same string at higher cost" as a shorter string may be better sometimes.

Concerning speed, I guess, not generating any strings is the way to go. As the text is given, all you need is to remember the substring indexes. Calling substring is wasting time, create a trivial immutable class containing start and end instead.
An exactly optimizing algorithm would probably keep track of the cheapest way of creating text.substring(0, i) for every value of i. In each step, it'd try to build a longer substring and store or update its cost. It's not trivial and I haven't solved it yet, so I can't give more details. But look at dynamic programming, which is the general way of solving such problems.
Slow code
Note that one big problem with your algorithm is that it's too long. You wrote "I really didn't know what I was doing" and I trust you on it. This happens to everyone, when the code gets too long and/or disorganized. Refactoring (e.g., extracting methods or classes) is the way to go (thought sometimes rewriting the good parts from scratch is better).
Without much thinking I wrote this O(3) code. It solves 10 test cases out of 21, when it fails, it's due to timeout.
private static int solve(int a, int b, String text) {
    // Cost as a function of length.
    final int costs[] = new int[text.length() + 1];
    Arrays.fill(costs, Integer.MAX_VALUE);
    costs[0] = 0; // Empty string is free.

    // Minimum length to be copied (as copying less is not worth it).
    final int minLen = Math.min(1, b / a);
    for (int i=1; i<costs.length; ++i) {
        costs[i] = Math.min(costs[i], costs[i-1] + a);
        final String start = text.substring(0, i);

        // We copy no more than we have and no more than we need.
        for (int len=minLen; len<=i && i+len<costs.length; ++len) {
            boolean found = start.contains(text.substring(i, i+len));
            if (!found) break;
            costs[i+len] = Math.min(costs[i+len], costs[i] + b);
        }
    }
    return costs[text.length()];
}


This is a a very, um, thorough way of doing things. Not necessarily a bad thing, and it does help learn some CoffeeScript, so yay for that, but still it's a little much. I'll roll with it though.

Before talking about the code proper, though, I have to point out that prompt, show and exit program aren't part of CoffeeScript or JavaScript. That would appear to be something wholly custom to that smooth-coffeescript site you mention. In other words, those only work on that site, so don't think it's something you can use anywhere else. In the code below I'll use alert instead of show (since works in browsers), and I'll get to the exit program thing in a second.

prompt is another matter, since that does exist in browsers, but it works differently. Instead of taking a callback function, it simply returns a string (or null). So this is actually pretty bad of the smooth-coffeescript author(s), since it doesn't merely add custom functionality, but takes an existing, well-documented feature of browser-based JavaScript and makes it behave differently, confusing everyone.

So just know that the stuff you write on that site, while it might teach you CoffeeScript, it can also mislead you.

Now, some notes on the code:

Put the strings and other variables inside the prompt function; don't pollute the global namespace. The only one you have to keep outside is the question itself, as that's used when calling prompt to begin with.
userEntry = answer does nothing useful. It just gives you two variables both containing what the user entered. Nothing gained.
This part has some weirdness:

if userEntry is correctAnswer
  show correctAnswerMsg
  exit program

As mentioned exit program is not standard. In Node.js you might use process.exit to explicitly quit/stop the entire script and runtime, but that the nearest thing that's actually common to see. However, you don't need to exit the script/program. Since you're inside a function (the callback for prompt), you can just say return when you want to stop. Since there's no other code after the call to prompt, the script will exit on its own.

However, you don't even need to return. You've written an if.. else if.. else structure, so if the user's answer is correct, none of the other else/else if branches will be run. So there's nothing to stop or return from.
Checking for both length and the number itself is a hassle. Both because if the number's wrong, who cares if the length was right? Secondly, it requires you to specify both length and value of the correct answer, meaning you have two things to change if you want to make the question what is 3 + 11? instead. And you'd have to change the singleDigitMsg text too - and the name of the singleDigitMsg variable itself - since neither of those make sense anymore.

I'd instead check "did the user enter only digits?" and "did they enter the correct number?". Checking "did the user enter something that's the same length as the string representation of the correct number?" is somehow both too precise and too vague to be useful.
For checking if the user's just-1-off from the correct answer, don't check if it's correct-1 or correct+1; check if the difference is 1.

Here's what I'd write (run the snippet, and open the developer console to see the output)

# a less confusing wrapper for the browser-native `prompt` function
promptWithCallback = (message, callback) ->
  response = prompt message
  callback response unless response is null

# the actual thing
promptWithCallback "What's 2 + 2?", (answer) ->
  correctAnswer = 4

  # complain if answer contains non-digit character
  if /\D/.test answer
    alert "Only digits, please"
    return # stop here

  # instead of casting to a Number, use parseInt with a radix/base argument
  # this avoids the string "08" being converted to NaN because JS thinks it's
  # an octal (base 8) number (due to the leading zero) that's invalid (due to
  # it containing an 8). Doesn't happen in most runtimes, but still
  number = parseInt answer, 10

  if number is correctAnswer
    alert "Yup, correct!"

  else if Math.abs(number - correctAnswer) is 1
    alert "Nope - but you were really close though. Try again"

  else
    alert "Nope. Try again"

If you want to try it in your browser (couldn't make it work with stack snippets due to a http/https conflict), go to coffeescript.org, click the "Try CoffeeScript" button at the top, paste in the code, and click "run".

You'll note that I didn't add variables for all the different strings. Frankly, I just didn't want to bother with that, since it's all pretty simple. It's not necessarily a bad thing to do (it puts all the text in one place, making it easier to change), but it's not a huge piece of code, so I just wrote it in place.


Solution to 90 degree rotation of an NxN matrix

There's nothing really wrong with your class, but you could use array functions and foreach instead of for.

Also, calling your class MatrixRotator is a bit weird. A class is used to combine and isolate several methods (= functions) and properties (= variables) into a handy package. A rotate() method would probably be part of a set of methods which can modify the matrix. And when that is the case it would make sense to store the matrix data in the matrix class. This would then require a set and get method.

This would result in something like this:

class Matrix
{
  private $data = [];

  public function __construct($data)
  // accepts an array with matrix data and stores it
  {
    $this->data = $data;
  }

  public function rotateClockwise()
  // rotate a matrix once clockwise
  {
    // check that the matrix contains data
    if (isset($this->data[0]) && is_array($this->data[0]))
    {
      // perform the actual rotation
      $rotated = [];
      foreach (array_keys($this->data[0]) as $columnKey)
      {
        $rotated[] = array_reverse(array_column($this->data,$columnKey));
      }
      $this->data = $rotated;
    }
    // return this class so this method can be chained
    return $this;
  }

  public function getData()
  // returns the stored matrix
  {
    return $this->data;
  }
}

It can then be used like this:

// creation of a matrix
$matrix = new Matrix([[1,2,3],[4,5,6],[7,8,9]]);

// rotation and output
echo '
';
print_r($matrix->rotateClockwise()->getData());
echo '
';

It is now easy to put other matrix manipulation methods into this class. For instance, by leaving out the array_reverse() from rotateClockwise() you will get a rotateAntiClockwise() method. So let's do that:

class Matrix
{
  private $data = [];

  public function __construct($data)
  {
    $this->data = $data;
    if (!$this->isValid()) trigger_error("Matrix data is invalid.");
  }

  public function isValid()
  {
    if (!is_array($this->data)) return FALSE;
    foreach ($this->data as $row)
    {
      if (!is_array($row)) return FALSE;
    }
    return TRUE;
  }

  public function reverseEachRow()
  {
    if ($this->isValid())
    {
      foreach ($this->data as $rowKey => $row)
      {
        $this->data[$rowKey] = array_reverse($row);
      }
    }
    return $this;
  }

  public function rotateAntiClockwise()
  {
    if ($this->isValid() && isset($this->data[0]))
    {
      $rotated = [];
      foreach (array_keys($this->data[0]) as $columnKey)
      {
        $rotated[] = array_column($this->data,$columnKey);
      }
      $this->data = $rotated;
    }
    return $this;
  }

  public function rotateClockwise()
  {
    return $this->rotateAntiClockwise()
                ->reverseEachRow();
  }

  public function getData()
  {
    return $this->isValid() ? $this->data : FALSE;
  }

}

$matrix = new Matrix([[1,2,3],[4,5,6],[7,8,9]]);

echo '
';
print_r($matrix->rotateClockwise()->getData());
echo '
';

I left out all comments, to keep the code short, and I also centralized the validity check. This goes beyond your question, but shows you why you wouldn't want to call your class MatrixRotator, it is too specific.


The design need to be simplified. From your explanation, it seems you only need 3 tables (Questions, Answers, and Feedback) the rest are not needed, since you can JOIN these tables.

  Comma separated values are affordable ?

For your design, no you don't need to, and it's not always a good idea to do it. There is some cases you can do it, and might be benefit you, but these are rare cases. Keep things simple and standard, don't join columns or rows into a single value, unless it's a requirement!

So, if your Feedback.Questions meant to store values of questions in comma separated value, I suggest you change that. just give each question a new feedback id, this way it'll be much more manageable.  And instead of storing the question string, just store the questionId (FK) instead. this way it'll be more appropriate and would process faster.

So I suggest you remodel it to :

#ListStatus
- Id [PK|IDENTITY]
- Description

#ListRate
- Id [PK|IDENTITY]
- Description

#FeedbackQuestions
- Id [PK|IDENTITY]
- Question
- CreatedAt
- UpdatedAt
- Deleted
- StatusId
- UserId

#FeedbackAnswers
- Id [PK|IDENTITY]
- QuestionId
- Answer
- CreatedAt
- UpdatedAt
- Deleted
- UserId

#Feedback
- Id [PK|IDENTITY]
- RateId
- QuestionId
- AnswerId
- CreatedAt
- Deleted
- UserId

The Listxxx tables would store a list of fixed descriptive values. For instance, ListRate would store the rate options such as Excellent, Very Good, Good, Fair, Poor ..etc. When a user rates an answer, the Id of ListRate would be inserted into Feedback table.

Also, since we defined them with a prefix List it would be standardized in the system design, for general use purpose on other tables, and best yet, easier to understand (so developers would know the purpose of these tables just from the table name).

I got confused between UserId & CustomerId, but I used userId so you're working with logged-in users doesn't matter if is it from Admin or some customer using the system, at the end, you need to record the Username that made this changes .

Another thing you might need is to add a category for the questions, and maybe the Feedback as well. This will be very helpful in filtering the results. You don't want to depend on any column that store user input with open text, it'll be a real pain in the neck. So, adding a category to the questions, which will store it's values in another table to have two columns (one for displaying text for user, the other one is the id) will make things easier to work with, and if you see that you can add more filtering options (either supporting sub-category or tags ..etc) go for it.

Sample  :

Questions Table

| Id |   Question |            CreatedAt | UpdatedAt | Deleted | StatusId | UserId |
|----|------------|----------------------|-----------|---------|----------|--------|
|  1 | Question 1 | 2019-12-14T00:00:00Z |    (null) |  (null) |        1 | User 1 |
|  2 | Question 2 | 2019-12-14T20:40:15Z |    (null) |  (null) |        2 | User 2 |
|  3 | Question 3 | 2019-12-14T07:05:01Z |    (null) |  (null) |        3 | User 3 |

Answers Table

| Id | QuestionId |   Answer |            CreatedAt | UpdatedAt | Deleted |  UserId |
|----|------------|----------|----------------------|-----------|---------|---------|
|  1 |          1 | Answer 1 | 2019-07-05T00:00:00Z |    (null) |  (null) | User 50 |
|  2 |          1 | Answer 2 | 2019-07-05T00:00:00Z |    (null) |  (null) | User 50 |
|  3 |          1 | Answer 3 | 2019-07-05T00:00:00Z |    (null) |  (null) | User 70 |
|  4 |          2 | Answer 1 | 2019-07-05T00:00:00Z |    (null) |  (null) | User 70 |

Feedback Table

| Id | RateId | QuestionId | AnswerId |            CreatedAt | UpdatedAt | Deleted |  UserId |
|----|--------|------------|----------|----------------------|-----------|---------|---------|
|  1 |      1 |          1 |        3 | 2019-07-05T00:00:00Z |    (null) |  (null) |   Admin |
|  2 |      2 |          2 |        4 | 2019-07-05T00:00:00Z |    (null) |  (null) | User 23 |
|  3 |      2 |          1 |        2 | 2019-07-05T00:00:00Z |    (null) |  (null) |  User 5 |
|  4 |      5 |          1 |        3 | 2019-07-05T00:00:00Z |    (null) |  (null) | User 23 |

Fiddle Demo


The code looks well presented, and it's clear how it maps to the problem statement.

The one thing that's not well defined is how we deal with exact equality of times.  I'm assuming that intervals are always half-open (i.e. including the start time, but excluding the end time); it would be wise to add suitable comments to ensure that all readers agree on what's expected.

It's possible to simplify considerably, because in all cases we want (and none we don't), t1 ends after t2 begins and t2 ends after t1 begins, giving us a simpler expression:

t1.begin.isBefore(t2.end) && t2.begin.isBefore(t1.end)

If the Interval class is under your control, consider making this method a public instance method of that class.  You might also want to check that the parameters are not null, if users might use that to indicate an empty interval:

if (t1 == null || t2 == null)
    return false;

(this latter is an argument against using an instance method, as then the caller would need to check t1 isn't null).


Cleaner way to construct a name using Immutable.js

Rather than repeating user.getIn(['response' twice, you can extract the response once into a variable. Also, both .getIn and .get accept a default value if the property isn't found in the collection, which you can use instead of || ''. For example, .get('foo') || '' is (existing falsey values aside) equivalent to .get('foo', '').
In up-to-date environments or if the code is being transpiled, you can use optional chaining to more concisely get the nested response if it exists.
Since you want to return something if one condition is fulfilled, and something else otherwise, rather than using if, you can make things more concise by using the conditional operator:

const getFullName = ({ user }) => {
    const response = user?.get('response');
    return !response
        ? ''
        : `${response.get('firstName', '')} ${response.get('lastName', '')}`;
};

console.log(getFullName({}));
console.log(getFullName({ user: Immutable.fromJS({}) }));
console.log(getFullName({ user: Immutable.fromJS({ response: { firstName: 'foo' } }) }));
console.log(getFullName({ user: Immutable.fromJS({ response: { firstName: 'foo', lastName: 'bar' } }) }));
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js"></script>


Magic numbers are a bad code smell and should be avoided. Use a constant instead.

In your definition of dateSort(), your third parameter is format=1. What does 1 mean? Without reviewing the code it isn't clear which makes maintaining the code more difficult. A common way to avoid this is to define constants with human readable names and use them in place of the magic numbers. Note that the names of these constants are arbitrary. Name them in such a way that makes sense to the reader what value they hold or reflect.

 defined('DATE_FORMAT_EU_SLASHES') || define('DATE_FORMAT_EU_SLASHES', 0);
 defined('DATE_FORMAT_US')         || define('DATE_FORMAT_US', 1);
 defined('DATE_FORMAT_YEAR_FIRST') || define('DATE_FORMAT_YEAR_FIRST', 2);

Using date_parse() is okay but working with DateTime() objects is preferred.

PHP offers a lot of ways of working with dates which can be a good or bad thing. In general using DateTime() objects are preferred as they were designed specifically for this purpose (and is the most powerful).

Your code can be simplified as DateTime() can parse most date formats natively and also handle not standard formats easily. date_parse() will fail once the format becomes non-standard or irregular.

Additionally, DateTime() objects are comparable so you don't need to output a string variable in a comparable format to do your comparison. Just compare the objects themselves.

$datetime1 = new DateTime($date1);
$datetime2 = new DateTime($date2);
return datetime1 <=> datetime2;

Simpler!

Use a switch statement instead of a potentially giant if/else

Because we can have situations where DateTime() can handle the format natively, there is no need to have an if/else statement for every date format. switch allows us to allow conditions to be handled by the same code block. It also offers us a default option which means we no longer need to define our default format in the function signature and can let the switch statement handle it for us.

defined('DATE_FORMAT_EU_SLASHES') || define('DATE_FORMAT_EU_SLASHES', 0);
defined('DATE_FORMAT_US')         || define('DATE_FORMAT_US', 1);
defined('DATE_FORMAT_YEAR_FIRST') || define('DATE_FORMAT_YEAR_FIRST', 2);

function dateSort($date1, $date2, $format = null)
    switch ($format) {
        case DATE_FORMAT_EU_SLASHES :
            // DateTime::createFromFormat() offers us flexibility
            $datetime1 = DateTime::createFromFormat('d/m/Y', $date1);
            $datetime2 = DateTime::createFromFormat('d/m/Y', $date2);
            break;
        case DATE_FORMAT_US :
        case DATE_FORMAT_YEAR_FIRST :
        default :
            // DateTime() can handle both formats natively so no need to handle them
            // individually. You can also ad formats like YYYY-MM-DD with only a couple
            // of lines of code
            $datetime1 = new DateTime($date1);
            $datetime2 = new DateTime($date2);
            break;
    }
    return datetime1 <=> datetime2;
}

If you want to take it a step further, you could simplify your code and only specify when the format is non-standard and handle them specifically. Otherwise, fall to the default date handler:

defined('DATE_FORMAT_EU_SLASHES') || define('DATE_FORMAT_EU_SLASHES', 0);

function dateSort($date1, $date2, $format = null)
    switch ($format) {
        case DATE_FORMAT_EU_SLASHES :
            $datetime1 = DateTime::createFromFormat('d/m/Y', $date1);
            $datetime2 = DateTime::createFromFormat('d/m/Y', $date2);
            break;
        default :
            $datetime1 = new DateTime($date1);
            $datetime2 = new DateTime($date2);
            break;
    }
    return datetime1 <=> datetime2;
}

*None of this code is tested -- I just wrote it off of the top of my head -- but hopefully it gives you ideas about how to improve this code