Raw filter with ternary operator for html class attribute

Does this work:

<body {{ bodyClass ? class='{bodyClass}'|raw : ''}}>

I don't think you need the brackets and tilde signs...


Your design is slightly off, String args[] works great for terminal programs, but for passing arguments around it's really not efficient. There's no compile time checking to see if you're passing around things that make sense.

Look up Strategy Pattern; You want several independent classes each implementing the interface.

To handle the exception, split your code into two halves:

The first half prepares,

The second half executes.

Additionally, you should split up the responsibility of input source and user input. Right now you'd have to re-implement userInput for each InputMethod, which is unwanted.

By splitting up your code to each case, you'll have 1 specific case where you're still in your calling code (you haven't instantiated an InputMethod yet), but you know that you're going to read from a file. You can handle your exception there.

Your code would be structured like so:

public static void main(String[] args) throws FileNotFoundException {
    IInputMethod input = null;
    if(args.length == 1){
        input = makeFileInputMethod(args);
    } else {
        input = makeStandardInputMethod();
    }

    //make user input object

    while (!input.getUserInput().equals("Exit")) {
        // awesome stuff
    }
    input.closeInput();
}

In the makeFileInputMethod you could handle the exception. Then, in main, you could say "well, if input is still null, we didn't instantiate properly and we ought to shut down".


Trying to catch and throw exceptions if error message window is found

The code that you submitted is not complete as it was missing the driver variable (Had to look up the type as I have not used Selenium).

private WebDriver driver;

First off move everything out of the main method even if you are going to only use one instance, whilst doing this you should also separate the code into single responsibility methods. This will improve the readability of the code and give the program a nicer "flow".

Methods you come to mind are:

private void init();
private void login(String username, String password);
private void clickElement(String element) throws Exception;
private void processWebElements(String header);
private void terminate();

init() will be:

private void init() {
    // The driver you want to use
    driver = new FirefoxDriver();
    File file = new File("C:/Program Files/Selenium/IEDriverServer.exe");
    System.setProperty("weObdriver.ie.driver", file.getAbsolutePath());
    driver.get("http://ap-apbase-d002/Ecx.Web/Account/Login/?ReturnUrl=%2fEcx.Web%2f");
}

login() will be:

private void login(String username, String password) {
    WebElement element;
    element = driver.findElement(By.id("username"));
    element.sendKeys(username);
    element = driver.findElement(By.id("password"));
    element.sendKeys(password);
    element.submit();

    WebElement homeFrame = (new WebDriverWait(driver, 30)).until(ExpectedConditions.presenceOfElementLocated(By.id("pnCenter_IFrame")));
    driver.switchTo().frame("pnCenter_IFrame");
    WebElement myHomeLink = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.linkText("My Projects")));
    driver.findElement(By.linkText("My Projects")).click();
    driver.switchTo().defaultContent();
    driver.switchTo().frame("pnCenter_IFrame");
    driver.switchTo().defaultContent();
}

clickelement() will be:

private void clickElement(String element, int wait) throws Exception {
    WebElement universalInboxLink = (new WebDriverWait(driver, wait)).until(ExpectedConditions.presenceOfElementLocated(By.linkText(element)));
    driver.findElement(By.linkText(element)).click();
}

processWebElements() will be:

private void processWebElements(String header) {
    List<WebElement> AppbaseErrorWindow = driver.findElements(By.cssSelector(header));
    for (WebElement item : AppbaseErrorWindow) {
        if (item.getText().contains("Request Failure")) {
            //Do Nothing
        }
    }
}

finally terminate() will be:

private void terminate() {
    System.exit(0);
    driver.quit();
}

This way you can easily change a bit of the program without rewriting for every time you wanted to call do something. Your try-catch can also be unested as the try inside will only start when everything inside the outside try block is finished. Using the above functions my constructor would be as follows:

public WebAuto() {
    init();
    login("Jh", "1");

    try {
        clickElement("Universal Inbox", 10);
        clickElement("My Projects", 10);
        clickElement("All Projects", 10);
        clickElement("My Team", 10);
        clickElement("WOT Tax Form", 10);
        clickElement("My Drafts", 10);
        clickElement("My Archives", 10);
        clickElement("Retrieve", 10);
        terminate();
    } catch (Exception e) {
        System.out.println("All is OK.");
    }

    try {
        processWebElements(".x-window-header");
    } catch (Exception e) {
        System.out.println("Exception is found here: " + e);
    }
    System.out.println("Normal behavior");
}

Extra: You should set up constants for strings such as file locations.


Merging is a thing a node and only a node does, using that function on a non-node is meaningless so include it in the node class:

class Node:
    ...
    def merge(self, other_node):

Now the person that uses your code knows that merge works for nodes and nothing else and the code has more structure.


Rather than making four variables just to index the matrix, I would go for two in such a way:

paddedA(i :i_end,j:j_end)


If you look at your code you have a lot of if pageCount.has_key(page): else:.
This can be replaced with a defaultdict.
pages defaults to a list, as if pages[page] does not exist you manually default it to a list.
And page_count defaults to zero.

As a simple example the following is how you could use default-dicts:

from collections import defaultdict

pages = defaultdict(list)
pages[0].append('Page 1')

I think changing page_dict to a set would be better, as they index the same way, but using a set will use less memory.

I would use a tuple as page_dict's key, rather than a string.
This is as (a, b) is easier to read than str(a) + "#" + str(b).

Python also has a style guide called PEP8, which basically means that your variables should be snake_case, and PageLimit should be UPPER_SNAKE_CASE as it's a constant.

Using the above should get you:

def page_result(score_result):
    pages = defaultdict(list)
    page_dict = set()
    page_count = defaultdict(int)
    for item in score_result:
        page = 0
        host_id = item.split(',')[0]

        while (host_id, page) in page_dict or page_count[page] >= PAGE_LIMIT:
            page += 1

        pages[page].append(item)
        page_dict.add((host_id, page))
        page_count[page] += 1

    for k, v in pages.items():
        print k
        print v

You could make another default-dict to store the latest page for a host_id.

This limits the amount of times the while loop runs. This dramatically reduces the amount of time it takes on larger data-sets. But has little diffrence on small data sets, and can perform slower!

I use the same data as given in the question, but timesed by 100.
scoreResult *= 100.

This gave me the following times, over 1000 tries:

Original: 225.99s
My original: 53.14s
My updatet: 2.97s
Mathias': 58.83s

This shows that there may be little speed-up from using a dictionary rather than len.
I also removed the prints.

def page_result(score_result):
    pages = defaultdict(list)
    page_dict = set()
    page_count = defaultdict(int)
    host_page = defaultdict(int)
    for item in score_result:
        host_id = item.split(',')[0]
        page = host_page[host_id]

        while page_count[page] >= PAGE_LIMIT:
            page += 1

        pages[page].append(item)
        page_dict.add((host_id, page))
        page_count[page] += 1
        host_page[host_id] = page + 1

    for k, v in pages.items():
        print k
        print v

I would also recommend:

Moving the print part of the function into it's own function.
Read the data from a file. Saving it as a JSON file and using Python's JSON library is a simple way to do this.


Swap Elements in Array if first characters match but only once per first character

Some thoughts:

Use Interfaces when the implementation type does not matter. In your code, the fact that your Map is a HashMap is irrelevant, so prefer the Map interface.

-1 is a magic number. Use a constant to document what it's doing.

