Let's go through it one section at a time.

jQuery.fn.center = function () {
            this.css("position","absolute");
            this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
            this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
            return this;
        }

You don't have to explicitly append 'px' to your numeric values. jQuery is smart enough to
correctly format your CSS styles.
Since this is a jQuery plugin, you return this; at the end of the function. This is good, as
it preserves chaining.
If the .center function is only used for the loading divs, consider removing it and instead
styling the divs with plain CSS.

#loader {
    position: fixed;
    top: 50%;
    left: 50%;
    margin-top: -50px; /* half of the height */
    margin-left: -100px; /* half of the width */
}
...

$( ".buttonFinish" ).on('click', function(event) {
    $('body').fadeOut('slow');
    $('#loader').center();
    $('#loading').center();
    $('#loader').show();
    $('#loading').show();

As mentioned by @Flambino, this particular code (as presented in the question) will fade out the entire body of the HTML document, which includes everything, even the loader elements. Perhaps the code that you're actually using is slightly different (is the selector .body or #body instead?).
It's best practice to enclose JavaScript that uses external dependencies inside an IIFE.
By doing so, you can use the "safe" name of an external dependency while still being able to
alias is to a more convenient identifier locally. In addition, you can freely create variables inside the scope
of the IIFE without polluting the global namespace. Your example code is fairly short, but you likely have much
more code on the page, and it is a good habit to have regardless. Here's one way to do it:

(function($) {
    $( ".buttonFinish" ).on('click', function(event) {
        ...
    });
})(jQuery);

You can select both elements at the same time, just like in CSS: $('#loader, #loading').
You can chain the .show() and .center() together: $('...').show().center().

    //Use the above function as:
    var request = $.ajax({
        url:'{{ URL::route('saveCart') }}',
        type:'POST'
        });

        request.done(function(msg) {
            $('.order_number').val(msg);
              $('#summaryForm').submit();
              event.preventDefault();
        });
    return false;
});

Since you're not using the request variable for anything other than .done(),
you can skip declaring it and simply chain .done() after $.ajax():

$.ajax({
    ...
}).done(function(msg) {
    ...
});

As an overall note, the indentation of the code (as it is in the question) seems haphazard,
making the control flow more difficult to see than it could be. Making matching
braces have the same indentation (and, in general, maintaining a consistent style)
will help make the code more readable and understandable.


The algorithm is actually pretty efficient, so congrats for that.

The first thing that I'd like to suggest is moving the logic outside the main check. In python, it's fairly common (and IMO more readable) to have your structure like this:

imports

def pile_algo(*args, **kwargs):
    """Docstring here"""
    # your code

def main():
    """Docstring here"""
    # process pile_algo

if __name__ == '__main__':
    main()

Of course, the main() is optional if you already have all the logic inside pile_algo().

Even if I said the algorithm is good, we can improve the way you're doing things.

You're not using num_cubes variable, so you can remove it (int(input().strip()) it's enough). Moving forward, neither use of strip() or list() or map() is necessary in your:

cube_sidelengths = list(map(int, map(str.strip, input().strip().split())))

You can rewrite that as:

cube_sidelengths = [int(x) for x in input().split()]

Apart from that, I don't have any other reasons to think about using deque. If it works, it works. And apparently works better enough to get over it.

Though, of course, I would also ask: Is it too slow right now? Most of the times, the aim of a programming challenge is both getting familiar with a specific library/module and improve your algorithms skills. You said:

  It would be possible to use a deque here but that felt like overkill -
  because pop and popLeft are O(1) but just keeping the indices and
  accessing a list is also O(1) so it wouldn't even provide better
  asymptotic behavior.

Well, it would provide a worse asymptotic behavior? Just start writing a deque-based solution and see what improvements might that bring. I can think of a few right now:

the code will be more comprehensive because of deque's already builtin methods which might do what you manually did (pop, etc..)
talking about efficiency, Python lists are much better for random-access and fixed-length operations, including slicing, while deques are much more useful for pushing and popping things off the ends, with indexing (but not slicing, interestingly) being possible but slower than with lists.

From the docs:

  Deques support thread-safe, memory efficient appends and pops from
  either side of the deque with approximately the same O(1) performance
  in either direction.

  Though list objects support similar operations, they are optimized for
  fast fixed-length operations and incur O(n) memory movement costs for
  pop(0) and insert(0, v) operations which change both the size and
  position of the underlying data representation.

This might look more of a theory answer, and might not specifically answer your question, but I just wanted to highlight a couple of things out.


Finding possible misconceptions in ColumnChart

It looks as if this can be solved using Linq.

If your datasource consists an IEnumerable of records each containing a MonthNumber, GroupName and ValueRevenue

Say,

public class DataRecord {

    public int MonthNbr { get; set; }
    public string GroupName { get; set; }
    public double ValueRevenue { get; set; }

}

then a GroupBy() should populate your ChartColumn

e.g.

private static ColumnChart GroupAndSort(IEnumerable<DataRecord> input) {

    return input.GroupBy(n => n.GroupName).Select(g => new ColumnChart {
            Type = "column",
            Name = g.Key,
            Data = g.OrderBy(d => d.MonthNbr).Select(d => d.ValueRevenue).ToList()
        }).First();

}

Note:

This was set up to deal with one set of records and only one ChartColumn being generated. If you have many groups in the input then remove the 'First()' and return an 'IEnumerable'


Do I need to override equals operators and hascode, or would this be enough?

Structs automatically implement Equals() and GetHashCode(), but that implementation is slow. If you're actually going to use them (even indirectly, e.g. by using some LINQ methods), and you care about performance, you should override them.

  Are there any important performance penalties (during a highload)? For i.e. garbage collection.

There shouldn't be. GC doesn't get involved (unless you're going to box the values, but that's the same for integers).

I'm not sure if the runtime can optimize code using UserId as well as it could for an integer, so for performance critical code, you should make sure it's okay by profiling.

  What could be any more negative consequences from this?

I think this is not a usual pattern in C#, so one negative consequence might be some confusion by your coworkers.


Just a couple of short comments as a starting point.

First of all, you don't need separate encrypt and decrypt functions -- the algorithm is identical for both. You just pass different parameters for them.

Second, I wouldn't use char const * for the input or output of the encrypt/decrypt function. It might be barely allowable for the plaintext (since you could restrict that to not contain zero bytes) but is definitely not acceptable as the encrypted data (since you can't stop it from containing zero bytes). Since, however, the same function can do either encryption or decryption, you don't want to use char const * for input or output. Personally, I'd probably have it take iterators for the input and output, so you can work with string, vector<char>, vector<wchar_t>, etc.

