Here is a rewritten version of your sum which incorporates some techniques which improve performance, numeric stability and the accuracy of the final result.

The two multiplicative terms (the power of x and the factorial) are combined into a single accumulated value (the variable named "term").  Obviously, for larger x, the two separate values grow rapidly, quickly surpassing the capacity of their types.
But the combined term (power / factorial) is well-behaved for a much broader range of input values, usually going to zero as iterations accumulate.
Each iteration of the loop corresponds to one term in the summation.  There is no fundamental reason for each iteration to correspond to each integer power of x. For this particular series, the term's power of x goes up by 2, so I precompute the square of x in order to do this with a single multiplication.  This also gets rid of that awkward conditional inside the loop (if(i%2==0)) (probably optimized away by the compiler, but still best to be rid of it).
The last trick automatically determines the iteration count by comparing this iteration's updated sum (the variable next_sum) with the last iteration's sum (the running sum variable).  If the sum hasn't changed, it stops iterating and returns that value.  This technique causes problems in several situations, however and cannot be universally relied upon.  For example, some series don't sum monotonically to a limit -- the sum will bounce around it, and the summation's state can end up oscillatory forever. Also, this relies on a fixed-precision data type (like float or double). In general, more work should probably be put into deciding when the sum's precision is acceptable and no further iterations need to be calculated. But, this trick is so super-cheap and easy to implement and it is usually so good at detecting the best final result that I include it here, but use it at your peril.

#include <iostream>
#include <iomanip>

int main() {
    float x;
    std::cout << "\nENTER x: ";
    std::cin >> x;

    std::cout << std::setprecision(9);

    const float x_squared = x * x;
    float sum = 0;
    float term = 1;
    for(int i = 2;; i += 2) {
        term *= x_squared / (i * (i - 1));
        const float next_sum = sum + term;
        if(next_sum == sum) break;
        sum = next_sum;
        std::cout << std::setw(2) << i << ": " << sum << "\n";
    }
    // std::cout << ">>  " << sum << "\n";
}

Here are some results.  I changed the code to dump the term's x exponent and the running sum at each iteration, rather than dumping the exponentiated x.

The original version and my version dump the same figures when given an input value of 1.2:

ENTER x: 1.2
 2: 0.720000029
 4: 0.806400061
 6: 0.810547233
 8: 0.810653865
10: 0.810655594

For an input value of 10, Wolfram says we should get about 11012.232920...
But with 10, the original code has problems (I went ahead and set the max iterated power to 30, just to see where things end up).

ENTER x: 10
 2: 50
 4: 466.666656
 6: 1855.55554
 8: 4335.71436
10: 7091.44629
12: 9179.12207
14: 87368.5547
16: 5076917.5
18: -1.1079721e+009
20: -4.86787072e+010
22: -1.91795581e+013
24: -1.30792867e+015
26: -5.52487843e+016
28: -7.32410864e+018
30: 7.02255016e+020

My version (For an input value of 10, it stops at a max x power of 30):

ENTER x: 10
 2: 50
 4: 466.666656
 6: 1855.55542
 8: 4335.71387
10: 7091.44531
12: 9179.12109
14: 10326.1953
16: 10804.1426
18: 10960.335
20: 11001.4385
22: 11010.335
24: 11011.9463
26: 11012.1943
28: 11012.2275
30: 11012.2314

And this is very close to Wolfram's cosh(10)-1, given the precision of a 32-bit float.


An Express route, which renders a page, and makes use of socket.io

Linting

The code reads well.

There is one convention you missed: use \s to indicate whitespace.

const encode = name => {
    return name.replace(/ /g, "+");
};

const encode = name => {
    return name.replace(/\s/g, "+");
};

And the else below is redundant.

if (await api.data[0]) return await api.data[0];
else return { name: [], quote: [], deathCount: [] };

if (await api.data[0]) return await api.data[0];
return { name: [], quote: [], deathCount: [] };


Your reverse, and swapCase functions are good. The native use of runes is great, and the functions are clear, etc. If I was to really nit-pick, I would suggest a real function (instead of an anonymous) for the switch statement.

func swapRuneCase(r rune) rune {
    switch {
    case unicode.IsLower(r):
        return unicode.ToUpper(r)
    case unicode.IsUpper(r):
        return unicode.ToLower(r)
    }
    return r
}

That makes it clearer, and potentially, later, reusable.

It also makes the swapCase function look like:

func swapCase(s string) string {
    return strings.Map(swapRuneCase, s)
}

Interestingly, it also leads to a more rune-based server handler function...

Here's your function:

func handleServerConnection(c net.Conn, i int) {
    for {
        // scan message
        scanner := bufio.NewScanner(c)
        for scanner.Scan() {
            msg := scanner.Text()
            log.Printf("Client %v sends: %v", i, msg)
            msgNew := swapCase(reverse((msg)))
            c.Write([]byte(msgNew + "\n"))
            log.Printf("Client %v receives: %v", i, msgNew)
            fmt.Println("---")
        }
        if errRead := scanner.Err(); errRead != nil {
            log.Printf("Client %v disconnected...", i)
            fmt.Println("---")
            return
        }
    }
}

That function is doing too many things .... hmmm actually it's just got a useless outer loop. The "scan" loop is all you need. The scanner.Scan() will only terminate the loop when the connection is closed (the c Reader returns an error - presumably EOF, but any other error has the same consequence... c is not readable). So, remove the outer loop, and, we know that the scanner will return an error too, so the condition at the end is not useful. This leaves:

func handleServerConnection(c net.Conn, i int) {
    // scan message
    scanner := bufio.NewScanner(c)
    for scanner.Scan() {
        msg := scanner.Text()
        log.Printf("Client %v sends: %v", i, msg)
        msgNew := swapCase(reverse((msg)))
        c.Write([]byte(msgNew + "\n"))
        log.Printf("Client %v receives: %v", i, msgNew)
        fmt.Println("---")
    }
    log.Printf("Client %v disconnected...", i)
    fmt.Println("---")
}

Note that the fiddling you do with the newline is necessary because you can't "reverse" it too.

Your mixing of both log and fmt in things like log.Printf and fmt.Println is confusing. Use one of them, not both. log is probably the better option. Also, you should be adding \n to the fmt.Printf format strings (you don't need to do that for log.Printf - but you can if you want). There's too much logging! You're not inspecting the error value for Write(...), and you're not closing the Conn which will lead to "CLOSE_WAIT" sockets in the OS network stack. In general, though. I would rationalize it all down to:

func handleServerConnection(c net.Conn, i int) {
    defer func() {
        if err := c.Close(); err != nil {
            log.Printf("Closing client %v connection returned error: %v\n", i, err)
        }
    }()

    // scan message
    scanner := bufio.NewScanner(c)
    for scanner.Scan() {
        msg := scanner.Text()
        msgNew := swapCase(reverse((msg)))
        if _, err := c.Write([]byte(msgNew + "\n")); err != nil {
            log.Printf("Client %v has closed writer: %v\n", i, err)
            break
        }
        log.Printf("Client %v\n received: %v\n returned: %v\n", i, msg, msgNew)
    }
    log.Printf("Client %v disconnected...\n", i)
}

Right, that's it for the handler function.

Your main function is structurally OK, but you MUST check the error state from the Listen call:

ln, _ := net.Listen("tcp", ":9999")

By ignoring the error, if you start your program twice, the second program will panic with a nil pointer reference on the ln.Accept() call (since ln will be nil)

That Accept() call should also have it's error checked too!

Again, using both log and fmt is confusing.

In general, you should specialize your network services/processes when you can. You use net.Listen and ln.Accept when you should probably use ListenTCP and AcceptTCP (you get a TCPListener instead of a Listener) - and your connection is a TCPConn and not a Conn (you should change the parameter type on the handler function too).

Your client side has similar issues, but I think you can figure them out as you go based on the above.


Matching a type T to a list of case statements

I don't think returning the artificial false_ in case of no match is a good idea. Just return nothing, and you won't need false_ at all. Replace

: std::conditional<match<T, Key>, Value, false_>

with

: std::enable_if<match<T, Key>, Value>

It's interesting that while you support an explicit default-case, the last case is always treated as the default case anyway, if it isn't the only case. Oops?

template<class T, class Key, class Value, class _, class Else>
struct switch_<T, case_<Key, Value>, case_<_, Else>>
:
        std::conditional<match<T, Key>, Value, Else>
{};

By the way, if you restrict the default-case to being the last case, which you should consider doing anyway, you can replace match with std::is_same and some changes to switch_, making default_ its own class-template. Might be worth it.

What I failed to find is any way to avoid the recursion, sorry. I hope you can make good use of my feedback anyway.

Modified code:

namespace meta {

// Only for the example-program:
template<auto N>
using int_c = std::integral_constant<decltype(N), N>;

template<class Key, class Value>
struct case_;

template<class Value>
struct default_;

template<class T, class... Cases>
struct switch_
{
    static_assert(!sizeof...(Cases), "this meta::switch_ is malformed");
}

template<class T, class Value>
struct switch_<T, default_<Value>>
: std::enable_if<true, Value>
{}

template<class T, class Key, class Value, class... Tail>
struct switch_<T, case_<Key, Value>, Tail...>
: std::conditional_t<std::is_same<T, Key>(),
    std::enable_if<true, Value>,
    switch_<T, Tail...>>
{}

template<class T, class... Cases>
using switch_t = typename switch_<T, Cases...>::type;

}   // namespace meta


Writing a reusable method in which only some of its parameters are different

What you're looking for is an Optional Argument. When using optional arguments, you have to supply a default value. So, you just have to check for that default value, and switch your control flow appropriately. It would look something like this. (Note I used empty quotes because String.Empty isn't a constant expression.)

private string FindFullRowForProvider(string id, string lastName, string firstName, string devSystem = "")
{
    //maybe some code here

    if (devSystem == String.Empty)
    {
        //handle that case
    }

    //maybe some more code here

}

But... this is Code Review after all, so let's take a look at what you've done.

private string FindFullRowForProvider(string id, string lastName, string firstName, string devSystem)

I'm making an assumption that id is tied to lastName and firstName,  but it looks like you're missing a class in your design. Creating a Person class would simplify the signature an awful lot. Be wary of passing lots of strings to a method.

private string FindFullRowForProvider(Person somePerson, string devSystem = "")

I like your use of String.Empty. I really do prefer it over empty quotes. I think it makes for nice readable code. Well done.

string fullRow = string.Empty;

