Identifying which paragraph, if any, is a superset of all words in a document

Your code is suffering from a lack of functions. Functions help to identify what core parts of your code does, and makes those parts reusable. It also makes the calling code more readable.

By using functions, and extracting core components, it's easy to see the actual logic. For example, a main method like:

public static void main(String[] args) throws IOException {
    List<Set<String>> paragraphs = composeParagraphs(Paths.get("java.txt"));
    int superIndex = superSetParagraph(paragraphs);
    System.out.println("SuperSet Paragraph is " + superIndex);
}

Well, that's simple enough... how is it done?

Given a list of paragraph sets, finding the paragraph which is a superset, is easy:

private static int superSetParagraph(List<Set<String>> paras) {
    // get all words from all paragraphs.
    Set<String> allwords = paras.stream().flatMap(p -> p.stream()).collect(Collectors.toSet());
    // which paragraph has all words.
    for (int i = 0; i < paras.size(); i++) {
        if (paras.get(i).size() == allwords.size()) {
            return i + 1;
        }
    }
    return 0;
}

How do you get all paragraphs?

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

public static Set<String>words(String input) {
    return Arrays.stream(SPACE.split(input))
          .filter(word -> !word.isEmpty())
          .collect(Collectors.toSet());
}

private static List<Set<String>> composeParagraphs(Path path) throws IOException {
    Set<String> para = new HashSet<>();
    List<Set<String>> contents = new ArrayList<>();
    for (String line : Files.readAllLines(path)) {
        if (line.trim().isEmpty()) {
            // indicates a new paragraph....
            if (!para.isEmpty()) {
                contents.add(para);
                para = new HashSet<>();
            }
        } else {
            para.addAll(words(line));
        }
    }
    if (!para.isEmpty()) {
        contents.add(para);
    }
    return contents;
}

Again, functional extraction makes a difference.


Find How Many Times Numbers Repeat on a Digital Clock

Input loop

Your

        print("Please enter an integer.")

can probably be lumped into the input statement after it.

Time math

Usually doing your own should be avoided. As an example, this:

total_minutes = (24 * 60) / 2

can be

from datetime import timedelta
# ...
total_minutes = timedelta(hours=12) / timedelta(minutes=1)

General approach

Currently you're doing a lot of string manipulation, including a stringly-typed hours and minutes in gen_times. Your code would be simpler if, instead of maintaining and incrementing those strings, increment a single datetime.time instance. From there, to get individual digits, you could  strftime it to a string and feed that to a Counter. The strftime format string in this case would be most useful as '%I%M'.

Variable names

Try to avoid names like i and ii. In particular, this:

    while(ii < 10):
        count = times[i].count(str(ii))
        #iterationcounter+=1
        if count >= int(input_repeats):
            counter_repeat+=1
            break

        ii+=1

is better represented as

for digit in range(10):
    count = times[i].count(str(digit))
    if count >= int(input_repeats):
        counter_repeat+=1
        break

Though that times[i].count should be replaced with the use of a Counter.


you could change the helper method to use switch if you're using C# 7.0 or higher then you can do this :
switch(PinNumber)
{
    case 1 when valueList.Count == 0:
    case 2 when valueList.Count == 0 || valueList.Count == 1:
    case 3 when valueList.Count == 3 || valueList.Count == 4:
    case 4 valueList.Count == 4:
        return value;
    default:
        return Brush.Transparent;
}

if not, then you can focus on readability by doing something like this :
var isPin1 = PinNumber == 1 && valueList.Count != 0;
var isPin2 = PinNumber == 2 && valueList.Count == 0 || valueList.Count == 1;
var isPin3 = PinNumber == 3 && valueList.Count == 3 || valueList.Count == 4;
var isPin4 = PinNumber == 4 && valueList.Count == 4;

return isPin1 || isPin2 || isPin3 || isPin4 ? value : Brush.Transparent;


Regular Expression matching customer number strings

^P\d{5}-13-TP\d{2}-\d{3}(-(L|R|\d{4})(-\d{3,4})*)?$

Your current regex is WAY too forgiving.  First of all, every one of your example starts with a P followed by some numbers, but you accept ANY COMBINATION of letters at the beginning. I'm assuming that ALEX01867-13-TP02-019-L-1137 isn't a valid key, so you should take steps to reject it by using hungry quantifiers as little as possible (*, +). Using \d{3,4} matches a digit between 3 and 4 times, so that will
let you limit the sort of input you accept.

The same goes for the 5th group -  according to your examples, it's either L, R, or 4 digits. In Regex, that looks like this: (L|R|\d{4})