Finally, I don't think I'd put implementation details like the first 100 primes directly in the rsa namespace -- I'd have rsa contain a detail namespace to contain details like that. I'm not sure I'd have keygen either -- I think I'd make key a class, probably with the default ctor deleted, and a static member function to create a key, and overloading operator>> and operator<< to serialize keys in a standard format (e.g., X.509, PKCS #8). About all that would be visible to the outside world would be key and crypt (or whatever you decide to call the combined encrypt/decrypt funct(ion|or).

Edit: the key class and signatures would be something like this:

class key {
    key() = delete; // `=delete;` is C++11 only; without that just declare private
public:
    static key create_key();
};


Keyboard handler for selecting radio buttons

If you are sure it will always have a value just use the charAt value to build the id you try to select in each if block. Something like:

$( '#mcnumber' ).keyup(function() {
    var mcnum = this.value;
    var id = "#1mcskel" + mcnum.charAt( 0 );
    $(id).prop("checked", "checked");
})

In the future just try to find patterns in the code. Every if block you have has the same code except for the number at the end of the id selector and the number you checked against charAt in the condition. And they are the same number in both places so try to merge the relevant parts of the code.

So seeing those patterns can help you write more versatile code. Of course the code above assumes you will have a definite value. Could be it needs some error handling added but hopefully this helps you get the idea.

EDIT

So I have taken what you added above and looked for a pattern, taken the relevant pieces of that pattern and shortened the code, just as I advised priorly in the answer. I would like to add as a comment that I have no context to this code only what you have shown me so I am simply applying my pattern searching/combining example here. Take a look:

$( '#mcnumber' ).keyup(function() {
    var mcnum = this.value, index = 0, id;
    for ( ; index < 3; index++) {
        id = "#" + (index + 1) + "mcskel" + mcnum.charAt( index );
        $(id).prop("checked", "checked");
    }
})

It seems odd to me that you were attaching the multiple anonymous functions to the same element and the same event so I made it a single one. As you can see the pattern I saw was you were attaching the same event (keyup) to the same element (mcnumber). So I took those relevant pieces and combined them.

Then I looked at the code inside the function and searched for a pattern. Again I saw most lines were exactly the same except for the middle line of code. What were the differences? The number at the beginning of the id selector and the number used in the charAt. OK, so can we find a pattern with those numbers? Well with the id the range goes from 1-3 and with charAt the range goes from 0-2. And looking at both those ranges they are the same length except for each number in the range id selector is +1 larger.

So lets loop over that range from 0-2 using 0-2 on the charAt and using 0-2 to build the id selector but add one every time so we get 1-3.


Here are some things I see that could help you improve your code.

Provide some guidance for the user

The user of the program might not know that this is expecting a numeric argument.  Instead of throwing an exception (and by the way, neither atoi nor std::atoi throw), you might instead simply check for the number of arguments like this:

if (argc < 2) {
    std::cout << "Usage: " << argv[0] << " maxint\n";
    return 0;
}

Provide a reasonable default argument

As you've noted in your comments, a reasonable default would be the product of all of the numbers.  That is, 3 * 5 * 7 * 11 * 13, but that's actually 15015 and not 15016 as your comments indicate.  Why not let the computer supply that?  Here's one way to do that:

const static int defaultMax = std::accumulate(
        FizzDict.cbegin(),
        FizzDict.cend(),
        1,
        [](int a, const std::pair<const int, std::basic_string<char> >& b){
            return a*b.first;
        }
      );
iMax = defaultMax;
if (argc > 1)
    iMax = std::stoi(argv[1]);

for (int i = 1; i <= iMax; ++i)
{
    printString(FizzBuzzer(i, FizzDict));
}

Note that the lambda could be shortened by making the second argument decltype(*FizzDict.cbegin()) b but we still need to know that it's a std::pair so that we can get the first element (integer), so it's not clear that it's really a win.

Separate interface from implementation

The interface goes into a header file and the implementation (that is, everything that actually emits bytes including all functions and data) should be in a separate .cpp file.  The reason is that you might have multiple source files including the .h file but only one instance of the corresponding .cpp file.  In other words, split your existing FizzBuzz.h file into a .h file and a .cpp file.

Make sure you have all required #includes

The code uses atoi but doesn't #include <cstdlib>.  Also, carefully consider which #includes are part of the interface (and belong in the .h file) and which are part of the implementation per the above advice.

Encapsulate helper functions within a class

Right now, there's probably little reason to use ifEmpty or checkModZero outside the context of your FizzBuzzer.  To that end, you could make those private member functions of a FizzBuzzer class and have your FizzBuzzer function be a public member function instead.  I'd probably either have the FizzDict map be a static member of that class or maybe an argument to the constructor.


Validate input
You should be certain that your program wouldn't fail for any kind of bad input, something the user shouldn't have entered that might cause the program to behave incorrectly
Is this possible for your program? Yes, take this line
username = input("Please enter your username: ")

If the user enters Ctrl+Z here, it causes an error and the program stops.

EOFError

We can catch these exceptions using try and except in Python
try:
    username = input("Please enter your username: ")
except (Exception, KeyboardInterrupt):
    print("Please enter a valid username!")

The same applies to the input for password
One step further, I would also like to check the length of the details, i.e if the username or password is too short. Show a custom message if that is true

On an exception
Due to the changes we made previously, we can easily print an error message if we catch an exception rather than the termination of the program. But what happens after?
You have two options, either to stop the program there because you cannot process bad input or, you can ask for input again.
If you choose the second option, that will take a few more lines of code but is surely better because the user gets another chance rather than running the whole program again
For that, we need to wrap it in a while loop that will iterate till it gets valid input
def username_input():
    while True:
        try:
            username = input("Please enter your username: ")
        except Exception:
            print("Please a enter valid username! \n\n")
            continue
        return username

def password_input():
    while True:
        try:
            password = input("Please enter your password: ")
        except Exception:
            print("Please enter a valid password! \n\n")
            continue
        return password

Here we are repeating ourselves, the functions are identical. With a little hack, we can clean up the code
def ask_input(field):
    while True:
        try:
            word = input(f"Please enter your {field}: ")
        except (Exception, KeyboardInterrupt):
            print(f"Please enter a valid {field}! \n\n")
            continue
        if not word: continue # if field is empty
        return word

def take_input():
    username = ask_input("username")
    password = ask_input("password")
    return username, password

Split work into functions
In my last point, you must've noticed I moved something into a function
We can really clean up our code if we follow the SRP rule or the Single-responsibility principle

The single-responsibility principle (SRP) is a computer-programming
principle that states that every module, class, or function in a
computer program should have responsibility over a single part of that
program's functionality,

If assig the task of taking input in this program, to let's say take_input()
We can re-use the same function if we would ever want to perform the same task again, without copy-pasting the same segment of code
username, password = take_input()
process_login( username, password ):

take_input() will take care of the input related tasks, and when it has proper valid it returns a username and password
process_login() decides whether the login will be authorized or not, based on the records

Check with key username
if username in username_password:
    if username == "Mert" and password == username_password[username]:
        print("Welcome Sir")
    else:
        print("You're not authorized!")

This works right now, but only due to the fact that the size of records is 1, any extra records added and your algorithm will fail, if the size was 50 you cannot write 50 if statements, you need to check with the username entered
def process_login(username, password, records):
    try:
        if records[username] == password:
            print("Authorized")
            return True
    except KeyError:
        print("Not authroized")
        return False

Here, if the username isn't present in records, a KeyError is raised, which I will catch and print Not authorized

Re-written
def ask_input(field):
    while True:
        try:
            word = input(f"Please enter your {field}: ")
        except (Exception, KeyboardInterrupt):
            print(f"Please enter a valid {field}! \n\n")
            continue
        if not word: continue

        return word

def take_input():
    username = ask_input("username")
    password = ask_input("password")
    return username,password

def process_login(username, password, records):
    try:
        if records[username] == password:
            print("Authorized")

    except KeyError:
        print("Not authroized")

I have left out the last part, which is the "registration". Which I will explain next
records = {
    "__Testu" : "__Testp",
    "__Testu2" : "__Testp2"
}

username, password = take_input()
process_login(username, password, records)

Write records into a file
As it is currently, you have pre-added a record to your dictionary, any record added after this is pointless since the next time you run the program, the dictionary will be initialized again with the same one record you added.
You need some way to save the users records so that the next time he opens your program, his previous details are saved
The best way to do this is the user the csv module in Python, - csv.DictReader which will automate all reading/writing of the file for you. But is something you would have to write on your own.
Cheers
>>> Please enter your username: (empty input)
>>> Please enter your username: __Testu
>>> Please enter your password: (empty input)
>>> Please enter your password: __Testp

>>> Authorized


Parsing a complex number using regular expressions

Both of your solutions are wrong, in different ways.  Yours is worse, though, because it fails in a way that can actually succeed in giving completely wrong answers.

Your solution

Your technique is, as your professor noted, sloppy.  It falls apart in several cases that I would consider reasonable inputs:

Pure imaginary numbers such as "5i"
No imaginary component, such as "1"
No imaginary coefficient, such as "5+i"
Imaginary number with a space, such as "3 - 3i"
Decimals more precise than one-tenth, such as "3.14"

Furthermore, using an ArrayList seems extravagant.  You shouldn't need one.

Professor's solution1

Sanitizing the input by discarding spaces — is that a good idea?  Why?  Is there another way to handle spaces?

Why three Patterns, three Matchers, and three .find()s?  Can it be done with fewer?

Within each pattern, is your regex more correct, or his?  Can you spot any bugs in his character classes (i.e. the stuff inside [square brackets])?

Are there any inputs that also fail with his code?  Does his code accept any inputs that should be considered invalid?

1 We shouldn't really be criticizing code that you didn't write, so I'll give you some questions to ponder instead.


Method that Saves user text messaging draft

In both cases (!hasDraft and not !hasDraft) you check whether the enteredText is empty. You can hoist that into a boolean variable outside the if statement.

Also, you are testing if (!hasDraft) but then also doing an else on that condition, which means else (if not)not hasDraft. That can be confusing, so unless some other part of your code flow requires it, I suggest you make your if statement be if (hasDraft) {} else {} so that the implied not from the else matches the !hasDraft case.

boolean noEnteredText = TextUtils.isEmpty(enteredText);

if (hasDraft) {
    if (noEnteredText) {
        removePreviousDraft();
    else {
        overwritePreviousDraft();
    }
} else {
    if (noEnteredText) {
        sendMessage();
    } else {
        saveDraftAndRefreshList();
    }
}

This does not read well, IMO. Again, though, it might be fine in the context of your other code. But I wonder if reversing the sense of noEnteredText to be hasEnteredText would make it better?

boolean hasEnteredText = !TextUtils.isEmpty(enteredText);

if (hasDraft) {
    if (hasEnteredText) {
        overwritePreviousDraft();
    else {
        removePreviousDraft();
    }
} else {
    if (hasEnteredText) {
        saveDraftAndRefreshList();
    } else {
        sendMessage();
    }
}

This still seems off. But I suspect that's probably because I don't know your app. Is it possible you're trying to do too much, and the two decisions should be at two different levels of method call?


A structure for a text messages dictionary with system notifications/errors

I consider that the second option is better for the following:

The first option is more verbose than the second, and it is in a way that there is no additional information which allow other developers or even you to obtain meaningful information.
The second option has a constant style name which represents what you are trying to tell us, "hey, this is a constant and its value is ..." and so, it clearly reflects a shorter and descriptive code style.
Having less properties (in your objects) implies less space, and less space computed implies less execution time. (even if it is very small).
Less content helps you to debug faster.

Well, I hope it helped you.


Sum to zero of all triples in a list - n^2 running time

Your first pair of loops builds the list sums. The length of this list is \$O(n^2)\$ in the length of the input.

In your second set of loops for each element in s_integers you filter all of sums to find those elements which match it. The runtime of this filter process is linear in the length of sums, and hence quadratic in the length of the input. You perform this quadratic process once for each member of the input list; the search loop is therefore cubic in the length of the input.

Your algorithm as a whole is therefore \$O(n^3)\$ in the length of the input.

To make the algorithm as a whole quadratic, you need to make the second (match) stage linear in the length of sums. Natural approaches would include:

Using a dictionary or some other map structure to lookup elements in the original either s_integers or sums by magnitude, in constant time; the match stage is then linear in the length of the other list. (Probably fastest on real input; it might be slightly tricky to check that there are no pathological cases, depending on which list you do lookup on).
Sorting sums (\$O(n \log n)\$), then effectively 'merging' sums and s_integers, (\$O(n)\$ in the length of the larger). This is easiest to prove to be \$O(n^2)\$


Parsing SOAP messages from a web service

Spot the inconsistency:

        var fault = result.Root.Element("{" + nsSoap + "}Body").Element("{" + ns_soap + "}Fault");
...
            var codeWithNs = error.Element("{" + nsSoap + "}Code").Element("{" + ns_soap + "}Value").Value;
...
        return userId = result.Descendants(ns + "UserId").First().Value;

Ok, there are two inconsistencies. Firstly, nsSoap vs ns_soap. I suspect that that difference is due to refactoring the code before posting in, in which case please don't do that again: we want to review code which compiles and works.

Secondly, "{" + nsSoap + "}Body" vs ns + "UserId". The simple concatenation is far more readable.

        var service = new WebService();
        var result = service.Invoke(soapAction, method, parameters);

        XNamespace nsSoap = "http://www.w3.org/2003/05/soap-envelope";
        XNamespace ns = "link-to-namespace";

        // Look for the "Fault" element in the response. If present, there was an error.
        var fault = result.Root.Element("{" + nsSoap + "}Body").Element("{" + ns_soap + "}Fault");
        if (error != null)
        {
            var codeWithNs = error.Element("{" + nsSoap + "}Code").Element("{" + ns_soap + "}Value").Value;
            var codeSplit = codeWithNs.Split(':');
            var code = codeSplit.Length == 2 ? codeSplit[1] : codeSplit[0];
            if (code == "InvalidUsernameOrPassword")
            {
                throw new InvalidUsernameOrPasswordException();
            }
            else
            {
                throw new Exception("Something went wrong.");
            }
        }

There's a strong asymmetry here which I don't grok. WebService does the job of assembling some simple strings into the XML request document: why does it not also do the job of disassembling the XML response document? I understand that it can't fully do that, because the response might be a complex datastructure, but IMO WebService should be detecting <soap:Fault> and returning some kind of "option" type.

As it happens, there is an option type in .Net: Task<TResult>. So I think that WebService.Invoke should return a Task<XElement> which has Status Faulted and a placeholder exception, or Status RanToCompletion and the contents of <soap:Body>. Then GetUser would look like

public string GetUserId(string username, string password)
{
    var soapAction = "link-to-soap-action";
    var method = "GetUserId";
    var parameters = new Dictionary<string, string>
    {
        { "Username", username },
        { "Password", password}
    };

    var service = new WebService();
    var result = service.Invoke(soapAction, method, parameters);

    if (result.Status == TaskStatus.Faulted)
    {
        // Handle specific errors
        if (result.Exception.Message == "InvalidUsernameOrPassword")
        {
            throw new InvalidUsernameOrPasswordException();
        }
        else
        {
            throw new Exception("Something went wrong.", result.Exception);
        }
    }

    XNamespace ns = "link-to-namespace";
    return userId = result.Value.Descendants(ns + "UserId").First().Value;
}


Let's see if I understand what's going on with get_filtered_lines() and apply_filter(). First, get_filtered_lines() reads physical lines from the file and strings them together in line_buffer. When we find the beginning of the next logical line ('['), we pass line_buffer off to apply_filter() so the material that has been collected gets processed. Then we empty out line_buffer and start over with the beginning of the logical line just read.

Here's an approach I think is simpler and clearer:

def apply_filter(lbuf):
    parsed = parse_line(lbuf)
    if filter(parsed):
        return [parsed]
    else
        return []

def get_filtered_lines(source):
    filtered_lines = []
    collected = ""
    for line in source:
        if line.startswith('[') and collected:
            filtered_lines.extend(apply_filter(collected))
            collected = ""
        collected += line
    filtered_lines.extend(apply_filter(collected))
    return filtered_lines

That way, apply_filter doesn't have to be aware of the list being built. It just returns a list of what it finds -- either a line that passes the filter or an empty list. Passing an empty list to extend is a no-op.


Using 'each' to print chunks of an array

No need to save group x already saving it.

(1..16).each do |x|
  print x
  puts if x % 4 == 0
end


Achieve error differentiation in Promises

Would it help to rewrite it along the lines of:

function notFoundErrorHandler(error) {
  if(error.reason === "ObjectNotFound")
      return {code: 404, error:err);
}
function someOtherErrorHandler(error) {
  if(error.reason === something else")
      return {code: 499, error:err);
}
function serverErrorHandler(error) {
  // No if because this is a catch all
  return {code: 500, error:err);
}

let handlers = [notFoundErrorHandler,
                someOtherErrorHandler,
                serverErrorHandler     ];

Survey.findOne({_id: surveyJSON.id})
  ...
  .catch(error => {
    respondToError(error, handlers);
  } );

function respondToError(error, handlers) {
  for (let handler of handlers) {
    let {code, error} = handler(error);
    if (code) {
       sendJsonResponse(res, code, error);
       return;
    }
  }
  console.error("Shouldn't get here");
}


Your multiplication expressions aren't ideal; instead (which might be faster) you could add 4 and subtract srcStride from the previous value at the top of each loop.

Apart from that (and this is just a guess) I guess some other things might in theory make this faster.

Have three loops: write to Luma in the 1st loop, then write to ChromaV in the 2nd loop, and write to ChromaU in the 3rd loop.
Calibrate the length of (number of bytes moved in) each loop, so that the chunk of input data stays in cache for each of the three loops
Use some kind of read-ahead, to ensure that the byte is read before it needs to be written, for example:

Read 1st byte
Read 2nd byte
Read 3rd byte
Read 4th byte
Write 1st byte
Read 5th byte
Write 2nd byte
etc.

Read 4 or 8 bytes at a time, for example into a struct which contains 4 or 8 byte-fields and is a union with an int32 or int64 field.


Finding difference between date now and last comment

Current time is easily obtained simply with new DateTime(), no need to specify any formatting (default is now). Also you don't need to format dates to compare strings because DateTime itself is comparable. All together:

$now = new DateTime();
$lastPostTime = new DateTime('2016-01-08 13:16:59');
$notEnabledBefore = lastPostTime->add(new DateInterval('PT9M'));

if (now < notEnabledBefore) {
    $timeToWait = notEnabledBefore->diff(now);
    echo $timeToWait->format('%i minutes left or ahead');
}


In your data structure include a validator (this should probably be a Predicate<String>); most of the predicates will just return true, but the two that require integers will have a nontrivial validator that checks for integer.

So I guess the type should be Dictionary<String, Tuple<Func<SqlConnection, String, DataSet>>,Predicate<String>>


Here are my comments in order of severity:

1) Bugs

1.1) resource handling

in load() you handled IO resources correctly with try-with-resources.  You forgot to do it in dump().

1.2) parsing

You split the line according to single comma. There are two problems with that: First, you do not accept cell values containing comma.  Imagine the following line

cell1,"cell with comma,",2018-05-31

Second, although the acronym stands for "comma separated values", parsers (and writers) usually accept any single character as argument for delimiter. this gives clients flexibility that sometimes is necessary. Imagine if an api produces  files in the following format

cell1;cell with comma,;2018-05-31

1.3) Instantiation of CSVDataPoint