Maybe I'm missing something, but I think declaring a character array for delimiter is overkill here.

char[] delimiter = new char[] { '|' };
int columnLocation = 0;

string[] columnheaders = streamreader.ReadLine().Split(delimiter);

I'm not very good at C#, so there may be an even simpler way, but you could certainly just split it like this.

string[] columnheaders = streamreader.ReadLine().Split(new char[] { '|' });

Nice use of brackets and formatting here.

        if (npi.Trim().ToUpper() == _NPI.Trim().ToUpper()
            && _LName.Trim().ToUpper() == lastName.Trim().ToUpper()
            && _FName.Trim().ToUpper() == firstName.Trim().ToUpper()
            && _dev.Trim().ToUpper() == devSystem.Trim().ToUpper())
        {
            // woot! we found the row of this guy.
            return fullRow;
        }


CSS attribute Selector: responsive grid performance

You should do neither.  Not for performance reasons, but for semantic and maintenance reasons.  Having class names that reflect what the element looks like is an extremely popular anti-pattern.  It's convenient in the here and now, but every single instance of these classes in your markup will need to be changed when your design changes.

Related reading:  http://www.kapowaz.net/articles/cargo-cult-css

Furthermore, the concept of phone/tablet/desktop styles is extremely narrow thinking and is rarely appropriate for any design.

Related reading: http://bradfrost.com/blog/post/7-habits-of-highly-effective-media-queries/


About handling data from an API call through RX and Retrofit

Let me start by saying I am by no means an expert in Rx. I have no authoritative references to back up my suggested improvements. They come from the little experience I have, as well as some statements in articles from memory. Do no consider my suggestions as "A is bad and B is good so always use B" and only take them into consideration if you agree they are actual improvements.

It makes little sense for a retrofit api call to be represented as an Observable. An api call either succeeds with 1 item (the response) or it errs. Rx has a great match for this: Single. There might be exceptions to this but I do not know of any. If anyone does, please let me know. I would suggest you change the method signature to Single<List<Fruit>> getFeaturedFruits()
The scheduler on which an operation should run should be decided by the component that does the actual operation. subscribeOn should therefore be in the fruitsRepository.getFeaturedFruits. It might look like this

Single<List<Fruit>> getFeaturedFruits() {
    fruitsApi.getFeaturedFruits()
            .subscribeOn(Schedulers.io())
}

In case you have an observable that only emits 1 item and then completes, which is the case if you have a retrofit api call wrapped in an obserable, it makes little sense to implement onComplete in the subscriber if you already implemented onNext and onError. onComplete is more commonly used when you have a hot observable can emit multiple items and you don't know how many there might be. If you use a Single instead, you don't even have to think about this because there is only success or error, no next and complete.
You have if (view.isLost() return; in every callback. This seems like you might not be disposing of the observables properly. I don't know what .isLost() is doing, but consider instead having the view tell the presenter when it is "lost" and have the presenter clean up the compositeDisposable when that happens.
Use lambdas. Especially when using Rx where you use anonymous classes all over the place, they will greatly reduce the lines of code and (debatable) readability of the Rx chain. In recent versions of the android sdk the lambda notation is supported natively, otherwise you can use "retrolambda". This will let you reduce

.subscribe(new Observer<UniversalResponse<Fruit>>() {

    @Override
    public void onSubscribe(Disposable d) {
    }

    @Override
    public void onNext(UniversalResponse<Fruit> universalResponse) {
    }

    @Override
    public void onError(Throwable e) {
    }

    @Override
    public void onComplete() {
    }
}

to something like

.subscribe(disposable -> {}, universalReponse -> {}, e -> {}, {})

If you were to use a Single and just handle the success and error callbacks, you don't have void onSubscribe(Disposable d) from where you can add d to the compositeSubscription anymore. However, the .subscribe() call returns a disposable that you can handle the same way:

compositeDisposable.add(getFeaturedFruits().blabla.subscribe());


Align text (left, center, right) without additional packages

Welcome to Perl, and to Code Review :)

There are a couple of things that could be improved:

It's good that you use strict. I recommend that you also use warnings.
If you are using any recent Perl (say, anything since v5.10.1), then you can gain access to many convenient new features. You can do this by either specifying a minimum version (such as use v5.10) or by explicitly asking for a feature (use feature 'say'). The say feature is exactly like print, but appends a newline automatically.
Please do not use here-docs like <<END. Always make it clear whether the here-doc behaves like a double-quoted string <<"END" or like a verbatim section <<'END'. Omitting quotes around the end marker behaves like double quotes, and can lead to bugs. Use single quotes if you don't want Perl to touch the string contents.
Avoid the $_ variable whenever possible. Instead, use a variable with a good name such as $unaligned_text. As an aside, do not declare a $_ variable with my. This is currently still allowed, but will probably be forbidden in upcoming versions of perl:

  $_ is by default a global variable. However, as of perl v5.10.0, you can use a lexical version of $_ by declaring it in a file or in a block with my. […] Though this seemed like a good idea at the time it was introduced, lexical $_ actually causes more problems than it solves. If you call a function that expects to be passed information via $_, it may or may not work, depending on how the function is written, there not being any easy way to solve this. Just avoid lexical $_, unless you are feeling particularly masochistic. For this reason lexical $_ is still experimental and will produce a warning unless warnings have been disabled. As with other experimental features, the behavior of lexical $_ is subject to change without notice, including change into a fatal error.

  – from perldoc -v '$_'

If you want to match any whitespace character in a regex, consider using the \s charclass rather than [ \t]. In this case, [ \t] may be preferable, but it will not match Unicode whitespace.
Unless needed, do not put regexes into separate variables. Rather, specify them in-place. If you do put a regex object into a variable (which here makes sense, as you are reusing it), use a proper name, such as $match_line.
Some regex modifiers change how a regex is compiled, others how a regex is matched. When creating a regex object with qr//, it is compiled. The /m flag changes the behaviour of the ^ and $ regex operators. By specifying this flag at the place of matching, you may be triggering multiple recompilations, slightly degrading performance. Instead: my $match_line = qr/.../m. The /g and /e flags change how matching and substitutions work, so they can't be used with qr//. For more information, see Regexp Quote-Like Operators in perldoc perlop.
Instead of matching and changing each line, consider splitting the input into an array of lines. Then loop over each line and apply the required transformation. Afterwards, join the lines together again. This happens to avoid all that hassle with regexes.
If an invalid alignment is passed, then you should throw an error rather than returning the input unaligned. I recommend you prefer the Carp module over the builtin die and warn.

Here is your align function, as I would write it.

sub align {
    my ($text_to_align, $alignment) = @_;
    my @lines = split /\n/, $text_to_align;

    # Trim whitespace, and find the longest line.
    # This is an OK use-case for the $_ variable.
    my $max_length = 0;
    for (@lines) {
        # I prefer \A and \z over ^ and $ because they always match at
        # string beginning and end, and are never influenced by /m.
        s{\A\s+}{};
        s{\s+\z}{};
        $max_length = length if length > $max_length;
    }

    # Perform the alignment, depending on the alignment type.
    # The alignment is performed in-place.
    if ($alignment eq 'left') {
        for my $line (@lines) {
            my $padding = $max_length - length $line;
            $line .= " " x $padding;
        }
    }
    elsif ($alignment eq 'right') {
        for my $line (@lines) {
            my $padding = $max_length - length $line;
            $line = (" " x $padding) . $line;
        }
    }
    elsif ($alignment eq 'center') {
        for my $line (@lines) {
            my $padding = $max_length - length $line;
            # we divide the $padding into two halves: $left and $right.
            # But what if $padding is an odd number?
            # Let's put the smaller padding $left.
            my $left = int($padding / 2);
            my $right = $padding - $left;
            $line = (" " x $left) . $line . (" " x $right);
        }
    }
    else {
        # this happens if an invalid $aligment was passed as argument.
        # Let's throw an error. We could use `die`, but that doesn't tell
        # an user of our function where *he* made an error. Instead, we use
        # the Carp module:
        require Carp;
        Carp::croak("Alignment must be one of left, right, center.");
    }

    # join the lines back together again, and return
    return join "\n", @lines;
}


In your main() function there is a while loop (while (!finish)) and in the first few lines of that there are a lot of printf() calls. Replace all of those printf's with this one line:

printf("[%s@%s] %s $ ", user, hostname, cwd);

It is easier to read that way, and with non optimising compilers is slightly more efficient.

Additionally, your main() function contains a lot of strings with vsh in them. I recommend you replace this:

printf("vsh: allocation error\n");

with this:

printf("%s: allocation error\n", argv[0]);

That will make sure that you can more easily change the name of your shell if you want to in the future. In functions other than main() the bother of passing argv[0] may be more than it is worth, though.


Algorithm to generate this alignment pattern locations table for QR codes

I don't think such algorithm exists, because I looked quite hard and couldn't find it. It seems you have to follow the given table. Your formula approximates it pretty well. Too bad about the magic branch, but this shouldn't be a major concern anyway:
it's a small table that you only need to calculate once and can reuse later,
so any performance issues should be negligible in practice.

Coding style

The coding style can be improved.
Follow PEP8, the official coding style guide of Python,
for example, put 2 blank lines in front of top-level method definitions

Unnecessary parentheses

The parentheses around the multiplication are unnecessary here:

w = 21 + ((ver - 1) * 4)       # Width

It would be better to use more meaningful variable names,
for example no need to shorten version as ver.

Unnecessary parentheses here:

if (w == 145):

The augmented assignment operator +=

Instead of:

    intervals = intervals + (intervals % 2)

This is better:

    intervals += intervals % 2

Use one statement per line

Break the line after :, for example instead of:

for m in (n-1) * [intervals]: xs.append(xs[-1] - m)

Write like this:

for m in (n-1) * [intervals]:
    xs.append(xs[-1] - m)

Avoid code in the global namespace

Move code out of the global namespace into methods, so instead of this:

for n in range(2, 41):
    print("Version {:2d}: {}".format(n, pattern(n)))

Do it this way:

def main():
    for n in range(2, 41):
        print("Version {:2d}: {}".format(n, pattern(n)))

if __name__ == '__main__':
    main()


Filtering the attributes for a custom tag

From a code review perspective, I'd say:

The function, "passthrough", is doing two things and doesn't describe what it does very clearly. I'd suggest two functions here, "filterAttributes" and "structToQueryString" (or whatever their exact purpose is)
The long filter logic could be concisely expressed as a regular expression to avoid the long line of logic ("^((data|ng)-|on)")
As for scoping closure arguments, I'd suggest this was a matter of preference. If the coding guidelines you work with ask for all variables to be scoped, then yes, they should be scoped. I personally find it more readable to not have them. Having small and concise functions should help prevent scoping issues.

Overall, I find the example without closures more readable, but the feedback above would make it more so IMO. Here's how it could look with closures:

struct function stripNonDataNgAndJsAttributes( required struct attributes ) {
    var patternToKeep = "^((data|ng)\-|on)\S";

    return attributes.filter( function( key, value ){
        return key.findNoCase( patternToKeep );
    } );
}

string function structToQueryString( required struct input ) {
    return input.reduce( function( result, key, value ){
        return result & ' #key.lCase()#="#value.encodeForHTMLAttribute()#"';
    }, "" );
}

http://trycf.com/scratch-pad/gist/d6ce9527fa3294b286cc


Implement total savings function on a record type

Yes, there are, indeed, a couple of code smells.

The first one is that TotalSavings is a type member, and not a function ;)