Next, you are using alternation (option1|option2) to capture the different "forms" your string comes in as, but you are repeating a bunch of stuff (for example, the \w*\d* at the beginning). You can limit the scope of the alternation by surrounding it in brackets (()). You can see this in action with the (L|R|\d{4}) example - that whole bracket group becomes a single token that matches somewhere in a string (or doesn't).

Sometimes the string ends after the 4th group (Before the L/R group), and sometimes it doesn't. Instead of using alternation to solve this, which makes the regex VERY long, you can just surround the entire regex AFTER that point in brackets with a question mark (an-(example)?). This makes the entire second part optional.

Finally, your problem asks if there is a simple method to improve the regex. By ending it in (-\d{3,4})* you can match ANY length of additions to the end, assuming the all come in the form -015 or -1992 or whatever. If you knew that there was always a max of 15 numbers added to the end, you could change that star (*) to a max quantifier ({,15}). If sometimes the number only has two digits, change the {3,4} to {2,4}, etc.

See it in action here


Not a merge sort

This step in the merge() function:

    for (size_t i = 0; i < d1; ++i) {
        for (size_t j = 0; j < d2; ++j) {
            if (*(f1 + i) > *(f2 + j)) {
                std::iter_swap(f1 + i, f2 + j);
            }
        }
    }

is an \$O(N^2)\$ operation and works more like an insertion sort or bubble sort rather than a merge.  Also, you should only have to merge once instead of four times.  The pseudocode for the mergesort function should be:

mergesort(leftHalf);
mergesort(rightHalf);
merge(leftHalf, rightHalf);

I believe your merge function is not only slow but also doesn't merge properly in one pass, which is why your program seems to require calling it four times.


Approximate (250 over 100) permutation best fitting certain criteria

1. Analysis

In the general case, the problem of finding the sample of words with the "most even" distribution of letters is NP-hard. Here I'm considering a general instance of this problem to be:

  Given an alphabet \$ Σ \$, a set \$ W \$ of 4-letter words over that alphabet, and an integer \$ n ≤ \left|W\right| \$, find the subset \$ W^* ⊆ W \$ with size \$ \left|W^*\right| = n \$ having the smallest variance of letter counts among all subsets of that size.

Here's a proof that this is NP-hard, by a reduction from EXACT COVER BY 3-SETS (that is, EXACT COVER restricted to sets of size 3, also known as "X3C").

Suppose that we have an instance of EXACT COVER BY 3-SETS in the form of a set \$ X \$ and a collection \$ S \$ of 3-element subsets of \$ X \$, and the problem is to determine if there is a subcollection \$ S^* ⊆ S \$ such that each element in \$ X \$ is contained in exactly one subset in \$ S^* \$.

This translates into the word problem as follows. Let \$ Σ = X ∪ S \$; let \$ W \$ be the set of four-letter words \$ abcd \$ such that \$ \{ a, b, c \} = d ∈ S \$, and let \$ n = { \left|X\right| \over 3 } \$. Then solve the word problem to find \$ W^* \$ with the smallest variance of letter counts. There is an exact cover if and only if the variance of the letter counts in \$ W^* \$ is zero. (Because there can only be one instance of any letter from \$ S \$, and so if the variance is zero, there must be exactly one instance of each letter from \$ X \$, and since there are  \$ \left|X\right| \over 3 \$ words, each element of \$ X \$ is covered exactly once.)

So there's no efficient (polynomial time) algorithm that solves your problem. Exhaustive search is out, because \$ {250 \choose 100} \approx 6×10^{71} \$. So the best you can do is to use heuristics to find good approximate solutions. I'll describe one possibility in §4 below.

2. Review

Having code at the top-level of a module makes it hard to test from the interactive interpreter, because whenever you reload the module, the code runs. It's best to guard top-level code with if __name__ == '__main__':.
The comment for sampl doesn't explain the most important points about the behaviour of the function, namely: what arguments does it take? and what does it return?
The number 100 is arbitrary, so it ought to be a parameter.
When finding the minimum or maximum, it's best to avoid a starting point like this, but instead to rearrange the code into a generator that can then be passed to min. That way you can avoid arbitrary starting points like 1000000.
Writing for w in range(r): is misleading, because w is not actually used (it's immediately overwritten by the random sample). It's conventional to write _ for unused loop variables.
The code uses NumPy to do the statistics on the sample. But there are at most 400 letters in the sample, so this doesn't really gain much: NumPy only shows a benefit for large volumes of data. I think that using the standard Python functions statistics.pstdev, max and min would be adequate for this amount of data.
Since the standard deviation is only used for comparison, you'd get the same results if you used the variance instead, and this would have the advantage of avoiding the square root.
Instead of Counter("".join(w)), use itertools.chain.from_iterable and write Counter(chain.from_iterable(w)). This avoids concatenating the words. [Improved by Veedrac in comments.]
Instead of:

counts = [v for k, v in Counter("".join(w)).items()]

write:

counts = list(Counter(chain.from_iterable(w)).values())

since you don't use the keys.
I dislike the logic for selecting w_candidate_3. This is only updated if both scoring functions show an improvement for this sample, and so the "best" sample according to this logic will depend on the order in which samples are examined. This is a bad property for a measure to have. It would be better to find some numeric way to combine the two scores (for example, their sum or product), so that all samples are comparable according to this measure.
The logic in sampl is complicated because you aren't sure of the right way to score the samples. In this kind of situation a better approach would be for sampl to take a scoring function as an argument. Then you could easily experiment with different kinds of score.

3. Revised code

from collections import Counter
from itertools import chain
import random
from statistics import pvariance

def letter_counts(words):
    """Generate the letter counts of the words."""
    return Counter(chain.from_iterable(words)).values()

def score_variance(words):
    """Score words according to variance of letter counts."""
    return pvariance(letter_counts(words))

def score_range(words):
    """Score words according to range of letter counts."""
    counts = list(letter_counts(words))
    return max(counts) - min(counts)

def best_sample(words, score, n=100, r=100):
    """Generate r (default 100) random samples of n (default 100) elements
    from words, and return the sample with the smallest score.

    """
    return min((random.sample(words, n) for _ in range(r)), key=score)

4. Hill climbing

A useful search technique in this kind of global optimization problem is hill climbing. The idea is to pick a random sample to start with, explore its neighbourhood by examining "nearby" samples, pick the best of the neighbours, and continue until no further improvement can be made. For example:

def best_sample_2(words, score, n=100, r=100):
    """Return a sample of n (default 100) elements from words, found by
    starting with a random sample and repeatedly hill climbing by
    generating r (default 100) neighbours and picking the one with
    smallest score, until no more progress is made.

    """
    words = set(words)
    current_sample = set(random.sample(words, n))
    current_score = score(current_sample)

    # Generate neighbouring samples (one word swapped).
    def neighbours():
        nonsample = words - current_sample
        for _ in range(r):
            s = set(current_sample)
            s.difference_update(random.sample(current_sample, 1))
            s.update(random.sample(nonsample, 1))
            yield s

    while True:
        new_sample = min(neighbours(), key=score)
        new_score = score(new_sample)
        if current_score <= new_score:
            # No neighbour is any better, so stop here.
            return current_sample
        current_sample, current_score = new_sample, new_score

Here's an example of how effective hill climbing can be in this problem. First, we'll use the original algorithm to pick the best of 10,000 samples.

>>> score_variance(best_sample(WORDS, score_variance, r=10000))
114.18300653594771

Now, using hill climbing:

>>> score_variance(best_sample_2(WORDS, score_variance))
23.241830065359476

The hill climbing approach reaches a local optimum. So usually it's a good idea to run it several times with different random starting points. For example, if I run it ten times and pick the best:

>>> f = lambda:best_sample_2(WORDS, score_variance)
>>> score_variance(min((f() for _ in range(10)), key=score_variance))
19.712418300653592

For further improvement, take a look at simulated annealing.


First, your comments:

They're structured well, but, the content could be improved:

-- SELECT the final results. Data is filtered based
   ^^^^^^^^^^^^^^^^^^^^^^^^^
-- on the following conditions.

You're not really SELECTing the final results, you SELECT them based on the conditions, you don't SELECT them and then filter them.

Your declaration DECLARE @QuestionTags NVARCHAR(150) = ##QuestionTag1## is a little confusing:
Tags is plural, but then the variable you ask for input is Tag1 (singular)?

You ask for input like ##MinQuestionVotes##, but there's no reason to abbreviate, it could really just be:
##MinimumQuestionVotes##. Same things applies to the other two.

Finally, CONCAT('%', @QuestionTags, '%') is good, but you could really just:
'%' + @QuestionTags + '%' instead.

You could even build the tag string with the ' attached so the user doesn't need to input.

Other than that, your code looks really clean and nice. Good Work!


Plain-text file encryption and decryption

Hello and welcome to Code Review! I try to give a possible explanation of what the reviewer meant when he was talking about inverse class structure; in the main method this code is present:

MyAlgorithm myAlgorithm = MyBuilder.builder()
               .withCipherSet(CIPHER_CHAR_SET)
               .build();

But from your code MyAlgorithm is a subclass of EncryptionAndDecryption and this is the class where you defined the operations of encryption and decryption , so the method shoud have return an instance of class EncryptionAndDecryption instead of one subclass.
Other problem: in the class EncryptionAndDecryption we have the below methods:

protected final String encryptOrDecryptText(final String cipher, final String inputText, final MyAlgorithm.Action action)

protected final void encryptOrDecryptFile(final String cipher, final Path filePath, final String baseDirectory, final MyAlgorithm.Action action)

With parameter MyAlgorithm.Action action the class EncryptionAndDecryption will be dependant from its subclass MyAlgorithm and without its subclass it cannot be even compiled.
In the class EncryptionAndDecryption I would make two distinct methods for encryption and decryption of strings, putting these related to files and directory in the subclass MyAlgorithm, deleting the enum value you are using to distinguish between the two operations.
Style problem : in the main method is present a list of if like this below:

if ("encrypt".equalsIgnoreCase(action)) {}

Normally it is the string compared to the string literal like:

if (action.equalsIgnoreCase("encrypt")) {}

You can substitute the list of if with a switch like documented in strings-switch.


First thing I would do is cache some selectors, like the form:

$form = $('#footer form');

And then you can use it like:

$form.find('h3');


Arranging words in sentences alphabetically

Your code here is far more complicated than it needs to be. The trick you need to follow is four-fold:

Use your library functionality
Use Regular Expressions
Use buffered input/output for performance
bend the rules on the input side.

You go to great lengths to store the data in two arrays (with bad names words and words_2), and you use the one to check for words in the other. The right structure in Java is a Set, which automatically, and efficiently does the check for you. Further, there's another specialized set, called the TreeSet which stores the data in sorted order already.

Regular Expressions are a good way to identify patterns in the data. They take some getting used to, but, because of the way they can be pre-compiled, and reused, they are fast. Note that the Scanner class looks for regular expressions.

When using input, and output, you get better performance if you use fewer operations. You should wrap the System.in in a BufferedInputStream, and perform all the output to a StringBuilder, and then dump that to System.out in one operation.

Now, about bending the rules on the input side.....

Many programming challenges are set up to work in many languages, including things like C, C++, etc. Some of those languages need to have an idea of how much space to allocate before processing the data. That's why the description says it will contain the number of lines, as well as the maximum line length. If you assume that the input will be valid, then there is no reason to process the data line by line, you can do it word by word, and just forget about the line count in the first line....

How would I do it?

    try (Scanner scan = new Scanner(new BufferedInputStream(System.in));) {
        // find word boundaries...
        scan.useDelimiter(Pattern.compile("[\\s;:,.'\n]+", Pattern.MULTILINE));
        scan.nextLine(); // ignore the count
        Set<String> words = new TreeSet<>();
        while (scan.hasNext()) {
            String word = scan.next().toLowerCase();
            words.add(word);
        }
        StringBuilder sb = new StringBuilder();
        sb.append(words.size()).append("\n");
        for (String word : words) {
            sb.append(word).append("\n");
        }
        System.out.print(sb.toString());
        System.out.flush();
    }

On further reflection, I would split the logic in to two parts, a word-finder, and a word printer:

Set<String> words = parseWords(System.in);
System.out.println(formatWords(words));


You remove the items when the iterator is requested. Are you sure that this is right in your use case? Imagine the user puts an item in with a lifetime of 20 ms, requests the iterator, gets it with this one element and uses the iterator later. Theoretically, the item would be dead then. You should mention this behavior of the iterator method.

Additionally, the performance of the iterator construction depends on the number of dead entities inside the collection -> mention it.


PEP-8
White space!  Your code needs more white space!  The Style Guide for Python Code enumerates many coding conventions Python programs should follow.  One is binary operators (like =, ==, +, % should have one space character before and after the operator.
alphabet is a constant.  It never changes.  PEP-8 would recommend you changing the name to ALPHABET to indicate it is a constant.
List of characters
A string is essentially just a list of characters.  Moreover, it will behave exactly as if it is list of characters.
alphabet=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","1","2","3","4","5","6","7","8","9","0",",","."]

could be replaced with the much less verbose ...
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890,."

... with no other changes required in your program.
One source of truth
How many characters are in your alphabet?  Did you count?  39?  Are you sure?  Great!  What if you added an apostrophe to the alphabet.  The 39 would become 40, and you'd have to change both occurrences of 39 in your code to 40.
Why are we counting and risking making a mistake?  Computers are much better at counting!
ALPHABET_LENGTH = len(alphabet)
...
    enc_letter = (index + int(enc_key)) % ALPHABET_LENGTH
...
    dec_letter = (index - int(enc_key)) % ALPHABET_LENGTH

Now if you decide additional letters should be included in the alphabet, you just add them; no other change would be required.
Global variables
alphabet is a global constant.  It never changes.  In contrast to that, enc_text, dec_text, org_text and message are global variables.  They are mutated by the program.
Avoid global variables.  They make the code harder to understand, and harder to maintain.
Consider encrypt().  You call it and org_text is processed, encrypted and added to the enc_text list.  What happens if you change org_text and call encrypt() again?  The new text gets added to enc_text.
Was that expected?
If enc_text was removed from global scope, and defined inside the encrypt() function, this unexpected behaviour would not happen.  Same with dec_text.
Additionally, global variables should not be used to pass the text to be encrypted/decrypted into the functions; these should be passed as parameters.
Bug
If you encrypt the message "This fails!", the program crashes with the exception ValueError: '!' is not in list.
This is another reason to use an alphabet string instead of a list of characters: strings have another method, .find(), which will return -1 if the target isn't found.  A list has no such method, forcing you to use try: ... except: ... to catch the exception.


Generating Ulam numbers with OpenMP and single-thread versions

My CPU is an AMD E1 2500

That CPU is a dual core CPU, so with perfect multithreading that introduces exactly zero overhead, which at best could double the performance. As the comments already pointed out, the overhead is more than zero. Other than that, your CPU is a Kabini low power CPU with 15W TDP, so it's not unlikely that thermal throttling lowers the clock speed when running multithreaded - try to look at the actual clock speed (not % use of CPU) when running the test again.

With that out of the way, the problem in your code is that you introduce absolutely massive overhead. In addition to the overhead due to having threads, the variable count is shared between threads, which forces the threads to wait for each other all the time. Also, your code will always run the entire loop, while the single-threaded version aborts early. A much faster version is the following, although that one still does not abort early (disclaimer: not tested, as I don't have OpenMP installed).

bool isulam (int n, int size) {
    int count = 0;
    bool toomany = false;
    for (int i = 0; i < size; i++)
        #pragma omp parallel for reduction (+:count)
        for (int j = 0; j < size; j++) {
            if (i != j && ulam[i]+ulam[j] == n) count++;
        }
    return count <= 2;
}


The only issue I see is with this:

else if(defaultSettings[option])

If you have any boolean options or numeric options which are set to 0, this will evaluate to false and the code within the if will not execute.

Perhaps use typeof instead.


From a personal standpoint, I think this method is fine. You might want to re-work it a little. I'd recommend creating an array with possible intersections, and looping through that array and checking user input against those. For example:

var intersections = [
    ["what", "do", "you", "think", "about"],
    ["what", "is", "your"],
    ...
];

Finally, I'd recommend having something that allows for multiple keywords, rather than one. In addition to this, you may not want to be checking the length of intersections based on a constant, in this case, three.

Anyways, if there's anything else that you want me to cover, just mention it in the comments, and I'll see what I can do.


CMS for allowing users to delete or edit a post

Usually you can use switch statements to clean up abundant if statements, but only if those if statements are similar; Such as checking for different values of the same variable. Since that is not the case here, there isn't much you can change in this area. Sometimes you just need a few if statements. I would, however, suggest that you not use the global $_REQUEST as it is rather insecure. Even if you think you are the only one who is ever going to use it, what if someone got in, you just removed one more step of security from your site making it that much more easier for someone to destroy your hard work. Even you could make a mistake later by accidentally duplicating a POST variable as a GET variable, or vice-versa. Or someone with malicious intent does it on purpose, you could run into a lot of problems there. You should also sanitize those. Check out filter_input (>=PHP 5.2) to get started, or check other forums on the best way to sanitize your form variables.

Your delima with checking for multiple checkboxes should be rather easy. You've already got your form set up to make them into an array after post. Or almost right. You need to change name to what you have for your value. That should work, but if it doesn't try making the value the $id and just leaving the name chk[], should probably do that anyways as it won't leave empty or useless values. After that just check the count.

$checkboxes = $_POST['chk[]'];
if(count($checkboxes) > 1) { etc... }

There is a minor change you should make to your if statements. Since you are checking $options for a "delete" value, you should also check it for an "edit" value, or move that if statement into the else block and give it an else for the edit block. Otherwise, as you can imagine, you'll end up editing and then deleting your posts and that would take up unneeded resources.

if( //more than one check box is checked but I still have to figure this...) {
    echo "
For now, please just select 1 post you would like to edit.
";
} else {
    if($options == "delete") { /*delete your post*/ }
    else { /*edit your post*/ }
}

I don't see anything else really. So good luck!


You can save some typing if you declare a variable for where your range ends:

for (start.i in seq(1, lengthdata, stepsize)){
  end.i <- if (i + stepsize > lengthdata) lengthdata else i + stepsize
  ## call function (start.i, end.i)
  print(paste(start.i, " - ", end.i))
}

Another improvement would be to compute end.i using the min function (less typing!)

end.i <- min(start.i + stepsize, lengthdata)

As you become an advance user, you might like working with vectors directly:

start.i <- seq(1, lengthdata-1, stepsize)
end.i   <- pmin(start.i + stepsize, lengthdata)

and call your function(s) (e.g. paste) on all using the Map (or mapply)

output <- Map(paste, start.i, " - ", end.i)

rather than use a for loop (even less typing). This is equivalent to doing:

output <- list()
for (i in 1:length(start.i)) {
   output[[i]] <- paste(start.i[i], " - ", end.i[i])
}


Calling common async code from a derived method

In your code you create 2 boolean variables for a simple if statement conditional, personally I think that you shouldn't create these variables unless you are going to use them in more than one place or for complex condition statements.

        using (FleetContext db = CreateDatabaseContext())
        {
            bool isSystemOnline = await db.IsSystemOnlineAsync();
            if (!isSystemOnline)
            {
                return ImmutableApiResult<TValue>.Offline;
            }

            bool isValidSession = await db.IsValidSessionAsync(context.Caller);
            if (!isValidSession)
            {
                return ImmutableApiResult<TValue>.Blocked;
            }

            Task<TValue> task = getTask(db, context.CancellationToken);
            TValue value = await task;

            return ImmutableApiResult.Create<TValue>(value);
        }

You can also avoid creating the Task variable at the end as well and just create the value.

using (FleetContext db = CreateDatabaseContext())
{
    if (!(await db.IsSystemOnlineAsync()))
    {
        return ImmutableApiResult<TValue>.Offline;
    }
    else if (!(await db.IsValidSessionAsync(context.Caller)))
    {
        return ImmutableApiResult<TValue>.Blocked;
    }

    TValue value = await (getTask(db, context.CancellationToken));

    return ImmutableApiResult.Create<TValue>(value);
}

This shortens the code a little bit and gets straight to the point.  Nothing really wrong with the way that you did it, and I haven't really done anything different here either, I just...well... golfed it a bit I guess.  I just didn't think we needed to create all those variables


There's a potential bug here:

public T pop() {
    if(isEmpty()) {
        throw new NullPointerException("Stack is empty");
    }
    return this.stackArray[top--];
}

The problem with this code is that a reference to the object stays in the array.  You've decremented the index, but the array still has the reference sitting there.  This could result in an object not being garbage collected when the user expects it to be.  While technically this doesn't affect how your stack works, hanging on to references you don't need is generally considered poor practice.

Consider something like this (not tested):

public T pop() {
    if(isEmpty()) {
        throw new NullPointerException("Stack is empty");
    }
    T retVal = this.stackArray[top];
    this.stackArray[top--] = null;
    return retVal;
}


JSLint says "unexpected function" doCalc

Well, you asked for general tips, so here goes ;)

I would almost always refrain from extending built-in types. I will "shim" to provide standard-compliant functions which are not available (e.g. "forEach" on Array.prototype), but adding new methods to existing types is a recipe for problems. You could simply have a factorial function without the Math and it would work just as well.

In fact, you could do yourself a favor and create your own Math object (named something different, of course) and add your formula functions to that, so:

var MathFactor = new function () {
    this.factorial = function (n) {
        return n < 2 ? 1 : n * this.factorial(n - 1);
    };
    this.permutate = function (n, r) {
        return this.factorial(n) / this.factorial(n - r);
    };
    this.combine = function (n, r) {
        return this.factorial(n) / (this.factorial(r) * this.factorial(n - r));
    };
};

Then doCalc is just a matter of a simple numeric check, then setting your T3.value to the output of a call to MathFactor.permutate() or MathFactor.combine(). Hope that helps!


yes its possible you need in index file include the ini file

require_once "../app/function/init.php";

and also need .htaccess something look like that

Options -MultiViews
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteBase MVC/Source Files/public

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?url=$1 [L,QSA]

</IfModule>

you can also put php ini file script in index.php file inside public directory

<?php
session_start();
error_reporting(E_ALL);

require_once "../app/functions/onfig.php";
require_once "../app/functions/functions.php";
require_once __DIR__ . '/../vendor/autoload.php';

use \App\Core as App;
use \App\Models\Auth\Login as Login;
use \App\Core\Database as Database;

$app = new App\App();

/**
 * Checks if login cookie exists and log in the user
 */
if(isset($_COOKIE['cookie_hash']) && isset($_SESSION['cookie_hash']))
{
    $login = new Login(Database::getInstance());
    $login->cookieLogin($_COOKIE['cookie_hash'], $_SESSION['cookie_hash']);
}

App\FlashMessage::clear();

you can install session in your App.php file so session start automatically in every file no need to write


Using Roslyn to find interfaces within a solution

Name captured variables as you would name local variables.
First SelectMany and Select can be merged into a single SelectMany.

code:

public async Task<IImmutableList<ISymbol>> GetMatchingInterfacesInSolution(string solutionPath, Func<string, bool> predicate)
{
    var workspace = MSBuildWorkspace.Create();
    var solution = await workspace.OpenSolutionAsync(solutionPath);
    var compilations = await Task.WhenAll(solution.Projects.Select(x => x.GetCompilationAsync()));

    return compilations
        .SelectMany(compilation => compilation.SyntaxTrees.Select(syntaxTree => compilation.GetSemanticModel(syntaxTree)))
        .SelectMany(
            semanticModel => semanticModel
                .SyntaxTree
                .GetRoot()
                .DescendantNodes()
                .OfType<InterfaceDeclarationSyntax>()
                .Select(interfaceDeclarationSyntax => semanticModel.GetDeclaredSymbol(interfaceDeclarationSyntax)))
        .Where(symbol => predicate(symbol.ToDisplayString()))
        .ToImmutableList();
}


It is fine to read the body and replace it, although see ioutil.NopCloser.

However,

it does not make sense to duplicate the http.Request type. Re use it instead. If you need finer control, embed it.
take care to make true copy when passing around slices, maps and pointers.
the code is lacking structured factorization, make use of type definition

This is a revised version i suggest,

package main

import (
    "bytes"
    "flag"
    "io"
    "io/ioutil"
    "log"
    "net/http"
    "net/url"
    "regexp"
    "sync"

    "github.com/elazarl/goproxy"
)

type store struct {
    requests map[string][]http.Request
    sync.Mutex
}

func (s *store) Add(r *http.Request) {
    var c http.Request
    c.Method = r.Method
    c.Proto = r.Proto
    c.ProtoMajor = r.ProtoMajor
    c.ProtoMinor = r.ProtoMinor
    c.Host = r.Host
    c.RequestURI = r.RequestURI
    c.ContentLength = r.ContentLength
    c.URL = r.URL

    c.Header = http.Header{}
    for k, vv := range r.Header {
        for _, v := range vv {
            c.Header.Set(k, v)
        }
    }

    c.PostForm = url.Values{}
    for k, vv := range r.PostForm {
        for _, v := range vv {
            c.PostForm.Set(k, v)
        }
    }

    c.Form = url.Values{}
    for k, vv := range r.Form {
        for _, v := range vv {
            c.Form.Set(k, v)
        }
    }

    var b bytes.Buffer
    io.Copy(&b, r.Body)
    r.Body.Close()
    buf := b.Bytes()

    var b1 bytes.Buffer
    b1.Write(buf)
    r.Body = ioutil.NopCloser(&b1)

    c.Body = ioutil.NopCloser(bytes.NewBuffer(buf))

    key := r.URL.Host
    s.Lock()
    s.requests[key] = append(s.requests[key], c)
    s.Unlock()
}

type storeHandler struct {
    requests *store
}

func (s storeHandler) Handle(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
    s.requests.Add(r)
    return r, nil
}

func main() {
    h := storeHandler{requests: &store{requests: map[string][]http.Request{}}}

    proxy := goproxy.NewProxyHttpServer()
    proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))).
        HandleConnect(goproxy.AlwaysMitm)
    proxy.OnRequest().DoFunc(h.Handle)

    addr := flag.String("addr", ":8080", "proxy listen address")
    flag.Parse()
    log.Fatal(http.ListenAndServe(*addr, proxy))
}