Later on I have more (much more) to say about CSVDataPoint but this comment is relevant for the general case of instantiation through reflection: You make the assumption that the default no args constructor exists, and this is not always true. A better aproach would be for you to accept an instance of factory that produces instances of CSVDataPoint.

2) Warning

2.1) variable types

List fields = new ArrayList<CSVDataPoint>();
I know the compiler accepts this definition, but it makes no sense. What type do you want for the items in the list?  If you want it to accept any type use the ? wildcard (not Object)

Also, dp instance variable has no generic type.

2.2) unsued imports

you have unsued imports. clean code helps maintainability.

3) Design

3.1) CSVDataPoint

I have several comments regarding the class:

name
It took me some time to understand that this class represents a complete CSV line.  In my eyes, DataPoint translates to single cell.  Why not CSVDataLine or use the term from RDBMS CSVDataRow or the term from old times' file processing CSVDataRecord
toLine()
You do no validation on the lines that the method produces.  What if it did not produce comma delimited values?  the method should give you List<String> and you write the line in the proper format (perhaps with the custom delimiter?).
Instantiation
In load() you create a new instane of the class for every input line and dump() (also a bad name if you ask me) you accept a list of instances. from that I gather that the design was that a CSVDataPoint instance represents a CSV line. However, the usage contradicts the design.  fromLine() is supposed to produce an Object.  Did you mean it to return an instance of CSVDataPoint? in this case, a better approach would be to use a constructor.  This is the proper way for a Java bean to populate its state.

3.2) input to CSVFile

CSVFile only accepts file name in String.  this is too limited for two reasons: First, consider the case of a client that already constructed a File instance and now has to convert that to a String for you. The bigger issue is the case where the client already opened the file. also, the client may wish to have control over the lifecycle of the file.  This is of course true for file load and write. at the very least you should provide overloaded constructor that accepts File and one that acepts InputStream (and in this case do not close it).  You may ask why InputStream and not Reader.  well, you can have overloaded constructors for both. but I think an InputStream is enough. You can open a Reader from an InputStream.  InputStream is used in more cases than Reader.  For example, a common usage is to open one from an HTTP request.


Increase performance creating Mandelbrot set in python

I'm going to reuse some parts of the answer I recently posted here on Code Review.

Losing your Loops

  (Most) loops are damn slow in Python. Especially multiple nested loops.

  NumPy can help to vectorize your code, i.e. in this case that more
  of the looping is done in the C backend instead of in the Python
  interpreter. I  would highly recommend to have a listen to the talk
  Losing your Loops: Fast Numerical Computing with NumPy by Jake
  VanderPlas.

All those loops used to generate the complex grid followed by the nested loops used to iterate over the grid and the image are slow when left to the Python interpreter. Fortunately, NumPy can take quite a lot of this burden off of you.

For example

real_axis = np.linspace(-2, 1, num=3000)
imaginary_axis = np.linspace(1, -1, num=2000)
complex_grid = [[complex(np.float64(a),np.float64(b)) for a in real_axis] for b in imaginary_axis]

could become

n_rows, n_cols = 2000, 3000
complex_grid_np = np.zeros((n_rows, n_cols), dtype=np.complex)
real, imag = np.meshgrid(real_axis, imaginary_axis)
complex_grid_np.real = real
complex_grid_np.imag = imag

No loops, just plain simple NumPy.

Same goes for

for complex_list in complex_grid:
    for complex_number in complex_list:
        for iteration in range(255):
            z = z**2 + complex_number
            if (z.real**2+z.imag**2)**0.5 > 2:
                pixel_grid[complex_grid.index(complex_list),complex_list.index(complex_number)]=[iteration,iteration,iteration]
                break
            else:
                continue
        z = 0

can be transformed to

z_grid_np = np.zeros_like(complex_grid_np)
elements_todo = np.ones((n_rows, n_cols), dtype=bool)
for iteration in range(255):
    z_grid_np[elements_todo] = \
        z_grid_np[elements_todo]**2 + complex_grid_np[elements_todo]
    mask = np.logical_and(np.absolute(z_grid_np) > 2, elements_todo)
    pixel_grid_np[mask, :] = (iteration, iteration, iteration)
    elements_todo = np.logical_and(elements_todo, np.logical_not(mask))

which is just a single loop instead of three nested ones. Here, a little more trickery was needed to treat the break case the same way as you did. elements_todo is used to only compute updates on the z value if it has not been marked as done. There might also be a better solution without this.

I added the following lines

complex_grid_close = np.allclose(np.array(complex_grid), complex_grid_np)
pixel_grid_close = np.allclose(pixel_grid, pixel_grid_np)
print("Results were similar: {}".format(all((complex_grid_close, pixel_grid_close))))

to validate my results against your reference implementation.

The vectorized code is about 9-10x faster on my machine for several n_rows/n_cols combinations I tested. E.g. for n_rows, n_cols = 1000, 1500:

Looped generation took 61.989842s
Vectorized generation took 6.656926s
Results were similar: True

Lose a dimension

An aspect I somehow slightly ignored while looking at your code was that you're essentially creating a grayscale image since all of your color channel values are the same. Accounting for this, you can easily reduce the size of data the program has handle to from, in your case, 3000x2000x3 to 3000x2000. This will likely help your program to be more cache efficient, although I'm not an expert in this field.

Edit/Appendix: Further timings

Including the "no square root" optimization as suggested by trichoplax in his answer and Peter Cordes in the comments like so