The other code smell is that you have the beginning of arrow code in your implementation.

I'd write it like this instead:

let totalSavings summary =
    let (ProvidersCharged charged) = summary.ProvidersCharged
    let (InsuranceSavings savings) = summary.InsuranceSavings
    charged - savings

Notice that you don't have to use the match keyword when doing pattern match. With single-case discriminated unions, you can also pattern match directly into let-bound values.

Normally, the brackets aren't necessary, but in this case they are, because e.g. ProvidersCharged is both a case constructor and a record label. If the case constructor had been unambiguous, you could have omitted the brackets, like this:

let Foo foo = bar

You can also pattern match directly in function arguments, but in this case, it becomes too verbose:

let totalSavings' { ProvidersCharged = ProvidersCharged charged; InsuranceSavings = InsuranceSavings savings; Claims = _ } =
    charged - savings

Notice how the record labels are automatically destructured here, using nested pattern matching: matching is done first on the record labels, then on the case constructors inside of the labels.

You'll also notice that I used a wildcard match on Claims because I don't care about that value.


Declaring arrays knowing their maximum size

Interesting question,

first off, you are worrying about the wrong things. Even if the first approach provides some better performance, (which I think unlikely), it would be premature optimization.

The right way would be simply:

var marks = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = marks[3];

Now, from a memory perspective, I am pretty sure that the only thing happening with new Array(6); is the setting of length to 6. It does not mean that memory is allocated. If you think about that, assigning memory would be silly because JS does not know what you will put in that array, it could be an integer or it could be a really long string, or a function or an object, you get the point..

My advise is to code in an idiomatic way, simply expressing what needs to be done.


I would define domain specific error classes like so:

module Lockable
  Error           = Class.new StandardError
  AlreadyLocked   = Class.new Error
  AlreadyUnlocked = Class.new Error

  def lock!
    raise AlreadyLocked if locked?
    @locked = true
  end

  def unlock!
    raise AlreadyUnlocked unless locked?
    @locked = false
  end

  def locked?
    # unless already defined, this assumes an
    # initial unlocked state (!!nil == false)
    !!@locked
  end
end

By having a common ancestor (LockedError), users can simply catch that one if they don't care about the inner state of the lockable object:

begin
  house.lock!
  house.lock!
rescue Lockable::Error
  # meh...
rescue StandardError
  # $! needs handling
end

On the other hand, if I try to lock an already locked lock, the key just won't move (and the lock doesn't blow up in my face). So, a more realistic reflection of the world would be this implementation:

module Lockable
  def lock!
    @locked = true
  end

  def unlock!
    @locked = false
  end
end


Pruning unwanted columns from a selected row

response is an implicit global, which is a no-no. Now, I imagine it is declared in a wider scope already, but it's still disconcerting to see a function have such crass side-effects. It just overwrites the entire response variable (but if other functions have their own references to the previous value, they won't know about the overwriting).
I'd use a callback or a promise to "return" a fresh object, and let some other piece of code deal with whether to redefine response.
Your find call can be reduced to keys.find(e => key === e) - you don't need braces or return for one-line statements, or parentheses around a single parameter. But the more conventional way to do things is using indexOf. I.e.

if(keys.indexOf(e) !== -1)


Your code is horrible:

You don't check for end-of-file, which will lead to endless loops
You don't check for failure of malloc or realloc
You call realloc way too often, which makes the code slow for large lines of input
You cast the result of malloc
You use the outdated style of function definition from the 1980s
The variable string is not a string but points to an array of pointers to strings, which is confusing
The #include for size_t is missing
Using [0] instead of * is extremely confusing
There is no need to initialize keystroke to a space character
The parameter size is useless since the only possible value that makes sense for it is 0
The return type of the function is implicitly int, which is obsolete
The returned value is of type size_t, which doesn't fit into an int and additionally differs in signedness


Angularjs alertservice and alertscontroller

So far, your code looks good. But here's some suggestions.

It's usually overkill to pull out success and error callbacks. You can simply inline them. Also, if you happen to have ES6 available via transpiler or if you just don't care about older browsers, by all means use it. It makes the code a lot shorter.

return $http.post('/api/payment', {
  id,
  paymentMethod,
  numberOfInstallments,
  creditCard,
  pin
}).then( _ => {
  alertService.success('Payment confirmed.');
}, _ => {
  alertService.success(response.data);
});

Angular also allows for implicit dependencies. Instead of an array of dependency names and a function at the end of the array, you can simply provide a function whose arguments are the name of the dependencies. Saves you keystrokes.

app.service('PaymentService', ['$http', 'AlertService', function ($http, alertService) {...}]);

app.service('PaymentService', function($http, AlertService){...});


Spring MVC @ControllerAdvice exception handling

Your approach seems well written and structured code-wise. However I feel that there is room to improve the structure of the application and the separation of concerns among the classes thus producing a more SOLID result.

My biggest concern is with the web-layer (The Controllers)having to deal with SQL related errors. You do not really describe how your application is structured, but I believe you have your logic implemented within the Controller methods.

If you enclose the application logic in a service class (e.g. UserService) there you could perform data validation and exception handling on the incoming request. For example you should check that the user exists before trying to run update queries that result in an Exception being thrown. You could then throw a custom ResourceNotFoundException with the custom message your ErrorServiceMessage generates and have your ControllerAdvice ExceptionHandler just wrap this to a ResponseEntity.

By hard coding your index names into your error handling classes. then you make it more error prone. What will happen if someone renames the Index? Additionally every time a new Index is being added you would then have to update the generate1452SqlExceptionResp method.

I hope you find my comments useful and thought provoking.

Best Regards


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

Use a switch instead of long if ...else chain

The pattern matching logic is much easier to see if a swtich statement is used instead of the long if...else chain.  The default case can then be used solely for the non-pattern characters and a relatively short if...else chain would go there.  On my machine, this also makes the code slightly faster.

Use longer, more meaningful names

Names like n and N are not very descriptive.  Instead, you might use capturegroup and groupnum.

Use const where practical

The strings should not be altered by the search and the captured array c is simply a list of pointers into the string.  For that reason, I would advise changing the signature of the function to this:

int globSearch(const char *pattern, const char *str, const char **capture)

Consider checking for NULL pointers

If speed is the primary consideration and if the caller checks, you don't need this, but I'd normally recommend having the called function check for NULL pointers before attempting to dereference them.

Differentiate between '(' and ')'

Right now, your program produces the same output for this pattern:

char *m = "(hello) (*)(?*?)?(?)?(*)(*)";

as this pattern:

char *m = ")hello) )*))?*?)?)?)?)*))*)";

Maybe that's OK, but it also produces the same for this pattern:

char *m = "(hello) (*((?*?)?)?)?(*)(*)";

That's a problem because it appears to those familiar with regular expressions that this is pattern contains nested capture patterns, which is not how the code actually interprets the string.

Consider changing the interface

Instead of an array of pointers, it might be more useful to have pointers and counts.  Otherwise, any time the values are returned, you'll have to do things like this:

int z = c[x + 1] - c[x];
memcpy(tmp, c[x], z);
tmp[z] = 0;
printf("%s:%d\n", tmp, z);

Pass the size of the array of pointers

Any time you pass an array to a function, you should either use a sentinel value (such as the terminating '\0' character to mark the end of a string) or pass a size with the pointer.  Otherwise, the called routine has no way to assure that it won't overrun the end of the array.

Avoid buffer overflow vulnerabilities

I realized it's just demo code, but any time you use memcpy it's important to make sure that the destination buffer has enough space for the number of bytes being copied.  That's the case here with these particular fixed strings, but it's better generally to dynamically check that at runtime, especially when the length parameter is not a constant.

Eliminate the return 0; in main

For many years, the C standard has specified that the compiler must automatically generate the equivalent of return 0; at the end of main so there is no reason to specfically include it manually.


Searching JSON recursively for an item with a "selected" attribute

Initially, I considered suggesting using Array.filter() but then that wouldn't allow breaking out of the loop once a selected item was found.

One approach is to use Array.some() or Array.find() (and disregard the return value) with a ternary operator. A variable can be initialized as the first line, then the .some() callback returns the result of setting that variable to either the current item if it is selected, otherwise the return value of the recursive call.

function findSelectedInList(list) {
  var selected;
  list.some(function(currentItem) {
    return selected = currentItem.selected === "selected" ? currentItem : findSelectedInList(currentItem.children);
  });
  return selected;
}

And one could use ecmascript-6 features like arrow functions and the let keyword), to condense it slightly:

function findSelectedInList(list){
  let selected;
  list.some((currentItem) => selected = currentItem.selected === "selected" ? currentItem : findSelectedInList(currentItem.children));
  return selected;
}

To see this demonstrated, expand the snippet below.

var treeList = [{
  "roleName": "User",
  "roleId": "role1",
  "children": [{
    "roleName": "subUser1",
    "roleId": "role11",
    "children": [],
    "selected": "selected"
  }]
}];

var treeList2 = [{
  "roleName": "User",
  "roleId": "role1",
  "children": [],
  "selected": "selected"
}];
var treeList3 = [{
  "roleName": "User",
  "roleId": "role1",
  "children": []
}];

function findSelectedInList(list) {
  var selected;
  list.some(function(currentItem) {
    return selected = currentItem.selected === "selected" ? currentItem : findSelectedInList(currentItem.children);
  });
  return selected;
}
console.log('treeList: ', findSelectedInList(treeList));
console.log('treeList2: ', findSelectedInList(treeList2));
console.log('treeList3: ', findSelectedInList(treeList3));

