Given a list of numbers and a number, return whether any two numbers from the list add up to

Indents
PEP 8: Use 4 spaces per indentation level.

True if condition else False
The pattern True if condition else False can be replaced by condition if it evaluates to a bool. If you are checking for truthy and falsey values you can replace the pattern by bool(condition).
While this lets us simplify the return statement
return any([sum(pair) == k for pair in c_k_2])

it actually performs worse (as pointed out by Manuel in the comments) without implementing further improvements (see the next point). While you originally create a list of only True values, this simplification will create a list that also includes all the False values, which we do not need at all.

Drop the list
You convert to a list twice in your code, once explicitly by calling the list(...) constructor and once implicitly by wrapping a generator expression with [...]. In your particular use case, both are unnecessary.
When dropping the call to the list constructor, combinations(numbers, 2) will provide an itertools.combinations object, which I would assume behaves similiarly to a generator, which is a lazily evaluated iterable. This way we don't compute and store all possible combinations of numbers in advance, which is perfect for us because we

only need one pair of numbers at a time
want to stop evaluating the expression once we find a pair that matches our criteria

Dropping the brackets [] around our generator expression follows the same logic.
Generator expressions vs. list comprehensions on StackOverflow

Applying these improvements will make the code more efficient, more readable and more concise:
def any_two_elements_add_up_to(numbers, k):
    pairs = combinations(numbers, 2)
    return any(sum(pair) == k for pair in pairs)

# or as a one-liner

def any_two_elements_add_up_to(numbers, k):
    return any(sum(pair) == k for pair in combinations(numbers, 2))

EDIT: Algorithm
I've tried my hand at a faster approach, this is the first solution I came up with. Although it's really simple it still outperforms the above solution by orders of magnitude as it runs in O(n).
Here's the code:
def new_approach(numbers, target):
    counterparts = set()

    for num in numbers:
        if num in counterparts:
            return True

        counterparts.add(target - num)

    return False

Since every number only has one counterpart k - x that would make it add up to k, we can keep a set of all possible counterparts that we've identified so far. Once we come across a number that is in our set of counterparts (i.e. adds up to k with a previous number) we return True. If we don't come across one such number, we simply return False.


Overall, this is pretty good. It's straightforward and to the point. Here are some other thoughts.

Don't Declare PI

You don't need to declare π. It's already declared in math.h as M_PI. Though in C++, it's preferred to #include <cmath> instead, which will put the standard math functions into the std namespace. In C++11 and later, it's suggested to use a calculation to define it such as:

const auto kPi = std::acos(-1.0);

Declare Functions constexpr When Appropriate

You don't say whether you're using C++11 or higher, or not. If you are, I would recommend declaring your degToRad() function constexpr so that it can be used in the definition of constants.

Don't Repeat Yourself

You have some code inside your loop that always calculates the same thing each iteration. The definition of mRelP, and mouseAngle should be moved outside the loop so you do less work in the loop.

Naming

mRelP is a confusing name. In many codebases it's a convention to prepend "m" to member variables. I'd just call it something more readable like mouseRelPos.


It would be a good idea to reimplement the whole thing using a regular expression.  Some uninitiated programmers despise or fear regular expressions, but in this case, avoiding them just means that you are giving up a language feature that is designed to solve just this kind of problem, forcing you to reinvent the wheel.