mask = np.logical_and((z_grid_np.real**2+z_grid_np.imag**2) > 4, elements_todo)

will give you about another second and a half for n_rows, n_cols = 1000, 1500, i.e. about 12x the speed of the original solution

10 loops, best of 5: 4.98 s per loop
10 loops, best of 5: 4.28 s per loop (in grayscale, 14x)

A quick implementation of Reinderien's hint towards the symmetry of the Mandelbrot set will again add a factor of about two to that.

10 loops, best of 5: 2.54 s per loop (~24x)
10 loops, best of 5: 2.07 s per loop (in grayscale, ~30x)

However, my quick hacking approach did not lead to an output that was completely within the tolerance of np.allclose compared to the original one. Funnily, it seems to be off by one at a single pixel, but visually still the same. Since this post is already quite long, I will leave the reimplementation as an exercise to the reader.

Depending on your needs, you might also go down with the floating point precision from 64bit to 32bit on addition to all the previously mentioned optimizations.

10 loops, best of 5: 1.49 s per loop (~41x)
10 loops, best of 5: 1.14 s per loop (in grayscale, ~54x)


Function to remove element from an array

The methodname sbSample doesn't tell anything about what the method is doing and this will make debugging the code very hard if not impossible.

You should leave your methodparameters some space to breathe so int a[],int i should be int a[], int i. The same is true for variables and operators.

Comments should tell the reader of the code why something is done in the way it is done. Stating the obvious what is done is only adding noise to the code and should be removed. Let the code itself tell what is done by using meaningful names for classes, methods and variables.

This method is doing to much hence it is breaking the single responsibility principle. It is "deleting" array elements and displaying the resulting array values.

If the source array has 10 elements and 3 of them have the value which you want to delete, the resulting array still has 10 elements which is somehow strange. Deleting means IMO that the size of the array should shrink afterwards. How about using an ArrayList<T> adding the items which aren't satisfying the search condition and later call toArray() to return the resulting array ?


Computing tangent space basis vectors for an arbitrary mesh

Here's my pass at it; without the rest of your source I can't verify it's integrity so I don't know if this will compile correctly with the rest of your code, so hopefully it can help:

// outside function since they're consts, decreases run time as no more construction each function call
const XMVECTOR NullVector = XMLoadFloat4A(&XMFLOAT4A(0.f, 0.f, 0.f, 0.f));
const XMVECTOR W_Null = XMLoadFloat4A(&XMFLOAT4A(1.f, 1.f, 1.f, 0.f));
const XMVECTOR signature = XMLoadFloat4A(&XMFLOAT4A(1.f,-1.f,-1.f,1.f));

void CalculateTangentsAndNormals( vector<Vertex>& verts, vector <U32>& idx )
{
    // Computing Tangent Space Basis Vectors for an Arbitrary Mesh
    //  http://www.terathon.com/code/tangent.html

    const U32 NumberOfVertices = (U32)verts.size();
    const U32 NumberOfIndices = (U32)idx.size();
    U32 i = 0;

    XMMATRIX st(NullVector, NullVector, NullVector, NullVector);

    // explicit construction
    vector <XMVECTOR> vTangents( NumberOfVertices , NullVector);
    vector <XMVECTOR> vBitangents( NumberOfVertices, NullVector);

    {
        U32 i0, i1, i2;
        XMVECTOR v0, v1, v2;
        XMVECTOR t0;
        XMFLOAT4A d;
        const U32* pSrc = 0;
        U32* pDst = 0;
        while (i < NumberOfIndices) {
            i0 = idx[i];
            i1 = idx[++i];
            i2 = idx[++i];

            v0 = XMLoadFloat3A(&verts[i0].pos);
            v1 = XMLoadFloat3A(&verts[i1].pos);
            v2 = XMLoadFloat3A(&verts[i2].pos);

            // e0, e1, NullVector, NullVector
            const XMMATRIX e01( XMVectorMultiply( v1 - v0, W_Null),
                                XMVectorMultiply( v2 - v0, W_Null),
                                NullVector,
                                NullVector);
            /*      | e0.x e0.y e0.z 0 |
                    | e1.x e1.y e1.z 0 |
            e01 =   | 0    0    0    0 |
                    | 0    0    0    0 |
            */
            t0 = XMLoadFloat2A(&verts[i0].tex);

            // s = (t1x - t0x, t2x - t0x, t1y - t0y, t2y - t0y)
            XMVECTOR s = XMVectorMergeXY((XMLoadFloat2A(&verts[i1].tex) - t0),
                                         (XMLoadFloat2A(&verts[i2].tex) - t0));
            XMStoreFloat4A(&d, s);
            s *= (1.0f/( d.x * d.w - d.z * d.y )); //DetInv;
            s = XMVectorMultiply(s, signature); // s = (sx, -sy, -sz, sw)

            pSrc = reinterpret_cast<const U32*>(&s);
            pDst = reinterpret_cast<U32*>(&st.r[0]);
            pDst[0] = pSrc[3];  // _00 = sw
            pDst[1] = pSrc[2];  // _01 = -sz
            pDst = reinterpret_cast<U32*>(&st.r[1]);
            pDst[0] = pSrc[1];  // _10 = -sy
            pDst[1] = pSrc[0];  // _11 = sz

            /*      | sw  -sz 0 0 |
                    | -sy sx  0 0 |
            st =    | 0    0  0 0 |*DetInv
                    | 0    0  0 0 |
            */

            const XMMATRIX uv( XMMatrixMultiply(st, e01) );

            vTangents[i0] += uv.r[0];
            vTangents[i1] += uv.r[0];
            vTangents[i2] += uv.r[0];

            vBitangents[i0] += uv.r[1];
            vBitangents[i1] += uv.r[1];
            vBitangents[i2] += uv.r[1];

            ++i;
        }
    } // end scope for temp vars
    i = 0;
    XMVECTOR normal, n0, n1;
    float w;
    while (i < NumberOfVertices) {
        normal = XMVector3Normalize(XMLoadFloat3A(&verts[i].normal));
        // normalize tangents and orthogonalize TBN
        n0 = XMVector3Normalize( vTangents[i] - XMVector3Dot( normal, vTangents[i] ) * normal );
        //calculate handedness
        n1 = XMVector3Cross( normal, vTangents[i] );
        w = (XMVector3Less(XMVector3Dot(n1, vBitangents[i] ), NullVector)) ? -1.f : 1.f;
        n0 = XMVectorSetW(n0, w);
        XMStoreFloat4A(&verts[i].tangent, n0);
        ++i;
    }
}


This method doesn't need any member of it's class, thus it can be declaced static.

You want to count the repetation of each letter, not the frequency in the string, don't you? At least, that's what I understood from your example result 4a2b2a1c where a is included twice. If you want the frequency 6a2b1c the algorithm would be different.

AN alternative approach to your proposal would be to convert the String in a char array and to analyze that.

public static void continousWords(String input) {
    char[] chars = input.toLowerCase().toCharArray();
    StringBuilder b = new StringBuilder();

    for (int i = 0, count; i < chars.length; i += count) {
        count = 1;
        while (i + count < chars.length && chars[i] == chars[i + count])
            count++;
        b.append(count).append(chars[i]);
    }

    String result = b.toString();
    System.out.println(result);
}


Search for row number of maximum value in matrix column

I see a number of things that may help you improve your code.

Pass by const reference where practical

The first argument to MaxLocColumnWise is a Matrix but that causes the entire input matrix to be duplicated.  Better would be to make it const Matrix & because it is not modified and it doesn't need to be duplicated.  This is very likely the crux of your code's performance problem.   On my machine with a matrix of size 1000, that single change drops the execution time down from 3.1 seconds to 11 milliseconds.

Prefer return value over reference

Instead of modifying one of the passed parameters, it's often better to return a value instead.  So in this case, the function would be

int MaxLocColumnWise(const Matrix &A, int idx);

Check parameters before use

If idx is a negative number or beyond the end of the Matrix, your program will invoke undefined behavior and it could crash or worse.  Better would be to verify the value is in a valid range before use.

Use appropriate data types

An index into an array is never negative, so instead of int, I'd recommend using std::size_t.

Provide complete code to reviewers

This is not so much a change to the code as a change in how you present it to other people.  Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code.  This affects not only code reviews, but also maintenance of the code in the future, by you or by others.  One good way to address that is by the use of comments.  Another good technique is to include test code showing how your code is intended to be used.  I split your code into a header Gauss.h and implementation file Gauss.cpp and then created a test driver.  These are the resulting files, after applying all of the suggestions above:

Gauss.h

#ifndef GAUSS_H
#define GAUSS_H
#include <vector>
typedef std::vector<double> Vector;
typedef std::vector<Vector> Matrix;
std::size_t MaxLocColumnWise(const Matrix &A, std::size_t idx);
void GaussElimPartialPivot(Matrix& A, Vector& b);
#endif // GAUSS_H

Gauss.cpp

#include "Gauss.h"
#include <cmath>

std::size_t MaxLocColumnWise(const Matrix &A, std::size_t idx){
    auto maxIndex{idx};
    const auto col{idx};
    for (double maxValue{-1}; idx < A.size(); ++idx)  {
        auto currentVal{std::abs(A[idx][col])};
        if (currentVal > maxValue){
                maxValue = currentVal;
                maxIndex = idx;
        }
    }
    return maxIndex;
}

void GaussElimPartialPivot(Matrix& A, Vector& b) {
    const std::size_t n{A.size()};
    for (std::size_t j{1}; j < n; ++j) {
        auto maxcol{MaxLocColumnWise(A, j)};
        SwapMatrixRows(A, j, maxcol);
        SwapVector(b, j, maxcol);
        for (std::size_t i{j-1}; i < n; ++i) {
            double m{A[i][j]/A[j][j]};
            b[i] -= m*b[j];
            for (auto k{j}; k < n; ++k){
                A[i][k] -= m*A[j][k];
            }
        }
    }
}

main.cpp

#include "Gauss.h"
#include <iostream>
#include <numeric>

int main() {
    constexpr size_t n{1000};
    Matrix m;
    m.reserve(n);
    int startval{1};
    for (size_t i{0}; i < n; ++i) {
        Vector v(n);
        std::iota(v.begin(), v.end(), startval);
        m.push_back(v);
        startval += n;
    }
    for (int i=0; i < n; ++i) {
        auto max{MaxLocColumnWise(m, i)};
        if (max != n-1) {
            std::cout << "Error:" << i << ", " << MaxLocColumnWise(m, i) << '\n';
        }
    }
}


Avoid using namespace std