I know it doesn't really cover the find or some methods, but these functional JS exercises are a good thing to go through.


Neither. Note: haven't tried this in and IDE, but you should be able to get the idea.

interface RegionID {
    boolean isRegionMatch(String fileID);
    String getRegionCode();
}

class SimpleMatchRegionID implements RegionID {
    private String regionPrefix;
    private String regionCode;

    public SimpleMatchRegionID(String regionPrefix, String regionCode) {
        this.regionPrefix = regionPrefix;
        this.regionCode = regionCode;
    }

    public boolean isRegionMatch(String fileID) {
        return fileID.startsWith(regeionPrefix);
    }

    public String getRegionCode() {
        return regionCode;
    }
}

RegionID us = new SimpleMatchRegionID("CPP420.A1", "US");
RegionID ca = new SimpleMatchRegionID("CPP350", "CA");
RegionID fr = new SimpleMatchRegionID("CPP350", "FR");
RegionID[] regions = {us, ca, fr};

public String findRegionCode(String fileID) {
    for (i = 0; i < regions.length; i++) {
        if (regions[i].isRegionMatch(fileID)) {
            return regions[i].getRegionCode();
        }
    }

    return "";
}

An implementation like this would allow you to load the regions array from a data file, or with some other run-time mechanism. It would also allow you to implement other strategies for recognizing a region that doesn't follow the same basic pattern.


Matrix multiplication using functions in C

I suggest you roll an explicit matrix type. For example:

typedef struct matrix_t {
    size_t rows;
    size_t cols;
    int* data;
} matrix_t;

void matrix_t_multiply(matrix_t* left, matrix_t* right, matrix_t* result) {
    ...
}


Node comparison using priority queue for Dijkstra's Shortest Path Algorithm

Stylistic issues

"Indivisual" is not an English word.  It seems likely that you mean "individual".

Please use CamelCase with an initial capital letter for class and interface names.  It makes your code much easier for others to read.  Specifically, indivisualvertex --> IndividualVertex, and neighbours --> Neighbours.

Please use camelCase with an initial lowercase letter for method, field, and parameter names.  In particular, pointer_of_vertex --> pointerOfVertex, or, more precisely, vertexIndex.

Class names generally should be singular nouns, for a class always describes one thing, even if that thing is an aggregate.

Descriptive class and variable names are generally good form, but it is possible to go overboard.  The name previousVertexOnShortestPathFromSource is considerably too long for my taste, and at the same time a bit inaccurate.  I tend to read it as "absurdly long name", which defeats the purpose of descriptive naming.  It would be even worse if there were other names of such length to distinguish among.  For this particular case, I would certainly choose something more pithy, such as previousVertexIndex.

Where descriptive comments for variables are needed, I generally prefer to see them on the preceding line, not as trailing in-line comments.  The latter work for me only if they are quite short.  However, do resist adding such comments at all when they add nothing to what your nice, descriptive variable names already say.

It's at minimum unnecessarily verbose to compare boolean variables with boolean literals, such as in the expression visited[nbr.pointer_of_vertex] == false.  It is usually better form to just use the boolean variable either directly or subject to boolean negation: !visited[nbr.pointer_of_vertex].

Correctness issues

indivisualvertex.compareTo() is flawed.  Given distinct indivisualvertex instaces v1 and v2 with the same values of distanceFromSource, v1.compareTo(v2) and v2.compareTo(v1) will both return -1.

Just because you're comparing floating-point values does not mean that you can ignore the equality case.

Performance considerations

You wrap up your question by raising a series of performance considerations:

  can there be any disadvantages to to not building our own minimum heap for this purpose?

Of course there can.  You already said yourself that the standard library's PriorityQueue does not offer some of the operations you really would like to have, and therefore that you have to use a workaround.  On the other hand, the standard library's PQ has to be very general; all the operations it does implement, it must implement in a generic way.  Although I have every reason to expect the result is robust and efficient -- and obviously, it's already there -- it is likely that additional efficiency would be possible from an implementation tuned to your need.

  Also, while relaxing the edges the method extracts the vertex and then puts it back. Is this an expensive operation?

It's at least twice as costly as rearranging a min heap appropriately without removing the modified element could be made to be.  You've given no basis or context for putting that on absolute grounds.

  How much does it affects the performance of the algorithm?

For the overall algorithm, that depends on the data.  For a single relaxation, see above.


Unfortunately I am not experienced with Pandas especially on large files. But I would have tried a more 'native' solution like VBA but it is because I have some experience with it. There is a chance that VBA (in the form of a macro) would perform faster.

Perhaps you can try a hybrid approach, for example add some temporary columns to the files you are processing in Python, and fill those columns with formulae like COUNTIF etc.
The aim is to let Excel do the computationally-intensive stuff. And then you let your script loop row by one using the precalculations made by Excel.

When you are done, you remove the temporary columns or simply close the file discarding changes.
This may not be the more elegant approach, but I am not surprised that an interpreted language like Python with all the middleware involved is slow for this kind of task.

Another option is to dump the sheets to a database, MS Access or SQLite, add some indexes where appropriate and use SQL to fill out the gaps and then re-import the result to Excel.

This is more a hack than a real solution. My considerations would be:

is this a one-shot operation or a process that you will have to repeat ? This is to answer the question: how much time and energy are you willing to invest in this ?
You have not mentioned the purpose of the Excel files, and you've not shared the structure or a data sample. 300K columns for an Excel file is very big. I am wondering if by any change you are on assignment with some corporate client where clerks use Excel like a database. This is a very common scenario unfortunately. Then I would advise them to use a better solution. The whole process and usage is flawed and the solution can hardly be elegant.

Probably there are solutions already available on the market, including free and open source software. From experience there is little added value trying to patch a flawed process.

Everybody uses Excel, so Excel files proliferate everywhere and the result is poorly-structured data that is hard to exploit.
Using Excel is often the problem and the solution is to move away from Excel.


Extracting numbers from a string into an ArrayList

Start by separating your code into input handling, computation, and output.  Each of those could have its own method(s).

For the input, you're working too hard.  The java.util.Scanner has methods to give you ints.

Think about what the inputs and outputs of each function should be.  For example, your input handling function should take an InputStream and return a List of Integers or an array of ints.


Rewrite method to decide the ShowLevel based on roles

I presume Role is an enum (if it is not, it should be). An enum is a great candidate for a switch statement, and it also makes the conditions very clear:

switch (role) {
    case HOD:
        return showInGui >= 1;
    case STAFF:
        return showInGui == 1 || showInGui == 2;
}
return showInGui == 1;

Note that, if you want you can embed that logic in to the enum itself, and have a simple call to an enum method:

return role.isVisible(showInGui);

Additionally, if you reverse the values of the showInGui to be:

0 -> nobody
1 -> HOD only
2 -> HOD & STAFF
3 -> everyone

then your logic is simplified further to:

switch (role) {
    case HOD:
        return showInGui >= 1;
    case STAFF:
        return showInGui >= 2;
}
return showInGui >= 3;


As mentioned here I'll provide a short answer to summarize what we discussed. A return statement only impacts code that short-circuits any remaining code that would have been called if omitted.

pseudo code snippets below

The return statement here skips snippet 2.

if (condition) {
  // .. snippet 1
  return;
}
// snippet 2

The return statement here is unnecessary.

if (condition) {
  // .. snippet 1
  return;
} else {
  // snippet 2
}


If you need to optimize bubble sort, you're doing it wrong. It's not really worth optimizing something that's inherently slow. You should just use a better sorting algorithm.


You could have an abstract superclass Response which has concrete derived classes of multipleChoiceResponse and freeResponse. Then you can have a method such as checkResponse which is different for each type of respones.

EDIT:

How about this:

from django.db import models

class Response(models.Model):
    user = models.ForeignKey(User)
    question = models.ForeignKey(Question)

    class Meta:
        abstract = True

class freeResponse(Response):
    free_response = models.TextField(max_length=2000,blank=True)

class multipleChoiceResponse(Response) #does not handle multi-select (tickbox) cases
    answer = models.ForeignKey(Answer)


Linked list with removal function in Rust

Read Learning Rust With Entirely Too Many Linked Lists.
Your code has compilation errors with Rust 1.18.0.

error[E0446]: private type `Node<T>` in public interface
  --> src/main.rs:82:5
   |
82 |     type Item = Rc<RefCell<Node<T>>>;
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can't leak private type

I derive Debug on almost every struct.
push can have all conditionals removed from it because doing
nothing is the same as setting None as the next value.
remove panics when called on a newly-created list.
pushing 1, 1, 1, 1, 2 and then removing 1 results in the list 2->1->1 which doesn't seem any flavor of correct. I assume you wanted to remove the first match.
It's way easier to get the code right when it operates on the same level of abstraction. I've created a method that removes on a &mut Link<T> because that's the shared type between List and Link.
Honestly, it's also easier to get this right with recursive code as well.
Doesn't make sense to return the Rc<RefCell<...>> as the iterator type - people care about the values, not the collection.
Can simplify the iterator by just taking the value out of the iterator state and putting a new value in sometimes.

use std::rc::Rc;
use std::cell::RefCell;

type Link<T> = Option<Rc<RefCell<Node<T>>>>;

#[derive(Debug)]
pub struct Node<T> {
    elem: T,
    next: Link<T>,
}

impl<T> Node<T> {
    fn new(elem: T) -> Rc<RefCell<Self>> {
        Rc::new(RefCell::new(Node {
            elem: elem,
            next: None,
        }))
    }
}

#[derive(Debug)]
pub struct List<T> {
    head: Link<T>,
}

impl<T: Eq> List<T> {
    pub fn new() -> Self {
        List { head: None }
    }

    pub fn push(&mut self, elem: T) {
        let new_head = Node::new(elem);
        new_head.borrow_mut().next = self.head.take();
        self.head = Some(new_head);
    }

    pub fn remove(&mut self, elem: T) {
        fn remove_inner<T: Eq>(node: &mut Link<T>, elem: T) {
            if let Some(ref mut n) = node.clone() {
                if elem == n.borrow().elem {
                    *node = n.borrow_mut().next.take();
                    return
                }

                remove_inner(&mut n.borrow_mut().next, elem);
            }
        }

        remove_inner(&mut self.head, elem)
    }
}