Stack implementation in python using jupyter

Welcome to the land of Python!

If you come from Java, think as self being the same as this in Java.
It is a reference to the object, the difference being in Python, you have to explicitly pass self as a parameter to the class methods.

If you write in Java

class Stack{

    //constructor and class variables goes here

    void pop(){
       if(this.index < 0)
       //logic of the function goes here
    }
}

In Python you write like you did here

class Stack:
    # constructor and class variables goes here

    def pop(self):
        if self.index<0:
        # logic of the function goes here

You see that self and this serve the same purpose.

An another point, you should use documentation! As in PEP257 the format recommanded is like:

def complex(real=0.0, imag=0.0):
    """Form a complex number.

    Keyword arguments:
    real -- the real part (default 0.0)
    imag -- the imaginary part (default 0.0)
    """
    if imag == 0.0 and real == 0.0:
        return complex_zero
    ...
        '''

Another thing, to follow PEP8 it is better to write assignment and condition with a space after the operator.
Write  items = [] or self.index >= 0 instead of items =[] or self.index >=0.

Also you can drop ; in Python, it's not Java :)

Edit: Also look at @Jon's comments below


A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++

No need for an overload that takes no parameters
Nothing calls recursive_count() without parameters, so that overload is unnecessary.
Unnecessary requirements
You don't need to require both is_elements_iterable<T> and is_iterable<T>, the former will already cover the requirements of the latter, and if you negate them then the latter covers the former. So the overloads should be:
template<class T> requires !is_iterable<T>
size_t recursive_count(const T& input)
{
    return 1;
}

template<class T> requires (!is_elements_iterable<T> && is_iterable<T>)
size_t recursive_count(const T& input)
{
    return input.size();
}

template<class T> requires is_elements_iterable<T>
size_t recursive_count(const T& input)
{
    size_t output{};
    for (auto &element : input)
    {
        output += recursive_count(element);
    }
    return output;
}

Naming
Indeed you already noticed that STL has a std::count that does something different. However there is a function that does what you want for non-nested containers: std::size. So consider naming your function std::recursive_size.
Consider making more use of STL algorithms
You are implementing your own algorithms but you are not making use of STL's algorithms. This can reduce the amount of code you write. For example, the last overload can be rewritten as:
template<class T> requires is_elements_iterable<T>
size_t recursive_count(const T& input)
{
    return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [](auto &element){
        return recursive_count(element);
    });
}

Although I'm not sure this is more readable than your version.


This code looks fine to me for a toy project. I especially appreciate the long names for identifiers.

Now, it could look better:

with more comments. You should describe the intent (the why behind the how) and the expected use case for the function: type and range of values in parameters, one line to describe what it does, and one more paragraph for details if needed.
my personal preference would be to use camelCase instead of underscore_between_words for long names. Although this is open to discussion.
a little trick: end the if branch with return; to avoid nesting all remaining code in the else branch:

function update_result_for(input, regexp_value) {
  var input_value   = input.val();
  var result_spans  = input.parent().children('span');
  if(!input_value || !$('#regexp').val()) {
    result_spans.hide();
    return; // return as soon as possible to avoid deep nesting
  }
  // no need for else
  var regexp = new RegExp(regexp_value);
  var result = regexp.exec(input_value);
  // ...
}

in the same vein, treat exceptional cases first and normal cases after. This is a useful convention which helps the reader, and the exception handling is usually shorter (or should be extracted to a separate function if longer) which avoids long runs of nested code:

if (!result) {
  result_spans.filter(".not_ok").show('fast');
  result_spans.filter(".ok").hide();
  return;
}
// reduced nesting
var matched_string = result.shift();
// ...

only use anonymous functions when you actually need a closure with access to the context: the intent of the function will be clearer with a name, you will avoid nesting, and may reuse the function more easily including for unit testing. There are many anonymous functions in your code, which makes it harder to understand:

function(submatch, index) {
  return '$' + (index + 1) + ' = ' + submatch;
})

function(e) {
  if(e.which === 17) isCtrl=false;
}

function(e) {
  if(e.which === 17) isCtrl=true;
    if(e.which === 69 && isCtrl) {
    $('#regexp').focus();
        return false;
    }
})

function() {
  $('#regexp').focus();
  $('span.result').hide();
  // ...
}

function() {
  update_result_for($(this), $('#regexp').val());
}

function() {
  $('input:not(#regexp)').each(function(i) {
    update_result_for($(this), $('#regexp').val());
  });
}

function() {
  new_example = $('div#examples p:last').clone();
  new_example.children('input').attr('value', '');
  new_example.children('span').hide();
  new_example.insertBefore($(this));
  new_example.children("input").focus();
}

once you define more than one function, you should wrap your code in a closure to avoid cluttering the global namespace, following the Module Pattern:

(function(){
  // private scope for your code
}());

break long lines to fit in about 80 characters to avoid the need for scrolling horizontally in typical console windows and in code areas on this site:

var regexp_to_highlight_matched_string =
  new RegExp('(.*)' + matched_string + '(.*)');
var regexp_to_highlight_matched_string_result =
  regexp_to_highlight_matched_string.exec(input_value);
var before_matched_string =
  regexp_to_highlight_matched_string_result[1];
var after_matched_string =
  regexp_to_highlight_matched_string_result[2];
var input_value_with_matched_string_highlighted =
  'matched: ' +
  before_matched_string +
  '' + matched_string + '' +
  after_matched_string;

To go further, my advice would be to read "JavaScript: The Good Parts" and start using JSLint, in this order: this is an enlightening experience on your way to mastering JavaScript. The other way round, using the tool without understanding the mindset of its author, is very frustrating.

I ran JSLint on your code. It has one critical complaint hidden among hair splittings: the declaration of new_example is missing, it is therefore a global variable which is susceptible to result in unexpected bugs.

   // var keyword added:
   var new_example = $('div#examples p:last').clone();


Improving on John Resig's Simple JavaScript Inheritance: avoiding `new`

If you really want to create your own inheritance pattern then John Resig's Simple Inheritance pattern is not a good candidate to build upon. The reason is because John Resig's code is very slow. The reason it's so slow is because of the way _super is handled:

// Copy the properties over onto the new prototype
for (var name in prop) {
  // Check if we're overwriting an existing function
  prototype[name] = typeof prop[name] == "function" &&
    typeof _super[name] == "function" && fnTest.test(prop[name]) ?
    (function(name, fn){
      return function() {
        var tmp = this._super;

        // Add a new ._super() method that is the same method
        // but on the super-class
        this._super = _super[name];

        // The method only need to be bound temporarily, so we
        // remove it when we're done executing
        var ret = fn.apply(this, arguments);
        this._super = tmp;

        return ret;
      };
    })(name, prop[name]) :
    prop[name];
}

I'll try to explain what's happening in the above code:

We loop through each property which we wish to copy onto the newly extended object.
If the property is a function and it overrides another function of the same name and it needs to call the overridden function then we replace it with a function which changes the value of this._super within the function to the overridden function for that particular function call.
Otherwise we simply copy the property as it is.

This little indirection allows you to call overridden methods using this._super. However it also makes the code very slow. Hence I suggest you don't use John Resig's Simple JavaScript Inheritance.

Since this is a code review site I'm also obliged to point out flaws in your code. The main problem with your code is in the Class.create function:

Class.create = function () {
  var instance = new this();
  if (instance.init) {
      instance.init();
  }
  return instance;
};

Compare that with John Resig's original dummy class constructor:

// The dummy class constructor
function Class() {
  // All construction is actually done in the init method
  if ( !initializing && this.init )
    this.init.apply(this, arguments);
}

The problem is that any argument applied to Class.create is lost. You need to apply the arguments passed to Class.create to instance.init as follows:

Class.create = function () {
  var instance = new this;
  if (instance.init) instance.init.apply(instance, arguments);
  return instance;
};

Beside that there's not much more scope for improvement if you plan to stick to John Resig's Simple Inheritance Pattern.

If you really want to create your own inheritance pattern in JavaScript then it pays to invest some time learning about how inheritance works in JavaScript. For example the following answer explains prototype-class isomorphism in JavaScript: https://stackoverflow.com/a/17893663/783743

Prototype-class isomorphism simply means that prototypes can be used to model classes. Armed with this knowledge we can write a function which takes an object (a prototype) and returns a class (a constructor function):

function CLASS(prototype) {
    var constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
}

Using the above function we may now create and instantiate classes as follows:

var Person = CLASS({
    constructor: function (isDancing) {
        this.dancing = isDancing;
    },
    dance: function () {
        return this.dancing;
    }
});

var p = new Person(true);

Although this pattern does not have inheritance yet it is a good base to build upon. With a little bit of modification we can make it behave the way we want it to. There are a few important points to note:

We want to be able to use the extend and create functions on any function. Hence it's better to add them to Function.prototype instead of creating a separate Class constructor.
For a function F it need not be true that F.prototype.constructor === F. Hence we may use F for extending and F.prototype.constructor for creating.
Instead of passing a prototype to extend it makes much more sense to pass a blueprint of a prototype instead. This makes looping over the prototype unnecessary.

Taking advantage of the above mentioned points we can implement extend and create as follows:

Function.prototype.extend = function (body) {
    var constructor = function () {};
    var prototype = constructor.prototype = new this;
    body.call(prototype, this.prototype);
    return constructor;
};

Function.prototype.create = function () {
    var instance = new this;
    instance.constructor.apply(instance, arguments);
    return instance;
};

That's all. Using two simple functions we may now create classes as follows:

var Person = Object.extend(function () {
    this.constructor = function (isDancing) {
        this.dancing = isDancing;
    };

    this.dance = function () {
        return this.dancing;
    };
});

var Ninja = Person.extend(function (base) {
    this.constructor = function () {
        base.constructor.call(this, false);
    };

    this.swingSword = function () {
        return true;
    };
});

To create an instance of the class we use create as follows:

var p = Person.create(true);
p.dance(); // => true

var n = Ninja.create();
n.dance(); // => false
n.swingSword(); // => true

// Should all be true
p instanceof Person && p instanceof Object &&
n instanceof Ninja && n instanceof Person && n instanceof Object

This code is similar to my very own augment function. However augment makes use of new instead of create. Because of the way JavaScript works, using new is the fastest way to create an instance which is why augment doesn't have create. Nevertheless if you want it, a functional version of new can be easily implemented as follows:

function Factory(constructor, args) {
    return constructor.apply(this, args);
}

Function.prototype.new = function () {
    Factory.prototype = this.prototype;
    return new Factory(constructor, args);
};

For more information read the following answer on StackOverflow.


Python code to continue if a certain type is seen, otherwise try again to get valid input

Your first code snippet has the problem that (in Python 3) input always returns a string, so type(user_in) will always be str, which will never compare equal to int.

Your second code snippet solves the problem in the correct way: try to convert the result to an integer, and catch the exception in case that fails.

Fixing that code is as simple as adding a break statement:

while True:
    try:
        user_in = int(input('Enter an integer value'))
        break
    except ValueError:
        print('Invalid input, please try again')
# do something with user_in here

There's no reason to assign the result to user_in and then to a. If you want it to be in a variable called a, just assign it to a to begin with.

Also, you should catch the specific exception that you are looking for, in this case ValueError. Catching every exception is almost never a good idea, because this code could fail for reasons other than the user entering something invalid. For example, if you inadvertently used input as a variable elsewhere in the same function, this call of it will probably raise a TypeError or NameError, and you'll want to see that error, not an infinite loop of "Invalid input, please try again".


Validation for Model Object using Fluent Validation

public bool IsValid(string stringToValidate)
{
    var charString = stringToValidate.ToCharArray();
    if (Regex.IsMatch(charString[0].ToString(), "[0-9]") || Regex.IsMatch(charString[1].ToString(), "[0-9]"))
    {
        return false;
    }
    return true;
}

Be aware that each char in a string can be reached by index as stringToValidate[0], so you don't need to call ToCharArray():
public bool IsValid(string stringToValidate)
{
    if (Regex.IsMatch(stringToValidate[0].ToString(), "[0-9]") || Regex.IsMatch(stringToValidate[1].ToString(), "[0-9]"))
    {
        return false;
    }
    return true;
}

But Char has a static method Char.IsLetter() that can be used instead of the Regex expression:
public bool IsValid(string stringToValidate)
{
     return stringToValidate.Length > 1 && Char.IsLetter(stringToValidate[0]) && Char.IsLetter(stringToValidate[1]);
}

This is more consistent with modern unicode character sets, and it will also catch if the two first characters are special chars like '&' or '!' etc. If you just want to ensure they are not numeric, you can use Char.IsDigit() instead.


Through a series of mechanical transformations, it's possible to simplify the code down to this:

private void buttonDelete_Click(object sender, EventArgs e)
{
    textBox1.Focus();

    if (textBox1.SelectionLength > 0)
    {
        textBox1.SelectedText = "";
    }
    else if (textBox1.SelectionStart > 0)
    {
        textBox1.Text = textBox1.Text.Remove(--textBox1.SelectionStart, 1);
    }
}

It's now simple enough that the code would be better without comments.

How I got there:

Both of your else { return; } are superfluous.
The if (TxTindex >0 && TxTindex == textBox1.Text.Length) case is a redundant special case; its else clause contains exactly the same code.

The code so far:

private void buttonDelete_Click(object sender, EventArgs e)
{
    textBox1.Focus(); // set the textbox focused.

    if (textBox1.SelectionStart >= 0) //check if there is text to delete
    {
        int TxTindex = textBox1.SelectionStart; // save the index position

        if (textBox1.SelectedText.Length > 0)  //// check if there is selected text
        {
            textBox1.SelectedText = "";
        }
        else if (TxTindex > 0) // check if there is text in texbox
        {
            textBox1.Text = textBox1.Text.Remove(TxTindex - 1, 1);
            textBox1.SelectionStart = TxTindex - 1; // to set the cursor position after the deleted number between the text.
        }
    }
}

The outer if (textBox1.SelectionStart >= 0) is redundant, since the if (textBox1.SelectionText.Length > 0) and else if (TxtIndex > 0) tests are both more specific.
textBox1.SelectedText.Length is better written as textBox1.SelectionLength.
The TxtIndex variable (which would be better named textIndex to be consistent with textBox1) can be eliminated.


Task.Finally extension, good, bad, or ugly?

I think what you've really got here is two extension methods hiding inside one.  Your method is doing the work of both a "finally" and a "catch", and I recommend refactoring it into two methods.  The catch method may look something like this:

Edit: clearly I missed checking the exception type before executing the action, but I'm away from a computer and trying to edit code with my iPhone isn't working too well.

public static void Catch<TException>(this Task task, Action<TException> exceptionHandler,
                                     TaskScheduler scheduler = null) where TException : Exception
{
    if (exceptionHandler == null)
        throw new ArgumentNullException("exceptionHandler cannot be null");

    task.ContinueWith(t =>
    {
        if(t.IsCanceled || !t.IsFaulted || t.Exception == null) return;
        var innerException = t.Exception.Flatten().InnerExceptions.FirstOrDefault();
        exceptionHandler(innerException ?? t.Exception);
    }, scheduler ?? TaskScheduler.Default);
}

Edit: Finally got time to get back to this.  Here's an example of a complete solution:

using System;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        Task.Run(() => {
                Console.WriteLine("In the Task");
                throw new ArgumentException("Thrown from task");
                //throw new Exception("Thrown from task");
            })
            .Catch<Exception>((e) => Console.WriteLine("Caught Exception {0}", e))
            .Catch<ArgumentException>((ae) => Console.WriteLine("Caught Argument Excetion {0}", ae))
            .Finally(() => Console.WriteLine("in the Finally"));

        Console.ReadKey();
        Console.ReadKey();
    }
}

static class TaskExtensions
{

    public static void Finally(this Task task, Action finalAction,
                               TaskScheduler scheduler = null)
    {
        if (finalAction == null)
            throw new ArgumentNullException("finalAction cannot be null");

        task.ContinueWith(t => finalAction(), scheduler ?? TaskScheduler.Default);
    }

    public static Task Catch<TException>(this Task task, Action<TException> exceptionHandler,
                                         TaskScheduler scheduler = null) where TException : Exception
    {
        if (exceptionHandler == null)
            throw new ArgumentNullException("exceptionHandler cannot be null");

        task.ContinueWith(t =>
        {
            if (t.IsCanceled || !t.IsFaulted || t.Exception == null)
                return;

            var exception =
                t.Exception.Flatten().InnerExceptions.FirstOrDefault() ?? t.Exception;

            if (exception is TException)
            {
                exceptionHandler((TException) exception);
            }
        }, scheduler ?? TaskScheduler.Default);

        return task;
    }
}
}


First, I believe that the Node class is an implementation detail. You could move it inside the Stack or your could rename it _Node to indicate that it is private.

Next, I will refer you to this answer to a different CR question, also written by me: https://codereview.stackexchange.com/a/185052/106818

Specifically, points 2-7:

... consider how the Python list class (and set, and dict, and tuple, and ...) is initialized. And how the Mutable Sequence Types are expected to work.

Because your code is implementing a "mutable sequence type." So there's no reason that your code shouldn't work the same way. In fact, if you want other people to use your code, you should try to produce as few surprises as possible. Conforming to an existing interface is a good way to do that!
Create an initializer that takes a sequence.

class Stack:
    def __init__(self, seq=None):
        ...
        if seq is not None:
            self.extend(sequence)

Implement as many of the mutable sequence operations as possible.
Use the standard method names where possible: clear, extend, append, remove, etc.
Implement special dundermethods (method names with "double-underscores" in them: double-under-methods, or "dundermethods") as needed to make standard Python idioms work:

def __contains__(self, item):
    for i in self:
        ...

def __iter__(self):
    node = self.head

    while node:
        yield node.value
        node = node.next

Implement your test code using standard Python idioms, to prove it's working and to show developers how your code should be used!

Finally, some direct code criticisms:

Don't use equality comparisons with None. Use is None or is not None instead. This is a PEP-8-ism, and also actually faster.
You don't really use self.bottom for anything. Go ahead and delete it.
Don't use CamelCase variable names. That's another PEP-8 violation. Use snake_case for local variables.


You could achieve a little more readability using Linq2Xml like this:

var ex = new XElement("ServiceResponse",
    response.details.Select(detail =>
        new XElement("Details",
            new XElement(CleanName(detail.name), detail.value))));

I have moved the line of code that performs some kind of cleaning on the detail's name to a separate method, like so:

private static string CleanName(string name)
{
    return Regex.Replace(name.Trim(), @"[^A-Za-z0-9.]+", "");
}

You could rename this method to communicate better what it does (for me it's not really obvious).

Two more things:

it's good to follow the C# naming guidelines. In your code, the local variables begin with a capital letter and the public fields/properties of the Request and Detail classes begin with lowercase letters. It should be the other way around.
you could add a using Nettium.FraudManagementBase.DataContext; clause at the top of the file. The data access code will look like this:

using (DBDataContext con = new DBDataContext())
{
    con.Requests.InsertOnSubmit(new Request { response = ex });
    con.SubmitChanges();
}

which is much cleaner IMO.

So, the final code could look like this:

var xml = new XElement("ServiceResponse",
    response.Details.Select(detail =>
        new XElement("Details",
            new XElement(CleanName(detail.Name), detail.Value))));

using (DBDataContext con = new DBDataContext())
{
    con.Requests.InsertOnSubmit(new Request { Response = xml });
    con.SubmitChanges();
}


When programming a solution like this, in order to simplify the problem create a separate function for each component. So, I would break it up into three different parts:

String getUserInput() {
    // Get input string and return it...
}

boolean isValidInput(String input) {
    // Return true or false based off of the validity of the input string.
}

boolean isPalindrome(String input) {
    int left = 0;
    int right = input.length();
    while(left < right) {
        if(input.charAt(left++) != input.charAt(--right)) return false;
    }
    return true;
}

The reason for returning a boolean rather than throwing an exception is that a try catch can be expensive especially if there is a good chance of an error being thrown. Now, a boolean means later that there may be some sort of conditional branch, but that is less expensive than if there is a high chance of an error being thrown. Also, there is more usability with returning a boolean, because now you can decide if you want to throw an exception or just print true or false.

Since the question was more geared towards the optimization of the palindrome detection algorithm, I provided a solution that I have found to work the best for when detecting palindromic inputs.

The solution cuts the number of steps down to a quarter of your solution. This is done by assuming that if the first half is the same as the second half then the String must be palindrome. So, we start from both ends and work our way to the center (essentially when left reaches or passes right). If any where along the way we find a point in which is not equal, then we know that we do not have a palindromic String. Therein, we can exit returning false. If we successfully exit the loop, then we know we were given a palindromic String. Therein, we return false.


The first thing I noticed is that you have grouped all the type signatures together, away from the function bodies. This seems very strange to me. It's way more common (and as far as I'm concerned also way more readable) to have a value's type directly before its definition.

The second thing I noticed were all the braces and semicolons. Unless you have a specific reason to use them, I'd strongly recommend making use of Haskell's significant indentation instead. Much less visual noise. I'm especially confused by the semicolon at the end of parseName's definition as parseName doesn't use do-notation and you didn't use a semicolon on any other definition which didn't use do.

You sometimes surround variables with parentheses (e.g. in values <- endBy1 (parseNameValue) (parseCmtOrSpace), but not in the line name <- between parseCmtOrSpace ... directly above it). I can't see any system to when you do this and when you don't, so it just seems random and inconsistent. So I'd recommend to get rid of the needless parentheses.

Speaking of parentheses, you might also want to get rid of some more parentheses by sprinkling a couple of $ signs in your code, to give it a more "haskellish" feel.

parseSectionHeader = do{
   name <- between (char '[') (char ']') parseName;
   return name;
}

parseIniFile  = do{
   result <- many1 (parseSection);
   return result;
}

Whenever you have something of the form:

foo <- bar
return foo

You can simply just write bar. I.e.:

parseSectionHeader = between (char '[') (char ']') parseName

parseIniFile  = many1 parseSection

iniFileToMap path = do{
   result <- parseFromFile parseIniFile path;
      case (result) of
         Left err -> error (show err)
         Right xs -> return (list2Map(xs));
}

Here the indentation is off - case should not be indented further than result <-. It should be:

iniFileToMap path = do
    result <- parseFromFile parseIniFile path
    case result of
        Left err -> error $ show err
        Right xs -> return $ list2Map xs


Is this the right way or is there an easier, smaller way to archive this?

It depends on how you define the right way. Is your goal short and small code or is your goal testability and maintainability? These two goals are mutualy exclusive.

If you want to have it short then of course there is a way. You don't need the nested class at all.

class NestedTest
{
    public int Position { get; private set; }

    public void Left()
    {
        Console.Write("<-");
        Position--;
    }
}

If you want to have maintainable code then you need to write more code and correctly use dependency injection and possibly use a few interfaces as abstractions. Nested public classes are a bad style anyway so you should avoid them.

This is how such an implementation could look like. The NestedTest gets an interface that allows accesing its Position. Its constructor also requries a lambda that lets you specify the navigator for this instance.

public interface IPositionable
{
    int Position { get; set; }
}

class NestedTest : IPositionable
{
    public int Position { get; set; }

    public INavigator Navigator { get; }

    public NestedTest(int num, Func<IPositionable, INavigator> createNavigator)
    {
        Position = num;
        Navigator = createNavigator(this);
    }
}

Where the Navigator is now also abstracted by an interface and can be faked for testing or exachnged for another navigator later:

public interface INavigator
{
    void Left();
}

public class Navigator : INavigator
{
    private IPositionable _positionable;

    public Navigator(IPositionable positionable)
    {
        _positionable = positionable;
    }

    public void Left()
    {
        _positionable.Position--;
    }
}

It's up to you to decide. Shortest code possible or testable and maintainable?


I've solved it by using Text.ParserCombinators.Parsec.GeneralizedToken from MissingH package:

psOpBracket = tokeng (\x -> case x of TokOpBracket -> Just Nothing ; _ -> Nothing)

I had to use tokenPrim for cases when Token constructor takes arguments, though.


Using Linq syntax, how can I remove the select n+1 issue in this method?

I think this might work for you

void EnsureIdentifiersAreNotInUse(AddOrEditClientCommand request)
{
    var identifiers = request.Editor.Identifiers;

    var errors =
        dbContext.ClientIdentifers
            .Where(ci => ci.Client.Id != request.Editor.ClientId
                   && identifiers.Any(i => ci.ClientIdentifierType.Id == i.TypeId
                                      && ci.Value.Equals(i.Value, StringComparison.InvariantCultureIgnoreCase)));
}

UPD
Ok, your identifier type is not presented at db, so the query cannot be converted to a db query.

Let's try this:

void EnsureIdentifiersAreNotInUse(AddOrEditClientCommand request)
{
    var identifiers = request.Editor.Identifiers;
    var identifiersIds = identifiers.Select(i => i.TypeId).ToList();
    var identifiersValues = identifiers.Select(i => i.Value).ToList();

    var errors =
        dbContext.ClientIdentifers
            .Where(ci =>
                   {
                       if (ci.Client.Id == request.Editor.ClientId)
                       {
                           return false;
                       }
                       var indexOfId = identifiersIds.IndexOf(ci.ClientIdentifierType.Id);
                       if (indexOfId == -1)
                       {
                           return false;
                       }
                       return indexOfId == identifiersValues.IndexOf(ci.Value);
                   });
}


I think I'd prefer something like this:

int findsum(int const *list, int length) {
    if (0 == length)
       return 0;
    return list[0] + findsum(list+1, length-1);
}

This follows one of the typical recursive formulations -- basically a function that's almost like an inductive proof. Start by establishing a correct value for the simplest possible base case (or some obvious base case anyway), and then establish a pattern that's correct for some some sort of "Base+1" type of case.


Tail-Recursion to get a Map of word counts

Yes, this is tail-recursive. Just annotate countWordsInFile with @tailrec and the compiler will check that for you.
Btw: why not name the method countWords? The Scanner is not limited to read from files.


No need to use quotes here, though it's not a problem:

useFile='deferred.php'
tempFile='/scripts/_inc/deferredTextTemplate.php'

On the other hand, it might be a good idea to double-quote $tempFile here:

newTop=$(head -n 15 $tempFile)
newBottom=$(tail -n 4 $tempFile)

It's hard to guess the meaning of the parameters $2 and $3 here:

changeFile () {

    ## Info About Action to be intered into File.
    workInfo="\n// Edited: $(date)\n// Directory: $2"
    logTag="$(date): [$3 @ $2]"

One way to improve that is to document them in a comment.
An even better way would be to reassign them to local variables with descriptive names.

The marker F8kR8ikBiF is buried deep within the script:

    if grep -q F8kR8ikBiF "$1"; ## Description: Does the file contain this marker?

It would be better to put it in a variable with a good name,
defined near the top of the script.

You were careful to double-quote most variables correctly, but not always:

orgFileCont=$(tail -n +2 $1 | sed -r 's/\/\*+ (.*) \*+\//\/\/ \1/')

You should double-quote the $1 there.

Also, the \/ make the expression hard to read. It would be better to use a different separator, for example ?:

... | sed -r 's?/\*+ (.*) \*+/?// \1?'

When you have an if-else block like this:

if [ -f "$1" ]
then
    # ... many many lines
    # ... many many lines
    # ... many many lines
else
    printf "%s File not found.\n" "$logTag"
fi

When there are too many lines in the middle,
it can be more readable to invert the if-else branches:

if [ ! -f "$1" ]
then
    printf "%s File not found.\n" "$logTag"
else
    # ... many many lines
    # ... many many lines
    # ... many many lines
fi


Python function to generate Spanish conjugations

I think that there are too many special cases in the code.  A data-driven approach would be easier to read and maintain than hard-coded logic.  The entire function could be done using just dictionary lookups.

Furthermore, I think that you are missing a translation layer.  You can classify the three pronouns "usted", "él", and "ella" as "third person singular", and it will be clear that they all lead to the same conjugation.  It would be more worthwhile to "compress" your conjugation tables that way than to try to override a few entries of the erDict with irDict.

I would also format the dictionaries to look more like the tables that would typically be presented in grammar books.  The line containing your arDict stretches to column 163, which is too wide to be readable.

from unidecode import unidecode

PRONOUN_CLASSIFICATION = {
    'yo': '1s',     'nosotros': '1p',
    'tú': '2s',     'vosotros': '2p',
    'usted': '3s',  'ustedes': '3p',
    'él': '3s',     'ellos': '3p',
    'ella': '3s',   'ellas': '3p',
}

PRESENT_CONJUGATION_ENDINGS = {
    'ar': {
        '1s': 'o',      '1p': 'amos',
        '2s': 'as',     '2p': 'áis',
        '3s': 'a',      '3p': 'an',
    },
    'er': {
        '1s': 'o',      '1p': 'emos',
        '2s': 'es',     '2p': 'éis',
        '3s': 'e',      '3p': 'en',
    },
    'ir': {
        '1s': 'o',      '1p': 'imos',
        '2s': 'es',     '2p': 'ís',
        '3s': 'e',      '3p': 'en',
    },
}

def conjugate_spanish_present(pronoun, infinitive):
    person = PRONOUN_CLASSIFICATION[pronoun]
    base, ending = infinitive[:-2], unidecode(infinitive)[-2:]
    try:
        return base + PRESENT_CONJUGATION_ENDINGS[ending][person]
    except KeyError:
        return infinitive


A transpose function would be useful here. This is the code I came up with:

(defn transpose [m]
  "Transposes a matrix, returning a new matrix. For 2D matrices, rows and columns are swapped."
  (vec (apply map vector m)))

(defn any-zero? [r]
  ((complement not-any?) #(= 0 %) r))

(defn empty-matrix [x y]
  (vec (repeat y (vec (repeat x 0)))))

(defn filter-matrix [m]
  (let [row-size (-> m first count)
        fm (filterv any-zero? m)
        padding-size (- (count m) (count fm))]
          (into (empty-matrix row-size padding-size) fm)))

(defn transform-matrix [m]
  (-> m
      transpose
      filter-matrix
      transpose))

Let's try it out:

=> (transform-matrix [[0 2 0] [1 3 5] [3 3 0]])
[[0 0 0] [0 1 5] [0 3 0]]

If you want to do more advanced operations on matrices I recommend looking into the core.matrix library.

Hope this helps!


Less insane interface design for a trigger component for T types?

Having thought a little bit on the problem, I've come up with a solution I think satisfy my goal without being too awkward or introducing gotchas with raw pointers and ownership. Below is my updated code and as always, I would appreciate any feedback or tips on improvement.

  class IComparable
  {
  public:
    virtual ~IComparable() {}
    virtual bool lessOrEqual() const = 0;
    virtual bool greaterOrEqual() const = 0;
    virtual bool equal() const = 0;
    virtual bool lessThan() const = 0;
    virtual bool greaterThan() const = 0;
  };

  /* trigger/threshold set of any type supporting the comparison operators. Can create new set by adhering to the interface*/
  template<class T>
  class ComparableTriggerSet : public IComparable
  {
  public:
    ComparableTriggerSet(std::shared_ptr<T> threshold, const T& trigger) : m_threshold(threshold), m_trigger(trigger) {}
    bool lessOrEqual() const { return m_trigger <= *m_threshold; }
    bool greaterOrEqual() const { return m_trigger >= *m_threshold; }
    bool equal() const { return m_trigger == *m_threshold; }
    bool lessThan() const { return m_trigger < *m_threshold; }
    bool greaterThan() const { return m_trigger > *m_threshold; }

  private:
    std::shared_ptr<T> m_threshold;
    const T& m_trigger;
  };

  /* supported operators */
  enum CompareOperator { LessOrEqual, GreaterOrEqual, Equal, LessThan, GreaterThan };

  /* TriggerComponent - getting checked at regular intervals by the TriggerSystem */
  class TriggerComponent : public artemis::Component
  {
  public:
    TriggerComponent(std::shared_ptr<IComparable> comparableTriggerSet, CompareOperator compareOperator)
      : m_comparableTriggerSet(comparableTriggerSet), m_compareOperator(compareOperator) {}

    void check() const
    {
      bool condition = false;
      switch(m_compareOperator)
      {
        case LessOrEqual:
          condition = m_comparableTriggerSet->lessOrEqual();
          break;
        case GreaterOrEqual:
          condition = m_comparableTriggerSet->greaterOrEqual();
          break;
        case Equal:
          condition = m_comparableTriggerSet->equal();
          break;
        case LessThan:
          condition = m_comparableTriggerSet->lessThan();
          break;
        case GreaterThan:
          condition = m_comparableTriggerSet->greaterThan();
          break;
        default:
          assert(false && "unsupported operator enum");
          break;
      }

      if(condition)
        execute();
    }

    /* supposed to invoke an event or maybe call a script or something similar */
    void execute() const
    {
      qDebug() << "execute!";
    }

  private:
    std::shared_ptr<IComparable> m_comparableTriggerSet;
    CompareOperator m_compareOperator;
  };

I would then add the component in my executable like so:

  artemis::Entity& ent = /* omitted */
  ScaleComponent* scaleComp = /* omitted */
  std::shared_ptr<float> threshold = std::make_shared<float>(1.0f);
  std::shared_ptr<ComparableTriggerSet<float>> triggerSet = std::make_shared<ComparableTriggerSet<float>>(threshold, scaleComp->getx());
  ent.addComponent(new TriggerComponent(triggerSet , CompareOperator::LessThan));

I think the updated code solves my original issues fairly well. I have thus far not encountered any problems with it, and I can add TriggerComponents without worry of whether threshold value is getting off the stack, cleaned up properly etc.


Deleting three consecutive numbers in an array

Remove(x) deletes the element and then shifts every element up so it alone is an O(n) operation making your entire algorithm O(n^2). I actually wrote a removeAtFast(x) which swaps the item being removed and the last element then removes the last element normally. But you can't do this because it messes up the ordering.

I'd create a new array like what Pure Evil suggested. Just go through the elements and if you find 3 consecutive numbers skip 3 ahead and continue copying.

Edit: Also it would appear your code would fail the first example given in the assignment.


Insert row into database using values from a html form submission

With prepared statements, I don't see anything that would immediately make it susceptible to sql injection (this isn't to say there isn't something that is there at a deeper level - I'm not a security auditor nor intimately familiar with php).  The "or something else" part remains quite large.

Look at OWASP (Open Web Application Security Project) which goes through a large set of possible attack vectors through the web.

Such a page is susceptible to various scripting injection where someone inserts a script (or flash, or even something like an image from another site) to be executed on another client machine. From the OWASP top 10 - 2013 pdf the XSS attack can be seen and described on page A3 (page 9).


Reading Excel (93-97) sheet with more than 65536 rows using cfspreadsheet

This is in a function, but you haven't given us the complete function.  How's your var scoping?  Maybe update your code to show us all the function.

You don't need to use the octothorpes in most cfset statements like this:

<cfset count1 =#Query1.recordcount#>

Could just be written as

<cfset count1 =Query1.recordcount>

Do you have to use SELECT * or could you specify columns?

And most importantly, and the reason it's probably timing out...  you have 2 queries.  By using UNION ALL to join them together, you're taking the 65533 rows of the first sheet and joining it to the X rows in the second sheet.  That's a pretty big dataset, especially if you're just using Excel.  Have you considered using a database?  Do you really need all this data at this point?


Loading more items for an activity feed that uses a global page counter

This doesn't have anything to do with ajax or the options exactly, just about "counting up" so i will show my example using a function called countUp which logs ever increasing numbers.

In short you can make page a member of countUp. You will recall that in javascript that functions are very much first class citizens and they are objects. Its easier to see this of course if you write your function definitions like:

var countUp = function () { /* .. function body */ }

So the variable countUp can have in it any number of members. The member we are interested in is page or more precisely this.page. So lets put this all together.

var countUp = function ()
{
    this.page = (typeof this.page !== "undefined") ? this.page : 0;
    this.page++;
    console.log(this.page);
}

countUp();
countUp();
countUp();
// logs 1 2 3


I don't see anything particularly wrong with the loops themselves, but, as far as coding style goes:

tempVal and displayLine should be declared as close as possible to the place where they're first used.
the values returned by Math.RoundToInt and Mathf.Clamp don't seem to have anything in common, so they should be assigned to different variables. Don't reuse tempVal for different and unrelated things.
tempVal, x, y and a should be given more meaningful names.
You should use a StringBuilder to build strings, instead of using string concatenation.
Your indentation is all over the place.
In C#, it is common practice to put the opening bracket { on its own line - although one could argue that this is a matter of personal preference and doesn't really matter as long as you're consistent throughout the codebase.

for(int y = 0; y < 16; y++)
{
    var sb = new StringBuilder();

    //HERE
    for(int x = 0; x < 40; x++)
    {
        int height = Mathf.RoundToInt(Physics.HeightAtPoint(x, a, 15f, 0));
        int clamp = Mathf.Clamp(height, 0, 16);

        if(Mathf.CloseTo(16 - y, clamp, 1))
            sb.Append(" X");
        else
            sb.Append(" .");

    }
    Console.WriteLine(sb.ToString());
}


Setting the positions of nodes based on a layout

If you have the control over the Position class, why not have a setPosition which takes the layout as a parameter? This would render the loop to be:

for (Node n: g.getNodes().values) {
    n.setPosition(lo);
}

This way you hide the conversion within the method, but it is still clear that your position is set relative to the layout, lo.  How you implement the setPosition() isn't then as interesting, but you could then easily do something like:

public void setPosition(Layout lo) {

    Position newPos = new Position(
        new Double(lo.getX(this.id)),
        new Double(lo.getY(this.id)));

    setPosition(newPos());
}

This assumes that the id is available as an Integer within the Node class, but you'll get the gist of the idea and can surely complete it.


A faster implementation of AcceptChanges?

It's quite easy to answer your question by looking at the DataTable.AcceptChanges source code.

As you can see they copy all DataRow objects into new array before iterating them. I suspect that your code will work incorrectly when rows are deleted (accepting changes for deleted rows means removing them from DataTable), most likely you'll get exception since it's not allowed to change collection while iterating it.


As others have mentioned, your program runs slowly because it is doing a lot of membership tests against fairly large lists, which is expensive. If you replace your lists with sets, that alone should improve performance by quite a bit.
Creating a set from the input list of words is also important to ensure the correctness of your algorithm. As @Tweakimp pointed out, we only want to find pairs of opposites within a collection of unique words, to avoid the possibility of duplicates of the same pair from showing up in the results.
Below is a simple algorithm which calculates all the pairs in one pass.

Create unique_words: set[str] from the input list of words.
Create results: list[tuple[str, str]] for our results. This will be our return value.
Create words_seen: set[str] to track which words from unique_words we've seen so far.
Iterate over unique_words; for each word, also calculate reversed_word.

If we haven't seen reversed_word yet, then we don't know if word has a matching pair (yet). So we add word to words_seen.
If we have seen reversed_word, then we just found a matching pair, so we append (word, reversed_word) to results.

Return results.

def find_opposites(words):
    unique_words = set(words)

    results = []
    words_seen = set()

    for word in unique_words:
        reversed_word = word[::-1]

        # if we have already seen reversed_word,
        # then we found a new pair of opposites: (word, reversed_word)
        if reversed_word in words_seen:
            results.append((word, reversed_word))
        else:
            words_seen.add(word)

    return results

Because we start with the set unique_words, we actually don't need to check explicitly for the palindrome case. This is because in order for a palindrome to end up in results, there would need to be at least two instances of the same palindrome in unique_words, which is impossible.


Queue over resizable array implementation

Imports:

import java.util.*;

NEVER do this. Look how many classes you got now. This is ineffective and needlessly clutters your IDE's "do what I want button"-suggestions.
The fun thing is, in your main class you do it the other way round:

java.util.Arrays.sort(data, new java.util.Comparator<Object>() {

why not:
import java.util.Arrays;
import java.util.Comparator;
import java.util.NoSuchElementException;

//Later:
Arrays.sort(data, new Comparator<Object>()) {

This is shorter, does exactly the same and allows your ClassLoader to preload the classes needed --> possible performance improvements
Queue<E> and Scoping
While we're in the java.util package.. You can find an interface there.. Queue<E>. This is something you can program against. To prevent a name-conflict I'd rename your implementation to MyQueue or something similar.
You class would then begin with the following:
public class MyQueue implements Queue<Integer> {
    private Integer[] data;
    private int head;
    private int tail;

Here I also made some changes to your code.
Why? In short: You should restrict the visibility of members as much as possible. With your code, classes in the same package as your Queue could do:
Queue queue = new Queue();
queue.data[0] = Integer.MAX_VALUE;

This is not good. noone should be messing with the state of your class. That's why these members should be private (or maximally protected), but definitely not package-private which is the default scope.
same goes for your head and tail.


My ColdFusion is a little rusty, but why would you not have the setting of the master dependent variables and the call to the master page both contained within the same page? Other than that, sure, you're implementing this the same way everyone does unless it's specifically built into the language.


To test case, you can use toLowerCase() and toUpperCase() methods in String to get case. Also using String, you can use the split(' ') method to get each word and compare them instead of using two lists. It would definately increase performance to some extent.

To get the contents a bit better, the new nio package was updated in java 8 and has methods like Files.readAllLines(Path p);, returning a List (a list of lines) instead of using the BufferedReader trick. You can also use readAllBytes(Path p); which will return a byte array, but it is much easier to use readAlLines for your case.

Other than that I don't think there is much to give you. You have done a good job.


There are no docstrings. What do these functions do? Lack of docstrings make the code hard to review, because we don't know what the functions are supposed to do.
The call indices(n) generates the Cartesian product of range(n) × range(n) in a particular order. A natural question is, does the order matter, or could we use itertools.product instead:

itertools.product(range(width), repeat=2)

The post explains why you've chosen the order. But how is someone reading the code supposed to know that? There needs to be a comment.
encode could be simplified to avoid the if:

sum(bit<<i for i, bit in enumerate(...))

This code:

for matrix in product((False, True), repeat=width**2):
    candidate = list(zip(*[iter(matrix)]*width))

is effectively the same as:

sol_matrices = (list(zip(*[iter(matrix)]*width)) for matrix
                in product((False, True), repeat=width**2))

and so would benefit from having its own function (which would have a name and docstring that would explain what it does).
The algorithm takes every nonogram puzzle, and then compares the run counts with the run counts for every nonogram puzzle of the same size. If width is \$ n \$, there are \$ 2^{n^2} \$ nonogram puzzles, and it takes \$ Ω(n^2) \$ to compute the run counts for a single puzzle, so the overall runtime is the ludicrous \$ Ω(n^24^{n^2}) \$.

This could be brought down to \$ Ω(n^22^{n^2}) \$ if you prepared a dictionary mapping run counts to sets of encoded nonogram solutions, and down to \$ Ω(n2^{n^2}) \$ if you prepared the list of all rows, prepared a dictionary mapping each row to its run counts, and then generated the puzzles and their run counts simultaneously using the Cartesian product of the rows.


What should I do to improve this snippet

I noticed that when moving through the OpenFileDialog to find files it
  felt sluggish. Is that because I had to set [STAThreadAttribute] just
  to get it to open?

That is a StackOverflow or GameDev.StackExchange kind of question.

Refactoring the code like this could be a start:

private void loadMapToolStripMenuItem_Click(object sender, EventArgs e)
{
    var openFile = new OpenFileDialog
                       {
                           Title = "Select a File",
                           InitialDirectory = Application.StartupPath + @"\Content\Map\",
                           Filter = "MAP Files (.MAP)|*.MAP",
                           FilterIndex = 1,
                           Multiselect = false
                       };

    if (openFile.ShowDialog() != DialogResult.Cancel)
    {
        try
        {
            string otherMapName;

            LoadMap(TileMapper, openFile.FileName, out otherMapName);

            txtMapName.Text = otherMapName;
        }
        catch
        {
            //TODO: display an error message box?
            System.Diagnostics.Debug.Print("Unable to load map file");
        }
    }
}

//TODO: why not move this method inside TileMapper?
private void LoadMap(TileMapper tileMapper, string fileName, out string mapName)
{
    mapName = null;

    // Example file - _W25_H25_SET_GL_test.Map
    tileMapper.LoadMap(new FileStream(fileName, FileMode.Open));

    mapName = Path.GetFileNameWithoutExtension(fileName);

    //get info stored in file name
    string[] nameParts = mapName.Split('_');
    string[] widthPart = nameParts[1].Split('W');
    string[] heightPart = nameParts[2].Split('H');

    tileMapper.MapWidth = int.Parse(widthPart[1]);
    tileMapper.MapHeight = int.Parse(heightPart[1]);
}


LeetCode 928: Minimize Malware Spread II

Misleading type alias
You are using uint16 = std::uint_fast16_t, but if I see the name uint16, as a programmer I assume this is identical to uint16_t. But uint16_t and uint_fast16_t might have very different properties, so therefore it is a potentially misleading name.
When you create a type alias, you usually want to give it a name that conveys its intent. Here, it's to hold sizes and indices. So I would recommed using size_type = ... instead.
Name functions after their intent, not their implementation
The function breadthFirstSearch() indeed uses a BFS algorithm internally, but the intent of this function is to return the number of infected nodes given a set of initial infectations and an excluded node. So name it something like countInfectedNodes() instead.
While you are at it, rename node in that function to excluded_node, to make it clear what its purpose is.
Use a std::vector<bool> to keep track of infected nodes
A bitset is much more compact and faster than a std::set in this case, since nodes are just numbers between zero and std::size(graph). However, you can't use std::bitset here because that needs the size to be known at compiletime. Instead, this is one of the few occasions where a std::vector<bool> is useful:
std::vector<bool> nodes_set(std::size(graph));
nodes_set[excluded_node] = true;
...

Avoid modifying the input parameters
While the LeetCode problem does state that the parameters are non-const, it is nevertheless bad practice to modify the input parameters if it's not expected that this will happen.
You can avoid sorting initial, by just modifying the way you set smallest_node:
if (curr_len < min_len || (curr_len == min_len && init_node < smallest_node)) {
    min_len = curr_len;
    smallest_node = init_node;
}

Consider stopping counting infections if it won't improve the minimum
Currently, for every candidate node to remove, you count all infections. However, if halfway you notice that you are already above the minimum seen so far, then you can stop early. Just pass the previous min_len to countInfectedNodes() and check it when incrementing count:
static size_type countInfectedNodes(
    const std::vector<std::vector<int>>& graph,
    std::vector<int>& initial,
    size_type excluded_node,
    size_type current_min,
) {
    ...
        nodes_set[curr_node] = true;
        if (++count > current_min) {
            break;
        }
    ...
}


using namespace std is considered bad practice.

to_be_handled.insert(to_be_handled.begin(), v); will badly hurt the performance. As mentioned in comments, BFS benefits from using std::queue, which is specifically designed for this purpose.

Simulating stack with std::vector is also dubious, again from the performance point of view. std::vector guarantees contiguous storage, and the you'd have to face reallocation penalty as it grows. Again, std::stack is specifically designed to avoid such a penalty.

The utility of the function is severely limited by the handler being hardcoded. You may pass the handler as an argument, or better yet restructure the code to make them iterators of Graph, and let the client handle vertices, e.g.:

    Graph g;
    for (auto it: g.bfs_iterator(start)) {
        handle(it);
    }


Maximum consecutive subarray sum for a variable sliding window size

While I'm not one who really promotes pasting solutions, a lot of the answers seem to be answering in a way that a C programmer would answer the question. This is more a problem that you would want to solve in a pipeline in python due to that being how python does things fast and keeps a majority of the operations in C. Look into David Beasley's work if you want to minimize the amount of code you have to write by making everything into pipelines and checkout the collections library to get to know the tools that make things like windowed operations easy and a lot faster in python.

from collections import deque
from itertools import chain

def window(iterable,size):
    ''' yields wondows of a given size '''
    d = deque(maxlen=size)
    # normalize iterable into a generator
    iterable = (i for i in iterable)
    # fill d until it only needs one more
    for i in iterable:
        d.append(i)
        if len(d) == size-1:
            break
    # yield the windows
    for i in iterable:
        d.append(i)
        yield d

def max_sequential_subarray_sum(iterable, max_size):
    ''' returns the max sum of sequential slices of an iterable '''
    g = chain(*(window(iterable,i) for i in range(2,max_size+1)))
    return max(sum(i) for i in g if all(
        a<b for a,b in window(i,2)
    ) or all(
        a>b for a,b in window(i,2)
    ))

L=[-200, 91, 82, 43]
k=3
print(max_sequential_subarray_sum(L,k))

L=[41, 90, -62, -16, 25, -61, -33, -32, -33]
k=5
print(max_sequential_subarray_sum(L,k))


Multiple Pandas Ranking Operations within a Loop - Better Optimization and Performance

A basic principle of performance optimization in pandas is to avoid for-loops and vectorize as much computation as possible.
Here is one version of improved code:
order_df = df.rank(axis=1, method="first", na_option="bottom")
order_df_avg = df.rank(axis=1, method="average", na_option="bottom")
order_df.where(df.astype(bool), order_df_avg, inplace=True)
matrix_computed = norm.ppf(order_df / (len(df.columns) + 1))
df[:] = matrix_computed

One potential further improvement is to compute only the orders that need to be updated rather than order_df_avg.
order_df = df.rank(axis=1, method="first", na_option="bottom")
mask = (df == 0)
orders_to_update = np.broadcast_to(np.expand_dims(order_df[mask].mean(axis = 1), 1), df.shape)
order_df.mask(mask, orders_to_update, inplace=True)
matrix_computed = norm.ppf(order_df / (len(df.columns) + 1))
df[:] = matrix_computed


Extracting the IP addresses of Docker containers using JSON API

Dictionaries, as any iterable in Python can be unpacked. It means that, if you know the length of said iterable, you can use as many variables to hold each item of the iterable independently.

For instance:

>>> l = [1, 2, 3]
>>> a, b, c = l
>>> a
1
>>> b
2
>>> c
3
>>> d = {"one": 1, "two": 2}
>>> a, b = d
>>> a
"two"
>>> b
"one"

(order may vary for the dictionary)

If the number of elements in the iterable and the number of variables mismatch, you get a ValueError:

>>> d = {"one": 1}
>>> a, b = d
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 2, got 1)

So, if you know that a dictionary has a single key, you can

network_settings, = i["NetworkSettings"]["Networks"]

and get it that way. If it appears that the dictionary may not contain that key, you have no other choice but to use a try: ... except ValueError: pass.

However, you only care about the values of this dictionary. So I wouldn't use this directly on the dictionary but on its .values() (.itervalues() in Python 2). So the loop would look like:

for container in response.json():
    network_settings, = container['NetworkSettings']['Networks'].values()
    table.add_row(
            container['Names'][0].encode('utf-8').replace('/', ''),
            container['Id'].encode('utf-8')[:12],
            container['State'],
            network_settings['IPAddress'])

or

for container in response.json():
    try:
        network_settings, = container['NetworkSettings']['Networks'].values()
    except ValueError:
        continue
    table.add_row(
            container['Names'][0].encode('utf-8').replace('/', ''),
            container['Id'].encode('utf-8')[:12],
            container['State'],
            network_settings['IPAddress'])

In case of possible missing keys.

Now, for the rest of the code. I wouldn't use any of the prettytable stuff within active_containers. It may be interesting, for reusability, to only extract relevant informations in this function, and let the caller format it.

I would also change the meaning of the container_status function a bit. Looking at the URLs, it seems to me that the status parameter is only there to filter out inactive containers. So it should be more obvious using a binary choice:

def container_status(include_stopped=False):
    url = 'http://127.0.0.1:6000/containers/json?all'
    if include_stopped:
        url += '=1'
    return requests.get(url)

You get to choose the default based on your most common needs.

Full code would look like:

import requests
from prettytable import PrettyTable

def container_status(include_stopped=False):
    url = 'http://127.0.0.1:6000/containers/json?all'
    if include_stopped:
        url += '=1'
    return requests.get(url)

def active_containers():
    for container in container_status().json():
        network_settings, = container['NetworkSettings']['Networks'].values()
        yield (
            container['Names'][0].encode('utf-8').replace('/', ''),
            container['Id'].encode('utf-8')[:12],
            container['State'],
            network_settings['IPAddress'])

def main():
    table = PrettyTable(['Container Name', 'Container ID', 'Status', 'IP ADDR'])
    for container_infos in active_containers():
        table.add_row(*container_infos)
    print(table)

if __name__ == '__main__':
    main()

(Just assuming that active_containers here means you only want running ones, main and active_containers may need an include_stopped parameter otherwise.)


Small syntactical changes

Bfs should at least be bfs. Some would probably argue that you should spell out depth_first_search and breadth_first_search entirely. I personally like small names,  but regardless, the capital B should not be there.

You wrote this one time:

if visited[i] == False:

And used the correct idiom the second time:

if not visited[i]:

Performance

According to here, generating a list with multiplication is the fastest way, so change both occurrences of:

visited = [False for i in range(len(self.graph))]

to:

visited = [False] * len(self.graph)