It's a bad idea to import large namespaces such as std into the global namespace, and it could possibly even change the meaning of your code when a later standard adds new identifiers.  Reserve using namespace for those few namespaces specifically designed to be used that way (notably std::literals).

Use const appropriately

We don't want alphabet or key to be modified, so prevent accidents by declaring them as const std::string.

getline() can fail

If the input stream is closed, getline() will read nothing, and the string will be empty.  That's probably acceptable for this program, but probably worth a comment to show that you've considered this.

Use range-based for

We have an integer loop whose value is used only for indexing into the string:

for(size_t i{0}; i<secretMessage.length(); ++i){
    // use secretMessage[i] here

That's easier to read with modern range-based syntax:

for (auto const c: secretMessage) {
    // use c here

Use standard algorithms

We can include <algorithm> to get some really useful functions from the standard library.  In particular, std::find() could replace the loop that searches in the alphabet.

Reduce duplication

Notice that there are two blocks of code that are almost identical, due to the symmetric nature of this cipher.  The only difference is that the role of alphabet and key are swapped.  This makes it a good candidate to extract as a function:

std::string substitute(const std::string& message,
                       const std::string& from,
                       const std::string& to)

Then we could just call it:

auto encrypted = substitute(secretMessage, alphabet, key);
auto decrypted = substitute(encrypted, key, alphabet);

Avoid linear search

We can be more efficient with our lookup than simple linear search.  For example, we could construct a pair of std::map<char,char> from the alphabet and key.

Clean up the plaintext

I know this is just toy encryption, but for real code, we'd want to overwrite the decrypted text when we finish using it, to reduce the ability for an attacker to access it (e.g. from a core dump).  Remembering <algorithm>, we'd use std::fill() for this.

Omit the return

In main() (and only there), we can omit the return statement and the compiler will automatically return 0 for us.  It's a fairly common convention to omit the return if we don't have any non-zero (i.e. error) returns from main().


Alternatives for appending a div from a JS object

You could use template literals to avoid the breaking the strings with + and doing \ to newline. Alternatively, you could use template libraries which are more flexible. Mustache is a good example.
Consider using a web framework that does the bulk of the rendering for you. That way, you only have to worry about your data. Web frameworks also do optimizations to avoid re-rendering the entire chunk of HTML, do housekeeping, etc.

Other than that, there's not much to review.


First of all, your function doesn't return anything and so you can remove -> bool since it only creates confusion. You can either use -> None or use nothing at all. Still related to type annotations, I find it kinda hard to read your code with annotations everywhere. This is subjective and it's just my personal preference but I usually tend to use type annotations only when dealing with function / class definitions and their arguments.
For example, milliseconds: int = int(round(time.time() * 1000)) it's obviously going to be an integer since we can see the cast to int().
More, round() already returns an int in your case so that can be removed as well. The done variable can also be omitted and added directly to the condition itself:
def set_timer(interval: int, function: Callable) -> None:
    global last_milliseconds
    milliseconds = round(time.time() * 1000)

    if milliseconds - last_milliseconds >= interval:
        function()
        last_milliseconds = milliseconds

You can also remove the parentheses from your condition since - has a higher precedence than >=.

Strictly speaking about the implementation, if you're not tied to using a function and want to get rid of the usage of global, I'd use a class:
from time import time
from typing import Callable

class Timer:
    def __init__(self):
        self.last_milliseconds = 0

    def set(self, interval: int, function: Callable) -> None:
        milliseconds = round(time() * 1000)

        if milliseconds - self.last_milliseconds >= interval:
            function()
            self.last_milliseconds = milliseconds

Which can be used like this:
def main():
    timer = Timer()
    while True:
        timer.set(1000, lambda: print("set_timer called."))

main()

Or, even better, you can have a static class if your workflow allows it:
class StaticTimer:
    last_milliseconds = 0

    @classmethod
    def set(cls, interval: int, function: Callable) -> None:
        milliseconds = round(time() * 1000)

        if milliseconds - cls.last_milliseconds >= interval:
            function()
            cls.last_milliseconds = milliseconds

Which you'd call like this:
def main():
    while True:
        StaticTimer.set(1000, lambda: print("set_timer called."))

main()

The difference between the two classes is that you can't have multiple of the latter because of the class attribute and @classmethod. So even if you made multiple instance of the class, they'd all share that value.


Well, I am not familiar with die, but the obvious improvement is to encapsulate those rules into separate entities. For example:

public interface IRollScoreRule
{
    int CalculateRollScore(IEnumerable<IRollResult<int>> results);
}

public interface IRollScoreRules : IRollScoreRule
{
    bool IsOpeningRoll(IEnumerable<IRollResult<int>> results);
    void AddRule(IRollScoreRule rule);
    void RemoveRule(IRollScoreRule rule);
}

public class ScoreFivesRule : IRollScoreRule
{
    int CalculateRollScore(IEnumerable<IRollResult<int>> results)
    {
        // i think some of this logic can be extracted to base class
        // results.GroupBy(e => e.Value).Where(g => g.Key == 5) part for example
        // is common for most of the rules
        var score = results.GroupBy(e => e.Value)
                        .Where(g => g.Key == 5)
                        .Where(g => g.Count() < 3)
                        .Sum(g => g.Count() * 50);
        return score;
    }
}

Then in your GameRollScoreRules.CalculateRollScore method you can iterate through collection of rules (using IEnumerable.Aggregate, for example) to get the total score, instead of having one huge method.

I also think you might want to tweak the IsOpeningRoll method. I mean, if I understand the use-case from your screenshots correctly, then with every dice roll, you want to know both - score value and if this value is higher then 500. Which means that using your GameRollScoreRules class as it is you would essentially calculate score twice (by calling CalculateRollScore and IsOpeningRoll methods). I think you sould either pass the resulting score to IsOpeningRoll method as a parameter, or remove this method all together and replace CalculateRollScore return type with some complex object (which will contain score value and bool flag) instead.


Can the performance of this canvas drawImage() test be improved?

Edit: Only now did I notice your comment that you require the tiles to be drawn individually. Since I don't know exactly why that is (I can only review the code I can see), I can't offer you any other advice than what I've already written below.
If you can redraw larger rects using a tiling fill style, or only update some tiles per frame, it'll be an improvement over redrawing everything each frame. But if your exact requirements are "redraw every tile by itself on every frame" then your current code is as probably as good as it gets. But the end result is the same as the much more efficient methods outlined below.

Edit edit: Don't know why I didn't think of it sooner, but off-screen drawing could be an improvement. The link provides a nice simple implementation.

You can draw the background using a single rect with a tiling background, and not do any drawImage calls. The technique is outlined in this StackOverflow answer. In its simplest form:

ctx.fillStyle = ctx.createPattern(image, 'repeat');
ctx.fillRect(0, 0, canvas.width, canvas.height);

Here's a demo - it runs at the target 60fps (in Chrome at least).

Alternatively, you could just set the image as a repeating CSS background image, and not do any JS at all. Just:

canvas { background: url(...) repeat; }

And done. Though I won't guarantee how that'll work with whatever you intend to draw on top of it.

In terms of code review, I noticed a couple of things

Single-letter variables - always better to use full words (the exception being known conventions like the i variable in a loop)
Speaking of, you can also avoid the hard-coded values for R, C, W and H "constants". The canvas' width/height you can get as simply canvas.width and canvas.height. Similarly (once the image has been loaded; see below), you can get its dimensions the same way: image.width and image.height.
You can use Date.now() instead of new Date().getTime()
You don't actually wait for the image to be loaded. It's a tiny image, but the network may be slow. So (as shown above), you should wait for the load event to fire on the image object, before trying to use it:

var image = new Image();
image.src = "...";
image.onload = function () {
  // use the image here
};

In general, though, don't expect exceptional performance from canvas. It's good, but it's not compiled code being mainlined to the GPUs in parallel. You're writing in JS - an interpreted language with a single-threaded runtime - doing compositing on top of an already complex view (the web page). Your many calls to drawImage each require the computer to do a lot of extra work - your loop is not a single operation; it's many individual operations and - depending on how smart the browser is, how much hardware acceleration there is, etc. - it takes time to update the screen after each draw.


Find a value between two of the same characters in a string using Python

Rather than using str.find, you could better describe yourself using regex. However it's not that much of an improvement.

For example using the regex _(.+)_ on the basename of the file is all you need. If you think a file extension is going to have an _ then you may need the splitext.

This can get:

from os.path import splitext, basename
from re import search

base = basename(splitext(filename_goes_here)[0])
value = search('_(.+)_', base)
if value is not None:
    value = value.group(1)

If you're using Python 3.6, as noted in the comments by 200_success, you could change the last line to:

value = value[0]


I have code that loops through a column of a dataframe. How can I make this code faster? (Python/Pandas)

Is this what you want?
import pandas as pd

datasetA = pd.DataFrame(
    [
        [
            'ID222'
        ],
        [
            'ID233'
        ],
        [
            'ID2123'
        ],
        [
            'ID233'
        ]
    ], columns = ['ID']
)

datasetB = pd.DataFrame(
    [
        [
            'ID222'
        ],
        [
            'ID233'
        ],
        [
            'ID212355'
        ],
        [
            'ID233'
        ]
    ], columns = ['ID']
)
datasetA["inB"] = datasetA.ID.isin(datasetB.ID)
datasetA.drop_duplicates()

    ID  inB
0   ID222   True
1   ID233   True
2   ID2123  False


Dijkstra's algorithm using a dictionary for the priority queue

A bug

For the shortest path from A to D, your implementation shows [B, A], which is wrong.

Indentation error

while True:
    temp_val = visited[lowest_key]
    shortest_path.append(temp_val)
    lowest_key = visited[lowest_key]
    if lowest_key == start:
        break
    print(shortest_path)

should be indented once to the right; otherwise your code does not compile.

Efficiency

Use the priority queue in order to speed up your implementation:

import heapq

class HeapEntry:
    def __init__(self, node, priority):
        self.node = node
        self.priority = priority

    def __lt__(self, other):
        return self.priority < other.priority

class Graph:
    def __init__(self):
        self.nodes = {}

    def add_node(self, key, neighbours):
        self.nodes[key] = neighbours

    def traceback_path(self, target, parents):
        path = []
        while target:
            path.append(target)
            target = parents[target]
        return list(reversed(path))

    def shortest_path(self, start, finish):
        OPEN = [HeapEntry(start, 0.0)]
        CLOSED = set()
        parents = {start: None}
        distance = {start: 0.0}

        while OPEN:
            current = heapq.heappop(OPEN).node

            if current is finish:
                return self.traceback_path(finish, parents)

            if current in CLOSED:
                continue

            CLOSED.add(current)

            for child in self.nodes[current].keys():
                if child in CLOSED:
                    continue
                tentative_cost = distance[current] + self.nodes[current][child]

                if child not in distance.keys() or distance[child] > tentative_cost:
                    distance[child] = tentative_cost
                    parents[child] = current
                    heap_entry = HeapEntry(child, tentative_cost)
                    heapq.heappush(OPEN, heap_entry)

g = Graph()
g.add_node('A', {'B': 5, 'C': 1})
g.add_node('B', {'D': 2, 'A': 5})
g.add_node('C', {'D': 9, 'A': 1})
g.add_node('D', {'B': 2, 'C': 9})
print(g.shortest_path("A", 'D'))

Note also that we do not need anymore

for node in self.nodes:
    if node == start:
        distance[node] = 0
        queue[node] = 0
    else:
        distance[node] = 1000
        queue[node] = 1000

Think about what happens if the graph is large but the terminal nodes are close to each other: you waste a lot of CPU cycles.

Hope that helps.


Take a specified weekday, and check if it falls on the remaining days of the current month

Calculate the accepted weekdays range for today's week once, then check the input array for any value in the range.

function weekdaysBelongToTheRestOfThisMonth(weekdays) {
    var today = new Date();
    var todayDay = today.getDate();
    var todayWeekday = today.getDay();

    var maxMonthDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    var maxMonthDay = maxMonthDate.getDate();
    var maxMonthWeekday = maxMonthDate.getDay();
    var maxWeekday = maxMonthDay - todayDay > 7 - todayWeekday ? 7 : maxMonthWeekday;

    return weekdays.some(function(d) { return d >= todayWeekday && d <= maxWeekday });
}


Check whether a string has all unique characters (time efficiency)

This is about the most efficient strategy you can get when it comes to uniqueness checking on a string, as far as I know. It can get pretty crazy with memory inefficiency with bigger data types, but it's still O(N) time.

But unless you are specifically dealing with ASCII-only strings, be careful with hardcoding the size of your filter array. Go will try to parse the string into single Unicode code points, also called runes. You can find an example of that here, which explicitly shows how characters can span multiple bytes.

Based on the answer to this SO question, UTF-8 encoding can be anywhere from 1-4 bytes. Using the same strategy, a bool array that handles all 4 possible bytes would be of size 232 = 4,294,967,296

Yikes, over 4GB of almost entirely unused memory. The most memory-efficient way I can think of approaching that would be a 256-way tree, where you track each byte encountered by creating nodes for each byte in the rune, and check for the rune by checking for existence of each node in order.

Is it still linear time? Well, existence is easy because the depth of the 256-way tree is at most 4, given the maximum number of bytes in a UTF-8 character, so we check for at most 4 things, which is constant. Same kind of logic applies to setting node values when we encounter unique runes. Since these are done per rune, it's still O(N), more memory efficient, and handles all UTF-8 characters.

I've actually never worked with Go before, thanks for inspiring me to research a bit :)


Redirection with params - No query string

Using the session to store this is icky, since a user may have multiple tabs open. I.e. multiple searches, but only one that your server remembers.

Anyway, if I understand this correctly, try this:

The first time a user hits the results page, have it pre-populated with results. Don't load anything via ajax; it should already be there. However, the results page should also have a different handler for the user clicking search/submitting the form.

Anywhere else on the site, searching should just send you to the results page. On the results page, however, the search function does its AJAX thing, and fetches the results, replacing whatever's on the page.

Now, to update the displayed URL, use pushState and listen for popState events too, to update the address bar, and keep a "correct" browsing history.

So on your results page, you'll want something like this for your search handler:

function search() {
    // get the search query text
    var query = $('#productSearchInput').val();

    // url for the search page
    var base = 'http://SearchPageUrl';

    // create the new URL to display in the address bar/history
    var url = base + '?query=' + encodeURIComponent(query);

    // fetch results for the new query
    $.get(base, { query: query })
        .done(function (data) {
            // push the url to the address bar/history
            history.pushState({query: query}, "Search results", url);

            // insert new results into the page ...
        });
}

And on any other page, you want no JS. Just a plain GET form pointing at the results page.

Alternatively, if I misunderstood and you don't want queries in the address bar at all, simply do what randcd suggested in the comments: Use POST. Make the search form's method POST, and use $.post() when you need to update results.


Your code, as shown, has a bug in that it will read past the end of the buffer you're computing the checksum for (by either 1 or 2 bytes, depending on if the length is odd or even).  As that is easy enough to fix, I'll assume you make the appropriate changes to the code and move on to answering your question.

If you read over Section 2, paragraphs (B), of the RFC, you'll see that the addition can be done in either byte order.  So rather than using two instructions to byte-swap the two bytes you're reading, just do one (mov ax,[rdi+rcx]).  This will result in the final checksum being byte-swapped, so you'll have to do the swap (xchg al,ah) to get the same value to return from this function.  If you're not doing anything with the checksum other than storing it into the TCP/IP packet, don't swap the return value, and don't swap the bytes when you write them out.

You can remove the cmp r9,0 instruction in the 4 block, as the shr instruction will set the z flag if the new register value is 0.

Now, to expand this method to utilize 32 or 64 bit registers, you can replace the (newly added) mov ax instruction with mov eax or mov rax (with appropriate changes to the value of ecx).  This will need adjustments at the end to shift, add, and handle the carry to collapse the multiple bytes pairs into one, and the carry handling with the 64 bit register will also need to be different (inserting an adc r9,0 after the add r9,rax instruction).  Also, the handling for packets with sizes that are not multiples of 4 (or 8) will need to be added.

Details of this technique are discussed in the RFC.


Write a helper method, e.g.

static Button createButton(Frame f, String label, int x0, int y0, int width, int height) {
    Button b = new Button(label);
    b.setBounds(x0, y0, width, height);
    f.add(b);
    return b;
}

Then your code would simplify to lines like:

createButton(f, "+", 70, 100, 50, 40);

which is a reduction of roughly 2/3.

Of course this does not address the problem that you are trying to do pixel-exact layouts. You should rather be dropping elements on a grid which can be resized freely. (However, it has been a long time since I've used AWT so I can't give an example).


A couple of observations:

You have code that says:

var annotationView: CustomMapAnnotationView?

if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationID) as? CustomMapAnnotationView {
    annotationView = dequeuedAnnotationView
    annotationView!.annotation = annotation
}
else
{
    annotationView = CustomMapAnnotationView(annotation: annotation, reuseIdentifier: annotationID)
    ...
}

In iOS 11 and later, the mapView.dequeueReusableAnnotationView(withIdentifier:for:) can reduce that to a single line:

let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationID, for: annotation)