fn main1() {
    let mut list = List::new();
    list.push(3);
    list.push(2);
    list.push(1);
    list.remove(2);
    let head = list.head.unwrap().clone();
    assert_eq!(head.borrow().elem, 1);
    let next = head.borrow().next.clone().unwrap();
    assert_eq!(next.borrow().elem, 3);

    let mut list = List::new();
    list.remove(2);

    let mut list = List::new();
    list.push(1);
    list.push(1);
    list.push(1);
    list.push(1);
    list.push(2);
    list.remove(1);
    println!("{:?}", list);
}

pub struct Iter<T> {
    next: Link<T>,
}

impl<T> Iterator for Iter<T> {
    type Item = Rc<RefCell<Node<T>>>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.next.take() {
            Some(next) => {
                self.next = next.borrow().next.clone();
                Some(next)
            }
            None => None,
        }
    }
}

impl<T: Eq> List<T> {
    pub fn iter(&self) -> Iter<T> {
        Iter { next: self.head.clone() }
    }
}

fn main2() {
    let mut list = List::new();
    list.push(3);
    list.push(2);
    list.push(1);
    list.remove(2);

    let mut it = list.iter();
    let next_node = it.next().unwrap();
    assert_eq!(next_node.borrow().elem, 1);
    let next_node = it.next().unwrap();
    assert_eq!(next_node.borrow().elem, 3);
    let next_node = it.next();
    assert_eq!(next_node.is_none(), true);
}

fn main() {
    main1();
    main2();
}

Frankly, I don't know why you used Rc and RefCell — they aren't needed to implement a singly linked list. There's no need for complicated shared ownership (no need for Rc) and there's no need for interior mutability (no need for RefCell).


Storing JWT in client side and putting tokens in all the future request

At the time of posting this question, I had no idea about Frontend Frameworks.
Later I choose Vue Js as my frontend framework, things are working great.

All I was missing a Frontend Framework.


Most efficient way to get columns where one is minimum

Formatting
You use a mixture of lowercase and UPPERCASE keywords, you should stick to one or the other. It makes it much easier to read the query if you do. I am going to stick with UPPERCASE as it is the convention.
An alternate approach
Might I suggest storing the minimum SortSequence value in a variable and then using that to filter out records you don't need.
Here is what I came up with.
DECLARE @Minimum_Sort_Seq INT =
(
    SELECT MIN(SortSequence)
    FROM WebcastChannelWebcastEventLink
)

SELECT wcwel.WebcastChannelId,wcwel.WebcastEventId
FROM WebcastChannelWebcastEventLink wcwel
WHERE wcwel.SortSequence = @Minimum_Sort_Seq

This query returned the same results in my testing. You can run this to check yourself:
CREATE TABLE #WebcastChannelWebcastEventLink
(
    WebcastChannelId INT,
    WebcastEventId INT,
    SortSequence INT
)

INSERT INTO #WebcastChannelWebcastEventLink
SELECT 1,2,1 UNION ALL
SELECT 1,5,2 UNION ALL
SELECT 1,3,3 UNION ALL
SELECT 2,7,2 UNION ALL
SELECT 2,8,1

SELECT wcwel.WebcastChannelId, wcwel.WebcastEventId
FROM #WebcastChannelWebcastEventLink wcwel WITH (NOLOCK)
INNER JOIN #WebcastChannelWebcastEventLink wcwel1 WITH (NOLOCK)
    ON wcwel1.WebcastChannelId = wcwel.WebcastChannelId
GROUP BY
wcwel.WebcastChannelId,
wcwel.WebcastEventId,
wcwel.SortSequence
HAVING
wcwel.SortSequence = MIN(wcwel1.SortSequence)

DECLARE @Minimum_Sort_Seq INT =
(
    SELECT MIN(SortSequence)
    FROM WebcastChannelWebcastEventLink
)

SELECT wcwel.WebcastChannelId,wcwel.WebcastEventId
FROM WebcastChannelWebcastEventLink wcwel
WHERE wcwel.SortSequence = @Minimum_Sort_Seq

DROP TABLE #WebcastChannelWebcastEventLink


Implementation of an asynchronous UDP server Listener

@MX D is correct in that you should not be catching exceptions, unless you are going to do something about them.

This code can and should be written without catch statements.

private void DoReceiveFrom(IAsyncResult iar)
{

    try
    {
        EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);
        int dataLen = 0;
        byte[] data = null;
        try
        {
            dataLen = this.serverSocket.EndReceiveFrom(iar, ref clientEP);
            data = new byte[dataLen];
            Array.Copy(this.byteData, data, dataLen);
        }
        catch (Exception e)
        {
        }
        finally
        {
            EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
            this.serverSocket.BeginReceiveFrom(this.byteData, 0, this.byteData.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, newClientEP);
        }

        if (!this.clientList.Any(client => client.Equals(clientEP)))
            this.clientList.Add(clientEP);

        //     DataList.Add(Tuple.Create(clientEP, data));

        string s = Encoding.ASCII.GetString(data);

    }
    catch (ObjectDisposedException)
    {
    }
}

you should also remove some of the empty space from the code as well.

The Commented code...what is it there for?  If this is dead code then you should remove it.

Declaring a Variable at the end of this code has me a little confused....

  string s = Encoding.ASCII.GetString(data);

Get rid of that too, it isn't used anywhere in the code that you present in the Original Post

I also got rid of the Try because there isn't a need for a try if you aren't going to catch anything or finally anything.  This also removes a level of unnecessary indentation.

The code now looks like this:

private void DoReceiveFrom(IAsyncResult iar)
{
    EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);
    int dataLen = 0;
    byte[] data = null;
    try
    {
        dataLen = this.serverSocket.EndReceiveFrom(iar, ref clientEP);
        data = new byte[dataLen];
        Array.Copy(this.byteData, data, dataLen);
    }
    finally
    {
        EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
        this.serverSocket.BeginReceiveFrom(this.byteData, 0, this.byteData.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, newClientEP);
    }

    if (!this.clientList.Any(client => client.Equals(clientEP)))
        this.clientList.Add(clientEP);
}

and while I am at it, I would implement the IDisposable interface and use a Dispose method instead of this

public void Stop()
{
    this.serverSocket.Close();
    this.serverSocket = null;
    this.clientList.Clear();
}

it would then look something like this

public void Dispose()
{
     this.serverSocket.Close();
     this.serverSocket = null;
     this.clientList.Clear();
}

this also gives you other options when using the class in your code.


Selecting three tables with relationship

I don't really understand what this join is trying to accomplish? Seems redundant since the information is the same, but perhaps with your real world data it is not always the case.

WHERE  posts.position = posts.submitter

Old-style JOINs are not recommended. Use INNER JOIN instead. This may also cause performance issues because rates is not explicitly joined so it would be trying to do a CROSS JOIN and those are very slow not to mention it can mess up your result set.

FROM    posts,
        users,
        rates
WHERE   posts.position = posts.submitter
AND     users.username = posts.submitter

Becomes:

SELECT  posts.*,
        users.username,
        SUM(
        IF(rates.hash = posts.hash, (rates.likes - rates.dislikes), 0)
        ) AS rate
FROM    posts
INNER JOIN users
    ON users.username = posts.submitter
INNER JOIN rates
    ON users.username = rates.username
WHERE   posts.position = posts.submitter
GROUP BY posts.hash
ORDER BY posts.ID DESC LIMIT 5;

I also formatted it for ease of reading. Executes in 2 ms using your data.
Try it: http://sqlfiddle.com/#!2/d198f/4

Edit: fixed a typo.


Well, you were right to think you are wrong.  We shouldn't need to instantiate an object with an empty constructor to something like this.  This is exactly what the Shared keyword is for.

First, make your getAllPatientsInList function Shared:

Public Shared Function GetAllPatients() As List(Of Patient)
    ' method implementation
End Function

And now we can call the method without instantiating an instance of the class:

For Each item as Patient in Patient.GetAllPatients()
    ' do something with item
Next

And once we've done this, arguably, we may want to eliminate the default, zero-argument constructor.


Without knowing much about your use case, the code looks straightforward. It does exactly what you specify and nothing more.

A few points:

The constant image hash can be defined as global(?)
Use === for comparison.


You should move to an authenticated mode of encryption like CCM, EAX, OCB or GCM. The fact that you are generating a random sequence of bytes from the OS's PRNG is sound. It looks like the argument provided to the crypto object is already padding the resulting cipher text of the file stream.

The top bit about removing the restrictions is suspect.

Padding attacks are a side channel attack in crypto that allows an attacker to perform cryptanalysis on a block of cipher text because the plain text input would determine the resulting cipher texts length.  By padding the resulting cipher text it makes that side channel more difficult.


Basic function to convert Country name to ISO code using Pycountry

I always get my code to be as clean as possible before starting work on performance. Here you have a bare except, which can hide errors. Change it to something better, for now I'll change it to Exception. You are also hiding a potential IndexError and AttributeError if the data ever changes shape as they are in the try.

def do_fuzzy_search(country):
    try:
        result = pycountry.countries.search_fuzzy(country)
    except Exception:
        return np.nan
    else:
        return result[0].alpha_3

Since there are roughly 200 sovereign states and you're working with 17003 rows you likely have a lot of the same values hitting a costly function. To resolve this issue you can use functools.lru_cache. Running in amortized \$O(n)\$ time and \$O(n)\$ space.

@functools.lru_cache(None)
def do_fuzzy_search(country):
    ...

Alternately you can sort the data by the provided countries name and then get each country once. Running in \$O(n\log n)\$ time and \$O(1)\$ space.


JS calculator, respecting order of operations

Overview

If you are using ES6, you should use the full ability of arrow functions: (args) => returnVal
In addition, some of the methods don't need to be defined as a property.
calculatorOperations should be a constant.
You don't need to access each element in an array like this: (getArgs[0], getArgs[1]), you can do (...getArgs)
I agree with @SamOnela in that you can iterate over the operations. However, their method pollutes global namespace

Questions

Why are you using x not *?