Use whitespace consistently. Just like for statements, if statements should have a blank space between the if and the (. There should also be whitespace before a { and after a , for readability.

Your comments are not contributing enough to offset the visual distraction they provide.

Your map's key is a string of length 1. It should probably be a character. And you definitely shouldn't label it a character in your variable names unless it is one.

Use final on variables which will not be reassigned as a statement of intent.

A for loop would more tightly constrain your indexing variable, which you're confusingly referring to as a counter.

You can use a guard clause to handle the simple case and then continue, rather than having a large nested if statement.

You're looking up firstChar three times. I agree that containsKey is clearer to read than a null check, but there's no reason to duplicate the other call. And you can use another constant to make clear what case you're trying to handle there too.

Note that you're destructively modifying the incoming array. In toy problems that's not a big deal, but if you're writing real code this is a very bad practice. It would be preferable to make a copy of the array and modify that instead.

If you were to apply all these changes, your code might look more like:

private static final Integer ALREADY_SWAPPED = -1;
private static final Integer FIRST_OCCURRENCE = null;

public String[] firstSwap(final String[] strings) {
    final Map<Character, Integer> map = new HashMap<>();
    final String[] result = Arrays.copyOf(strings, strings.length);

    for (int i = 0; i < result.length; i++) {
        final char firstCharacter = result[i].charAt(0);
        final Integer priorIndex = map.get(firstCharacter);

        if (priorIndex == FIRST_OCCURRENCE) {
            map.put(firstCharacter, i);
            continue;
        }

        if (priorIndex == ALREADY_SWAPPED) {
            continue;
        }

        final String temp = result[i];
        result[i] = result[priorIndex];
        result[priorIndex] = temp;
        map.put(firstCharacter, ALREADY_SWAPPED);
    }

    return result;
}


Converting to Roman Numeral with Recursive Algorithm

Not to be negative, but...
Your Else case is making a bad assumption, that whichever number reaches that branch is going to be greater than 1000. I don't mind the recursion; I don't even mind the Select Case - but by not handling negative integers you have a bug there, where -42 is going to be treated as if it were greater than 1000, and even worse, it's going to be subtracted 1000 before being fed into a recursive call: I haven't executed it, but it seems your code would blow up with a very easily avoidable overflow error with just about any negative input.
There should be an input validation guard clause before the select block, to ensure you're not entering a recursive logic with a zero or negative input.
Now if valid input is an integer between 1 and 3999, then there is no need to intake a Long - the Integer data type is sufficient.


You do not provide much context for this method, so I can only give you general advice.
Logic

never use exception handling as part of the routine/regular code path in you program. Most Java VM's require significant locking and processing to generate the actual exception and its stack trace. I have seen 10% performance improvements in large commercial applications where simple pre-validation of common exceptional conditions saves a huge amount of processing resources.

What if the user enters the non-existent class name dev.null.TurningIntoZomies, they get an Integer.class back.

In the event that the Class.forname(...) fails, you do exception handling and return null. If the program asks for the same value again, it will do the full search again, and so on. If the class exists, it is not normally very slow, but, if the class does not exist, the Class.forname() has to search the entire classpath. Cache the results (of both the successes and the failures so you only have to call Class.forName() once.

Code Style

Use correct Java brace placement, at the end of the line.

Finally, you can use short-circuit return statements to make it easier:
private Class<?> getClass(String value) {
    try {
        return Class.forName(StringUtils.trim(value));
    } catch (ClassNotFoundException ex) {
        if (value.contains("double") || value.contains("Double")) {
            return Double.class;
        }
        if (value.contains("int") || value.contains("Int")) {
            return Integer.class;
        }
        if (value.contains("bool")) {
            return = Boolean.class;
        }
        if (value.contains("long") || value.contains("Long")) {
            return Long.class;
        }
        log.error("FAILED. Class object is not supported: " + value, ex);
        return null;

    }
}


The code is broken
Before asking “can this code be sexier”, you should be asking “does this code work”.
Spoiler: it doesn’t.
Always test your code
You have written a function comp(a, b). You haven’t written any tests for it. You’ve used it in a single case and got the correct answer, but that means very little.
At the bare minimum, you should have a test suite that has two test cases: one for when a and b are equal, and one for when they are not.
For example, for the “equal” test case, you can just generate bunch of random numbers between 0 and some maximum. Here’s what that might look like using the Catch2 test framework:
#define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"

#include <cstdint> // need for std::size_t, std::uint32_t
#include <limits>

// include the header with comp() declared

TEST_CASE("comparing equal")
{
    constexpr auto num_trials = std::size_t{10};

    constexpr auto min_val = std::int32_t{0};
    constexpr auto max_val = std::numeric_limits<std::int32_t>::max();

    auto value = GENERATE(take(num_trials, random(min_val, max_val)));

    INFO("value = " << value);
    CHECK_FALSE(comp(value, value)); // value cannot be less-than itself
}

This compiles (with warnings, more on that later), and runs, and all tests pass. That’s what happened for me, anyway. You may or may not get all tests passing, because there is a critical bug in your code. We’ll get back to that in the next section, but for now, I’ll just assume all tests passed.
So now for the “unequal” test case, you just list a bunch of pairs of numbers, where the first number should always compare less-than the second:
TEST_CASE("comparing unequal")
{
    auto data = GENERATE(table<std::uint32_t, std::uint32_t>({
        // single digit numbers
        {1, 0},
        {9, 0},
        {9, 8},
        // ... etc.
        // multi-digit numbers
        {111, 110},
        {124, 123},
        {130, 120},
        {130, 129},
        {200, 100},
        {200, 109},
        {200, 190},
        {200, 199},
        // ... etc.
        // other interesting cases, add as many as you please

        {1, 110}, // this works, but...
        {112, 1}, // try this one!

        {321, 3212}, // okay...
        {3214, 321}, // ... also okay...
        {3213, 321}, // ... but uh-oh!
    }));

    INFO("a = " << std::get<0>(data));
    INFO("b = " << std::get<1>(data));

    CHECK(comp(std::get<0>(data), std::get<1>(data)));

    CHECK_FALSE(comp(std::get<1>(data), std::get<0>(data)));
}

Again, compile and run. This time, there are failures.
Why does those cases fail? I’ll explain later, but for now I’ll just say that your algorithm will fail for some cases where one number is <pattern>, and the second number is <pattern>D<something> where the digit D is the same as the first digit of the pattern. For example, 545 and 54 (the former should come first, to get 54554, rather than 54545) would fail, but 565 and 56 work (56556 is less than 56565).
This is why we write tests.
Turn on warnings
If you compile with g++ or clang (and probably any other compiler), and turn warnings on… which you always should… you will get a warning like this:
warning: control reaches end of non-void function [-Wreturn-type]

(I actually get two warnings, and both matter, but the second isn’t as critical, because you’re only going to be dealing with small sizes. I’ll mention it later, though.)
What that warning is telling is you that you have a function—comp()—that returns something—something that is not void—but somehow it is possible to reach the end of the function—the closing }—without returning a value.
We can figure out exactly what is going on later, but for now, let’s hack a nasty little fix to shut the warning up. At the very end of comp(), right before the closing brace, add the following two lines:

    std::cerr << "you have a bug!" <<
        "\n    a = " << ia <<
        "\n    b = " << ib <<
        '\n';
    return false;

If the compiler is right, and if it is possible to get to the end of this function without returning a value, this will display an error message, and then just return false. So compile the test code again, and run it and…
… you get the same results as before… but now there are 10 messages in the output:
you have a bug!
    a = 1867888929
    b = 1867888929
you have a bug!
    a = 1276619030
    b = 1276619030
you have a bug!
    a = 1911218783
    b = 1911218783
... [ and so on ]

(The random numbers will be different, of course, but the pattern—the same number appearing for both a and b—will be the same.)
The compiler was right. You have a bug.
Looking at the messages printed, it seems to only happen when a equals b. Before we caught the bug, the function was just returning gibberish whenever a and b were equal… but you didn’t notice, because it didn’t matter to the algorithm (and also because you didn’t test), because when a and b are equal, the function could either return true or false and it makes no difference. It is undefined behaviour, and just happens to “work” on my platform (and probably yours, but who’s to say, because you didn’t test)… but on other platforms, anything could happen.
This is why we turn on warnings, and fix them.
Summary
Although your code appeared to be working, writing some tests and turning on warnings revealed:

There are cases where it fails.
Even when it appears to work, there is dangerous undefined behaviour.

You should always write tests to test your code; oftentimes it will blow your mind how it can fail in surprising and unexpected ways.
You should also always turn on all warnings, and then fix them. Some people even recommend turning warnings into errors, so that even a single warning will kill the compile. That’s not bad advice.
Code review
General issues
Overall, the biggest issue with your code is that it is—as you suspected—wildly overcomplicated. It is so ridiculously overcomplicated, that at least two expert level C++ programmers looked at your code and missed critical bugs, and/or failed to understand what was actually going on. (And I’m not even counting myself; I probably missed stuff, too.) That should be a sign.
There are two general rules that would make a HUGE difference:

Break up complicated functions into simpler ones. There are multiple parts of comp() that really should be broken out into separate functions. You have 4 loops in comp(); 1 is the max you should aim for… and even that might be too much, because of the second rule.
Avoid writing loops. If you find yourself writing a loop, stop… think about what you’re actually trying to do… it’s probably some standard algorithm. In that case, use that algorithm.

The second rule is really the most important, because when you stop yourself from writing naked loops and think in terms of algorithms instead:

Your code becomes easier to understand. std::mismatch(a.begin(), a.begin() + min_size, b.begin(), b.begin() + min_size) is already complicated, but I can still tell at a glance roughly what’s going on much easier than I can with a manual loop.
Complications are easier to spot. It is trivial to spot the difference between std::mismatch(p, p + max_str.size(), max_str.begin(), max_str.end()) and std::mismatch(max_str.begin(), max_str.end(), p, p + max_str.size()). Spotting the difference between those two loops? Not so much.
Mistakes are easier to spot. That first loop is just return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end());. But because of the complexity of the loop, you didn’t realize you’d failed to account for the situation where the two strings are equal, and you get to the end of the loop without returning anything.
Especially when dealing with standard algorithms, they’re already tested and optimized. You can almost never beat them without serious sorcery (and even then, often not).

Review
bool comp(const int32_t ia, const int32_t ib)

You use int32_t throughout, but there are two problems with that.

First, it’s not int32_t. It’s std::int32_t, and you have to include <cstdint>. The reason it appears to work for you is probably that you’re using a C++ compiler/library that also doubles as a C compiler/library, and they just include int32_t without the std:: to be lazy. But it’s not guaranteed to work everywhere.
Second, int32_t is not portable in any case. All the fixed-width types are platform dependent. The moment you use one, you make your code less portable. And in this case, there’s no reason whatsoever for using one.

There’s absolutely no reason to use int32_t and not int. Using the wrong type breaks your code in some places (like returning it from main()).  Where it doesn’t, it just makes your code unnecessarily unportable.
const std::string a = std::to_string(ia);
const std::string b = std::to_string(ib);

While these work fine, they’re unnecessarily inefficient. You already know the maximum size string you’ll need, and you know that both ia and ib should be greater than or equal to zero. You could use arrays and numeric_limits<type>::digits10(), and then to_chars() to do all this lightning fast, and with no memory allocation, something like so:
auto a_chars = std::array<char, std::numeric_limits<decltype(ia)>::digits10() + 2>{};
auto b_chars = std::array<char, std::numeric_limits<decltype(ib)>::digits10() + 2>{};

std::to_chars(a_chars.data(), a_chars.data() + a_chars.size(), ia);
std::to_chars(b_chars.data(), b_chars.data() + b_chars.size(), ib);

Or, better yet, move all that into its own function.
int32_t i = 0;

This is bad practice for a number of reasons.
First, you should only declare variables where you’re going to use them; unless you have a damn good reason, you should never declare them up at the top of a function.
And you should especially not reuse a variable for different things throughout a function. i is used as a loop counter in both branches of that if, for two (or more) entirely different loops. That’s bad. You don’t need it at all for either of the first two loops; in the first loop, it should just be a local counter for a for, if anything, and in the second loop, the same, and after you could set it using min_size.
if (a.size() == b.size()) {
    while (i < a.size()) {
        if (a.at(i) == b.at(i)) {
            ++i;

            continue;
        }
        else if (a.at(i) > b.at(i))
            return true;
        else
            return false;
    }
} else {

Alright, so what exactly is going on here? The manual loop just complicates what is actually a very simple thing. If the two strings are the same size, you go through looking for any mismatched characters, and if you find a mismatched pair, you return true if the character in a is less than the character in b.
What you don’t account for, though, is what happens if all the characters are equal. In that case, you just fall out of the loop and continue on… and eventually get to the end of the function, which returns nothing. That’s your critical bug.
This is what the code above is actually doing, using algorithms to make everything clearer:
if (a.size() == b.size())
{
    auto [it_a, it_b] = std::mismatch(a.begin(), a.end(), b.begin()); // don't need b.end(), because the sizes are the same
    if (it_a != a.end()) // don't need to check it_b, because the sizes are the same
    {
        return *it_a < *it_b;
    }
    else
    {
        // what happens here?
        //
        // your current code does nothing, so the program continues on to the
        // end of the function, which has no return statement... thus, the bug
    }
}

So what is supposed to happen if the two strings are equal? Logically, I’d think, you would return false, because if the two strings are equal, then ia is not less-than ib. So:
if (a.size() == b.size())
{
    auto [it_a, it_b] = std::mismatch(a.begin(), a.end(), b.begin());
    if (it_a != a.end())
    {
        return *it_a < *it_b;
    }
    else
    {
        return false;
    }
}

But searching for the first mismatch and then returning true if the first char is less than the second is just a lexicographical compare:
if (a.size() == b.size())
{
    return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end());
}

But that’s just what std::string’s operator< does:
if (a.size() == b.size())
{
    return a < b;
}

In other words, if the two strings are same size, return true only if a is lexicographically less than b. If you reason about your code at a higher level, rather than getting bogged down with loops, you can spot these simplifications much more easily. In other words, don’t focus on the details, step back and think about the big picture.
int32_t min_size = static_cast<int32_t>(std::min(a.size(), b.size()));
int32_t max_size = static_cast<int32_t>(std::max(a.size(), b.size()));

Forcing int32_t here introduces potential bugs. None are likely to trigger in reality, because the lengths of the two strings should be very, very small, even for 64- or 128-bit integers. However, there’s no sensible reason to tempt fate.
The first potential bug is truncation if the size is greater than what would fit in an int32_t. Again, that will never happen in reality, but again, why play dangerously for no good reason?
The second potential bug is what a decent compiler with warnings turned on will warn you about. Comparing signed and unsigned values is a craps shoot. If you are mixing signedness in a comparison, you can get absurdities like -1 > 1u.
There’s no reason to force-cast any of the above into int32_t… or to force-cast it into anything. Just use auto, and everything works:
auto const min_size = std::min(a.size(), b.size());
auto const max_size = std::min(a.size(), b.size());

Much less typing, too. Or:
auto const [min_size, max_size] = std::minmax(a.size(), b.size());

That works just as well.
while (i < min_size) {
    if (a.at(i) == b.at(i)) {
        ++i;

        continue;
    }
    else if (a.at(i) > b.at(i))
        return true;
    else
        return false;
}

The next naked loop; what exactly is this one doing? Well, it’s going from 0 (which is the value of i at the start of the loop, though it isn’t immediately obvious from the code), to the minimum size of the two strings, and doing a lexicographical comparison. In other words:
if (auto const res = a.compare(0, min_size, b); res != 0)
{
    return res < 0;
}

We don’t even need to check which one is smaller here, because we’re using the minimum size.
Now from this point on is where the problems really start. At this point, you’ve dealt with the case where the two strings have equal length (of course, you need to fix the bug when they’re exactly equal). You’ve also dealt with the case where you have a short string and a long string, and the first part of the long string is either greater or less than the short string. So what you have now is the case where you have a short string, and a longer string that starts with the short string. In other words: the short string is <pattern>, and the long string is <pattern><something>.
So what happens next?
Well, what you do is get the first digit of <pattern>, and then compare it with every digit in <something>. But does that make sense?
Consider when <pattern> is 42, and <something> is 41 or 49:

With 41, you compare the first 4 with the 4 in 41… it’s >=, so you return true.
No problem, 42 should compare less than 4241, because 424241 is greater than 424142.

With 49, you compare the first 4 with the 4 in 49… it’s >=, so you return true.
But 42 should compare less than 4249, because 424249 is NOT greater than 424942.

So your algorithm doesn’t work.
As for the rest of the function, I won’t review it in detail (because it needs to be rewritten), but I’ll just say:

Avoid std::string.at(). It’s unnecessary. You know for a fact the string is not empty, so a[0] is guaranteed to work.
You do some trickery with multiple loops to handle the two cases where a is shorter or longer than b, but that just caused confusion (as you saw). Instead, just do something like:

if (a.size() < b.size())
    some_helper_function(a, b);
else
    some_helper_function(b, a);

This is clearer, and safer.
Suggestions for fixing
First, write test cases. Especially consider test cases that might be troublesome.
Your function basically has two paths, one for when the two numbers have equal amounts of digits, and one for when they don’t. So you probably need (at least) three test cases:
TEST_CASE("equal values")
{
    // ...
}

TEST_CASE("unequal values with the same digit count")
{
    // ...
}

TEST_CASE("unequal values with different digit counts")
{
    // ...
}

In the latter case, you should check a bunch of of cases, but especially some cases where the short value is repeated one or more times, like:

1 and 11
1 and 1111111
12 and 1212
12 and 12121212
21 and 2121
21 and 21212121

And you should check cases where the short value is repeated, then followed by something that will make it sort before or after, like:

45 and 451
45 and 454
45 and 459
45 and 4545451
45 and 4545454
45 and 4545459
54 and 541
54 and 545
54 and 549
54 and 5454541
54 and 5454545
54 and 5454549

Once you have your test cases set up, you should think about what makes one number sort before or after another… especially when there is a repeated pattern. Like, does 56 come before or after 561, 565 and 569, and why? What about 56 and 5656561, 5656565, and 5656569? I’ll give you one tip: it’s all about lexical comparisons with the short pattern… repeated lexical comparisons with the short pattern, not just one-and-done.
And of course, turn on warnings, and heed them.


Well, PDO wrapper is not a good object to exercise on, because

PDO is a wrapper already, and by writing your own wrapper you'd rather spoil most of PDO's excellent features
there is a very specific issue about database wrappers that makes them distinct from other objects - a database connection should be made only once per script execution, so you cannot instantiate it anywhere you need, but rather should pass around a single instance.

Having said that, there is a room for the improvement, either in database wrappers, OOP and general programming techniques.
Database wrapper related
Some mistakes are so common that I even wrote an article, Your first database wrapper's common mistakes. Some highlights from it:

error reporting doesn't actually exist in your wrapper
connection is made every time a function is called, slowing your app significantly and endangering your server to fail under too many connections
statefulness. this one is related to your question about $this. It's ok to keep the sate related to the connection, but not for the query result. So, all your class variables beside $conn just shouldn't be

OOP related

Database credentials as class variables. You aren't going to use $databaseHost more than once. So it makes no sense to make it a class variable. Create a PDO instance in the constructor, and then assign it to a class variable $conn. That's the only variable that would make sense to use.
function setVariables() is rather pointless. We use constructors for setting class variables. Such a function would make sense only if your class is static and therefore never gets instantiated explicitly
so you can tell that your class lacks  a constructor
your class is too diverse. It creates a connection, runs a specific query, and even formats the output as HTML. That's too much. Each class should be responsible for just a single job
moreover, everything said above is stuffed in a single function

General programming issues
Error reporting
Again, I've got an article that explains the basics, PHP error reporting. Some highlights:

NEVER EVER do anything like echo "Failure"; on error. It is both useless and harmful. If you don't know what to do with an error you get, then just let it go
neither you should wrap a code block in a try..catch if you don't know what to do with an exception. Just let it go
you could use a try..catch to wrap your entire code, and then write some useful handling in the catch block. the absolute minimum is to log the error message for the programmer and to show some nice excuse for a site user

Displaying results
It should be a different story, irrelevant to all database interactions. Gather all the required data first, collect it in a convenient array / structure, and then proceed to displaying your HTML page. Given there are situations when you don't have to show an HTML page but just send JSON-encoded data, or there is no data but just an HTTP header at all, it is natural that all output starts only after all database interactions are ended.
PDO wrapper
Given you called your exercise a PDO wrapper, it would be logical to show you a better code for this kind of a class. Well, you can tell I've got an article on that as well :)
Given the explanations above, your PDO wrapper should only let you to hold a database connection and to run a query. Everything else should be done by another class / procedure, even getting the query result.
PDO is made very wisely: it actually consists of two classes, PDO proper and PDOstatement, which is used to hold all the stuff specific to the particular query. Although you could wrap the latter too, let's use it as is, as PDOstatement is a very good class by itself. So, just like vanilla PDO, our wrapper would return an instance of PDOStatement that could be then used to retrieve the selected data.
class MyPDO extends PDO
{
    public function __construct($dsn, $username = NULL, $password = NULL, $options = [])
    {
        $default_options = [
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        ];
        $options = array_replace($default_options, $options);
        parent::__construct($dsn, $username, $password, $options);
    }
    public function run($sql, $args = NULL)
    {
        if (!$args)
        {
             return $this->query($sql);
        }
        $stmt = $this->prepare($sql);
        $stmt->execute($args);
        return $stmt;
    }
}

As of the running particular queries, it should be done in a completely distinct class / routine. Let's create a Student class that uses our PDO instance as a service:
class Student
{
    /* @var MyPDO */
    protected $db;

    protected $data;

    public function __construct(MyPDO $db)
    {
        $this->db = $db;
    }

    public function findAll()
    {
        return $this->db->run("SELECT * FROM student_data")->fetchAll();
    }
}

which uses function findAll() to return all the students' data. Whereas output should be a completely different story:
$mypdo = new MyPDO('mysql:host=localhost;dbname=test;charset=utf8');
$student = new Student($mypdo);
$list = $student->findAll();

echo " Displaying All Records

";
foreach ($list as $row) {
    echo $row['name'];
    echo "
";
    echo $row['email'];
    echo "
";
}


The first set of code, while it's straightforward, isn't "ideal" in a sense that you are repeating code. You violate the DRY principle, so let's scratch that for your second code instead.

Now I'm not sure how data is set to the data property. I assume your filters are some kind of custom checkbox which sets com-* data attributes (since your checks are a "yes or not yes").

if (memCom3.length > 0 || filter3.length > 0)

Now as far as I understand, this condition is used only to conditionally attach the click handler. From what I see, the second condition is not required. jQuery objects are collections and jQuery methods iterate through and operate through each. If the collection is empty, the operation does nothing since it iterates through nothing. So your condition can be simplified to

$('.filter').on('click', function(){
  // What happens to each filter
});

One more touch. Your click depends on a certain number. Now if you could just extract that number by itself, possibly using a data-* attribute on the filter.

$(".filter").on('click', function(){
  var element = $(this);
  var number = element.data('number');
  var com = element.data('com-' + number);
  var memberData = $(".member").data('com-' + number).length;
  if(!(com === 'yes' && memberData)) return;
  $(this).addClass(active);
});


I would create a class and define an input operator:

struct Person
{
    std::string name;
    std::string age;
    std::string salary;
    std::string hoursWorked;
    std::string randomText;

    friend std::istream& operator>>(std::istream& str, Person& data)
    {
        std::string line;
        Person tmp;
        if (std::getline(str,line))
        {
            std::stringstream iss(line);
            if ( std::getline(iss, tmp.name, ':')        &&
                 std::getline(iss, tmp.age, '-')         &&
                 std::getline(iss, tmp.salary, ',')      &&
                 std::getline(iss, tmp.hoursWorked, '[') &&
                 std::getline(iss, tmp.randomText, ']'))
             {
                 /* OK: All read operations worked */
                 data.swap(tmp);  // C++03 as this answer was written a long time ago.
             }
             else
             {
                 // One operation failed.
                 // So set the state on the main stream
                 // to indicate failure.
                 str.setstate(std::ios::failbit);
             }
        }
        return str;
    }
    void swap(Person& other) throws() // C++03 as this answer was written a long time ago.
    {
        swap(name,        other.name);
        swap(age,         other.age);
        swap(salary,      other.salary);
        swap(hoursWorked, other.hoursWorked);
        swap(randomText,  other.randomText)
    }
};

Now your code looks like this:

Person   data;
while(readFile >> data)
{
    // Do Stuff
}

PS. I noticed you were using string and ifstream without the std::. This suggests you have using namespace std; in your code. Please don't do that. see Why is “using namespace std;” considered bad practice?

Don't explictly close() a file unless you are going to check that it worked (or are going the re-open). Prefer to let the destructor do the closing (that way it is exception safe). See: My C++ code involving an fstream failed review


Removing whitespace and space in list that contains different types of elements

Some suggestions

Follow pep8
Use duck-typing.  So, for example, use elt.strip() if hasattr(elt, 'strip')
It will be much more efficient to filter items in another list comprehension, since it only requires one search through the list rather than many.
The simplest approach would probably be to change the first list comprehension to a generator expression, then feed that to a list comprehension that filters out empty strings.
This could conceivably be a single list comprehension, but I think it would be too verbose.  Further, it would require stripping twice.

So I would do something like this:

def strip_list_noempty(mylist):
    newlist = (item.strip() if hasattr(item, 'strip') else item for item in mylist)
    return [item for item in newlist if item != '']

You could also duck-type the filtering, like so:

def strip_list_noempty(mylist):
    newlist = (item.strip() if hasattr(item, 'strip') else item for item in mylist)
    return [item for item in newlist if item or not hasattr(item, 'strip')]


Without more context it's really hard to give you a particularly helpful answer but I can suggest a couple of things.

Your first option is about as bad as it gets, it will thrash CPU because as far as the CPU is concerned that while loop is important work - it doesn't know you're just calculating a time over and over again.

Your second option isn't bad but you should accept an action to run after the delay otherwise it won't be very flexible. You should also use TimeSpan to represent an interval - an int can mean many things, a TimeSpan represents the information unambiguously.

For the sake of completeness, for this trivial example I think it's clearer without the async and await but that's just personal preference.

public static Task DoActionAfter(TimeSpan delay, Action action)
{
    return Task.Delay(delay).ContinueWith(_ => action());
}

As you're returning a Task your code can synchronously wait using .Wait() (not great) or await the result. If it doesn't need the result straight away it can just store the task and check its status later.

If you want to be able to cancel your action you should feed a CancellationToken into the method (and the delay).

Update

To actually use the method:

using System;
using System.Threading.Tasks;

namespace CountdownTimer
{
    class Program
    {
        public static void Main()
        {
            var delayInterval = TimeSpan.FromMilliseconds(5000);
            var runningTask = DoActionAfter(
                delayInterval,
                () => Console.WriteLine("Done"));

            // if you want your main method to wait for the action
            // runningTask.Wait()

            Console.ReadKey();
        }

        public static Task DoActionAfter(TimeSpan delay, Action action)
        {
            return Task.Delay(delay).ContinueWith(_ => action());
        }
    }
}


Welcome to Code Review.

Before reviewing your code, it needs to be fixed:

First, make it work...

Usage is never printed

Your program is supposed to print the usage instructions if the wrong number of parameters ist supplied. Check what happens if you run it without any parameters:

  Exception in thread "main"

java.lang.ArrayIndexOutOfBoundsException: 0
at codereview.TestClass.main(TestClass.java:30)

To fix this, you need to check the length of args before accessing args[0] and args[1].
Failure because of unnecessary cast
If the correct number of arguments is supplied, your program will fail with the following output:

  Exception in thread "main"

java.lang.ClassCastException: java.util.Date cannot be cast to java.lang.String
at codereview.TestClass.main(TestClass.java:59)

This is because you inserted a Date object into your fileContents Vector. Please thoroughly study generics as a better understanding of this important topic would have prevented the error.

For now, just remove the cast (String)fileContents.get(i) and test your code. A complete solution is given later in this answer. No, really run your code now. You'll see that there is another problem:
Sorting is not in the natural order

You are sorting a list of Strings. This means that the sort order will always be alphabetical (1,3,10,12 would be sorted as 1,10,12,3) even though your documentation comments state that the lines are sorted in their natural order. You can't promise to do that without knowing what kind of input they contain. As it currently stands, you should just change your comments.
You are appending to the end of the output file
The signature of the FileWriter constructor is:

public FileWriter(String fileName, boolean append) throws IOException

So your OVERWRITE_FILE is a lie. Rename it to APPEND_FILE and set it to false (a cleaner, completely different solution will be given below).

... then, clean it up.

General issues

You have several unused imports. Remove them.
RuntimeException is unchecked, so you should remove throws RuntimeException from main.
Your error messages are unhelpful. Error performing IO does not tell the user what went wrong.

Code structure

Readability, maintainability, reusability: you should strive to achieve these three goals in your code (apart from correctness, of course, which goes above all else). One problem with your code is that everything happens directly inside main. You should delegate the bulk of your work into helper methods:

public static void main(String[] args) {
    try
    {
        validateNumberOfArguments(args.length);
        String inputFilename = args[0];
        String outputFilename = args[1];
        List<String> lines = readLinesFrom(inputFilename);
        sortAndAddTimestampTo(lines);
        writeLinesTo(outputFilename, lines);
    }
    catch (IOException e){
        exitBecause("Error accessing file", e);
    }
}

This gives a nice overview of what your code does - similar to article headings in a newspaper or chapters in a book.

Here's the implementation. Your main has been split up into concise methods. Each of them does one thing, so they are easy to understand.

private static void validateNumberOfArguments(int length) {
    if (length != 2) {
        exitBecause("Incorrect number of args", "Correct usage is:",
        "java TestClass <input_filename> <output_filename>");
    }
}

private static List<String> readLinesFrom(String path) throws IOException {
    return Files.readAllLines(getPath(path), StandardCharsets.UTF_8);
}

private static void sortAndAddTimestampTo(List<String> lines) {
    Collections.sort(lines);
    lines.add("File sorted on: ");
    lines.add(new Date().toString());
}

private static void writeLinesTo(String path, List<String> lines) throws IOException {
    Files.write(getPath(path), lines, StandardCharsets.UTF_8);
}

private static Path getPath(String fileName) {
    return new File(fileName).toPath();
}

private static void exitBecause(Object... reasons) {
    for (Object reason : reasons) {
        System.out.println(reason);
    }
    System.exit(-1);
}

Required imports (JRE7):

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Date;
import java.util.List;

The error messages will now be a bit more helpful:

Error accessing file
java.nio.file.NoSuchFileException: input.txt

or

Error accessing file
java.io.IOException: The process cannot access the file because it is being used by
another process


Maximum contiguous subarray with recursion

In this loop:

negetiveinfinity = -10000000000
summ = 0
for i in range(mid, low - 1, -1):
    summ = summ + A[i]
    if summ > negetiveinfinity:
        negetiveinfinity = summ
        leftindex = i
left = negetiveinfinity

First, 'negetiveinfinity' isn't a good variable name - it should be 'negative', for a start. More importantly, it doesn't reflect how you're using it - it "negative infinity" would be a number that always tests lower than any other number, but you're using it as the highest contiguous sum you've found so far. Similarly, you're using summ (another misspelling, although presumably this one is to avoid shadowing the builtin sum) as a trial total that you test to see if it is better than the stored one. Better names might be max_sum and trial_sum.

Then once you've found that, you reset those variables and reuse them in almost exactly the same loop on the other half of the list. Both of these loops also have a possible logic error: you start the trial sum at a 'sufficiently small' value. That can be problematic if it isn't small enough. Instead, it would be more usual to start it at the 'mid' value.

But the ideal thing to do here is to fix that error both times by factoring out the repeated code. You can do this really easily with a bit of analytic clarity of what your problem is: you're looking for the the maximum cumulative sum of the elements in a sequence. That immediately suggests using itertools.accumulate, like this:

left_half = it.accumulate(A[low-1:mid:-1])
right_half = it.accumulate(A[mid:high+1])
left = max(left_half, key=lambda x: x[1])
right = max(right_half, key=lambda x: x[1])
return (mid - left[0], mid + right[0], left[1] + right[1])

And that whole function is now five lines.

You can use do something similar here:

leftlow, lefthigh, leftsum = findmaxarray(alist, low, mid)
rightlow, righthigh, rightsum = findmaxarray(alist, mid + 1, high)
crosslow, crosshigh, crosssum = crossingsubarray(alist, low, mid, high)

if leftsum >= rightsum and leftsum >= crosssum:
    return leftlow, lefthigh, leftsum
elif rightsum >= leftsum and rightsum >= crosssum:
    return rightlow, righthigh, rightsum
else:
    return crosslow, crosshigh, crosssum

You never use *low and *high separately, and you only use *sum to compare the three sets. So instead of using nine variables, use a single list of tuples and a single call to max:

candidates = [findmaxarray(alist, low, mid),
              findmaxarray(alist, mid + 1, high),
              crossingsubarray(alist, low, mid, high)]

return max(candidates, key=lambda x: x[2])

You appear to be using Python 2. In Python 3.x, this line:

mid = (low+high)/2

will actually cause an error further along your code. Division of two integers now returns a float, so that eg, 5/2 = 2.5 (instead of 2). Use floor division to guarantee an integer result:

mid = (low+high) // 2

If you can't upgrade to Python 3, I highly recommend at least putting yourself in as close-to-future proof environment as possible. Include this line:

from __future__ import division

at the top of your file to back port this particular behavior.

Slicing the array into left_half and right_half does start creating copies that you have otherwise avoided by passing low and high around. For the right half, you could not copy it by using it.islice. But that won't work for the left half, because islice doesn't support using a negative step. If this is a problem, you may want to consider using numpy - slicing numpy arrays doesn't create copies.

For mutual consistency, and to better describe what the 'crossing' one does, rename your two functions to max_crossing_subarray and max_subarray. The usual written rule seems to be that functions should be named with verb phrases, but in practice there are some exceptions to this - in my experience, for functions that would be named find_blah dropping the find_ seems to be preferred.

In terms of overall complexity, this previous question implements a C version of what appears to be the same algorithm as yours and claims to be O(n log n). The accepted answer points to Kadane's algorithm, a non-recursive O(n) solution. The Wikipedia page provides a Python implementation that only returns the actual sum, but claims that it can be modified to return the start and end indices as well.


Don't repeat yourself

You twice say

                System.out.println("\nWould you like to play again?");
                restart = scan.next();
                if (restart.equalsIgnoreCase("Y"))
                {
                    System.out.print("Enter a number to start playing");
                    guess = scan.nextInt();
                }
                else
                    break;

And five times say

                    guess = scan.nextInt();

Including twice in the previous repeated code.  Don't do that.  Instead organize the code so that you say these things once each.

Consider the following

        String restart = "Y";
        while (restart.equalsIgnoreCase("Y")) {
            int answer = generator.nextInt(100) + 1;

            System.out.print("What number do you guess (enter 0 to quit)? ");
            while (true) {
                int guess = scan.nextInt();
                if (guess == 0) {
                    System.out.println("\nQuitting game");
                    break;
                }

                count++;
                if (guess == answer) {
                    System.out.println("That's correct! You made " + count + " guesses.");
                    break;
                }

                if (guess < answer) {
                    System.out.println("Your guess is too low, try again.");
                } else {
                    System.out.println("Your guess is too high, try again.");
                }
            }

            System.out.println("\nWould you like to play again (Y/N)?");
            restart = scan.next();
        }

This won't necessarily work any better.  But this pattern will generally be easier to maintain.  One of the problems with academic code is its low reuse.  You never have to maintain it, so it's easy to slip into unmaintainable habits.  Outside the academic context, most of your time will be spent on maintaining existing code.

I used a while for the outer loop even though a do/while would have been more natural (since you always loop once).  Notice though that it is gated by restart rather than guess.  I find this to be a cheesy solution and would prefer the do/while.

The inner loop will loop forever until explicitly exited (with the break statements).  Notice how the first thing that it does is collect the next guess.  This saves collecting it in the five different places.  Collect it once and then process it once.

When processing guess, you don't need to do three comparisons.  There are only three states.  If it's not equal (otherwise we break out of the loop) and not less than, it must be greater than.  So use an else rather than the third comparison.

We could also use an else if after guess == answer, but we don't need to do so since we break.

I added a (Y/N) to your play again query.  As is, it works if you know how.  But someone who doesn't know what to do might type "Yes." which seems like a reasonable response but won't work.  Give a little extra guidance as to what to type there.  You also might consider accepting "Yes" as a positive answer.

The Java standard is to put { on the same line as a method declaration or control structure, so I switched to that.  It's more important to be consist though.  So the other way is OK.  It's just not how I normally write Java.

Bugs

You don't manage the count correctly.  I fixed a small mistake for you, but I left the bigger one.  The small mistake was that you incremented the count even if the guess was 0, which is not a real guess but the exit criterion.  Without the larger mistake, this doesn't really matter.  You don't display the incorrect count anyway.

The larger mistake comes when you play repeated games.  To my mind, the correct way to fix this would be to move the count declaration and initialization to a different location.  Note that in Java, variable declarations do not need to be at the beginning of a block.  They can appear anywhere.  Figure out what's wrong with the current behavior (win repeated games until it becomes obvious).  Then think about where it should be.

Use methods

I would prefer to move generator and scan into class fields.  This means inside the class but outside any method.

    private static final Random GENERATOR = new Random();
    private static final Scanner SCAN = new Scanner(System.in);

That would allow them to be shared across multiple methods.

I would expect main to look more like

    public static void main(String[] args) {
        String restart;
        do {
            play();

            System.out.println("Would you like to play again (Y/N)?");
            restart = SCAN.next();
        } while (restart.equalsIgnoreCase("Y"));
    }

Perhaps you haven't gotten to methods yet.  When you do, consider going back to this and writing a play method.


Refactoring Event Handlers - How to go about this for growing WinForms application

You can create a Dictionary, where key is a MenuItem, a value us function/delegate that has to be called on click. All 140+ menu items subscribe to the same event hadler and in that event
handler write something like

myMenuItemsDictionary[((MenuItem)sender)]()

this is good, in case when you have no parameters to pass to a delegate, in case when you need to pass them, you can go farther:

define a class

public class MenuItemHandler
{
    delegate MethoddToInvokeOnClick()
    List<object> parametersToPassToDelegate = ..
}

and the instances of this class have in a Value of the dictionary


A counterexample in balanced parentheses

May I suggest a simpler solution:
You need only a counter. it is incremented by 1 whenever you encounter an openning parenthesis "(" and is decreased by 1 whenever you encounter a closing parenthesis ")"
The input is invalid if the counter drops below zero or is not zero by the end of scanning.

EDIT
since OP specified they must use a stack, we can follow @JollyJoker's advice: counter increament is implemented by a push operation, counter decrement by a pop one.  counter falling below zero is implemented by attemt to pop when the stack is empty. by the end of scanning the stack has to be empty.


Better way to iterate through a dictionary and comparing its keys with itself

Before speaking about the actual algorithm, let me hint you at the official Style Guide for Python Code (often just called PEP 8), a set of guidelines to write idiomatic-looking Python code. A core takeaway of the read should be, that in Python lower_case_with_underscores is the preferred way to name variables and functions. Fortunately you don't have to remember all those rules. There is good tool support for style and also static code checking in Python. A non-exhaustive list can be found here on this post here on Code Review Meta. I personally most often use flake8 and pylint from that list.

With that out of the way, let's have a look at the code. First, you don't need to have two copies of your dict. Also, the whitespace normalization inside the loop is run more often than needed, because it is calculated several times for every key. Fortunately, it's easy to solve both of those problems:

keys = list(dict_of_all_data.keys())
authors = {key: ' '.join(key.split()) for key in keys}

keys now holds all author names from the original dict, whereas authors holds their normalized versions. Maybe you should also consider to convert all the names to upper-/lowercase in order to make it even more robust, but you'll have to see yourself if that's worth it.

Looking at the fuzzywuzzy documentation of fuzzywuzzy.fuzz reveals that it basically seems to be a wrapper around difflib.SequenceMatcher. From a few quick experiments I got the impression that the following is true:

fuzzywuzzy.fuzz(str1, str2) == fuzzywuzzy.fuzz(str2, str1)

With that in mind, the amount of computations can be cut down even more, by avoiding duplicate comparisons. Since you gave no special reason for using UUIDs, I skipped them in the reworked code for the moment.

dict_of_all_data = {'Trevor Jacobs': None, 'Josh Francis': None, 'Marcie Lank': None, 'Marcie H. Lank': None}

keys = list(dict_of_all_data.keys())
authors = {key: ' '.join(key.split()) for key in keys}
authors_to_delete = []

for i, key1 in enumerate(keys, 1):
    author1 = authors[key1]
    for key2 in keys[i:]:   # this helps to avoid duplicate comparison
        author2 = authors[key2]
        ratio = fuzz.ratio(author1, author2)
        if ratio > 85 and dict_of_all_data[key1] is None:
            dict_of_all_data[key1] = True   # likely not even necessary
            authors_to_delete.append(key2)

for delete_me in authors_to_delete:
    dict_of_all_data.pop(delete_me)

print(dict_of_all_data)

As a bonus, one should wrap the code into a function to nicely separate it from the rest of the code. Whether or not you want to convert this code into a function, it would be a good idea to replace the magic value 85 with a parameter/constant with a meaningful name.

Grajdeanu Alex presents a similar idea in his answer, but uses itertools.combinations instead of doing the de-duplication manually as I suggested above.


Class to simplify skipping some actions on the first loop iteration

Don't try to over-generalize early. This is a situation I've run into quite a few times for strings, but never anywhere else, so I would recommend you start with a string-specific solution, and only try to come up with something more general if it ever becomes necessary.

You mention String.join- is there any situation where you face this problem where String.join wouldn't solve your problem? It's quite possible that the problem you actually need to solve isn't "skipping some actions on the first loop iteration", it's "cleanly joining strings with a separator". If that's the case, then why not just reimplement String.join yourself, rather than creating your own very different way of achieving the same thing?

If you do need to generalize, then your solution could work, but its main problem is that now you're creating a class whose only purpose is to run a chunk of some arbitrary (possible private!) procedure, just because that chunk happened to follow a particular structure. If Java 6 supported functional programming, then a single class which was passed functions would have been acceptable, but the need to create a new class that inherits from FirstCartridgeIsBlank every time you want to use it seems like a design headache to me.

So I think instead of trying to create a class for this, it'd probably just be simpler to do it by extracting methods:

public static String prepareUrl(String url, List<? extends NameValuePair> arguments) {
    boolean firstIteration = true;
    StringBuilder urlBuilder = new StringBuilder(url);
    for (NameValuePair argument : arguments) {
        String argumentString = getQueryArgument(argument.getName(), argument.getValue(), firstIteration);
        firstIteration = false;
    }

    return urlBuilder.toString();
}

private static String getQueryArgument(String name, String value, Boolean includeSeparator) {
    //...
}


CakePHP 2.x Custom PagesController & Routing

Use a pattern
The general principle is fine, though it won't handle plugin routes (which I assume isn't a problem)
However instead of a loop (and therefore defining 6 routes per controller) a parameter for the controller name can be used which will be more concise and likely overall more performant. The code could be rewritten like this:
// Define a home route
Router::connect('/', array('controller' => 'pages', 'action' => 'displayHome'));

// Generate a regex-like controller name pattern (e.g. "posts|comments|users")
$controllerList = App::objects('controller');
$controllerList = array_map(function($c) {
    return Inflector::underscore(substr($c, 0, strlen($c)-10);
}, $controllerList));
$controllerList = array_filter($controllerList, function ($c) {
    return $c !== 'app'
});
$controller = implode('|', $controllerList);

// Define normal routes
$params = array('controller' => $controller);
Router::connect('/:controller', $params);
Router::connect('/:controller/:action', $params);
Router::connect('/:controller/:action/*', $params);

// Define admin routes
$params += array('admin' => true, 'prefix' => 'admin');
Router::connect('/admin/:controller', $params);
Router::connect('/admin/:controller/:action', $params);
Router::connect('/admin/:controller/:action/*', $params);

// Define catchall
Router::connect('/**', array('controller'=>'pages', 'action'=>'display'));

In this way there are 8 routes in total, no matter how many controllers there are in the application.


Detecting a combination of characters from input

Here are some inputs on command line which break your code:

dan@albatross  $ gcc -Wall f.c -o f
dan@albatross  $ ./f
please enter your input:
bfiqwb23b r9pu3h2ru23r
9aisdbfuiasdf
adsf#asdf
#
#
#
    adsfadsfasdf
34324!
^C

I assume your program is supposed to terminate at the first #, but notice here that it does not. I have to kill the program to stop it. The shows there is a problem with one of your loops. By seeing the manipulation of the index variable in the second loop, I think it's the problem.

Code Review

First: you do not need to have the line index++ inside the loop. Use the single variable total instead. This is a minor thing.

Instead of having a nested if-statement, use an and conditional. And stop decreasing the index variable - that's what causing all those problems. Try this:

for (index = 1; index < total; index++)
    {
        if (wordChar[index] == 'i' && wordChar[index - 1] == 'e')
            combinationTimes++;
    }

However, that is still inefficient code, because you should be processing the input as it is given, not processing it after the last hash. Notice that you are doing length_of_input work at the end, when you could be doing constant work at each step, which is computationally less noticeable to a user. In addition, the array has length_of_input memory overhead, which seems unnecessary here. Consider writing something like this instead:

#define FALSE 0
#define TRUE 1

int main(void)
{
    int combinationTimes = 0;
    char userInput;
    short int last_e = FALSE;

    printf("please enter your input:\n");

    while ((userInput = getchar()) != '#')
    {
        if (userInput == 'e')
        {
            last_e = TRUE;
        }
        else if (userInput == 'i' && last_e)
        {
            combinationTimes++;
            last_e = FALSE;
        }
        else
        {
            //this is important, otherwise combinations like 'ite' are counted
            last_e = FALSE;
        }
    }

    printf("Number of combos: %d\n", combinationTimes);
    return 0;
}

Here are some key features:

I removed your array, so I have no significant memory overhead. Each char is processed and discarded, one at a time
I remove your variables total and index
I process the event you care about inside the first for loop, as you read the character
I create boolean variables with compiler flags

This code also has a lot of room for improvement, but that's left as an exercise...


C++ code that convolves a data file for smoothing random data curves of microcanonical ensemble graphs

Algorithm takes \$O(n^2)\$ time

Fundamentally, your algorithm takes \$O(n^2)\$ time because it used two nested loops.  On a large input such as 1.5 million items, you must perform at a minimum somewhere around \$2.25 * 10^{12}\$ operations, which will definitely take some time.

However, there are at least two main ways I can think of to speed up your program:

Use multithreading to take advantage of your computer's multiple cores.  Since your program is just doing a massive computation, you can split the work so that each of N cores does 1/N of the work.  Assuming you had a 4 core computer, you could reasonably expect to get a 4x speedup in your program.  It is beyond the scope of my review to present a multithreaded solution, but you could research how to do this on your own.
You can improve the main loop.  I noticed a few things that you could do to speed up your main loop, which I will present in the following sections.

Remove the division loop

The first thing I noticed is that you have a division loop, but it isn't necessary.  Look here:

    double sum = 0;

    for(int i=0;i<count;++i) sum += binom[i];
    for(int i=0;i<count;++i) binom[i] /= sum;  // <-- This loop

    sum = 0;

    for(int i=1;i<count;++i) sum += d[i]*binom[i];

    summ[j] = sum;

Notice how you compute the sum of the binom array, divide each of the binom[i] entries by the total, and then add up the total of d[i] * binom[i].  Mathematically, if you skipped the division loop and just divided by the total at the end, you would get the same answer.  In other words, you could rewrite the above like this:

    double total = 0;

    for(int i=0;i<count;++i) total += binom[i];

    double sum = 0;

    for(int i=1;i<count;++i) sum += d[i]*binom[i];

    summ[j] = sum / total;

Note that the division loop was the costliest of the three loops, since division is slower than addition and multiplication.

No need for binom array

The next thing you could do is to compute the sum on the fly instead of storing your intermediate results into a binom array.  The binom array isn't really needed except to compute the final sum.  So you could just add to sum as you compute the binom values instead of creating an array and adding up the array at the end.  So I rewrote your main loop to look like this:

    //here the main convolution of data takes place
    for (int j=1;j<count;++j) {
        double prob     = (double) j / (count-1);
        double factor   = 0;
        double binom    = 0;
        double prev     = 0;
        double binomTot = 1;
        double sum      = d[j];

        factor = prob / (1-prob);
        prev   = 1;
        for (int i=j+1;i<count;++i) {
            binom     = prev * ((count-1)-i+1)/i*factor;
            binomTot += binom;
            sum      += d[i] * binom;
            prev      = binom;
        }

        factor = (1-prob)/prob;
        prev   = 1;
        for (int i=j-1;i>=0;--i) {
            binom     = prev * (i+1) / (count-1-i) * factor;
            binomTot += binom;
            sum      += d[i] * binom;
            prev      = binom;
        }

        summ[j] = sum / binomTot;

        if(j%1000==0)// just to make the process faster and check progress
        cout<<count-1<<'\t'<<j<<endl;
    }

With this modified loop, the program ran 2x faster than the original program, on a test case of 20000 random floats.

Cache reused values

Finally, you can speed up your loop even more by caching the values that are reused on each loop.  I noticed that these values:

((count-1)-i+1)/i
(i+1) / (count-1-i)

are used in your inner loops, and they only depend on i and count.  So instead of doing the computation over and over again, we can precompute these values once and then just use the precomputed values in the inner loops.  This avoids costly division operations.

Here is a rewrite using cached values:

double *factor1 = new double[count];
double *factor2 = new double[count];

for (int i=0;i<count;++i) {
    factor1[i] = (double) ((count-1)-i+1) / i;
    factor2[i] = (double) (i+1) / (count-1-i);
}

//here the main convolution of data takes place
for (int j=1;j<count;++j) {
    double prob     = (double) j / (count-1);
    double factor   = 0;
    double binom    = 0;
    double prev     = 0;
    double binomTot = 1;
    double sum      = d[j];

    factor = prob / (1-prob);
    prev   = 1;
    for (int i=j+1;i<count;++i) {
        binom     = prev * factor1[i] * factor;
        binomTot += binom;
        sum      += d[i] * binom;
        prev      = binom;
    }

    factor = (1-prob)/prob;
    prev   = 1;
    for (int i=j-1;i>=0;--i) {
        binom     = prev * factor2[i] * factor;
        binomTot += binom;
        sum      += d[i] * binom;
        prev      = binom;
    }

    summ[j] = sum / binomTot;

    if(j%1000==0)// just to make the process faster and check progress
    cout<<count-1<<'\t'<<j<<endl;
}
delete [] factor1;
delete [] factor2;

This rewrite was about 4x faster than the original version, on a test case of 20000 random floats.  However, on a test case of 100000 random floats, it was 14x faster.  My guess is that the original program scaled badly with larger inputs because of the temporary binom array polluting the cache.  I would advise testing this version for yourself on your own computer with various sized inputs to see how it performs.


Some functions in the Prelude can be of help. One is map, which allows you to write a simpler handleFizzBuzz.  Another is unwords, which is equivalent to your concatOutput.

handleFizzBuzz :: String -> String
handleFizzBuzz =
    map $ unwords . fizzBuzz . convertInputLine

main :: IO ()
main = do
    args <- getArgs
    let path = args !! 0
    file <- readFile path
    putStrLn . unlines . map handleFizzBuzz . lines $ file

Another is <>, the simple monoidal concat. As both String is a Monoid and (Monoid a) => Maybe a is a Monoid, so is Maybe String. It lets us eliminate two cases in fizzBuzzSingle if we also return a Maybe:

fizzBuzzSingle :: Int -> Int -> Int -> Maybe String
fizzBuzzSingle f b n =
    ("F" <$ guard (mod n f == 0)) <> ("B" <$ guard (mod n b == 0))

The <$ is a useful operator from Data.Functor. Its implementation is something like b <$ fa = fmap (\_ -> b) fa. guard returns a Nothing when our divisibility checks return False, which is perfect for us since that means "F" <$ Nothing evaluates to Nothing.

But, as we're now in Maybe-land, we need to discharge it. In the case where a number is divisible by either divisor, we just want to print the number. So we can turn to fromMaybe from Data.Maybe:

fizzBuzz :: [Int] -> [String]
fizzBuzz [f, b, end] =
    map (\n -> fromMaybe (show n) (fizzBuzzSingle f b n)) [1 .. end]

But we notice that the inner closure can be rewritten as \n -> (fromMaybe . show $ n) (fizzBuzzSingle f b $ n). That seems useless, but it's exactly like the implementation of the applicative sequencing operator for (->) r.

fizzBuzz :: [Int] -> [String]
fizzBuzz [f, b, end] =
    map (fromMaybe . show <*> fizzBuzzSingle f b) [1 .. end]

This is a pretty esoteric trick. Applicative is already somewhat of a stumper, but I think there's something about (->) r that makes its Applicative instance especially difficult to understand.

But, if we elect to use this trick and combine it with everything else, the program boils down to:

import Data.Monoid
import Data.Maybe
import Control.Monad
import System.Environment

fizzBuzzSingle :: Int -> Int -> Int -> Maybe String
fizzBuzzSingle f b n =
    ("F" <$ guard (mod n f == 0)) <> ("B" <$ guard (mod n b == 0))

fizzBuzz :: [Int] -> [String]
fizzBuzz [f, b, end] =
    map (fromMaybe . show <*> fizzBuzzSingle f b) [1 .. end]

main :: IO ()
main = do
    args <- getArgs
    file <- readFile (head args)
    (putStrLn . unlines . map (unwords . fizzBuzz . map read . words) . lines) file

I think there's something to be said for simplicity. I think your pattern matching makes for a more readable fizzBuzzSingle at the end of the day, though this implementation easily extends if you want to test three or four or five divisors. Anyway, monoids and functors and applicatives, oh my!

Credit is due: I saw this originally on /r/haskell.


Is this good practice with unit-testing?

No, I would say, and the reason for that is that you have too many asserts in your test (it does to many thinks). There should only be one reason for a test to fail. So:

Split your test into smaller ones with a more descriptive name and stick to one assert per test. By doing so it's also easier to track down why a test is failing, both in the case is the bug is in the test or in the production code.


You could just use str.join in a list comprehension and create deck directly:

import itertools
kind = 'HCDS'
value = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
deck = ["".join(card) for card in itertools.product(kind,value)]

Note that a regular French card set starts at 2, there is no 1.


Getting a list of all fields in an object

If you are using Java 8, you can do:

private String[] getFields() {
    Class<? extends Component> componentClass = getClass();
    Field[] fields = componentClass.getFields();
    List<String> lines = new ArrayList<>(fields.length);

    Arrays.stream(fields).forEach(field -> {
        field.setAccessible(true);
        try {
            lines.add(field.getName() + " = " + field.get(this));
        } catch (final IllegalAccessException e) {
            lines.add(field.getName() + " > " + e.getClass().getSimpleName());
        }
    });

    return lines.toArray(new String[lines.size()]);
}

or to improve formatting:

private String[] getFields() {
    Class<? extends Component> componentClass = getClass();
    Field[] fields = componentClass.getFields();
    List<String> lines = new ArrayList<>(fields.length);

    Arrays.stream(fields)
            .forEach(
                    field -> {
                        field.setAccessible(true);
                        try {
                            lines.add(field.getName() + " = " + field.get(this));
                        } catch (final IllegalAccessException e) {
                            lines.add(field.getName() + " > "
                                    + e.getClass().getSimpleName());
                        }
                    });

    return lines.toArray(new String[lines.size()]);
}

Note that this is adding to @EricStein's excellent answer on normal concatenation instead of StringBuilders.

(I'm just starting to look into Streams, so if this is bad, please comment on why)

Otherwise...

Just a small comment:

lineBuilder.append(" = ");
lineBuilder.append(value);

can easily be:

lineBuilder.append(" = ").append(value);

Same with:

lineBuilder.append(" > ");
lineBuilder.append(e.getClass().getSimpleName());

becomes:

lineBuilder.append(" > ").append(e.getClass().getSimpleName());

Also, I would use a simple array instead of an ArrayList:

private String[] getFields() {
    Class<? extends Component> componentClass = getClass();
    Field[] fields = componentClass.getFields();
    String[] lines = new String[fields.length];

    int index = 0;
    for (Field field : fields) {
        StringBuilder lineBuilder = new StringBuilder();

        lineBuilder.append(field.getName());

        field.setAccessible(true);

        try {
            Object value = field.get(this);

            lineBuilder.append(" = ");
            lineBuilder.append(value);
        } catch (IllegalAccessException e) {
            lineBuilder.append(" > ");
            lineBuilder.append(e.getClass().getSimpleName());
        }

        lines[index++] = lineBuilder.toString();
    }

    return lines;
}

EDIT: The above review, if not using Java 8, should be replaced by @EricStein's code.

Also, getFields() is a bad name. Try getFieldDescriptions().


(Project Euler #1) Find the sum of all the multiples of 3 or 5 below 1000

The keyword sum is a built in function and you shouldn't name variables from within the reserved keywords.

Here's a list of the most common used keywords which you shouldn't be naming any of your variables:

[False, class, finally, is, return, None, continue, for, lambda, try, True, def, from, nonlocal, while, and, del, global, not, with, as, elif, if   or, yield, assert, else, import, pass, break, except, in, raise]

And for the built-in functions check https://www.programiz.com/python-programming/methods/built-in

for n in range(0, 1000):

Can be written for n in range(1000):

The range() function as well as the whole Python is zero-indexed.

You might also want to use comprehension syntax (which is much more efficient than explicit loops) and enclose it inside a function like this:

def get_multiples(upper_bound):
    """Return sum of multiples of 3 and multiples of 5 within specified range."""
    return sum(number for number in range(upper_bound) if not number % 3 or not number % 5)


It is quite hard to understand what your code is supposed to do. Let's try to progress little by little.

I've based my analysis on the test cases you have provided.

if tl == 1:

A list with a single element seems to be handled in a special way. If we replace the check with if tl == 1 and False:, we can see that the result is the same if we don't handle this case in a particular way.

I've removed the corresponding check.

hold

You are performing some super tricky logic involving string manipulation, list slicing and split. I realised that the whole thing does the same thing as d = ['-'] * amount.

Comparison of d[z] and con[z]

You are handling the three different cases here. Funny thing is that you have a case where you do nothing (pass) and one where you do something which looks like nothing to me (d[z] = d[z]). At the end of the day, I have the feeling that this could be written : d[z] = max(x, con[z]).

Hard coded strings

You have ',' in multiple places. If you ever want to change this, this will be pretty akward. You could store this in a variable on its own. Even better, you could make this a parameter with a default value. You have the benefit of making things easier for you as a developer of the function but also as a user of the function because it is easier to change its behavior if needed.

At this point, the code looks like:

def clean(li, sep=','):
    amount = len(li[0].split(sep))
    d = ['-'] *  amount
    for i in li:
        con = i.split(sep)
        for z, x in enumerate(d):
            d[z] = max(x, con[z])
    return sep.join(d)

Splitting string once

As you only care about the splitted version of the string, it would probably be interesting to split them at the very beginning so that you don't have to worry about this later on in the function.

splitted = [i.split(sep) for i in li]

Input handling

A few special cases could lead to troubles :

if len(li) == 0, your code will crash.
if the elements of splitted (which are lists of strings) have different lengths, your code will either crash (if a list is smaller that the first one) or ignore additional elements (if a list is bigger than the first one).

You might want to handle this properly.

Now, the code looks like :

def clean(li, sep=','):
    splitted = [i.split(sep) for i in li]
    if not splitted:
        return "invalid input" # or anything you like
    amount = len(splitted[0])
    if any(len(s) != amount for s in splitted):
        return "invalid input 2" # or anything you like
    d = ['-'] *  amount
    for s in splitted:
        for z, (dz, sz) in enumerate(zip(d, s)):
            d[z] = max(dz, sz)
    return sep.join(d)


This is not a SessionHelper but a UserSessionHelper in the first place. A session is a container that could contain anything, not only user credentials. A shopping cart items for example. Therefore you have to either extend its functionality or at least rename a class.

In 2018 you are obligatory supposed to utilize a PSR-4: Autoloader so not to include your class definitions manually.

What is most important, I don't see any getSession() method. Are you checking $_SESSION array directly? If so, that makes you class essentially incomplete. When writing OOP, you must encapsulate the full functionality, leaving something outside just makes no sense.

Given there is no constructor, consider using static methods, it will save you the very absent constructor call.


Change the limit from CakePHP 3 Paginator by click in link inside an

I will admit that I am not really familiar with CakePHP so I am not sure how to answer "Exist any way to do this in cakephp style?" - did you ever find an answer for that?

I am intrigued by the following line:

@$limit = $this->request->query['limit'] ?: 3;

shouldn't the error control operator be prepended before the right hand side of the assignment operator?

$limit = @$this->request->query['limit'] ?: 3;

I haven't tried the error control operator on that side... maybe it still works the same...

Looking at the JavaScript code, it appears that the option parameter actually corresponds to the select list

$('#products-view').change(function(){
    changeLimitPagination(this);
});

function changeLimitPagination(option){
    console.log(' option tagName: ', option.tagName, ' id: ', option.id);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="products-view" class="form-control products-view inline-pagination-menu" id="products-view">
    <option value="3">3</option>
    <option value="6">6</option>
    <option value="9">9</option>
</select>

So a better name would be something like productsList or limitList. Also, that doesn't really need to be a parameter - it could be stored in a variable outside the function. While you might still need to use jQuery for other code, regular JavaScript code could be used to select the element by id attribute with document.getElementById() and then add the change handler via EventTarget.addEventHandler(). That way, changeLimitPagination could simply be added as the callback to the change handler instead of an extra anonymous function that has the sole purpose of calling changeLimitPagination.

var productsView = document.getElementById('products-view');
productsView.addEventListener('change', changeLimitPagination);

function changeLimitPagination(){
    console.log('changeLimitPagintation() - value: ', productsView.value);
    //location.search = $.query.set('limit', option.value).toString();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="products-view" class="form-control products-view inline-pagination-menu" id="products-view">
    <option value="3">3</option>
    <option value="6">6</option>
    <option value="9">9</option>
</select>


Ansible playbook to generate webserver folder structure with users and projects

I can think of 3 options.

Using a role

As you work in Ansible progresses you'll find the number of tasks and variables harder to manage as a single file.  You'll likely want to create an ansible role.

ansible-galaxy init <your role name>

This will create a structure of folders with defaults, vars, files, handlers, tasks, meta and templates.

You can then separate out your variables into separate files while keeping them originally defined in defaults/main.yml in order to easily override them while controlling how there initialized.
Force 'manual' loading of vars conditionally within the role by overriding defaults/main.yml with custom logic in tasks.

This can apply to stand alone task files also, but I prefer using roles.
Here are two examples:

# including vars that are outside your role on inventory dir path level.
- include_vars:
   file: "{{inventory_dir | dirname}}/group_vars/rdu.yml"
  when: env == 'rdu'

# including vars that are within your role to a var called dataset.
- include_vars:
   file: "{{role_path}}/defaults/datasets/{{dataset_name}}.yml"
  when: dataset_name is defined

You can also use the vars folder within the role but I prefer to use defaults/main.yml to set defaults and then write over the defaults later.
If the values are static and should not be changed then you can consider using vars/main.yml this assumes you are using a role.
Put variables which are associated with a specific group under your group_vars and then make the association in your inventory file.

See http://docs.ansible.com/ansible/latest/intro_inventory.html#group-variables

My suggestion is to create a role, and then organize your variables into similar groups where possible and keep defaults in the role/role-name/defaults.main.yml and then override them based on the logic of your variables.

So looking at your code it seems that each project (mars, venusnew, and venusold) could like get there own yml file.  Using conditional logic you can decide which vars to load.


Abort thread on new request, but complete only last request

Basically it is in its current state senseless to have a

var listCancellationTokens = new List<CancellationTokenSource>();

if all you want is one running thread at any time.

So what I suggest instead is to create one Task and if there comes the situation that this task should be canceled you should cancel the task and Wait until the task returned.

After the Task returned you then create the new Task.

private static Task task;
private static CancellationTokenSource cancelSource;
static void Main(string[] args)
{

    for (var i = 1; i <= 5; i++)
    {
        if(task != null && (!task.IsCompleted || !task.IsFaulted))
        {

            try
            {
                cancelSource.Cancel();
                task.Wait(cancelSource.Token);
            }
            catch (OperationCanceledException ex)
            {
                //swallow because by using ThrowIfCancellationRequested()
                //in combination with cancelSource.Cancel() an exception is thrown.
            }
        }
        cancelSource = new CancellationTokenSource();

        task = Task.Factory.StartNew(() => ConsolidateResults(cancelSource.Token));

    }
    Console.ReadLine();
}

then you should change the ConsolidateResults() method to

private static void ConsolidateResults(CancellationToken cancelToken)
{
    cancelToken.ThrowIfCancellationRequested();

    UpdateValues();
    TurnOffEvents();
    GetMarginPercentage();
    TurnOnEvents();
}


Is this base 62 encoding algorithm okay?

It is 'standard' to have 0-9 at the beginning of the 'alphabet' for numbers....

I would have suggested that you use the native functionality in BigInteger to convert the value to a String in any given radix, but unfortunately, it does not support more than radix 36. Still, you should follow that standard and start with 0-9 instead of ending with it.

I would also suggest two things:

you should convert the alphabet to an array immediately:

private val Base62Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray()

you should not have the magic number '62' in your code, but should base it off the array size:

private val Radix = Base62Alphabet.length

your code then becomes:

val remainder = (left % Radix).toInt
left /= Radix

Finally, I don't like that you have variable-length results from the conversion. You should ensure that all hashes of data with the same length have the same length of output... -left-padding with 0 as needed. It is possible for something to hash to 0x0000000000 (hex).... which will give you 0-value number.bitCount.


Prime factorization for integers with up to 9-digit long prime factors

Code Comments

First, that is a thoroughly excessive amount of commenting. I appreciate your zeal in documentation, but you do not need to comment every line. Just a couple comments here and there is thoroughly sufficient.

Second, your function should do its job. If you want to time it, that is an external job. Use the timeit library:

def pf(n):
    # stuff that doesn't involve datetime
    return factors

print timeit.timeit('pf(val)',
                    setup='from __main__ import pf; val = 145721*(145721+2)',
                    number=10)

That will print how long it took your function to run 10 times. Great library, highly recommended.

Thirdly, factors += [p] should be spelled factors.append(p).

Algorithm Comments

The reason your code performs so poorly is because of the its algorithmic complexity. You are trying every odd number from 2 to sqrt(N), so your algorithm is O(sqrt(N)). But here N is the actual number... if we express N in terms of digits, it's O(sqrt(10^N)) = O(10^(N/2)). So when we go from 30-digit number to a 43-digit number, we would expect to see an increase in time on the order of a million in the worst case (if we were looking at twin primes). The fact that we see an increase of "only" 20x is an artifact of case selection more than anything else. I tried picking multiples of (arbitrary) twin primes, and the runtimes I got after 10 runs each were:

145721 * 145723        0.536s
1117811 * 1117813      2.716s
18363797 * 18363799   45.436s

Roughly 10x each time. Yay predictions.

So what can we do to speed this up? When our times are this bad, it's either because we have a really stupid bug or we're using a bad algorithm. There isn't anything I see that will save this particular algorithm. At best, we can improve by changing the iteration to avoid multiples of 3 and 5:

jump = 4
while p*p <= n:
    ...
    else:
        p += jump
        jump ^= 6 #so it alternates between 2 and 4

That gets us to:

145721 * 145723        0.263s
1117811 * 1117813      2.172s
18363797 * 18363799   34.740s

Still exponential, but better constants at least. Not sure how much better we're going to do than that. So let's just google some prime factorization algorithms. First one I came across was Pollard's rho. Simply copying the algorithm gives produces:

def pollard(n):
    from fractions import gcd

    def get_factor(n):
        x_fixed = 2
        x = 2
        cycle_size = 2
        factor = 1

        while factor == 1:
            for count in xrange(cycle_size):
                if factor > 1: break
                x = (x * x + 1) % n
                factor = gcd(x - x_fixed, n)

            cycle_size *= 2
            x_fixed = x

        return factor

    factors = []
    while n > 1:
        next = get_factor(n)
        factors.append(next)
        n //= next
    return factors

That gives me the correct response on all three twin primes, with this performance:

145721 * 145723          0.021s (12.5x improvement)
1117811 * 1117813        0.295s ( 7.4x)
18363797 * 18363799      1.131s (30.7x)
1500450269 * 1500450271  5.733s (est. ~1000x)

Even jumping up to 10-digits, we still see good performance (we'd expect over an hour with the previous algorithm, so we're talking 1000x improvement), and we see better growth to.

Sometimes, you just need a better algorithm.


Not relevant to your algo, but you shouldn't be using "" like this; use the vbNullString language constant instead, which consumes 0 memory (as opposed to "" which has the overhead of a string).

As for suggestions, in order to find a better way to do something, it's important to first understand what's going on. And proper indentation greatly helps for that:

CurMonth = target.Offset(5 - target.Row).Value
If CurMonth = vbNullString Then
    CurMonth = target.Offset((5 - target.Row), -1).Value
    If CurMonth = vbNullString Then
        CurMonth = target.Offset((5 - target.Row), -2).Value
        If CurMonth = vbNullString Then
            CurMonth = target.Offset((5 - target.Row), -3).Value
        End If
    End If
End If
Debug.Print CurMonth

Something sticks out right away - every new nested level seems to increment the offset, so what you really have is this:

CurMonth = target.Offset((5 - target.Row), n).Value
If CurMonth = vbNullString Then
    n = n - 1
    [and do that again while n > -3]

This looks like a recursive logic - something like this:

Private Function GetCurMonth(ByVal n As Long) As String
    Dim result As String

    result = target.Offset((5 - target.Row), n).Value
    If result = vbNullString And n > -3 Then
        n = n - 1
        result = GetCurMonth(n) 'recursive call
    End If

    GetCurMonth = result
End Sub

Also CurMonth has no reason not to be called CurrentMonth I guess. As Comintern mentioned, it would be easier to give a better review with more [code] context.


Some issues:

the assignment operator doesn't call the destructor of the existing data, before setting a new value (results in UB, likely a resource leak).
by default you do not instantiate an empty variant with the default constructor; the first type in the union may not even be default-constructible.
bad_variant_access should probably inherit from a standard exception (std::runtime_error or std::logic_error are common as base classes).


Edit: Well my previous suggestions don't work with the fact that
get_response has to be called with the correct timezone active.

Is the time_zone attribute from GeoIP2 always compatible with
pytz btw.?

Perhaps the following would work, verifying the cookie value only once
and discarding it if it doesn't fit:

cookie = request.COOKIES.get(TIMEZONE_COOKIE_NAME)
if cookie not in pytz.all_timezones_set:
    cookie = None

if not cookie and request.ip:
    try:
        cookie = GeoIP2().city(request.ip).time_zone
    except GeoIP2Error:
        self.logger.warning('Could not determine time zone of ip address: %s', request.ip)

if cookie:
    timezone.activate(pytz.timezone(cookie))

response = self.get_response(request)
if cookie:
    response.set_cookie(TIMEZONE_COOKIE_NAME, cookie)
return response

So, downside is a lot of mentions of cookie, upside is that it's not
more costly what you had before and the call to set the timezone is only
there once.

Last point, if anything like this happens to be needed more than once,
put it into separate functions.  This snippet is a bit short to make
that call.


Profile picture upload method in Laravel 5.2

I think your program is good. I repeat, IMO, it's good.
As you said in questions, the answers are

 Move your image manipulation related methods to a TRAIT. that'll help you while using the same code in different controllers. Because, if you want it to be done like this way, you must have to declare objects, if you want to use the same code from different controllers/classes. On the other hand, if you use TRAIT, you just have to use them.

 As you're passing the Request to your method, you may pass the array instead. Otherwise, you may use check the file existence, on the previous method then pass the values to next method. You may wish to use varargs as a method parameter.


Displaying data as binary in C with bitmasks

You may use the shift operation;

char mask = 0x01; //define initial mask

if (mask&mychar) printf("1"); // check that spesific bit

mask<<=1; //shift left

of course if you want to start checking from right hand then shift right you can do :

char mask = 0x80;

mask>>=1;


Porting a web-based POS system to Android

You can use fragmentManager.findFragmentByTag() instead.

If the fragment is not found, initalize a new one.

fragment = new YourFragment();


Matlab - Fastest way to parallel read many files line by line?

Performing this in parallel using PARFOR should be straightforward if you have the Parallel Computing Toolbox installed. Whether it goes any faster or not depends entirely on the size of your data, the speed of your disks etc. Here's how I would approach it:

function [x, y] = readOnePairOfFiles(name1, name2)
   x = {}; y = {};
   fid1 = fopen(name1); fid2 = fopen(name2);
   %# Read from fid1 and fid2, build up x and y
end

% Use PARFOR to invoke readOnePairOfFiles
x = {}; y = {};
parfor ii = 1:length(dir)
   name1 = fullfile(directory, dir1(ii).name);
   name2 = fullfile(directory, dir2(ii).name);
   [thisX, thisY] = readOnePairOfFiles(name1, name2);
   x = [x, thisX]; %# concatenation reduction to get x and y
   y = [y, thisY];
end