Your mapView(_:viewFor:) is configuring the annotation views. I’d move that configuration code into the MKAnnotationView implementations for better separation of responsibilities and eliminating cruft from your view controller. For example:

class CustomMapAnnotationView: MKMarkerAnnotationView {
    static let clusteringIdentifier = Bundle.main.bundleIdentifier! + ".c"

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)

        clusteringIdentifier = CustomMapAnnotationView.clusteringIdentifier
        markerTintColor = .orange
        displayPriority = .defaultLow
        collisionMode = .circle
        rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override var annotation: MKAnnotation? {
        willSet {
            clusteringIdentifier = CustomMapAnnotationView.clusteringIdentifier
        }
    }
}

And

class ClusterView: MKMarkerAnnotationView {
    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        displayPriority = .required
        collisionMode = .circle
        markerTintColor = .purple
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

This cleans up your mapView(_:viewFor:) and keeps the annotation view configuration code where it belongs.
Consider your registration of these classes:

mapView.register(CustomMapAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
mapView.register(ClusterView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)

Note, you’re registering these identifiers, so your mapView(_:viewFor:) shouldn’t then use its own reuse identifiers of c and Cluster, respectively.
But the whole point of MKMapViewDefaultAnnotationViewReuseIdentifier, etc., in iOS 11 and later is so that you don’t have to implement mapView(_:viewFor:) at all. So you can comment out that whole routine (now that you’ve moved the annotation view configuration code to the annotation views, themselves, where it belongs).

That having been said, sometimes you need a mapView(_:viewFor:). For example, maybe you need to support iOS versions prior to 11. Or perhaps you have more than three types of annotation types (your main custom annotation, your cluster annotation, and MKUserLocation). But then you wouldn’t register MKMapViewDefaultAnnotationViewReuseIdentifier as the reuse identifier. You’d register your own reuse identifier.

If you do use your own reused identifier, I would have a static property in my annotation view with the preferred reuse identifier, rather than sprinkling hardcoded strings throughout my codebase. E.g.

class CustomMapAnnotationView: MKMarkerAnnotationView {
    static let preferredReuseIdentifier = Bundle.main.bundleIdentifier! + ".customMapAnnotationView”

    ...
}

And

mapView.register(CustomMapAnnotationView.self, forAnnotationViewWithReuseIdentifier: CustomMapAnnotationView.preferredReuseIdentifier)

And

extension ViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        switch annotation {
        case let annotation as CustomMapAnnotation:
            return mapView.dequeueReusableAnnotationView(withIdentifier: CustomMapAnnotationView.preferredReuseIdentifier, for: annotation)

        ...
        }
    }
}

But that’s not needed in your case. You can remove mapView(_:viewFor:) entirely.


Portability
The function strcasecmp() is a POSIX standard and not a in the C programming standard as pointed out in this stack overflow question. Therefore the sort_entries() function may not compile or link on some systems. It would be better if the program that contained the sort_entries() function also contained a version of strcasecmp().

Performance
Generally a bubble sort will be implemented as nested loops, the inner loop going over the whole input list to perform as many swaps as possible in a single pass. This implementation restarts at the beginning after a single swap requiring more passes. There is no performance improvement by this single loop over the nested loop implementation, and there may be a performance hit.

If the code swapped the pointers rather than the strings themselves there might be an improvement in the performance.

Variable Scope
It is better from a maintainability perspective and overall code comprehension to create variables as needed rather than create all the variables at the top of the function. It would be better if the variables t, next and value were defined within the loop rather than at the top of the function. The variables t and next are only needed within the if statement.


Functions to convert camelCase strings to snake_case

A couple of things:

Why 2 functions?
Now that we established (1), you can get rid of the yields.
yield is useful when you want to process stuff in chunks and do not want to wait for the entire population to be created first. This is not the case here.
There are some continues that do make sense and some that are redundant. Yours are of the latter type.
Nested if statements without corresponding else clauses can be merged with and if readability is not reduced.