function parseJavaScriptPathIntoKeyNames(path) {
    /**
     * Repeatedly capture either:
     * - a bracketed expression, discarding optional matching quotes inside, or
     * - an unbracketed expression, delimited by a dot or a bracket.
     */
    var re = /\[("|'|)(.*?)\1\]|([^.\[\]]+)/g;

    var elements = [];
    var result;
    while ((result = re.exec(path)) !== null) {
        elements.push(result[2] || result[3]);
    }
    return elements;
}

I can't say for sure that this version behaves exactly the same as the original, especially in the face of illegal input.  However, the reduction in code makes it a much more worthwhile approach, and you can work out the details.


Returns all primes p between m <= p <= n

Here are a few things that may help you improve your program.

Improve your algorithm

Right now, within the isPrime routine, the loop begins at 2 and does a test division of every number from \$2\$ to \$\sqrt{n}\$.  However, we already know that other than 2, all prime numbers are odd.  You can approximately double the speed of this algorithm by writing it like this instead:

bool isPrime(int n) {
    if (n == 1) return false;
    if (n == 2) return true;
    if (n % 2) return false;
    int root = int(ceil(sqrt(n)));
    for (int i = 3; i <= root; i+=2){
        if (n % i == 0) return false;
    }
    return true;
}

Prefer for to while where appropriate

The input section of the code has these lines:

int tempA = 0;
while (tempA < 2*lines) {
    cin >> toPush;
    inputs.push_back(toPush);
    ++tempA;
}

It seems to me that this would be more clear as a for loop:

for(int tempA = 2*lines; tempA; --tempA) {
    std::cin >> toPush;
    inputs.push_back(toPush);
}

The same is true for the main loop in the program.  It could be written this way:

for (auto i = inputs.begin(); i != inputs.end(); ++i) {
    for (int m = *i++, n=*i; m <= n; ++m) {
        if (isPrime(m)){
            std::cout << m << " ";
        }
    }
    std::cout << '\n';
}

Store std::pairs instead of ints

After the first number, the program's input consists of pairs.  It might make more sense to store them in a std::vector<std::pair<int, int>>

The input routine would then look like this:

for(int tempA = 2*lines; tempA; --tempA) {
    std::pair<int, int> toPush;
    std::cin >> toPush.first >> toPush.second;
    inputs.push_back(toPush);
}

The main loop is then considerably simplified by the use of the pair and a "range-for" outer loop:

for (const auto &lim : inputs) {
    for (int m = lim.first; m <= lim.second; ++m) {
        if (isPrime(m)){
            std::cout << m << " ";
        }
    }
    std::cout << '\n';
}

}

Use a better algorithm

The code works as it is, but could be still further improved.  Since the inputs are all read at the beginning, you could choose the largest upper bound and run a sieve of Eratosthenes to derive all primes up to that number.  Then printing for any range would be simply a matter of lookup.


Counting numbers that have an even number of digits

A couple of points. Firstly about the code you have listed.

Are the constraints problems to be enforced or assumptions you can make while writing your solution? It's odd to artificially limit it.

len does not need to be defined outside the loop. It is overwritten on each loop so could be replaced with let len =  inside the loop.

Within the for loop, you are counting the number of digits, then checking the size of num and panicking if it's too high. It's better in general to exit as soon as possible if something's wrong, so in this case check the size before the more expensive process of counting digits.

In your character counting you are converting to characters, then back to digits before counting. If you only care about how many of them there are, you can leave them as characters. This gives num.to_string().chars().collect();

Once you have an iterator, you can use count instead of collecting to a vec and then finding the length. This reduces it further to let len = num.to_string().chars().count()

The outer for loop can also be replaced with an iterator
nums.iter()
        .map(|n| n.to_string().chars().count())
        .filter(|n| n % 2 == 0)
        .count();

This then doesn't need the count variable either.

Secondly, you ask about other ways to solve the problem. Converting between numbers and strings is slow, and keeping things as numbers wherever possible is generally preferable. In this case, the number of digits in a number (in base 10) is log10 of that number rounded up to the next integer. The edge cases are the powers of 10 which need to be 'rounded' to the next number.
The difficulty in writing this in rust is that log10 is only available for floating point types but as your values are bound 1 <= n <= 100_000, you can assume that all values can be mapped exactly to an f32. Numbers being >1 means that you can safely find a log (log isn't defined for negative numbers).
This lets you rewrite your method as something like
impl Solution {
    pub fn find_numbers(nums: Vec<i32>) -> i32 {
        // iterate over the numbers
        nums.iter()
            // for each n, find log10(n), round down and +1
            // this is the number of digits
            .map(|n| (*n as f32).log10().floor() as i32 + 1)
            // discard numbers that don't have an even number of digits
            .filter(|n| n % 2 == 0)
            // count how many are left
            .count()
    }
}

There is no restriction here of the size  or number of numbers. If that is required, an additional check can be made before the iter call.


Setter method for an object using a special logic

Why do you recreate this.exits every time you add new items? This:
                    final List<CoordinateBE> result = new ArrayList<>();
                    result.addAll(getExits());
                    result.addAll(exits);
                    this.exits = result;

could be simplified to
                    this.exits.addAll(exits);

If coordinates are always meaningfully equal based on latitude + longitude, you may want to override equals() and hashCode() so that so you can better leverage built-in methods. With an overrided equals(), you would not need compareCoordinates, and existenceOfCoordinates could be replaced with collection methods.
For example:
private boolean existenceOfCoordinates2(List<CoordinateBE> a, List<CoordinateBE> b) {
  return b.stream().anyMatch(a::contains);
}

With the above simplifications, (I'll skip the equals() override in case you actually don't want that), it's distilled down to:
public void setExits(final List<CoordinateBE> exits) {
  if (!getExits().isEmpty()) {
    // Check that no new exits are already in the list
    for (CoordinateBE exit : getExits()) {
      if (exits.stream().anyMatch(x -> compareCoordinates(x, c))) {
        return;
      }
    }
  }

  this.exits.addAll(exits);
}

// If CoordinateBE overrides equals(), you could also do:

public void setExits(final List<CoordinateBE> exits) {
  // In this case, I'm not checking whether this.exits is empty, because
  // we're streaming the new exits as opposed to the current, and that stream
  // will just be empty if the new exits are empty.
  if (exits.stream().anyMatch(this.exits::contains)) {
    return;
  }
  this.exits.addAll(exits);
}

Finally, I am assuming that order is important here, which is why you're using a List as opposed to a Set. Even so, if you're okay with overriding equals() and if duplicates are not allowed, using a LinkedHashSet for this.exits would likely be faster beyond lists of a few dozen elements.


Remove extra spaces from a string without using Regex or any internal library methods

A few things to point out.

char[] longChars = longString.ToCharArray();

strings in C# are array-like, and can be indexed directly. We don't need to convert it into a char[].

int spaceCount = 0;

We don't really need to keep track of how many spaces so much as whether the last character was a space. Therefore, this can become a boolean flag instead.

if (longChars[i] == 32)

This line has a magic number (32), and that makes it a little harder to understand. I'm guessing it's the Unicode number for the space character, but the fact that I have to guess makes it bad. Better would be: if(longChars[i] == ' '), but best would be: if(Char.IsWhiteSpace(longChars[i])). That catches all potential whitespace characters, and will be more robust. Also, it makes your intention much clearer.

if (spaceCount > 1 && sb.Length > 0)
    sb.Append(" ");

I always recommend using braces in light of goto fail.

//Reset the space count
spaceCount = 1;

This confuses me. You say you are "resetting" the space count, but the original value was 0, not 1, so I might (incorrectly) think this is a bug and try to fix it. The root of this issue lies in how you are tracking spaces.

So incorporating those suggestions, here's what I come up with:

public static string Despace(string longString) {
    StringBuilder sb = new StringBuilder();
    bool lastWasSpace = true; // True to eliminate leading spaces

    for(int i = 0; i < longString.Length; i++) {
        if(Char.IsWhiteSpace(longString[i]) && lastWasSpace) {
            continue;
        }

        lastWasSpace = Char.IsWhiteSpace(longString[i]);

        sb.Append(longString[i]);
    }

    // The last character might be a space
    if(Char.IsWhiteSpace(sb[sb.Length - 1])) {
        sb.Remove(sb.Length - 1, 1);
    }

    return sb.ToString();
}


Making C++11 range-based for loops a bit more useful

You can use braces to return from your functions. That way, you won't have to repeat long and cumbersome types (DRY, as much as possible). For example, ConditionalRange::end:

iterator_type end() const
{
    return { range.end(), range.end(), condition };
}

Also, you probably want your function to accept C-style arrays too. Therefore, you should use std::begin and std::end instead of calling the member functions:

iterator_type end() const
{
    return { std::end(range), std::end(range), condition };
}

With that (everywhere in your code) and some trivial changes, your code will also work for C-style arrays (tested here and it works fine).

Naming your function

The name makeConditionalRange is quite long. The function you created already exists in other libraries and programming languages (Python comes to my mind) under the name filter. You should consider changing its name in order for many users to recognize the name at first glance (moreover, it will be shorter).


Testable authentication handler for web API

Basically you need somehow confirm that

StatusCode == HttpStatusCode.Unauthorized
ReasonPhrase == someDefinedConstant

If you only Assert the first, you can't be sure that the logic is flawless. If you only test the second you can't be sure that StatusCode == HttpStatusCode.Unauthorized.

But again, proper unit tests should fail exactly for one reason.

As others had this problem also, Omer Rauchwerger has created a NUnit addin which can be found here: http://rauchy.net/oapt/

Comments

Comments should be used to describe why something is done. The code itself should describe what is done.
So comments like // Check for API key should be removed and the code following should be extracted to a separate method.

timestamp validation

As the message will be "Timestamp is required" for a failed validation, I guess that you need to check if at least one key is found. There it is better to use Any() over Count().

Style

You should be consistent in your coding style. Here you one time use if (!condition) and another time you use if (condition == false).

Refactoring

Extracted validation methods

private bool ContainsApiKey(HttpRequestMessage request)
{
    return request.Headers.Contains(AuthConfig.ApiKeyHeader);
}

private bool ContainsTimeStamp(HttpRequestMessage request)
{
    return request.GetQueryNameValuePairs().Any(k => k.Key.ToLower() == "timestamp");
}

private bool ContainsSignature(HttpRequestMessage request)
{
    return (request.Headers.Authorization != null && request.Headers.Authorization.Scheme == AuthConfig.AuthenticationScheme);
}

private UserDTO GetUser(HttpRequestMessage request)
{
    string apikey = request.Headers.GetValues(AuthConfig.ApiKeyHeader).First();
    return  _userRepo.GetUserAuthInfo(apikey);
}

private bool IsValidUser(UserDTO user)
{
    return user != null;
}

private bool IsValidSignature(UserDTO user, HttpRequestMessage request)
{
    string signature = _signatureCalculator.GetSignature(user.Secret, request.RequestUri.OriginalString);
    return  request.Headers.Authorization.Parameter == signature
}

and the cleaned up former method

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{

    if (!ContainsApiKey(request))
    {
        return SendResponseText(SecurityHandler.AuthError.ApiKeyMissing);
    }

    if (!ContainsTimeStamp(request))
    {
        return SendResponseText(SecurityHandler.AuthError.TimeStampMissing);
    }

    if (!IsValidTimestamp(request))
    {
        return SendResponseText(SecurityHandler.AuthError.TimeStampInvalid);
    }

    if (!ContainsSignature(request))
    {
        return SendResponseText(SecurityHandler.AuthError.SignatureMissing);
    }

    UserDTO user = GetUser(request);
    if (!IsValidUser(user))
    {
        return SendResponseText(SecurityHandler.AuthError.ApiKeyInvalid);
    }

    if (!IsValidSignature(user,request))
    {
        return SendResponseText(SecurityHandler.AuthError.SignatureInvalid);
    }

    return base.SendAsync(request, cancellationToken);
}


Your Main method has too many responsibilities: it's your application's composition root, and it's executing the program's logic... if printing to Console can be considered logic.

There's not enough meat in this project to even justify using DI/IoC: you have a service that nothing depends on.

If you had, say, an Application class:

public interface IApplication
{
    void Run();
}

public class Application : IApplication
{
    private readonly IBatchService _service;
    public Application(IBatchService service)
    {
        _service = service;
    }

    public void Run()
    {
        _service.WriteInformation("Injected!");
    }
}

...then composition would refer to resolving all dependencies of an Application instance, regardless of how complex that might be.

The Main method would only ask for an Application instance (let's call it app), and your IoC container would do its job - the Main method would only call app.Run();, and the rest of the application doesn't need to know there's an IoC container involved.

You don't need the static IContainer field; I've never used Autofac (you should look into Ninject, seems much simpler), but your IoC container should only live (and die) in the Main method - if you're using it anywhere else, you're doing something wrong (Service Locator).

I'd make it something like this:

static void Main(string[] args)
{
    var builder = new ContainerBuilder();

    builder.RegisterType<BatchService.BatchService>().As<IBatchService>();
    var container = builder.Build();

    using (var scope = container.BeginLifetimeScope())
    {
        var app = scope.Resolve<IApplication>();
        app.Run();
    }
}

Then your Main method is done with. If you're going to expand the application, you just inject new dependencies, and consume them.

Actually, this:

builder.RegisterType<BatchService.BatchService>().As<IBatchService>();

I'd move elsewhere; as your application grows, you'll be registering tons of stuff here, registration is a concern of its own, that deserves its own class IMO. That class can be static for all you care, it's infrastructure stuff, its only goal is to spit out a configured IContainer.

The configuration class could look like this:

public static class ContainerConfig
{
    public static IContainer Configure()
    {
        var builder = new ContainerBuilder();

        builder.RegisterType<BatchService.BatchService>().As<IBatchService>();
        // add other registrations here...

        return builder.Build();
    }
}

Leaving your Main method like this:

static void Main(string[] args)
{
    var container = ContainerConfig.Configure();
    using (var scope = container.BeginLifetimeScope())
    {
        var app = scope.Resolve<IApplication>();
        app.Run();
    }
}


Use a data frame of functions to calculate values using specific columns in another data frame

I would suggest you merge your data.frames so you can split the data per function:

mg <- merge(funcs_df, tree_df)
sp <- split(mg, mg$funcs)

print(sp)
# $func1
#   spcd region funcs dbh  ht
# 2  122   OR_W func1  12 101
# 3  122   OR_W func1  21  76
# 5  141   OR_W func1  15 100
# 6  141   OR_W func1  10  88
#
# $func2
#   spcd region funcs dbh  ht
# 1  122   OR_E func2  11  99
# 4  141   OR_E func2  13 121

Then, you just have to call each function once (since you confirmed the functions are vectorized):

cvts_list <- Map(function(fun, x) fun(x$dbh, x$ht),
                 fun = mget(names(sp)), x = sp)

print(cvts_list)
# $func1
# [1] 245 517 325 188
#
# $func2
# [1] 22 48

and stack the results into a new column, using unsplit:

mg$cvts <- unsplit(cvts_list, mg$funcs)

print(mg)
#   spcd region funcs dbh  ht cvts
# 1  122   OR_E func2  11  99   22
# 2  122   OR_W func1  12 101  245
# 3  122   OR_W func1  21  76  517
# 4  141   OR_E func2  13 121   48
# 5  141   OR_W func1  15 100  325
# 6  141   OR_W func1  10  88  188


Since you're not using the try-with-resources statement with Scanner, you must close it at the end of main() to avoid leaking resources:

in.close();

You should consider converting a to uppercase, in case the input is in lowercase.

I would also rename a to something like guess.  The name a says nothing about this variable, and it's generally discouraged to use single-letter variable names.

String guess = in.nextLine().toUpperCase();

The renaming also applies to arr.  You could name it something like elemsToCheck.


One edge case you're missing is how to handle null. isEmpty(null) will  fail because Object.getOwnPropertyNames(null) will throw TypeError: can't convert null to object.

Also be aware that isEmpty(NaN) will return false, which may or may not be what you want.


Generate next available filename based on current date

Your code can be made much simpler:

var basename = today;
var filename;
for (var k = 0; fs.existsSync(filename = './' + basename + '.pdf'); k++) {
    basename = today + ' (' + k + ')';
}
return filename;


Reinitialize cache periodically, catching and logging any Throwables

That is exactly what Sonar says: "... from which an application should not attempt to recover".

Thus, if you catch Exception and NOT Error, yes, this will effectively terminate your scheduler and probably impact the DataStore. BUT: as Errors indicate a severity, where the VM probably won't be working reliably anyway (also see https://docs.oracle.com/javase/8/docs/api/java/lang/Error.html) this is exactly the thing to do: terminate the program, bail out, call the admin. When you continue working under error conditions, the result is generally somewhat undefined. Better avoid this.


Generating a performance report for clans in Clash Royale

Cool project!
Good work so far.
Clean code is important and that's one of the things I struggle with. A lot.
From your code, I can see that you would benefit a lot from that too.
const token = "TOKEN_HERE";

Tokens and sensitive information you should try to store in .env files. Especially if your code might be accessible on github or similar sites.
const mergeByProperty...

This function seems too complicated for what you want to do. I really don't think you need it at all.
Same for this:
const finalise...

Try to extract logic into functions, especially if you need to use it in other places.
Try to identify repeating code, if you see that, then you might be able to create a function for it.
Do not repeat yourself. Code you repeat is hard to maintain because if you make a small change you need to make that change everywhere.
Naming your functions and variables is equally important and it's harder than it seems.
This is what I would do differently (and even this can be improved a lot):
const baseUrl = 'https://proxy.royaleapi.dev/v1/clans';
const clanUrl =  `${baseUrl}/#${clanTag}/`;
const requestOptions = {
    headers: {
        authorization: token
        }
    }

// wrap your requests into a promise
const GET = (url, options = {}) => {
    return new Promise((resolve, reject) => {
        const request = https.get(url, options, (response) => {
            if (response.statusCode < 200 || response.statusCode > 299) {
                reject(new Error(response.statusCode));
            }
            let data = '';
            response.on('data', (chunk) => data += chunk);
            response.on('end', () => resolve(JSON.parse(data)));
        });
        request.on('error', (err) => reject(err))
    })
};

// do all the data manipulation inside these helper functions
// this transforms the data you get from the server into the format
// you want

const getMembers = (members) => {
    const donors = {
        top: [...members].sort((a, b) => b.donations - a.donations).slice(0, 10),
        worst: [...members].filter(x => x.donations < 100).sort((a, b) => a.donations - b.donations)
    }
    return donors;
}

// transform the data from server into the format you want

const getCurrentRiverRace= (clanParticipants) => {
    const clan = {
        participants: clanParticipants,
        bestPlayers: [...clanParticipants].map(x => {
            return {
                ...x,
                netScore: x.fame * x.donations / 100000
            };
        }).sort((a,b) => b.netScore - a.netScore).slice(0, 10)
    }
    return clan;
}

// this one makes both requests to the server at the same time
// Notice the async. Since your requests return promises, this is how you
// handle the promises

const requests = async () => {
    const membersCall = GET(`${clanUrl}/members`, requestOptions);
    const riverRaceCall = GET(`${clanUrl}/currentriverrace`, requestOptions);
    const [members, riverRace] = await Promise.all([membersCall, riverRaceCall]);

    return {
        members: getMembers(members),
        riverRace: getCurrentRiverRace(riverRace)
    }
}

// here you just 'finalise' or output whatever you want
// you should handle the errors so maybe wrap it in a try/catch.

const output = async () => {
    try {
        //
        const r = await requests();
        const stats = `
        CR Clan Youtube Weekly Report
        °•°•°•°•°•°•°•°•°•°•°•°•

        — Top Donators ——
        ${stats.members.top}
        ....
        `;

        console.log(stats);
        return stats;
   } catch (err) {
       // here you handle the error in case the promise rejects
       // (returns error)
       // console.log is NOT error handling but it gives you an idea

       console.log(err);
   }
}

Try to puzzle it together. I'm not sure if it's 100% functional but it should be pretty close. Consider it a homework :)


I got here reading about garbage collection and memory leakage in CS. It's an old post but I 'll give my 2 cents anyway. When emptying an array it's often recommended to avoid using array = [], but use array.length = 0.

Also, in functions that you don't indent to return, perhaps it's better to implicitly return undefined so that to avoid returning functions just because they appear at the very end of your CS function call.


Compare result files from two different runs the smart way?

Simplify all the things! You and your users will benefit from simplicity.

Option parsing

If the --compare option is either True or False, make it a boolean flag with False as the default value. Your users won't have to remember if the --compare argument is 1, true or yes, they will simply write --compare.

You should also consider moving from optparse to argparse: optparse is deprecated since Python 2.7 and Python 3.2 and could be removed in any future release.

About your assumptions

If the pickle file is moved away from data_output, then the users will simply see that the file is missing. You could catch the resulting exception to ask them to first run the program without comparison.
If the removing fails, then something is really wrong anyway.

I don't think resolving those specific issues is the way to go, and it should be easier for your users to provide this comparison feature differently.

Comparison logic

Your current solution is mostly a hack. It looks like you only asked yourself: what is the simplest way to implement this? The question should be different: what is the simplest way to use this?

Say I want to compare 2010 and 2011. I first run your program with 2010, then with 2011 plus comparison. What if I actually made a typo and typed 2010 instead of 2009? What if one of the options for 2011 was wrong? I have to start all over again. Very frustrating since the processing is slow.

I don't know your program well enough to be sure, but the simplest way could be to provide a --dump option, so that users would dump the first dataset (slow), dump the second dataset (slow), then compare the two (fast!).

It would also be even clearer to provide two binaries, one for processing the datasets, and another one for comparison: this would reduce confusion.

Users are now in control and understand what happens and how the comparison works. Fixing any issue does not require to run processing for the two datasets. User won't delete the dumped files, and if they did, that would be their fault since you exposed those files to them.


Instead of comparing the class with if( source.getClass() == ColorButton.class) you can use if (source instanceof ColorButton). This is preferable in case you would make a subclass of ColorButton. If it's an instance of a subclass of ColorButton it is still an instanceof but source.getClass() != ColorButton.class.

With the way that you are using the code above, I would save the color in the listener instead of in the button. This way you don't need the if statement in your code at all, since you can pass the appropriate type to the Listener. In this case, .setBackground is declared in the JComponent class so all you need to make sure is that it's a JComponent that gets passed to the Listener, which is no problem:

static class Listener implements ActionListener {
    private Color color;
    private JComponent comp;
    public Listener(JComponent comp, Color color) {
        this.color = color;
        this.comp = comp;
    }
    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        comp.setBackground(this.color);
    }
}

By using this, you don't need the ColorButton subclass, instead you create multiple instances of your listener:

JPanel panel = new JPanel();
JButton b = new JButton("Blue");
JButton r = new JButton("Red");
r.addActionListener(new Listener(panel, Color.BLUE));
b.addActionListener(new Listener(panel, Color.RED));
panel.add(b);
panel.add(r);
add(panel);


Get all data from an external and paginated Swagger API using Java / Feign / Spring

I see these lines in your code :
List<Item> items = restPage.getContent();
List<Item> result = new ArrayList<Item>();
result.addAll(items);

You can use the ArrayList(Collection<? extends E> c) constructor obtaining the same result:
List<Item> result = new ArrayList<>(restPage.getContent());

Your filtering code looks good to me and for the for loop adding elements to an existing list for me you made the right choice. Although it is possible to add new elements to an existing list using streams this is discouraged because easy cause of errors, see for example this thread.


I would put the try/catch over as little code as possible.  This also makes it easier to add an else case to the if statement if necessary.  For example:

String parsedValue = DEFAULT_VALUE;
if (myValue != null) {
  try {
    parsedValue = parse(myValue);
  } catch (ParseException e) {
    log(e);
  }
} else {
  log(new Exception("Empty myValue!"));
}

This allows for more flexibility than the other version.

As a general rule, it's best to put as little code inside a try block as possible.  Only things that can throw an exception that should be caught by the catch and connecting code.  One reason is that other code than you originally intended may throw the exception and the solution in the catch block may not apply to the new case.


Here's a recursive definition of reverse (named rev) that uses primitives (car/cdr/cons) and an inner definition of snoc (reverse cons):

(define (rev lis)
  (define (snoc elem lis)
    (if (null? lis)
        (cons elem lis)
        (cons (car lis) (snoc elem (cdr lis)))))
  (if (null? lis)
      lis
      (snoc (car lis) (rev (cdr lis)))))

Obviously, this definition is not meant to be efficient. =)