Rewrite

    function operateOnEntry(userEntry) {
        let indexOfOperand,
            operation;
        Object.keys(calculatorOperations.ops).forEach(function(functionName) {
            while (userEntry.includes(functionName)) {
                indexOfOperand = userEntry.indexOf(functionName);
                userEntry = calculatorOperations.calculationSequence(functionName, indexOfOperand, userEntry);
            };
        });
        return userEntry;
    }

    const calculatorOperations = {
        ops: {
            'x': (arg1, arg2) => arg1 * arg2,
            '/': (arg1, arg2) => arg1 / arg2,
            '+': (arg1, arg2) => arg1 + arg2,
            '-': (arg1, arg2) => arg1 - arg2
        },
        returnIndexOfEntry(index, userEntry) {
            let arg1 = Number(userEntry[index - 1]),
                arg2 = Number(userEntry[index + 1]);
            return [arg1, arg2];
        },
        returnSpliced(index, newTotal, userEntry) {
            userEntry.splice((index - 1), 3, newTotal);
            return userEntry;
        },
        calculationSequence(operation, indexOfOperand, userEntry) {

            let getArgs = calculatorOperations.returnIndexOfEntry(indexOfOperand, userEntry),
                newTotalForEntry = calculatorOperations.ops[operation](...getArgs),
                newUserEntry = calculatorOperations.returnSpliced(indexOfOperand, newTotalForEntry, userEntry);
            return newUserEntry;
        }
    };
    var userEntry = [3, '+', 3, 'x', 3];
    console.log(operateOnEntry(userEntry));


Checking whether any anagram of a string appears within another string

The asymptotic time complexity of your implementation is:
$$O(\ (s-t)*(t*log(t))\ )$$