Putting all that together, we get the following:

def cc2jl(my_str):
  """Camel case to joint-lower"""

  r = my_str[0].lower()
  for i, letter in enumerate(my_str[1:], 1):
    if letter.isupper():
      try:
        if my_str[i-1].islower() or my_str[i+1].islower():
          r += '_'
      except IndexError:
        pass
    r += letter.lower()
  return r

print(cc2jl('m'))                  #-> m
print(cc2jl('AA'))                 #-> aa
print(cc2jl('MySQLDatabase'))      #-> my_sql_database
print(cc2jl('GarbageCollection'))  #-> garbage_collection
print(cc2jl('AAAAAAAAAAAAAAAAA'))  #-> aaaaaaaaaaaaaaaaa

Finally, some thoughts on avoiding the try block that bothers me personally.

We can leverage from the short-circuiting used in Python's logical expressions and (re-)write the following:

def cc2jl(my_str):
  """Camel case to joint-lower"""

  r = my_str[0].lower()
  for i, letter in enumerate(my_str[1:], 1):
    if letter.isupper():
      if my_str[i-1].islower() or (i != len(my_str)-1 and my_str[i+1].islower()):
        r += '_'
    r += letter.lower()
  return r

Note the i != len(my_str)-1 on the left side of the and. If this returns False the my_str[i+1] is not evaluated at all and thus cannot raise the IndexError.


Pythonic way to count if a value is 'NaN' in a dictionary of dictionaries

If you want this to use a comprehension, you need to get the sum of each each in enron_data, where eachs salary is not 'NaN'. As highlighted by the word exercise, you should notice that each is probably not the best variable name for this. Take the following example:

  you need to get the sum of each boat in boats, where the boats cost is not 'NaN'.

Which is easier to read. With Python it's the same, and is why good variable names are advised.

And so you'd want to do:

counter += sum(enron_data[each]["salary"] !='NaN' for each in enron_data)
valid_email += sum(enron_data[each]["email_address"] !='NaN' for each in enron_data)

If enron_data has a function like dict.values, or better dict.itervalues, then you'd want to use that instead. The latter one is simply a version of the former with better memory usage.

And so you could instead use:

counter += sum(each["salary"] !='NaN' for each in enron_data.itervalues())
valid_email += sum(each["email_address"] !='NaN' for each in enron_data.itervalues())

I don't think this approach is that much better than your current, but you could make it a function, to reduce code duplication, but whether it's better ultimately comes down to how you're using it.

But it's definitely better than the answer you provided. There's no need to create a new dictionary, it changes memory usage from \$O(1)\$ to \$O(n)\$, is harder to read, and is slower, as it requires more effort to create a dictionary, then to sum booleans.


Nearest point using 2D tree, static variable for the closest point so far

You're right in sensing there has to be a better way to do this.  Right now, you're setting static fields from within instance methods, which is rarely a good idea.  Luckily, your code is already sufficiently structured that fixing this requires very little work.

Explicitly pass an instance containing a Point2D and double as a parameter in the nearest method.  This keeps your algorithm as it is, but it limits the scope of changes so that they stay within local execution:

private static final class PointDistance {
    // note that these are not static
    Point2D p;
    double d;
}

private void nearest(Point2D p, Node x, PointDistance closest) {
    // replace pointDist with closest here
}

public Point2D nearest(Point2D p) {
    final PointDistance closest = new PointDistance();
    nearest(p, root, closest);
    return closest.p;
}


Interactive Discord bot for tabletop RPG

List Comprehension

Instead of

roll = []
for x in range(0, dice):
    roll.append(roll_die())

do this

roll = [roll_die() for _ in range(0, dice)]

The result is the same, it requires less code, and more pythonic. This also utilizes the _. The underscore is meant to show that the variable in the loop isn't used. This applies to other places in your code as well.

Ternary Operator

Instead of

if (ability < 0):
    keep = 'lowest'
else:
    keep = 'highest'

do this

keep = 'lowest' if ability < 0 else 'highest'

Using a ternary operator can keep you from writing more code, and looks a lot nicer. In this case, it converts four lines into one, which is a big plus.

Direct Returns

You don't have to assign a value inside a function before returning it. In this case, you don't need a dice variable inside roll_die(). You can simply return the call to random.randint. Take a look:

def roll_die(sides=10):
    return random.randint(1, sides)

Using sum

Instead of

sum = 0
for d in outcome:
    sum += d

use pythons built-in sum function

dice_sum = sum(outcome)

The sum functions returns the sum of all the numbers in an iterable. So, you can pass the list used in the loop to that function. It does the same thing you do, but it's already written.