Simulating gravitational attraction between bodies - follow up

Disclaimer: I have no idea about Unity3D.

that being said, if there is no reason regarding Unity3D to keep this public

public float gravityConstant = 1;
public Vector3 startingForce;

then make it private.

I don't like this method writing style

public void Start()
{ this.rigidbody.AddForce(this.startingForce); }

public void FixedUpdate()
{ this.ApplyAttraction(); }

IMO if something doesn't fit good into the same line, one should use 4 lines of code.

The only obvious place where you can gain some performance boost would be at calculating the attraction.

float attraction =
              (this.gravityConstant * this.rigidbody.mass * body.rigidbody.mass)
            / (Mathf.Pow(force.magnitude, 2));

instead of calling Mathf.Pow(force.magnitude, 2) a simple force.magnitude * force.magnitude will be faster, because there won't be done any checks if e.g the power contains a valid value.


What is a better way to get unique array Items based on key in PHP?

Assuming your array is already sorted, you can just overwrite the values every time. Skip the inner if.

function uniqueAssocArray($array, $uniqueKey) {
    if (!is_array($array)) {
        return array();
    }
    $uniqueKeys = array();
    foreach ($array as $key => $item) {
        $groupBy=$item[$uniqueKey];
        if (isset( $uniqueKeys[$groupBy]))
        {
            //compare $item with $uniqueKeys[$groupBy] and decide if you
            //want to use the new item
            $replace= ...
        }
        else
        {
            $replace=true;
        }
        if ($replace) $uniqueKeys[$groupBy] = $item;
    }
    return $uniqueKeys;
}


Just like bogosort will never be a fast sorting algorithm. Your "throw away the board and randomly place N new queens" solution will never really be faster than those 5 to 10 seconds.

Nevertheless it made me happy to see that it actually does find a solution somewhat consistently. And the question itself is composed fine as well, so I do think it deserves an answer.

Like CiaPan already suggested in a comment a far better way to solve the n-queens problem is with backtracking. My quick test program with this approach solves the 8-queens in 1 millisecond (or less). (And a the 20-queens in 50 ms).

However, the "reset and randomly place n new queens" approach is interesting to see, so let's add one major improvement to speed up finding a solution.

/** placeQueens randomly places eight queens on the board*/
public static void placeQueens(char[] board) {
    int location;
    for (int i = 0; i < 8; i++) {
        do {
            location = placeQueens(i);
        } while (isOccupied(board[location]));
        board[location] = 'Q';
    }
}

/** placeQueens randomly places one queen on the board */
public static int placeQueens(int row) {
    return row * 8 + (int)(Math.random() * 8);
}