Because you sort and compare \$s-t\$ substrings of length \$t\$.
(I'm assuming Python uses \$n*log(n)\$ sort).

Here is a solution with \$\  O(\ t*(s-t+log(t))\ ) \ \$ time complexity.

It uses a sorted sliding window of length \$t\$. When the window slides through s, an old character is removed and a new one is added into a specific position, such that the window is kept sorted.

Initial sorting of string t is \$\ t*log(t)\$
Initial sorting of the sliding window is \$\ t*log(t)\$
Initial comparison of sorted(t) with the window is \$\ t\$
For each character in s[len(t):], total of \$\ s-t\ \$ items, there is:

one bisection of window for the character to be removed : \$\ log(t)\$
one removal of a character : \$\ t\$
one bisection of window for the character to be inserted : \$\ log(t)\$
one insertion of a character : \$\ t\$
one comparison of sorted(t) with the window : \$\ t\$

So the asymptotic complexity is \$O(\ t*log(t)\ +\ (s-t)*t\ )\$,
or simply \$O(\ t*(s-t+log(t))\ )\$.

from bisect import bisect_left, bisect_right

def question1_fast(t, s):

  if len(s) < len(t):
    return False

  t = sorted(t)
  window = sorted(s[:len(t)])

  if window == t:
    return True

  for i, c_new in enumerate(s[len(t):]):

    c_old = s[i]

    if c_old < c_new:
      idx_old = bisect_right(window, c_old) - 1
      idx_new = bisect_left(window, c_new) - 1

    elif c_new < c_old:
      idx_new = bisect_right(window, c_new)
      idx_old = bisect_left(window, c_old)

    else:
      continue

    del window[idx_old]
    window.insert(idx_new, c_new)

    if window == t:
      return True

  return False

A little comparison of efficiency on large s and t:

>>> from random import randint, shuffle
>>>
>>> # `s` is a string of 10,000 random characters
>>> s = ''.join(chr(randint(32,127)) for _ in range(10000))
>>>
>>> # `t` is a random permutation of `s[5000:6000]`
>>> t_list = list(s[5000:6000])
>>> shuffle(t_list)
>>> t = ''.join(t_list)
>>>
>>> timeit('Question1_original(t,s)', globals=locals(), number=10)
25.469552749997092
>>> timeit('Question1_Caridorc(t,s)', globals=locals(), number=10)
12.726046560999748
>>> timeit('question1_fast(t,s)', globals=locals(), number=10)
0.10736406500291196

With small strings, the differences are not so significant:

>>> timeit('Question1_original("ad", "udacity")', globals=locals())
4.730070723002427
>>> timeit('Question1_Caridorc("ad", "udacity")', globals=locals())
6.0496803390014975
>>> timeit('question1_fast("ad", "udacity")', globals=locals())
3.89388234800208

EDIT

Scratch that. I just realized there's a more efficient way to do it. One that is \$\ O(s+t)\ \$ in time complexity.

My original idea was to have a window which is a sorted list, and keeping the window sorted the whole time, all for the sake of the comparison window == t. If window and t weren't both sorted, the comparison obviously wouldn't work as needed.

But to find out whether one string is an anagram of another string, we don't have to sort them, we just need to know if they contain the same characters. Sorting and comparing them is one way. A more efficient way is to count the number of occurrences of each distinct character. The result would be a dictionary mapping to each character the number of its occurrences. Then you just compare the dictionary of str1 with the dictionary of str2, and if they are equal, the strings are anagrams of each other.

The comparison of dictionaries is not much more efficient than comparing sorted lists. If anything, I suspect it might be even slower. It's the insertions and deletions, which are nearly \$O(1)\$ in dictionary, but \$O(t)\$ in the case of a sorted list.

Since neither t nor window have to be sorted, neither be kept sorted, the time complexity is drastically reduced:

Creation of dictionary for t : \$\ t\$
Creation of dictionary for window : \$\ t\$
For each character in s[len(t):] (repeated \$s-t\$ times):

one decrementation of counter : \$\ 1\$
one incrementation of counter : \$\ 1\$

That adds up to \$\ O(\ t+(s-t)\ )\ \$ or just \$\ O(s+t)\$.

def make_counter_dict(s, t):
  counter_dict = dict.fromkeys(s, 0)
  for c in t:
    counter_dict[c] += 1
  return counter_dict

def question1_even_faster(t, s):

  if len(s) < len(t):
    return False

  t_dict = make_counter_dict(s, t)
  window = make_counter_dict(s, s[:len(t)])

  for c_old, c_new in zip(s, s[len(t):]):

    if window == t_dict:
      return True

    window[c_new] += 1
    window[c_old] -= 1

  return window == t_dict

Performance (measured with another random s and t of the same parameters as before):

>>> timeit('question1_fast(t,s)', globals=locals(), number=1000)
10.559728353000537
>>> timeit('question1_even_faster(t,s)', globals=locals(), number=1000)
2.1034470079976018

This version is slower on small strings though:

>>> timeit('question1_fast("ad", "udacity")', globals=locals())
3.886769873002777
>>> timeit('question1_even_faster("ad", "udacity")', globals=locals())
4.691746060998412


HTML5 semantic layout (div, article, section) and explicit identifiers

#logo → h1

Your

 should be a h1, otherwise the document outline wouldn't be correct:

See https://stackoverflow.com/a/14920215/1591669 for an explanation.

#banner → header or aside

If your

 doesn't contain main content, it should go in an aside element, or, if it can be understood as part of the header (probably on each page of the site), in the header element.

#main → section (or article)

Instead of

 you could use a sectioning element here. I assume your div contains a heading ("Welcome, dear visitor!"), so you have something like an implict section anyhow. Why not make it explicit? So use a section instead of the div (depending on the actual content, article might be suitable instead).

#content > aside → section

I'd say on the front page the testimonials could be considered part of the main content (in the end it depends on the real content/context), so instead of aside you could use section then.

Each single testimonial should be in its own article, of course.

#extra > article → section

I don't think article elements in the footer are suitable for that kind of content (unless your actual page contains something different). (Only the newsletter form could possibly get article instead of section, but that's not that clear; personally I'd use section for it, too).

So, I'd go with section here. If the contact details listed under "Address" are relevant for the whole page, you should use the address element, too.

Address

      <address>…</address>


Split coins into combinations of different denominations

It may less fragile if you deal with the numbers directly rather than converting to strings. It will also be cleaner code.

You could start with your values in a list sorted highest to lowest. Then in your function you can find the next-largest value and remained with divmod(). After than it's a matter of deciding how you want to format the resulting dict:

coins = [
    ("gold",  100 * 100),
    ("silver", 100),
    ("copper", 1)
]

def translate_coins(value, coins):
    res = {}
    for coin, v in coins:
        res[coin], value = divmod(value, v)
    return res

translate_coins(1013323, coins)

Result:

{'gold': 101, 'silver': 33, 'copper': 23}


Using a thread to update a table automatically in Django

Keep a base URL

'https://api.worldtradingdata.com/api/v1/' should be factored out of your URL variables. You can use the Python libraries in urllib to safely construct the URLs after, which is preferable to using join as you do.

Don't manually construct a URL

    url = ''.join([cls.forex_url,
                   '?base=' + base_currency,
                   '&api_token=' + cls.api_token,
                   ])

This is more work than you have to do. Just pass a dict to requests.get's params kwarg.

Don't call json.loads()

        res = requests.get(url)
        forex_dict = json.loads(res.content).get('data', {})

Just call res.json().

Check your HTTP result

Call res.raise_for_status(), or at the absolute least check the status of the result. Currently, there are some failure modes that will not throw from your code at all.


SSE Assembly vs GCC Compiler - Dot Product

While harold reviewed your assembly code, I'll just comment on how you are compiling your C code:

Increase the duration of the benchmark

Your code runs for a very short amount of time, only tens of microseconds. This is too short to get accurate measurements:

clock() only has a resolution of a microsecond, so this is not insignificant compared to the duration.
the processor's caches, branch predictors and prefetchers might not have had time to fully warm up.
interrupts and other processes running on your system add noise.

Aim to run your benchmarks for at least a second. That might be easier said than done: if you increase the size of the arrays you might become memory bandwidth bound instead of CPU bound. And if you naively just repeat the computations with the small array, the compiler might notice and just calculate the sum once and the multiply it by the number of repeats, depending on the level of optimization used.

Use a proper optimization level

There is no such thing as -O7. The highest supported optimization level for GCC is -O3. However, even that does not enable all possible optimzations. In particular, GCC is a bit careful when it comes to floating point math, and tries to ensure the code is correct even if there are infinities, NaNs and denormals. It also knows that floating point math is not strictly associative and commutative, and so will try to keep operations in the same order as you specified them, which prevents it from using some vectorization tricks. If you don't care about that, you can enable -ffast-math, or use -Ofast.

Consider using -mtune=... and/or -march=...

If you don't specify any specific CPU, then on an x86-64 platform, GCC will output code that can run on any 64-bit Intel or AMD CPU, and might not be able to use certain SSE instructions that are not available in the x86-64 baseline. Also, the compiler will assume a certain CPU for instruction timing, delay slots, and other micro-architecural optimizations, which might not be ideal for the Xeon CPU you are running the code on. Typically you would use -march=native to ensure the compiler will provide code using all features of the CPU you are compiling on, but that might cause it to use AVX instructions if your CPU supports those.

Consider using SSE intrinsics

Instead of having a pure assembly version and a pure C version, you can have something inbetween by using SSE intrinsics. These are functions that are compiled into specific CPU instructions. However, the function arguments and return values are just variables (either regular ones or special vector type variables), not registers. The compiler will pick registers as it sees fit, and will also be able to reorder the intrinsics calls if possible, using its knowledge about the CPU's micro-architecture, and if you use the intrinsics in a loop then the compiler can unroll the loop for you.

While GCC and Clang are able to vectorize certain loops, they are quite bad at using horizontal operations such as haddps, so if you help it by using intrinsics you might get code comparable to the best hand-optimized assembly.

Some results

If I increase the size of the array to 25600000, and compile with -O7 (which will effectively be -O3), I get the following results on an AMD Ryzen 9 3900X:

0.008444000000000
Solution 16.000000000000000
0.018092000000000
Solution 15.403682708740234

With -Ofast I get:

0.008399000000000
Solution 16.000000000000000
0.006617000000000
Solution 16.419670104980469

So clearly there is a speed-up when going to -Ofast, but the resulting solution is also different.


Reflection optimization for export CSV on large scale

ParseContent()

Type type = entities.First().GetType(); can throw an exception if entities doesn't contain any items. I may be wrong but you could use the T as well like  Type type = typeof(T);.
If entities is null an ArgumentNullException should be thrown instead of an ArgumentException.
The foreach could be simplified and you should use a StringBuilder instead of concating strings in a loop. Thats because strings are immutable and for each contentToExport += $"{template}{NewLineDelimiter}"; you create a new string object.
If the right hand side of an assignment makes the type clear one should use var instead of the concrete type.
Omitting braces {} althought they might be optional can lead to hidden and therefor hard to find bugs. I would like to encourage you to always use them.
Having a variable memoryStream doesn't buy you anything. Just return the new memorystream.

Applying these points will lead to

public System.IO.Stream ParseContent<T>(IEnumerable<T> entities) where T : class
{
    if (entities == null)
    {
        throw new ArgumentNullException(nameof(entities), "List accepted is empty.");
    }
    if (!entities.Any())
    {
        //assuming thats the desired behaviour
        return null;
    }

    Type type = typeof(T);

    PropertyInfo[] properties = type.GetProperties();

    string headers = GenerateTemplate(properties);

    //No headers accepted - cannot export the content
    if (string.IsNullOrEmpty(headers))
    {
        return null;
    }

    StringBuilder contentToExport = new StringBuilder( $"{headers}{NewLineDelimiter}");

    foreach (T entity in entities.Where(e=>e!=null))
    {

        string template = this.ExportLine(entity, properties);
        contentToExport.Append($"{template}{NewLineDelimiter}");
    }

    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(contentToExport.ToString());

    return new System.IO.MemoryStream(bytes);
}


General
I do not know exactly why your question remains unanswered till now. But I guess "exercises" tend to have less attention as this exercise seems to be really basic. Do not get me wrong. Everybody had to go through basic things.
So the point is that you found a solution to a problem. And so far you did very well. But I want encourage you to keep on going as this is only the surface. Here are the things every programmer has to go through.

Learn the theory of sequence, selection and iteration

Train your algorithmic thinking by solving problems with the elements of 1. in a programming language of your choice by increasing difficulty

Get familiar with the language mechanisms

Apply programming paradigms like functional or object-oriented programming

Formalize you code fragments by learning the currently identified 26 design patterns and learn to to apply them in the correct situations

Organize your code by following the correct semantic of each code fragment and learn and apply the SOLID principles as they guide you through the jungle of design decisions

Learn the restrictions of the language you use for a problem. Maybe in another language you are able to express the solution in another way that is more elegant.

The point is that the code provided can only be judged under point 1, 2 and 3. And there your are on a good way. As I do not know how deep you dived into the java programming language maybe it is time to apply the object-oriented or functional programming paradigm.
As your code currently is procedural I suggest to formulate your code in a more object-oriented way.
Suggestions
Reduce static elements
The static modifier is not overall bad (e.g. constants) but for methods it hinders you to benefit from the OO mechanism "polymorphism".
Introduce OO
Try to formulate your code with objects. To start here remove all static modifiers from all methods but the the main-method. Introduce a constructor for your class "NaturalLanguageMultiply". Pass in the arg-Array make the validation and store it in a local variable.
Do not exit with System.exit(0);
This does not make sense at all as every program will leave with the exit code 0 if the program ends. It is a needless statement.
Exception handling
I suggest to have a single concept of exception handling. If you want to promote execution failure of a program by calling System.exit(...) then do this in the final statement in your program. Internally you should rely on exceptions. So your argument validation should not exit the JVM but throwing an IllegalArgumentException.
Currently you catch "Exception". I suggest to catch expected Exceptions explicitly. This helps you to return distinguishable exit codes.
Furthermore avoid System.out.println at arbitrary locations in your code to promote exceptions. This will cause redundant code spread all over the place. Promote the exceptions where you are going to handle them.
Provide a calculation-method
Introduce a method called getResult() to do the multiplication.
Naming
As mentined in the comments naming things properly will help others to read your code. I would change the constant name from "WORD_SEPARATOR" to "TOKEN_SEPARATOR" and renaming "args" into "words". This how it makes sense to me. You have two words that are both spoken numbers. And one word is partitioned into token by a separator of those tokens. Maybe you can also rename "words" into "spokenNumbers" and "word" into "spokenNumber". But I think I made case.
Code
public class NaturalLanguageMultiply {

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

    private static final String TOKEN_SEPARATOR = "-";

    static {
        numericValues.put("zero", 0);
        numericValues.put("one", 1);
        numericValues.put("two", 2);
        ...
        numericValues.put("ninety", 90);
    }

    private String[] words;

    NaturalLanguageMultiply(String[] words) {

        if(words.length < 2) {
            throw new IllegalArgumentException("argument missing");
        }

        this.words = words;

    }

    private int wordToNumber(String word) {

        String[] tokens = word.split(TOKEN_SEPARATOR);

        int number = 0;

        for (String token: tokens) {

            Integer numericValue = numericValues.get(token);

            if(numericValue == null) {
                throw new IllegalArgumentException("unknown token " + token + " in word " + word);
            }

            number += numericValue;
        }

        return number;
    }

    private int getResult() {

        int firstNumber = wordToNumber(words[0]);
        int secondNumber = wordToNumber(words[1]);

        return firstNumber * secondNumber;
    }

    public void main(String[] args) {

        try {

            int result = new NaturalLanguageMultiply(args).getResult();

            System.out.format("%d%n", result);

        } catch (IllegalArgumentException e) {

            System.out.println(e.getMessage());
            System.exit(1);

        } catch (Exception e) {

            System.out.println(e.getMessage());
            System.exit(2);

        }

    }

}

Further steps
Your solution parses and interpretes incoming data and processes calculations. This is best addressed with the state pattern and the interpreter pattern. This is an advanced technique you should have in mind when you feel ready for it.


Style

The style for naming in Python is as follows.

Variables should be in snake_case.
Constant variables should be in UPPER_SNAKE_CASE.
Functions should also be in snake_case.
Classes should be in PascalCase.

You should also replace comments in functions like this:

#keys = a list of all keybord keys currently being pressed.
#I have imported a module that has a bunch of variables that represent each key.
#keyup = the current key that was just released, if any.

To docstrings, like this:

"""Brief description of the function/class.

More detailed description of function/class.

Keyword Arguments:
argument -- Argument description.
...
"""

Design

There's not much about your design that I can nitpick, the only thing I'd really suggest is shortening these two blocks of code:

self.moveHorz('r')
self.accelerate('r')
self.set_crnt_acc('r')
self.faceDir = 'r'
self.des_dir = 'r'

And:

self.moveHorz('l')
self.accelerate('l')
self.set_crnt_acc('l')
self.faceDir = 'l'
self.des_dir = 'l'

To a shortened method, like this:

def change_direction(self, direction):
    if direction == "l" or direction == "r":
        self.moveHorz(direction)
        self.accelerate(direction)
        self.set_crnt_acc(direction)
        self.faceDir = direction
        self.des_dir = direction
    else:
        print("Direction must either be \"l\" or \"r\"")

This is especially useful if you need to repeat this code in many places.

On a side note, you should get rid of the magic values 'l' and 'r' and do something like this:

LEFT = 'l'
RIGHT = 'r'

You could also use integers to represent this as well:

LEFT = 0
RIGHT = 1

Or if you're feeling really adventurous, you can use an Enum, like this:

class Directions(Enum):
    LEFT = 0
    RIGHT = 1


Sudoku solver recursive backtrack in Java

Object Orientated Programming

you don't use object orientated programming! that would clean up the code in a large scale

public class Board {
    //private int[][] board; primitive obsession - use objects instead
    private Field[][] fields;
    private Column[] columns;
    private Row[] rows;
    private Block[] blocks;
    public final static int SIZE = 9;

    ...
}

you could provide the proper methods for the field - so you could easily represent the field - instead of trying to interpret an int value.

you could provide methods that are specific for these objects - you could even define an interface for common code, like isFieldValid(Field candidate) for Row, Column and Block

Naming

consider these names and you might find better

Random rand = new Random();
int random, randomrow, randomcolumn;

maybe it would be

Field candidate;

again here, in Java we don't use the hungarian notation and name a variable by it's type:

//int[][] boardarr = board.getBoard();
int[][] board = board.getBoard(); //would be better
Field[][] fields = board.getFields(); //even more better

Data Structure

if you would use Objects for your Sudoku-Solver you could re-use values (here an example snippet for Block)

class Block {
    final private Set<Field> fields = new HashSet<>();

    boolean isFieldValid(Field field) {
        //Set<Integer> set = new HashSet<>(); we already have such set
        //and don't need to create a new one whenever we check
        return !fields.contains(field);
    }
}

Magic numbers

you already provide a SIZE = 9 constant - so why don't you use a proper one for the block size?

int blockrow = (row / 3) * 3;
int blockcolumn = (column / 3) * 3;

Testing

i assume you provide enough tests but just don't put these in the question

Summary

very nice piece of code - i'm glad you have posted it here! The algorithm seems straight forward, i like it! The OO-thing is the only flaw here. I would appreciate if you would provide another question with applied OOP!


Disclaimer

Because a lot of context is missing, here's the code I will review :

def split_entry(entry):
    splitentry = entry.split(',')
    for ii in range(len(splitentry))[::-1]:
        start_bracket = splitentry[ii].count('[')
        end_bracket = splitentry[ii].count(']')
        if not start_bracket == end_bracket:
            splitentry[ii-1:ii+1] = [splitentry[ii-1] + ',' + splitentry[ii]]
    return splitentry

event_lable = ["id", "date_time", "path", "type","duration","count", "rate"]
raw_data = "1,2014-4-3 10:1:10,somerandompath,some/screwy!stringwithstufflike[0,0,0,0]inIt,0,0;"
events = raw_data.split(';')[:-1]
event_table = [{key:value for key,value in zip(event_lable,split_entry(entry) )} for entry in events ]
print event_table

ii is a pretty bad name. i is twice shorter and so many times easier to understand.

Instead of creating a new list by reversing the return of range, you could just use all the potential of range (or xrange):

Instead of using not A == B, you could write a more natural A != B

Looping over an array using range(len(a)) is an anti-pattern in python. To loop on an array while keeping track of the index, the usual solution is to use enumerate(). In your case, because you are updating the array anyway, it is quite tricky to loop on it.

Final point : I had trouble understanding your list slicing stuff but as I was messing a bit with it, I obtained a result different from yours ('rate' appears in the final result so it might actually be a good thing) :

def split_entry(entry):
    splitentry = entry.split(',')
    for i in xrange(len(splitentry)-1,0,-1):
        chunk = splitentry[i]
        if chunk.count('[') != chunk.count(']'):
                splitentry[i-1] += ',' + chunk
                splitentry[i] = '0'
    return splitentry

event_lable = ["id", "date_time", "path", "type","duration","count", "rate"]
raw_data = "1,2014-4-3 10:1:10,somerandompath,some/screwy!stringwithstufflike[0,0,0,0]inIt,0,0;"
events = raw_data.split(';')[:-1]
event_table = [{key:value for key,value in zip(event_lable,split_entry(entry) )} for entry in events]
print event_table


Fantasy game inventory — Ch. 5 Automate the Boring Stuff

I am suggesting to use fstrings and the dictionary items() method.

The

print(f'{value} {key}')

instead of

print(str(inventory[item]) + ' ' + item)

is more neatly:

def display_inventory(inventory):
    total_items = 0
    print ("Inventory:")

    for key, value in inventory.items():
        print(f'{value} {key}')
        total_items += value

    print(f'Total number of items: {total_items}')

Also, you can just calculate the total number in the needed place by the sum() function and the dictionary values() method. Then, you are not needing the total_items variable.

def display_inventory(inventory):
    print ("Inventory:")

    for key, value in inventory.items():
        print(f'{value} {key}')

    print(f'Total number of items: {sum(inventory.values())}')


Finding the minimum difference in a list of numbers

You're worrying about the wrong problems: there isn't a lot more performance to be squeezed out of your code, but you could make substantial improvements to readability.

Choose a better file format
Why are you encoding the number of lines to be read into the file itself? That seems like redundant information. Just read all the lines there are and use those. You are also redundantly encoding the number of numbers per line: int N = int.Parse(sr.ReadLine());
You aren't doing anything with the parsed value, which is an indication that it shouldn't be in the file to start with.
Make your code reusable
Why not define the algorithm for finding the smallest difference inside an extension method? This allows you to separate the concerns of I/O and your minimum difference finding logic.

public static int SmallestDifference(this IEnumerable<int> source)
{
    var numbers = source as int[] ?? source.ToArray();
    Array.Sort(numbers);
    int difference = int.MaxValue;
    for (int i = 1; i < numbers.Length; i++)
    {
        difference = Math.Min(difference, numbers[i] - numbers[i - 1]);
    }
    return difference;
}

Be expressive
Using the deferred execution streaming File.ReadLines method together with an expressive LINQ query, you can write code that reads fluently and makes sense rather than confusing the reader with details:

var minDifferences = from line in File.ReadLines("IN.in")
                     let numbers = from number in line.Split(' ')
                                   select int.Parse(number)
                     select numbers.SmallestDifference().ToString();
File.WriteAllLines("OUT.out", minDifferences);

Now here's a tiny surprise left for the end:

  This solution consistently performs at least as well as your original code.
  (On average, it's a couple of milliseconds faster per fifty thousand lines, but that's in the realm of microbenchmarking which should be avoided. Just trying to give you a rough idea.)
  So stop worrying about performance; strive for clean code instead.

EDIT: I understand that you can't change the format (as per your comment), so I've added the code below to allow you to stick with your current file layout. The modification required is tiny: simply skip the first line, and only look for the smallest difference in lines that have more than one number.

var minDifferences = from line in File.ReadLines("IN.in").Skip(1)
                     let numbers = from number in line.Split(' ')
                                   select int.Parse(number)
                     where numbers.Count() > 1
                     select numbers.SmallestDifference().ToString();
File.WriteAllLines("OUT.out", minDifferences);


A Java class for reading MaCH dosage files v2.0

I have a number of suggestions:

Exceptions

I don't think your constructor actually throws Exception. Remove it?

Braces in if-blocks

Use braces even for one line if-blocks.

if(start < 1) {
    start = 1;
}
if(end > nCol)  {
    end = nCol;
}

Start parameter adjustment

The adjustment of start can be done before entering the while-loop. Making the while loop shorter and easier to understand. I suggest placing it at the beginning of the function, as you are adjusting an input parameter. Some people think it is bad practice to overwrite a parameter's value, but that depends on your personal taste. I think it is ok in this case, if done at the beginning of the function.

A different way to handle the situation of an incorrect input would be to throw an exception, because clearly the input is incorrect.

Documentation

I'd sugguest adding some comments to at least your public methods, so that the user of your utility function knows how to use it properly. This would also be a good place to document how you handle incorrect input (e.g. the correction of the start value to one, in case the entered value is smaller than 1).

Pattern as static variable

As the used pattern for splitting is a constant, you could handle it as such buy using a static attribute like this:

private static final Pattern splitPattern = Pattern.compile("\\s+");

This saves the jvm from compiling the pattern for each new instance of the Dosage class.

Micro optimization

You can save yourself the firstLine boolean by checking dosageList.isEmpty() instead.


Finding the number of ways to partition {1,2, ..., N} into p1 and p2 such that sum(p1) == sum(p2)

Duplicated code/values

You have both:

s = set([i+1 for i in range(n)])

and

p2 = set(range(1,n+1)) - p1

This is bad because you have the same sets generated in 2 places with 2 different pieces of code:

it is not efficient
it is not easy to read and understand
it is easy to get wrong if you ever need to update the set definition.

You should write something like:

        p2 = frozenset(s - p1)

Various hints

If sum(p1) == sum(p2), then sum(p1) == sum(p2) == sum(s) // 2 and sum(p1) == sum(s) // 2 is a sufficient condition.
You could write something like:

def f(n):
    s = set([i+1 for i in range(n)])
    target_sum = sum(s) / 2
    valid_partitions = []
    for i in range(1,n):
        for c in combinations(s,i):
            if sum(c) == target_sum:
                p1 = frozenset(c)
                p2 = frozenset(s - p1)
                valid_partitions.append(frozenset((p1,p2)))
    return len(set(valid_partitions))

You could just consider only p1 without bothering about p2. Partitions would be counted twice but you can always divide the result at the end. Once you start this, you realise that all the logic about removing duplicates can be removed (all generation combinations are unique): you do not need sets and you do not need frozensets:

def f(n):
    s = set([i+1 for i in range(n)])
    target_sum = sum(s) / 2
    valid_partitions = []
    for i in range(1,n):
        for c in combinations(s,i):
            if sum(c) == target_sum:
                valid_partitions.append(c)
    return len(valid_partitions) // 2

Then, you do not need the have all partitions in a container, a simple counter will do the trick:

def f(n):
    s = set([i+1 for i in range(n)])
    target_sum = sum(s) / 2
    nb_partitions = 0
    for i in range(1,n):
        for c in combinations(s,i):
            if sum(c) == target_sum:
                nb_partitions += 1
    return nb_partitions // 2

Then, if you want to make things more concise, you could use the sum builtin and use the fact that True is 1 and False is 0 to write something like:

def f(n):
    s = set([i+1 for i in range(n)])
    target_sum = sum(s) / 2
    return sum(sum(c) == target_sum for i in range(1, n) for c in combinations(s, i)) // 2

Final optimisation

If you look at the value returned for the first 19 values, you get something like:

0 0
1 0
2 0
3 1
4 1
5 0
6 0
7 4
8 7
9 0
10 0
11 35
12 62
13 0
14 0
15 361
16 657
17 0
18 0
19 4110

We can see that the functions return 0 in 1 case out of 2. This corresponds to the fact that we cannot partition an odd sum. This can be taken into account to avoid computing combinations when this happens:

def f(n):
    s = set([i+1 for i in range(n)])
    target_sum, rem = divmod(sum(s), 2)
    if rem:
        return 0
    return sum(sum(c) == target_sum for i in range(1, n) for c in combinations(s, i)) // 2

Last detail

Your first call to set is useless because the elements are unique already and you just need an iterable. Also, you could get rid of the list comprehension by tweaking the parameters given to range: s = range(1, n+1).


JavaScript queue implementation using linked list

Some observations in addition to the other answer:

inconsistent space between function name and () - use eslint or similar to prevent typos
Node is used as a template for extra properties, not as a type, so I doubt its name should be capitalized as though it's a class. Also, it's effectively unused in your code.
const in JS is not for named constants only, but for any value that's assigned just once:

  The reason is simple, it's much easier to reason about code when it is dead obvious what can change and what cannot change. [...]

  Going back and changing a const to a let is dead simple. And going const by default makes you think twice before doing so. And this is in many cases a good thing.

  How many bugs have you seen that involved variables changing unexpectedly? I'd guess a lot. I know that the majority of bugs that I see involve unexpected state changes. You won't get rid of all of these bugs by liberally using const, but you will get rid of a lot of them!

+ if you use a JavaScript IDE, it'll warn about accidental reassignment of a const identifier.
A separate assignment statement with newNode doesn't seem warranted as the code would be just as obvious with a direct assignment to head.
getSize is too verbose. I suggest exposing it as size just like the read-only size getter in Map and Set.
Since you're using ES2015, also use object literal shorthand:

return {
  enqueue,
  dequeue,
  size: getSize
};