Some things which just jump into my eyes (even if not asked, I'll tell you anyway):

Whitespaces: Use whitespaces were appropriate, f.e. for(int i=0;i<nums;i++) is harder to rad then for(int i = 0; i < nums; i++).
Meaningful names: Name your variables after what they are, not what type they are. This especially includes simple for loops. It might be taught or standard to use i, but I consider it bad practice because you never know what exactly i is at first glance. Give your variables meaningful names, please, they deserve love too! Same goes for your classes.
Split up where appropriate: if you've got only one function (main) you're most likely doing something wrong. Split it into Input, Processing and Output.


I think your hexdump implementation looks pretty good.  I have no immediate comments on the implementation.  I will however comment on the implied requirements.

Hex Dumper Definition

Most hex dumpers that I am familiar with dump hex as a modulo of the stride length.  The example you show implies that, but that is because your example uses n=32, where 32 is an even modulus of the stride length (16).  If you pass in different stride lengths, or pass in an n that is not an even modulus of the stride, the output doesn't (to my eye) look quite as nice.

So I suggest you consider adding another parameter (let's call it base_addr) which is the address of the beginning of the byte array.  And, then also consider adding fill at the beginning of the dump to allow it to align the dump with an even modulus of the stride length.  Such that:

hexdump_gen(byte_string, base_addr=1, n=1, sep='')

Would produce:

00000000        9a 39 81 c2 b5 b9  ce 02 97 39 b5 19 a0 b9  |  .9.......9....|
00000010  ca 02 97 39 b5 19 a0 b9  ca 02 97 39 b5 19 a0 b9  |...9.......9....|
00000020  ca 8c 96 39 fb 89 8e b9  0a 6a b1 39 81 18 84 b9  |...9.....j.9....|
00000030  95 6a b1 39 81 18 84 b9  95 6a b1 39 81 18 84 b9  |.j.9.....j.9....|
00000040  95 6a b1 39 81 18 84 b9  95 6a b1 39 81 18 84 b9  |.j.9.....j.9....|
00000050  95                                                |.               |

One way that could be done:

def hexdump_gen(byte_string, _len=16, base_addr=0, n=0, sep='-'):
    not_shown = ['  ']
    leader = (base_addr + n) % _len
    next_n = n + _len - leader
    while byte_string[n:]:
        col0 = format(n + base_addr - leader, '08x')
        col1 = not_shown * leader
        col2 = ' ' * leader
        leader = 0
        for i in bytearray(byte_string[n:next_n]):
            col1 += [format(i, '02x')]
            col2 += chr(i) if 31 < i < 127 else '.'
        trailer = _len - len(col1)
        if trailer:
            col1 += not_shown * trailer
            col2 += ' ' * trailer
        col1.insert(_len // 2, sep)
        yield FMT.format(col0, ' '.join(col1), col2)
        n = next_n
        next_n += _len

Symmetric parameters

The n parameter is an offset into the bytearray, which specifies where in the bytearray to start the dump.  But there is no equivalent end address.

So currently, the dumper always goes to the end of the byte array.  From a symmetry perspective it would seem a good idea to also provide a terminal condition.


What is the best practice? Would you sacrifice readability for refactoring?

That highly depends on the case. Most of the time I write code for readability. Most of my code reviews here focus more on readability. Only if there's sufficient proof that my code is a bottleneck do I actually refactor it.

So, yes, I prefer your old code. However, it could be done a bit better if you used Promises. It's longer, but avoids callback pyramid. There's a package called BlueBird that converts callback-style APIs into Promises.

save: function (req, res, next) {
  var dao = topicsDaoFactory.create(req.dbSession);

  // Try validating
  validate(req.body.topic, constrainsObj)
  // Listen for validate
  .then(function(){
    return dao.save(req.body.topic);
  }, function(error){
    res.error(error);
  })
  // Listen for dao.save
  .then(function(result){
    res.send(result);
  },function(error){
    res.fail(error);
  });

}


I definitely prefer the second version. The steps taken just "leap out" of the code and the method is easier to read. It will also be a lot easier to debug (or to pinpoint the problem in a stack trace).

Always go for readability, it makes for easier understanding when going back to your old code and it's a lot easier for someone else to understand what is going on.

I also prefer the "data = fillImages(data)" if possible. It makes clear that the data is modified.


Variable names
Variables such as a, b, c, d are meaningless.  Use names with meaning such as position, numChests, chestValues, etc.  Sure, this is just a small program with 8 total variables, but you should get in the habit of producing readable code and not just correct code.
Bug
You don't allocate enough space for your string here:

char *d = malloc(a * sizeof(char));
scanf("%s", d);

Suppose a had value 5, as in the example.  The string "TVTTT" has 5 characters plus a terminating null character, for a total of 6 characters.  So you need to allocate an extra byte for the null character when you call malloc().
Also, it is unsafe to just call scanf() because if the input string happened to be wrong and contain more than 5 characters, you would overflow your buffer.  To be safe, you can use fgets(), which limits the number of characters it writes to your buffer:
char *chestValues = malloc(numChests+1);
fgets(chestValues, numChests+1, stdin);

Note also that sizeof(char) is always equal to 1, so you can omit that.
No need for second loop
You have a second loop to count the number of X in your chest array.  But you could have counted the number of chests found that were T in your first loop and then you wouldn't need the second loop at all.
Sample rewrite
Here is a rewrite of your program which fixes all of the above:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int   numChests   = 0;
    int   position    = 0;
    int   numMoves    = 0;
    int   numFound    = 0;
    char *chestValues = NULL;

    scanf("%d %d %d\n", &numChests, &position, &numMoves);
    chestValues = malloc(numChests+1);
    fgets(chestValues, numChests+1, stdin);

    for (int i = 0; i < numMoves; i++) {
        char direction = 0;
        int  distance  = 0;
        scanf(" %c %d", &direction, &distance);
        for (int j = 0; j <= distance; j++) {
            if (chestValues[position - 1] == 'T') {
                chestValues[position - 1] = 'X';
                numFound++;
            }
            position += (direction == 'E' ? 1 : -1);
        }
    }
    printf("%d\n", numFound);
    return 0;
}


tup = input()[1:-1].split(',')

It's really bad style to require interactive input without the slightest hint about the expected format.

x = input('Enter mapping to generate valid Sudoku eg. 3 for 9 x 9')
e = input('Enter 9 for 9 x 9 ...12 for 12 x 12')
f = input('Enter 3 if its a 9 x 9 and corresponding for n^2 x n^2')

These variable names are horrible. Do not use single-letter variable names unless you are using the exact names as they appear in a mathematical paper. And in that case, always provide a comment that links to the paper.

Why and how did you choose the variable name x?
Why and how did you choose the variable name e?
Why and how did you choose the variable name e?
What is the difference between x and f? For a 9×9 sudoku, both should be 3.
Why do you make the user of the program enter the value anyway? If there's only one valid value, there is no reason to annoy the user with unnecessary questions.

Continuing with your code:

x = int(x)
e = int(e)
f = int(f)

squares = []

for index in range(len(tup)):
  tup.append(tup.pop(0))
  squares.append(tup.copy())

It's unexpected that the code modifies tup here. The code can be written in an alternative form that doesn't modify tup:

for i in range(len(tup)):
    squares.append(tup[i:] + tup[:i])

To give the readers of the code some hints about the structure, you should define separate functions for the different tasks. In this case, these are:

reading the parameters from the input
generating the square
printing the square

By doing this, it becomes immediately clear which parameters are needed for generating the square, and which parameters are only needed for printing it. For example:

def generate_square(symbols):
    square = []
    for i in range(len(symbols)):
        square.append(symbols[i:] + symbols[:i])
    return square

Or, a little shorter:

def generate_square(symbols):
    return [symbols[i:] + symbols[:i] for i in range(len(symbols))]

I did a test run of your program:

1,2,3,4,5,6,7,8,9
Enter mapping to generate valid Sudoku eg. 3 for 9 x 93
Enter 9 for 9 x 9 ...12 for 12 x 1211
Enter 3 if its a 9 x 9 and corresponding for n^2 x n^23
2345678Traceback (most recent call last):
  File "a.py", line 28, in <module>
    main()
  File "a.py", line 24, in main
    print(squares[si][li], end = '')
IndexError: list index out of range

Doing that I noticed:

if I hadn't read the code before, I would not know what to type in the first line
in the second line, in 9 x 93, it is not clearly visible what is the prompt and what is the input. The prompt should end with 3 for 9 x 9:.
there is no input validation. As I said before, if there is only one valid input, the program should not ask for it.
because of the missing input validation, the program crashes.

Next test run:

1,2,3,4,5,6,7,8,9
Enter mapping to generate valid Sudoku eg. 3 for 9 x 93
Enter 9 for 9 x 9 ...12 for 12 x 129
Enter 3 if its a 9 x 9 and corresponding for n^2 x n^23
2345678
5678234
8234567
3456782
6782345
2345678
4567823
7823456
2345678

The program outputs 7×9 digits. That's not a sudoku. There is a bug in the printing part.  This bug is so obvious that it makes your question off-topic on this site. This site is only for code that is regarded as working.


Longest common subsequence (LCS) for multiple strings

Conventions

It's highly recommended to have all imports at the top of your file.
It's not nice for readers to have a different environment than expected.

It's also better to be safe than sorry, so you may want to wrap your global code in a if __name__ == '__main__':.

One-line docstrings by convention have both """ on the same line.
You must be thinking of multi-line docstrings, where the last """ goes on a new line.

Code

checkall

Python has some strong readability conventions.
For example, in checkall you use the not operator after the equals operator.
This is strange, as you could just use the not equals operator.
But in Python if a != 0: is always true and false every time if a: is.
And so it's better to just use if a.

# Using two operators rather than one
if not a == 0:
    ...

# Comparing to value (twice).
if a != 0:
    ...

# What you want to be doing:
if a:
    ...

I like the idea of writing declarative statements from functional programming,
which can really help readability in checkall.

If we were to say what the algorithm is:
Go through the list of strings, if any of them after going through check are true return false, otherwise return true.

Which can be converted to:

def checkall(strings, seq):
    return not any(check(x, seq) for x in strings)

check

A bit of a 'out there' one, even though it's harder to think backward in algorithms, or at least for me.
Changing check to run backwards can improve readability.
Rather than doing n < len(...) you can just do n >= 0.

It's not that big a difference, so you may not want to think about doing it.
But it will save a few cycles on all the lens.

mlcs

poor variable names such as s, make reading a little harder, s is short for string, but could be super, special or soup.
It's much easier to comprehend enumerate(string). In changing it it will also not be hidden in the other one letter variables.

this lead to me not quickly understanding what you are doing in the bits after candidates.

There are other problems, candidates can be put in the for loop, rather than as a function. And you should try to reduce the 8 for-loops that the function has.


Booking validation in a big if-elseif block

Conditionals

isValidEmail != false && isIntPositive != false

I'd make that isValidEmail == true && isIntPositive == true. You could even short these to isValidEmail && isIntPositive. This makes your code more readable AND uses less characters (less that has to be read). It's a win-win.

var isIntPositive = procs.isPositiveInteger(guest.value);
... isIntPositive != false && guest.value > 0 ...

I don't know what isPositiveInteger does, but I have the feeling this check (guest.value > 0) is redundant. If you don't allow 0 then explicitly decline that value with guest.value != 0.

Duplication

You have a lot of message = { ... }. I'd create a separate function that takes the arguments. Then I'd create separate functions for the constants to be wrapped in, so you get things like this:

function createInvalidEmailMessage(){
    return createMessageObject(1, "Error", "Invalid Email Address. Please re-enter valid Address!");
}
function createMessageObject(ref, title, text){
    return {
        "ref": ref,
        "title": title,
        "text": text
    };
}


Consider using two variables — an x and a y component — to store the direction.  The left and right turns are based on cross product principles.

Then, each forward move can be done using unconditional additions with no modulo operations.  An additional advantage is that the meaning of the direction is self-evident.  (It's not immediately obvious what direction = 1 would mean in your code.)

import java.util.Scanner;

public class CartesianAgent {
    public static void main(String[] args) {
        int x = 0, y = 0;
        int dx = 0, dy = 1;

        Scanner scanner = new Scanner(System.in);
        System.out.print("Introduce the command: ");
        String command = scanner.nextLine();

        for (int i = 0; i < command.length(); i++) {
            switch (command.charAt(i)) {
              case 'l':
                int old_dx = dx;
                dx = -dy;
                dy = old_dx;
                break;
              case 'r':
                old_dx = dx;
                dx = dy;
                dy = -old_dx;
                break;
              case 'f':
                x += dx;
                y += dy;
                break;
            }
        }
        System.out.printf("Result: [%d,%d]%n", x, y);
    }
}

Alternatively, store the direction as a single integer, and use lookup tables to decode it.

According to the convention you chose, direction = 0 points up (in the +y direction), and turns left as direction increases (assuming a standard Cartesian grid that follows the right-hand rule).  I consider that to be weird.  You should either use

direction = 0 points up, then turns clockwise as direction increases (like navigation headings), or
direction = 0 points to the right (in the +x direction), then turns counterclockwise as direction increases (like polar coordinates).

The modulo operation should be done when turning, rather than when advancing.

import java.util.Scanner;

public class CartesianAgent {
    private static final int[] DX = {  0, +1,  0, -1 },
                               DY = { +1,  0, -1,  0 };

    public static void main(String[] args) {
        int x = 0, y = 0, direction = 0;

        Scanner scanner = new Scanner(System.in);
        System.out.print("Introduce the command: ");
        String command = scanner.nextLine();

        for (int i = 0; i < command.length(); i++) {
            switch (command.charAt(i)) {
              case 'l':
                direction = (direction + 3) % 4;
                break;
              case 'r':
                direction = (direction + 1) % 4;
                break;
              case 'f':
                x += DX[direction];
                y += DY[direction];
                break;
            }
        }
        System.out.printf("Result: [%s,%s]%n", x, y);
    }
}

Printing the result using System.out.printf() is a bit more readable than concatenating the string using +.


Review points:

removeFirst on an empty list should be a no-op, (or throw an exception).
last was dangling.
Setting things to null of the removed first node, is not done in OOP, is
left to the garbage collection. This also removes the need for an extra variable. And the resulting binary code is smaller.

So:

public void removeFirst() {
    if (first != null) {
        if (first == last) { // Either this.
            last = null;
        }
        first = first.next;
        if (first == null) { // Or this.
            last = null;
        }
    }
}

One can only remove the first, when there is one.
Then the last might be the biblical first.

This is for the single linked list, where a node has just one next pointer.


Laravel function to add a supplier, and associated addresses and contacts

You could use events for triggering these kinds of things, but there is a danger that your code starts to become harder to follow. Martin Fowler gives a good top-level talk on it here.

There are two issues jumping out at me:

Firstly, your method accepts a request object so there is no indication as to what the requirements of that method are. You could change the method to accept specific arguments such as $created_by, $address_details, etc. This would make it easier to re-use the code elsewhere if needed.

I would make the controller then responsible for preparing that set of data (e.g. handling the preparation of the address details array, getting the 'created_by' etc). And make your addSupplier method work with a set of arguments that could be run from anywhere in your app.

public function addSupplier ($primary_contact_details, $contact_addresses, $created_by = NULL) {
    // ADDING THE SUPPLIER BASIC INFO
    $supplier_fillable_values = array_merge(
        $primary_contact_details,
        ['created_by' => $created_by]
    );
    $new_supplier = Supplier::create($supplier_fillable_values);

    // ADDING THE SUPPLIER ADDRESSES AND THE ADDRESS CONTACTS
    foreach ($contact_addresses as $address) {
        // ADD ADDRESS
        $new_supplier_address = $new_supplier -> addresses() -> create([
            'address'       => $address['address'],
            'created_by'    => $this -> getAuthUserId()
        ]);

        // ADD ADDRESS CONTACTS
        foreach ($address['contacts'] as $contact)
            $new_supplier_address -> contacts() -> create([
                'name'          => $contact['name'],
                'phone_number'  => $contact['phone_number'],
                'created_by'    => $this -> getAuthUserId()
            ]);
    }

    return $request -> address_contact_inputs;
}

Secondly, it's good practise to avoid too many levels of indention, so you could  refactor to use one level of indentation and splitting out the foreach loops to their own public/private methods on the same class.