This little change here got the time till solution down to under 100 ms consistently.
Why? Because this reduces the search space from O(n³) to O(n²).
The reason this works, is that in all solutions there is exactly 1 queen on each row. So I generate one randomly for each row, instead of on the entire board.


Asynchronous wrapper for database connection

I would first start by saying that such a class is generally regarded as a bad practice because it doesn't achieve what's supposed to do, or simply there are better ways of doing it.

But let's go to the actual code, in the ConnectAsync method.

var connectionTask = Task.Run(() =>
{
    try
    {
        var _loader = new DatabaseDriverLoader();
        DatabaseDriver _driver = _loader.Connect(connectionString, login, password);
    }
    catch (Exception e) { }
});

Here you delegate the connection to the main class and initialize the _driver field. The first problem is that, since it's wrapped in a Task, it uses a separate thread and that new thread is the blocked one instead of the calling one. In a desktop program, it can be  a good thing (since it keeps the UI thread free to handle the UI), but in a web site you free the original thread and stall another one, which is what you want to avoid with an async method.

Even worse, the empty catch block will swallow any exceptions, so you won't get any clue why a connection fails if that happens.

The next part also has its problems:

await Task.Run(async () =>
{
    while(!connectionTask.IsCompleted && !cancellationToken.IsCancellationRequested)
    {
        await Task.Delay(100);
    }
});

This employs a second thread and loops until the first one finishes or the cancellation is requested. While it sounds neat in principle, it actually ends up using double the resources it should for the ability to "cancel" the connection (more on that latter), which is far suboptimal. Callers expect NO threads consumed when you see an async DB connection, but instead this code stalls 2 of them.

What to do instead?

In short, leave the decision to the caller! This class introduced some side effects that callers normally don't expect. In web pages, it consumes far more resources than necesary, and in desktop programs it can be simply invoked via Task.Run method directly, instead of wrapping in a class, if keeping the UI responsive is desired. This removes the need for this class, using the provided driver directly.

About your other points

  Be able to connect asynchronously (not waiting for actual connection)

It clearly does that, but I would simply use the first chunk of code (awaiting for it) directly, and remove the need for this, because of unwanted side effects.

  Be able to cancel the connection if I need to

Here is the bigger catch. It does NOT cancel the connection at all!  When the cancellation token is triggered, the loop is interrupted, but the first thread is left running, and its result is ignored. This means that if the connection succeeds, you have a floating connection that won't be disposed of properly, and the involved resources will still be consumed. The only practical effect of cancellation is the early return.

  Maybe Connect method should return successful Task when connection occurs?

Yes, that's a good practice. I don't see a particular use for an event here (not that it's a bad thing to have one, but it serves little purpose). Most important, in its current form, the code does return a task and completes it on sucessful connection, and that's what you use in your "demo" code in fact. That's a good thing.


A C++ program to check if a string is a pangram

Here are a number of things that may help you improve your program.
Make sure you have all required #includes
The code uses toupper but doesn't #include <cctype>.
Eliminate spurious semicolons
The code has a number of spurious semicolons immediately after closing braces.  They don't bother the compiler but they will bother any other programmer who looks at your code.
Check your if statements for proper braces
It appears from the indentation in the if statement in the isPangram routine is not what you intended to write.  The only thing that is currently associated with the if statement is index = c - 'A'; -- all of the lines after that are executed in every case.
Initialize variables before use
The index variable, as mentioned above, may or may not actually get initialized to anything as it's currently written.  That leads to undefined behavior of your program, which is not a good thing.  Best practice is to initialize variables when they are declared.
Return boolean values directly
The isPangram ends with this strange construct:
if(std::any_of(hash_table.begin(), hash_table.end(), [](bool v) { return !v; })) {
    return false;
}
return true;

Here's a much more direct way to do that:
return std::all_of(hash_table.begin(), hash_table.end(), [](bool v){return v;});

Similarly, within main, I'd write this:
std::cout << (isPangram(str) ? "Yes" : "No" ) << '\n';

Consider a more efficient approach
Consider that the the transform must necessarily visit every letter.  We then make another pass through with the main loop.  It is possible to do everything in a single pass.
Don't use std::endl unless you really need to flush the stream
The difference between std::endl and '\n' is that std::endl actually flushes the stream. This can be a costly operation in terms of processing time, so it's best to get in the habit of only using it when flushing the stream is actually required. It's not for this code.
Eliminate return 0 at the end of main
When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so it is not necessary to explicitly write that.  Some people prefer to do so for style reasons, but it's important to know that it's not required by the standard.
Consider using std::spanstd::accumulate
If your compiler is C++20 capable, this would be a good use of std::accumulate (not std::span as I originally wrote).  This version is faster than anything so far.
// helper function for isPangram_accum
constexpr uint_fast32_t charToMask(const unsigned char c){
    // can't use non-const toupper in constexpr function
    unsigned index{(c | 0x20u) - 'a'};
    return index < 26 ? ~(1u << index) : ~0;
}

bool isPangram_accum(const std::string& str) {
    uint_fast32_t present{(1u << 26) - 1};
    constexpr auto letterMask = [](uint_fast32_t collection, char ch) {
      if (collection)
        collection &= charToMask(ch);
      return collection;
    };
    return std::accumulate(str.begin(), str.end(), present, letterMask) == 0;
}


Displaying days of the week for all of 2015

Critique

The way to generalize your for-loops is to determine what varies — namely, the number of days in each month and the day of the week that each month starts on.  Then, you want to extract the magic numbers into arrays so that your code is data-directed.

The second argument to findDay() does not make obvious sense.  Considering that January 2015 starts on a Thursday, why would you call findDay(jan, 0)?  I would expect something like findDay(jan, 4), give or take 1 depending on your numbering convention.  Better yet, make your numbering convention clearer by defining an enum.

Similarly, findDay() would be better implemented using a lookup table instead of a switch.

findDay() is misnamed and poorly designed.  It doesn't just return the result: it also prints it (with a leading space and a trailing newline!).  Printing the result limits your ability to ever reuse that function for anything else in the future.  (Normally, returning a string from a C function could be a tricky proposition.  In this case, you'll be returning constant strings, which is fine.)

Suggested solution

#include <stdio.h>

typedef enum {
    SUN, MON, TUE, WED, THU, FRI, SAT
} Weekday;

static const char *DAY_NAMES[] = {
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
};

static const int MONTH_LENGTHS_NON_LEAP_YEAR[] = {
    31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};

const char *dayOfWeekIn2015(int month, int dayOfMonth) {
    static const Weekday DAY0[] = {
        WED,    // 2014-12-31
        SAT,    // 2015-01-31
        SAT,    // 2015-02-28
        TUE,    // 2015-03-31
        THU,    // 2015-04-30
        SUN,    // 2015-05-31
        TUE,    // 2015-06-30
        FRI,    // 2015-07-31
        MON,    // 2015-08-31
        WED,    // 2015-09-30
        SAT,    // 2015-10-31
        MON     // 2015-11-30
    };
    return DAY_NAMES[(DAY0[month - 1] + dayOfMonth) % 7];
}

int main(void) {
    for (int month = 1; month <= 12; month++) {
        for (int dayOfMonth = 1; dayOfMonth <= MONTH_LENGTHS_NON_LEAP_YEAR[month - 1]; dayOfMonth++) {
            printf("%02d/%02d/2015 is a %s\n",
                   month, dayOfMonth, dayOfWeekIn2015(month, dayOfMonth));
        }
    }
}


There are several points which can be improved, and by the style of your code I'm assuming that you are using this project to learn OOP..?

First off, your questions:
a) Since you are not outputting anything to the browser, or anything but an SQL server, this code has very few possible attack vectors. You are using prepared statements, which means that you have correctly protected yourself against SQL-injections.
That is, as long as you've ensured that the strings are indeed valid UTF-8, before sending them over to the DB server. This is especially important if these strings comes from a browser, and not the code itself.

b) Only two, really. Always set the timezone, and make sure it's set to the same timezone everywhere (and every time) you create a new time/date object. The timezone can/should be changed after creation, if it's necessary to change it.

c) You seem to have taken the appropriate steps, at least in the code posted above. I've found a site listing the general steps for UTF-8 support in PHP scripts, which might be useful for you.

That said, here are some points that could be improved in the code posted:

First off I'd change the line retrieving the DB variables, from your $my_env array(?). I would rather implement a DB connection factory here, or even a singleton if it's a small enough project. (Or to learn singletons.)
You've set the timezone using the old date_*() functions, which aren't really recommended any more. I strongly recommend looking into DateTime class family for date-time related needs.
Even though you've set the timezone, the code you've posted doesn't actually use it. You've used SQL's NOW() function instead, which uses the DBMS' timezone. This can be an issue if the PHP code and the database server are using different timezones, and you're later on using PHP to manipulate/compare timestamps.
You don't need to close the cursor, unset variables or anything like that. PHP normally does a perfectly good job of cleaning up afterwards, and it might even be detrimental to prematurely doing "cleanup". Normally this is only done when you have a specific use-case which requires you to clean up early.
You have what is essentially three return values, to communicate whether or not the query succeeded. You only need one, which should be either "0" for not OK, or the ID for OK. Any error messages or such should be added to an error log, by a dedicated function for this.
This one ties to the above, as the code should really be made into a function/method. This will allow you to maintain the code a lot easier, and make things quite a bit more flexible.
The try-catch block encompasses a lot more code than it needs to, which makes it a bit harder to follow the control-flow than necessary. One should only encompass the functions that actually can throw exceptions, if one doesn't just let them bubble up to a layer which can handle them in the proper location in the code-flow.
The connection class you have seems to have nothing to do with neither databases or connections to do, in fact it doesn't seem to following the OOP principles either. A method that simply takes input and returns output, without altering or depending upon the state of the object, isn't OOP. It just normal procedural programming, which is better done with pure functions. ;)

Here's a quick reorganization of your code, to give an example of the points I've listed:

function add_role ($name, $cby) {
    try {
        // Create or retrieve the database connection
        $conn = DB_Factory::create ($my_env);

        // Prepare an SQL statement
        $my_sql = 'INSERT INTO Role (Role_Name, Role_CDate, Role_CBy, Role_EDate, Role_EBy)
                    VALUES (:Role_Name, NOW(), :Role_CBy, NOW(), :Role_EBy)';
        $stmt = $conn->prepare ($my_sql);

        // bind parameters to prevent SQL Injection
        $stmt->bindValue(':Role_Name', $role_name);
        // defaults to Now()...
        $stmt->bindValue(':Role_CBy', $role_cby);
        // defaults to Now()...
        $stmt->bindValue(':Role_EBy', $role_cby);

        // execute the SQL statement
        $stmt->execute();
    } catch (PDOException $e) {
        // Catch error message
        $error_message = $e->getMessage();

        // Append error message to error log
        // ...

        // Set success value to FALSE & return an error message
        return 0;
    }

    // grab ID value of the new record
    return $conn->lastInsertId();
}


There are several problems in your code:

What is r.price?

h5["innerHTML" || "textContent"] = obj.name makes no sense. You could just a well write h5["innerHTML"] = obj.name. Your code won't test if such properties exist.

Even h5["innerHTML"] || h5["textContent"] won't do much good, since that just returns the value of either property, so you can't use it to set it.

You'd need to use something like

if (typeof h5.innerHTML == "undefined") { // no need for bracket notation here any more
  h5.innerHTML = obj.name
} else {
  h5.textContent = obj.name
}

However even that isn't very nice, since the element may have innerHTML set even if the browser doesn't actually use it.

Also innerHTML and textContent are "incompatible" to each other. For example, if you would assign the string "Example" to them, then using innerHTML will parse the HTML and display the text Example (in italic), while textContent will display the literal text Example.

The cleanest way would be to create and append explicit text nodes.

I don't see any benefit in using a function as the body of the for loop.

Generally building a fragment like this isn't very practical. For one it's terribly slow. For the other it's very difficult to read and makes changing the HTML structure a real bother, especially since it contains presentational information, such as Bootstraps grid classes and the clearfix elements (which IMHO are usually unnecessary nowadays).

Consider using a template mechanic of some kind. Either build something simple yourself, or use one of the plenty JavaScript template libraries, such as mustache.


Utilizing HTML5 Canvas to apply color theme to .png icons

Pretty nice overall. You're missing a semi-colon or two, but otherwise it's a nice solution.

The only real criticism I have are the "magic numbers" in there, like the 40x40 size that's hardcoded everywhere. Technically, you could derive the canvas dimension from the image, or pass the width/height as arguments. (Incidentally, setting a canvas's size will also clear its contents, which is helpful if there's one shared canvas that needs to be cleared between uses.) In either case, though, you'd have to get rid of the hardcoded "40".

Optimization-wise, the only addition I've made is to simply skip pixels with a zero alpha component; if they're transparent anyway, there's no need to bother with them.

Other than that, I've just broken the code into a couple of functions; nothing special (Note, haven't tested this yet.)

var changeIconColor = (function () {
  var canvas  = document.createElement("canvas"), // shared instance
      context = canvas.getContext("2d");

  // only place the dimensions are hardcoded
  // everything else just references canvas.width/canvas.height
  canvas.width  = 40;
  canvas.height = 40;

  function desaturate() {
    var imageData = context.getImageData(0, 0, canvas.width, canvas.height),
        pixels    = imageData.data,
        i, l, r, g, b, a, average;

    for(i = 0, l = pixels.length ; i < l ; i += 4) {
      a = pixels[i + 3];
      if( a === 0 ) { continue; } // skip if pixel is transparent

      r = pixels[i];
      g = pixels[i + 1];
      b = pixels[i + 2];

      average = (r + g + b) / 3 >>> 0; // quick floor
      pixels[i] = pixels[i + 1] = pixels[i + 2] = average;
    }

    context.putImageData(imageData, 0, 0);
  }

  function colorize(color) {
    context.globalCompositeOperation = "source-atop";
    context.globalAlpha = 0.3; // you may want to make this an argument
    context.fillStyle   = color;
    context.fillRect(0, 0, canvas.width, canvas.height);
    // reset
    context.globalCompositeOperation = "source-over";
    context.globalAlpha = 1.0;
  }

  return function (iconElement, color) {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(iconElement, 0, 0, canvas.width, canvas.height);
    desaturate();
    colorize(color);
    return canvas.toDataURL("image/png", 1);
  };
}());

As for invoking it, I don't think you need the $.proxy and promise stuff. I would think it'd be enough to just do

$('.custom-module').each(function () {
    this.src = changeIconColor(this, '#33CC33');
});
$('.module-li').removeClass('hidden');


Controller method to do fuzzy search for companies

Unless I've misjudged what you're going for, this should work (it's not pretty though, I'm sure there's an even better way)

def search
  @query = params[:query].try(:strip) # strip here instead

  unless @query.blank?
    tags = Tag.where("name LIKE ?", "%#{@query}%").pluck(:name)
    @companies  = Company.tagged_with(tags, :any => true).includes(:vouchers) # eager load vouchers
    @vouchers   = [
      Voucher.tagged_with(tags, :any => true),
      companies.map(&:vouchers)
    ].flatten.uniq
    @categories = @vouchers.map(&:categories).uniq
  else
    # you need something here, by the way...
  end
end

If you don't need each of the collections in the search results, but only need the categories, you should probably add this to the Company model

has_many :categories, :through => :vouchers

then you can do

def search
  @query = params[:query].strip # strip here instead

  unless @query.blank?
    tags = Tag.where("name LIKE ?", "%#{@query}%").pluck(:name)
    vouchers  = Voucher.tagged_with(tags, :any => true).includes(:categories)
    companies = Company.tagged_with(tags, :any => true).includes(:categories)

    @categories = [vouchers, companies].flatten.map(&:categories).flatten.uniq
  end
end

However, I'd think about restructuring the database if possible, to avoid the mix of 1st and 2nd order associations.


I have made some changes to make it neater and more efficient. See the end of this response for the final solution. But I'll start with a few comments.

There is no point making your class inherit the object class, especially if you're working with Python 3.

class Page(object):

The soup() method seems to be called indiscriminately causing BeautifulSoup to parse the contents of the page in concern too many times (see the map_page() method, for example). It is probably more efficient to parse once, afterwhich you can save whatever (e.g. title and links)you need as object properties.

Using list and map in this context seems unnecessary. It helps if you strive for readability --- your future self will thank you.

links = [i for i in (list(map((lambda url : url if bool(urlparse(url).netloc) == True else urljoin (self.base_url, url)),href))) if i.startswith(self.base_url)]

Also, checking the truthiness of urlparse(url).netloc doesn't require you to coerce it to a boolean result first. Simply replacing if bool(urlparse(url).netloc) with if urlparse(url).netloc would suffice.

In the site_map() function, you can replace the while loop with something simpler, e.g.:

while links_to_map:
    check_and_add(links_to_map.pop())

I have also made other subjective simplifications that hopefully should be obvious to you.

import pprint
import urllib.request
from pprint import pprint
from urllib.parse import urlparse, urljoin

import bs4 as bs

class Page:
    def __init__(self, base_url, url):
        self.url = url
        self.base_url = base_url
        self.souped = None
        self.title = None
        self.links = None

    def soup(self):
        def clean(url):
            return url if urlparse(url).netloc else urljoin(self.base_url, url)

    sauce = urllib.request.urlopen(self.url).read()
    self.souped = bs.BeautifulSoup(sauce, "lxml")
    self.title = self.souped.title.string
    hrefs = set([clean(i.get("href")) for i in self.souped.findAll("a")])
    self.links = [link for link in hrefs if link.startswith(self.base_url)]
    return self

    @property
    def map_page(self):
        lookup = {self.url: {"title": self.title, "links": self.links}}
        return lookup

def site_map(base_url):
    map_pages = {}
    links_to_map = [base_url]

    def check_and_add(url):
    if url not in map_pages:
        page = Page(base_url, url).soup()
        links_to_map.extend(page.links)
        map_pages.update(page.map_page)

    while links_to_map:
        check_and_add(links_to_map.pop())

    pprint(map_pages)


Trying to understand appropriate routing in MVC

Have you thought about calling the overview only when the URI ends in "overview" and preceded by a product slug?

$controller = new Controller();
if ( preg_match("#^/([a-zA-Z0-9_-]+)/overview/?$#", $uri, $matches) ) {
    $controller->showOverview($matches[1]);
}

This way, you define your routes with the following assumption:

/:product
/:product/specs
/:product/comments
/about

You should check out the Slim Framework: http://www.slimframework.com/

I've used it just for routing when performance was a crucial requirement.


You can use -p option (see perl --help):

  assume loop like -n but print line also, like sed

So the script becomes:

echo hi | perl -pe 's/i/o/g'

which is really compiled to:

$ perl -MO=Deparse -pe 's/i/o/g'
LINE: while (defined($_ = <ARGV>)) {
    s/i/o/g;
}
continue {
    die "-p destination: $!\n" unless print $_;
}
-e syntax OK


Looks good to me.

Your specification, "at least one group in second format appears", is stated in the positive, yet your not rlike is stated in the negative. You might consider phrasing it as where groups rlike '(^|#)[A-Z][A-Z](#|$)'.

You asked about performance. These queries will certainly have to read all rows, which costs more CPU cycles than evaluating the regexes. You might consider adding derived boolean column(s) that indicate whether "format1" and "format2" groups are present. Then you could index on such a column.


Is there a beter way to check input besides a switch case?

You don't need a switch here.

The easiest way is to just

if(emptyValueIsDetected)
{
    ShowErrorMessage
    return;
}

like

if (GalleryName == null || GalleryName == "Default")
{
    Debug.Log("No Gallery name assigned, please give the gallery a proper name");
    return;
}
if (gallerySize.x == 0 || gallerySize.y == 0 || gallerySize.width == 0 || gallerySize.height == 0)
{
    Debug.Log("No gallery Sizes assigned, please set some sizes before creating a gallery");
    return;
}

and so on.

Naming

The name indvImages for a variable is not really meaningful. If Mr.Maintainer will inherit this code, he will need some time to understand what the variable should mean.

//Enable Bullet Buttons for the gallery
if (enbBB)

If you need a comment to explain what a variable stands for, you haven't named your variable in a meaningful way. A comment should only describe why something has been done, and not what it is //This is a rectangle.


Add elements to a textfile using a dictionary

PEP8
There are quite a number of style-related "errors" in the code. Try to adhere to the Python PEP8 style guide. Here are a few key points for this particular case:

Variables and functions are written in snake_case, classes PascalCase and constants (if any) are written fully in UPPERCASE.
Use a single space around operators, assignments, comparisons, etc.
Use proper indentation (e.g. at People)
Use descriptive variable names.

Also use some whitespace here and there to make it more readable.
Some examples from the code:

people instead of People
get_score instead of getscore. Also get_score seems more like a function name rather than a variable name. Perhaps just use score as this is the actual value of the variable.
if get_score >= 100 instead of if getscore>=100
file = open('presfile.txt', 'a') instead of `File=open("presfile.txt",'a')
chosen_name instead of schoice. Perhaps person or chosen_person is even better, as this gets a value from People.

Use functions
Functions make the code more readable and splits up the responsibility of the code in smaller, reusable code. This also makes it a lot easier to test the application with for instance unittest. Once divided into functions, the code can easily be imported into another project, if need be.

You are doubly checking if schoice is in People

while schoice not in People:
    schoice=input('Invalid entry name is non existant, Enter a chosen name: ')
if schoice in People:
    getscore=People[schoice]

Once the if is reached, it is already certain that schoice is in People, otherwise the while loop would not be broken.
The code
presents = []
for x in range (5):
    present=input('Enter present ' +str(x+1))
    while present == '':
        present = input('Invalid. Try again: ')
    presents.append(present)

is repeated 3 times only with a different range. Put it in a separate function. See also: DRY
def get_presents(amount):
    """Return a list of presents equal in size to the given amount"""
    presents = []
    for x in range(amount):
        while True:
            present = input('Enter present #{}: '.format(x+1))
            if present:
                presents.append(present)
                break
            else:
                print('Invalid present, try again.')
    return presents

Now you can call this function with the amount of expected presents and it will return the list of presents: get_presents(5)
The if checks
if score < 50:
    ...
if score >= 100:
    ...
if score >= 50 and score < 100
# can also be written as 50 <= score < 100
    ...

has the code check get_score up to three times. This is not particularly a performance issue in this case, but could also be written as:
if score < 50:
    ...
elif score >= 100:
    ...
else:
    ...

Use with to open the file:
with open('presfile.txt', 'a') as presfile:
    presfile.write(chosen_person)
    presfile.write(str(presents) + '\n')

This ensures that the file is always closed. See also file.close and this answer about with

The code:
def get_presents(amount):
    """Return a list of presents equal in size to the given amount"""
    presents = []
    for x in range(amount):
        while True:
            present = input('Enter present #{}: '.format(x+1))
            if present:
                presents.append(present)
                break
            else:
                print('Invalid present, try again.')
    return presents

def get_presents_for_person():
    """Description of function."""
    people = {
        "Dan": 22,
        "Matt": 54,
        "Harry": 78,
        "Bob": 91,
    }

    chosen_person = input('Enter existing name: ')
    while chosen_person not in people:
        chosen_person = input('The chosen name does not exist. '
                              'Please enter an existing name: ')

    score = people[chosen_person]
    presents = []

    if score < 50:
        presents = get_presents(2)
    elif score >= 100:
        presents = get_presents(8)
    else:
        presents = get_presents(5)

    return chosen_person, presents

if __name__ == '__main__':
    chosen_person, presents = get_presents_for_person()

    with open('presfile.txt', 'a') as presfile:
        presfile.write(chosen_person)
        presfile.write(str(presents) + '\n')

What's next?
You could make the values of People an actual class. This allows you to further expand upon it if necessary in the future. For example something like:
class Person:

    def __init__(self, name, score):
        self.name = name
        self.score = score


Javascript browser charset rendering detection

Just don't. Standard practice is to use UTF-8 everywhere possible, and get rid of all other encodings. Especially if you have a multilingual system, dealing with multiple legacy encodings is a huge headache — just like this code above.


Basic commenting structure for commenting on objects

#####################################################################
# Comment ###########################################################

This sort of stuff is useless noise that adds a lot of maintenance.

If your classes are getting hard to find, move them over to separate files. If you don't want to move them to separate files, consider making use of your IDE to find the class you're looking for, rather than relying on optical recognition via big blocks of screenfilling characters.

The reasons for this are twofold:

If you refactor the name of the class, the comment doesn't change and you spend time formatting a comment like this, when you could have been doing normal programming
If you ever had a name that is longer or wanted to describe a class with a docstring you might break convention and might have to restyle all your classes or risk inconsistencies


A few comments:

Algorithms typically use the names first and last for the iterators they take, not begin and end (in common usage, begin and end refer specifically to the iterators that delimit a range in a container).
The use of find_if seems a bit excessive:  yes, it is good to use the Standard Library algorithms, but if you are writing your own algorithm, you may as well just write a loop, especially if it makes the code much clearer.
With respect to template parameter naming, it is helpful if you say what category of iterator is required; this helps to document the algorithm.

Consider the following, alternative implementation:

template <typename ForwardIterator, typename T>
ForwardIterator skip_over(ForwardIterator first, ForwardIterator last, T const& x)
{
    while (first != last && *first == x)
        ++first;

    return first;
}


Converting string of hex values to numpy array of specific shape

You can simplify bin(...)[2:].zfill(columns) to f'{...:0>{columns}b}'.

This can use f'{int(row[:2], 16):0>{columns}b}'.
I'd recommend you convert to a NumPy array out of the function, as it's not really that important to be in there.
Your code isn't idiomatic, as Python uses snake_case not camelCase.

def from_hex(values, columns):
    return [
        list(f'{int(row[:2], 16):0>{columns}b}')
        for row in values.split("\n")
    ]


Recode algorithm for merged cells on HTML table

Some tips to make it faster

Use references in foreach loops with &, like foreach ($matrix as $pkey => &$pvalue)
Don't use $htmlx variable, just output everything with echo
For some scecific purposes you may use ob_start(), ob_get_contents() and ob_end_clean() - it's much faster than concat like $html_d.=
Don't output html with php, just close php tags

if($d==1){ ?>
   <?php echo $dkey ?>	<?php echo $dvalue ?>
<?php }else{ ?>


That next_state function creates two brand new numpy array. Creating numpy array is slow. Should just update an existing numpy array.
Can divide the code into two classes. One for world, the other for the engine. World can have the world array and visualization. Engine can have the neighbor array.
Actually the neighbor array can be much smaller than the world if we update the world from left to right.
Python loop over each element (the row and col loops) is much slower than numpy's method. Can vectorize counting of neighbor by shifting the world and add to neighbor:

.

neighbor = np.zeros(world.shape, dtype=int)
neighbor[1:] += world[:-1]  # North
neighbor[:-1] += world[1:]  # South
neighbor[:,1:] += world[:,:-1]  # West
neighbor[:,:-1] += world[:,1:]  # East

neighbor[1:,1:] += world[:-1,:-1]  # NW
neighbor[1:,1:] += world[:-1,:-1]  # NE

Draw animation of world with matplotlib:

import numpy as np
import matplotlib.pyplot as plt

class World(object):
    def __init__(self, shape, random=True, dtype=np.int8):
        if random:
            self.data = np.random.randint(0, 2, size=shape, dtype=dtype)
        else:
            self.data = np.zeros(shape, dtype=dtype)
        self.shape = self.data.shape
        self.dtype = dtype
        self._engine = Engine(self)

        self.step = 0

    def animate(self):
        return Animate(self).animate()

    def __str__(self):
        # probably can make a nicer text output here.
        return self.data.__str__()

class Animate(object):
    def __init__(self, world):
        self.world = world
        self.im = None

    def animate(self):
        while (True):
            if self.world.step == 0:
                plt.ion()
                self.im = plt.imshow(self.world.data,vmin=0,vmax=2,
                                     cmap=plt.cm.gray)
            else:
                self.im.set_data(self.world.data)

            self.world.step += 1
            self.world._engine.next_state()
            plt.pause(0.01)
            yield self.world

class Engine(object):
    def __init__(self, world, dtype=np.int8):
        self._world = world
        self.shape = world.shape
        self.neighbor = np.zeros(world.shape, dtype=dtype)
        self._neighbor_id = self._make_neighbor_indices()

    def _make_neighbor_indices(self):
        # create a list of 2D indices that represents the neighbors of each
        # cell such that list[i] and list[7-i] represents the neighbor at
        # opposite directions. The neighbors are at North, NE, E, SE, S, SW,
        # W, NE directions.
        d = [slice(None), slice(1, None), slice(0, -1)]
        d2 = [
            (0, 1), (1, 1), (1, 0), (1, -1)
        ]
        out = [None for i in range(8)]
        for i, idx in enumerate(d2):
            x, y = idx
            out[i] = [d[x], d[y]]
            out[7 - i] = [d[-x], d[-y]]
        return out

    def _count_neighbors(self):
        self.neighbor[:, :] = 0  # reset neighbors
        # count #neighbors of each cell.
        w = self._world.data
        n_id = self._neighbor_id
        n = self.neighbor
        for i in range(8):
            n[n_id[i]] += w[n_id[7 - i]]

    def _update_world(self):
        w = self._world.data
        n = self.neighbor

        # The rules:
        #    cell        neighbor    cell's next state
        #    ---------   --------    -----------------
        # 1. live        < 2         dead
        # 2. live        2 or 3      live
        # 3. live        > 3         dead
        # 4. dead        3           live

        # Simplified rules:
        #    cell        neighbor    cell's next state
        #    ---------   --------    -----------------
        # 1. live        2           live
        # 2. live/dead   3           live
        # 3. Otherwise, dead.

        w &= (n == 2)  # alive if it was alive and has 2 neighbors
        w |= (n == 3)  # alive if it has 3 neighbors

    def next_state(self):
        self._count_neighbors()
        self._update_world()

def main():
    world = World((1000, 1000))

    for w in world.animate():
        pass

if __name__ == '__main__':
    main()


Conventions
In java, methods begin with a lowercase letter.
Design
Methods should be private unless they are required by clients. In this case, only the difference() method should be public.
Implementation
There are a few things to look at here. First, your code is made much more complex by swapping around the two inputs based on size. It would be neater if you did the size comparison once, then called a helper method with parameters shorterString and longerString.
Your two size methods are clunky because they don't return early when they find a (mis)match, and because they run off of the longer string rather than the shorter string.
There may be a slight performance gain to be made if the two strings are frequently equal. In that case only, it may be faster to check if the two strings are equals() and return -1 from differenceStartIndex() right away. In your particular case, I highly doubt this check would be anything more than clutter.
Applying these changes might make the code look something like:
public final class Difference {

    public static String difference(final String string1, final String string2) {
        if (string1.length() <= string2.length()) {
            return differenceHelper(string1, string2);
        }
        return differenceHelper(string2, string1);
    }

    private static String differenceHelper(final String shorterString, final String longerString) {
        final int start = differenceStartIndex(shorterString, longerString);
        if (start < 0) {
            return "";
        }
        final int end = differenceEndIndex(shorterString, longerString, start);
        return longerString.substring(start, end);
    }

    private static int differenceStartIndex(final String shorterString, final String longerString) {
        for (int i = 0; i < shorterString.length(); i++) {
            if (shorterString.charAt(i) != longerString.charAt(i)) {
                return i;
            }
        }

        if (shorterString.length() == longerString.length()) {
            return -1;
        }

        return shorterString.length();
    }

    private static int differenceEndIndex(final String shorterString, final String longerString, final int startIndex) {
        for (int i = startIndex; i < shorterString.length(); i++) {
            if (shorterString.charAt(i) == longerString.charAt(i)) {
                return i + 1;
            }
        }
        return longerString.length();
    }

    public static void main(final String[] argv) {
        System.out.println(Difference.difference("Hello", "Hello world!"));
        System.out.println(Difference.difference("Removing text", "Removi"));
        System.out.println(Difference.difference("same size", "SAME size"));

    }
}


Really fast Knight's Tour using concurrency and Goroutines

Your code does the task at hand, and that's a good thing. It's pretty quick too, an that's great.

What your code lacks though, is a sense of readability, and maintainability. There are also a number of potential bugs, and some variable shadowing.

Slices

My initial beefs with the code are that it depends heavily on constants, and on fixed arrays, instead of slices. In general Go favors slices over arrays. Consider this method:

func printChess(chess [a][b]int) {

it requires a 2D array with very specific dimensions, you can't use that function to print different size boards in the same program. It would be better to have a slice:

func printChess(chess [][]int) {

That can print any 2D slices, not just arrays of a very specific dimension. It makes it reusable.

Changing to slice from array would be quite a change in your code, though.

Constants

Your use of constants is impacting the code in odd ways. I mentioned the array-to-slice above, but it also impacts things like passing pointers in to arrays instead of slices, etc.

The names of your constants are also "horrible", a, and b are ugly.

your maxLevels constant is a better name, but really it is a computed value: maxLevels = a * b. I would not use it at all as a separate constant.

Constants in general are a bad idea, unless they really are constants. The dimensions of the board should be passed around, or inferred, as parameters.

Channels

Your use of the result channel appears to be a good idea, but it runs the risk of failing when no result is found. The fact that the 8x8 board has at least one valid result means that you are lucky, and that the channel completes OK. If there was no solution, though, your code would hang indefinitely.

You would be better by having a combination of a waitgroup and closing the channel if/when the waitgroup completes.

it would be best to solve that problem in it's own method too. It makes the process easier to read.

Dangling go-routines

your code does not clean up any go-routines that are still working when the first solution is found. You should find a way to terminate these routines cleanly - this would make your code usable in an application that does not immediately exit on the first solution.

You can use a select-with-default on the channels to implement a killer.

select {
case <-killer:
    // we were killed
    ....
default:
    //not killed, so keep going
    .....
}

Closure Shadowing.

This code here is complicated and made worse by bad variable naming:

for x1 := 0; x1 < a; x1++ {
    for y1 := 0; y1 < b; y1++ {
        go func(x1 int, y1 int) {
            var chess [a][b]int
            var current int
            success := tryToMove(&chess, current, x1, y1)
            if success {
                c <- chess
            }
        }(x1, y1)
    }
}

The x1 and y1 variables are duplicated in different scopes. The closure pattern is the right pattern, but give your variables different, non-shadowing names. Also, why x1 and y1 instead of just x and y?

for x := 0; x < a; x++ {
    for y := 0; y < b; y++ {
        go func(startx int, starty int) {
            var chess [a][b]int
            var current int
            success := tryToMove(&chess, current, startx, starty)
            if success {
                c <- chess
            }
        }(x, y)
    }
}

The above makes it clear that startx and x are different variables.

Additionally, if you create a parameter-based closure for the x and y variables, you should probably be consistent and create it for the c channel too.

Rows vs. Colums

It's a good thing your board is square - you mix up the use of the a and b constants, and the use of the x and y coordinates. If you were to have a rectangular board, say 6x8, your would cause index-out-of-bounds exceptions. Hmmm, no, actually, it will work, but your logic of using x and y implies that x is a horizontal position, but really, x in your code is the vertical position, and y is the horizontal position.

a is the height of the board, and b is the width (at least, that's the way that the printChess will print it out.

If you use variable names that imply a secondary meaning (like x), then you should ensure that the secondary meaning is consistent with the code's implementation.

Verbose Knight "Moves"

Your code embeds the knight-move logic as a series of if statements like:

if tryToMove(chess, current, x+2, y+1) {
    return true
}
if tryToMove(chess, current, x+2, y-1) {
    return true
}
if tryToMove(chess, current, x-2, y+1) {
    return true
}
if tryToMove(chess, current, x-2, y-1) {
    return true
}
if tryToMove(chess, current, x+1, y+2) {
    return true
}
if tryToMove(chess, current, x+1, y-2) {
    return true
}
if tryToMove(chess, current, x-1, y+2) {
    return true
}
if tryToMove(chess, current, x-1, y-2) {
    return true
}

it is often neater to encode it as a set of values in a slice:

var (
    knightMoves = []struct{ drow, dcol int }{
        {-2, -1}, {-2, +1},
        {-1, -2}, {-1, +2},
        {+1, -2}, {+1, +2},
        {+2, -1}, {+2, +1},
    }
)

and then iterate that slice to get the moves:

for _, move := range knightMoves {
    if tryToMove(width, height, board, current+1, col+move.dcol, row+move.drow) {
        return true
    }
}

Conclusion

Putting all the above together, I came up with a main method that inputs the solution constraints and handles a non-solution too:

func main() {
    if soln := solveBoard(8, 8); soln != nil {
        printChess(soln)
    } else {
        fmt.Println("No solution")
    }
}

Additionally, the actual solving method handles all cases:

func solveBoard(width, height int) [][]int {
    attempts := width * height
    results := make(chan [][]int)

    var wg sync.WaitGroup
    wg.Add(attempts)
    killer := make(chan bool)

    defer close(killer)
    for x := 0; x < width; x++ {
        for y := 0; y < height; y++ {
            startx := x
            starty := y
            go func() {
                if ok, soln := solveBoardFrom(killer, width, height, startx, starty); ok {
                    results <- soln
                }
                wg.Done()
            }()
        }
    }
    go func() {
        wg.Wait()
        close(results)
    }()
    return <-results
}

Note the creation of the WaitGroup and the killer channel that allows you to capture the no-solution condition, and the early solution killer.

Also note the different mechanism for creating the closure. I am not recommending one way vs. the other, but creating the variables in the inside scope like startx := x allows you to access startx inside the goroutine without worrying about the scope, just like a parameter-based closure function.

The recursive function is simplified with the loop, but more complicated by the killer process:

func tryToMove(killer chan bool, width, height int, board [][]int, current int, col int, row int) bool {
    // check to see whether we have been killed
    select {
    case <-killer:
        // we were killed
        return false
    default:
        //not killed, so keep going
    }

    if col < 0 || row < 0 || col >= width || row >= height {
        return false
    }
    if board[row][col] > 0 {
        return false
    }
    board[row][col] = current
    if current == width*height {
        // solved
        return true
    }
    for _, move := range knightMoves {
        if tryToMove(killer, width, height, board, current+1, col+move.dcol, row+move.drow) {
            return true
        }
    }

    board[row][col] = 0
    return false
}

It has a lot of parameters. It is past the point where a structure may be a better solution, but I left it as a lot of parameters for you to correlate things back to your code better.

Playground

You can see this running in the playground: https://play.golang.org/p/5zxmj8WV5u

The full code I am playing with is:

package main

import (
    "fmt"
    "sync"
)

var (
    knightMoves = []struct{ drow, dcol int }{
        {-2, -1}, {-2, +1},
        {-1, -2}, {-1, +2},
        {+1, -2}, {+1, +2},
        {+2, -1}, {+2, +1},
    }
)

func main() {
    if soln := solveBoard(8, 8); soln != nil {
        printChess(soln)
    } else {
        fmt.Println("No solution")
    }

    fmt.Println("-------------------")

    if soln := solveBoard(7, 9); soln != nil {
        printChess(soln)
    } else {
        fmt.Println("No solution")
    }

    fmt.Println("-------------------")

    if soln := solveBoard(2, 2); soln != nil {
        printChess(soln)
    } else {
        fmt.Println("No solution")
    }

}

func solveBoard(width, height int) [][]int {
    attempts := width * height
    results := make(chan [][]int)

    var wg sync.WaitGroup
    wg.Add(attempts)
    killer := make(chan bool)

    defer close(killer)
    for x := 0; x < width; x++ {
        for y := 0; y < height; y++ {
            startx := x
            starty := y
            go func() {
                if ok, soln := solveBoardFrom(killer, width, height, startx, starty); ok {
                    results <- soln
                }
                wg.Done()
            }()
        }
    }
    go func() {
        wg.Wait()
        close(results)
    }()
    return <-results
}

func tryToMove(killer chan bool, width, height int, board [][]int, current int, col int, row int) bool {
    // check to see whether we have been killed
    select {
    case <-killer:
        // we were killed
        return false
    default:
        //not killed, so keep going
    }

    if col < 0 || row < 0 || col >= width || row >= height {
        return false
    }
    if board[row][col] > 0 {
        return false
    }
    board[row][col] = current
    if current == width*height {
        // solved
        return true
    }
    for _, move := range knightMoves {
        if tryToMove(killer, width, height, board, current+1, col+move.dcol, row+move.drow) {
            return true
        }
    }

    board[row][col] = 0
    return false
}

func solveBoardFrom(killer chan bool, width, height, col, row int) (bool, [][]int) {
    board := make([][]int, height)
    for i := range board {
        board[i] = make([]int, width)
    }
    if tryToMove(killer, width, height, board, 1, col, row) {
        return true, board
    }
    return false, nil
}

func printChess(board [][]int) {
    for r := 0; r < len(board); r++ {
        fmt.Println(board[r])
    }
}


You should probably prefer #!/usr/bin/env python3 as it's less likely to vary on different systems. It's not a big deal, though.

You should use snake_case, even for IP, so names like get_ip and send_ip.

Don't call os.system; use subprocess.Popen instead:

subprocess.Popen('dig +short myip.opendns.com @resolver1.opendns.com > raspip.txt'.split())

subprocess.Popen([
    'sendEmail',
    '-o', 'tls=yes',
    '-f', '***@outlook.com',
    '-t', '***@outlook.com',
    '-s', 'smtp.live.com',
    '-xu', '***@outlook.com',
    '-xp', '**password**',
    '-u', 'raspberry via python', '-m',
    current_ip
])

This is safe against quoting errors (what if the IP contained "?).

You also didn't need the +s; strings automatically concatenate. You don't need to escape 's inside "" or " inside '' - but it doesn't matter with Popen since you don't need to worry about quoting.

You do:

with open('raspip.txt', 'r') as f:
        return f.readline().rstrip('\n')

It's more idiomatic to treat files as iterables, so instead one would do

with open('raspip.txt', 'r') as f:
        return next(f).rstrip('\n')

This also lets you add a default if wanted with next(f, default). It might be a better idea to catch the error explicitly, since StopIteration can interfere with generators:

with open('raspip.txt', 'r') as f:
        try:
                return next(f).rstrip('\n')
        except StopIteration:
                raise ValueError("No text in raspip.txt!")

You also don't need the 'r' argument - it's default.

Don't put brackets around conditions in loops of ifs. It's just while True: and if last_ip != current_ip.

A more fancy example might use, say, Python's email library - but this is fine for what it does.


C# AES Encryption/Decryption or byte[] array with a custom Key/IV

ctor
Neither key.Length nor iv.Length can be smaller than 0 you only need to check if it is equal to 0. But for me as a user of that class it would look strange to receive an ArgumentNullException if I pass e.g a key with Length == 0. I would expect an ArgumentOutOfRangeException.
Omitting braces althougth they might be optional can lead to hidden and therfor hard to find bugs.
Encrypt()

The default Mode of RijndaelManaged is already CipherMode.CBC so there is no need to set it again.

By returning out of the most inner using you can remove byte[] encrypted.

By stacking the using's you save some levels of indentation.

You can use the parameterless CreateEncryptor() method because you already set the Key and IV.

As the method is public you should validate its parameter.

Decrypt()

The default Mode of RijndaelManaged is already CipherMode.CBC so there is no need to set it again.

By returning out of the most inner using you can remove byte[] decrypted.

By stacking the using's you save some levels of indentation.

You can use the parameterless CreateDecryptor() method because you already set the Key and IV.

You shouldn't mix styles. In the using's you sometimes use the concrete type and sometimes you use var.

General
Naming things in a good way is hard. Mostly it is sufficient and just more readable to just use a classname in camelCase casing. If you stumble in a few months over the variable rijAlg you will need to ask yourself what it stands for. By naming it rijndaelManaged you will see at first glance what it is about.
Another example of "bad"  naming is in Encrypt() you name the MemoryStream msEncrypt but in Decrypt() you name it ms the same is true for csEncrypt vs cryptoStream.
Implementing the mentioned points leads to
public class AesGenericEncryptionService
{
    private readonly byte[] m_Key;
    private readonly byte[] m_IV;

    public AesGenericEncryptionService(byte[] key, byte[] iv)
    {
        if (key == null)
        {
            throw new ArgumentNullException(nameof(key));
        }
        else if (key.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(key));
        }

        if (iv == null || iv.Length <= 0)
        {
            throw new ArgumentNullException(nameof(iv));
        }
        else if (iv.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(iv));
        }

        m_Key = key;
        m_IV = iv;
    }

    public byte[] Encrypt(byte[] data)
    {
        if (data == null)
        {
            throw new ArgumentNullException(nameof(data));
        }

        using (var rijndaelManaged = new RijndaelManaged())
        {
            rijndaelManaged.KeySize = m_Key.Length * 8;
            rijndaelManaged.Key = m_Key;
            rijndaelManaged.BlockSize = m_IV.Length * 8;
            rijndaelManaged.IV = m_IV;

            using (var encryptor = rijndaelManaged.CreateEncryptor())
            using (var ms = new MemoryStream())
            using (var cryptoStream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
            {
                cryptoStream.Write(data, 0, data.Length);
                cryptoStream.FlushFinalBlock();

                return ms.ToArray();
            }
        }
    }
    public byte[] Decrypt(byte[] cipher)
    {
        // Check arguments.
        if (cipher == null)
        {
            throw new ArgumentNullException(nameof(cipher));
        }
        else if (cipher.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(cipher));
        }

        using (var rijndaelManaged = new RijndaelManaged())
        {
            rijndaelManaged.KeySize = m_Key.Length * 8;
            rijndaelManaged.Key = m_Key;
            rijndaelManaged.BlockSize = m_IV.Length * 8;
            rijndaelManaged.IV = m_IV;

            using (var decryptor = rijndaelManaged.CreateDecryptor())
            using (var ms = new MemoryStream(cipher))
            using (var cryptoStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
            {

                var dycrypted = new byte[cipher.Length];
                var bytesRead = cryptoStream.Read(dycrypted, 0, cipher.Length);

                return dycrypted.Take(bytesRead).ToArray();
            }
        }
    }
}


Bash script to install zsh on different distributions

if [[ $NAME = "Fedora" ]]; then
elif [[ $NAME = "void" ]]; then
elif [[ $NAME = "Debian" ]] || [[ $NAME = "Ubuntu" ]] || [[ $NAME = "Linux Mint" ]]; then

That looks like a candidate for case "$NAME" in.  However, instead of changing that, let's look at what we're doing:

if [[ $NAME = "Fedora" ]]
then
   dnf install -y git zsh zsh-autosuggestions zsh-syntax-highlighting

Ah, so we're using that to determine which package manager is in use.  It might be better to just test that directly:

if [ -x /usr/bin/dnf ]
then
   dnf install

That has the added benefit that it's plain POSIX shell, not requiring Bash.

Hang on, where did that $NAME come from?  Let's look:

if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
    VER=$VERSION_ID
elif type lsb_release >/dev/null 2>&1; then
    OS=$(lsb_release -si)
    VER=$(lsb_release -sr)
fi

Oh dear, it looks like NAME is assigned in only one of those two paths, and we actually wanted to be using OS (or assigning to NAME and VERSION_ID in the elif branch, and getting rid of OS and VER).
This is why it's a good idea to set -u, so that you get an error when expanding an undefined variable.

echo "Operating system not identified"
pause

That should be echo >&2, since it's an error message.  What's pause?  It's certainly not a common tool, and you probably just want to exit 1 at that point anyway.

Not a big fan of copying those font files into /usr/share (that should be only for files under control of the package manager).  That's what /usr/local is for.

Why are we using scp for a local copy?  Just use plain cp and reduce the dependencies.

Many platforms have a configurable preferred terminal emulator, so use that first if it exists.  For example /usr/bin/x-terminal-emulator on Debian.

On the use of sudo and su (not sure why you feel the need to double up like that!), I'd recommend turning this the other way around, and having a script that you must be root to run, but which drops privileges for the parts where that's possible.  That's certainly better than being repeatedly asked for passwords (in many sudo configurations), which isn't something you want to be training users to do.


Find permutation of a specified lexicographic rank

This is nicely written, readable and efficient.

The most significant improvement I can suggest is to rewrite this as a for loop:

int index = 0;
while (index < result.length) {
    result[index] = (int) (rank / factorial(digits - 1));
    rank %= factorial(digits - 1);
    index++;
    digits--;
}

Because this is essentially a counting loop, and index is not needed outside of it anyway. That is:

for (int index = 0; index < result.length; ++index) {
    result[index] = (int) (rank / factorial(digits - 1));
    rank %= factorial(digits - 1);
    digits--;
}

It's recommended to declare variables using their interfaces, so instead of:

private static ArrayList<Long> factorialList = new ArrayList<Long>(Arrays.asList(1L,1L));

This is better:

private static List<Long> factorialList = new ArrayList<>(Arrays.asList(1L, 1L));

Lastly, a couple of nitpicks:

In lexicographicPermutation, int result[] = {-1} is a redundant local variable
It's recommended to use braces with single-statement if too
There are some redundant parentheses here and there, for example if ((rank < 1) || ...)


Alarm clock with "ringing" functionality

Calendar

You created an alarmclock, which is really just a time-representation. A Calendar has both a date and time component. I strongly, strongly suggest you use that so you can let your user define how he wants his date represented and let the API handle fancy stuff like timezones, summer hours, etc.

You can also look into the Java 8 time API but I think that might not be appropriate yet.

Enums

When you have a limited set of different possibilities, your mind should immediately wander to enums. This way you can represent your AM/PM by saying DayPart.AM and DayPart.PM instead of the literal string "AM" which could mistakenly be used as "aM", "am", "AX", etc. It will provide compile-time safety and is a lot more pleasant to work with.

Indentation

Stick to conventions. Some people indent a block with one tab (or 4 spaces), some with 2 spaces. This will keep the code readable for everyone.

Methods without a meaningful body

Look at your code here:

public int getHour() {
if ((hour >= 1) && (hour <= 12)) {
}
return hour;
}

With formatting this becomes this:

public int getHour() {
    if ((hour >= 1) && (hour <= 12)) {
    }

    return hour;
}

Can you tell what's wrong here? Note that there are several methods that have this construct!

Assignment vs Comparison

This is a very common mistake:

if (isAlarmRinging = true)

What you do here is set isAlarmRinging to true, you never compare it.

Keep in mind:

Comparison: ==.
Assignment: =.

Unused parameters

In your method setTime you never use the parameter newMinute.
Likewise in method setAlarmTime you never use newAlarmAmOrPm.