Generating stock prices using geometric brownian motion

This looks like a really interesting use of Brownian motion! Neat idea! Here are some suggestions for improving the code:
Avoid using namespace std
In general, using using namespace std is a bad idea. In a header, it's a very bad idea. Here's one description of why.
Naming
You should name your function arguments in the header so a user of your code knows what they represent. For example, in the future, you might compile this into a library to include in other programs, and ship just the header and the compiled library. If you do that, a user of your library will have no idea what the arguments to the LSM constructor are. (And remember that that user may be a future you who doesn't remember all the details of the implementation!)
I'd also recommend that you use better names than 1 letter names that may be meaningless or worse, confusing to readers of your code. You have some great ideas for what the names should be in the comments in main(). Instead of adding comments to explain the names, just name the variables what you wrote in the comments. For example, instead of r, call it risklessInterestRate. Instead of q, call it dividendYield. Yes, it takes a little bit longer to type, but those few extra seconds of typing will end up saving minutes or hours of frustration if you get 2 of the variables with similar names confused (like M and N).
Headers
Only include what you need. Only include it where you need it. Your main() function doesn't need any header other than LSM.h, so it should be the only thing you include there. LSM.h doesn't need any of the files it has included except for <vector>. LSM.cpp should include those files instead because it does use them. It might not seem like a big deal now, but once your project gets a little bigger, including the wrong files or including files you don't need can really slow down a compile.
Constructors
In C++, the constructor should never call a virtual method of its own class because it's not yet fully constructed. Luckily your code does not do that. But it does call a non-virtual method. When I see that, it raises a red flag to me, because it's fairly common for a non-virtual method to later become virtual if a subclass needs to override it. For that reason, I tend to avoid calling any (non-static) methods of the same class within a constructor. Furthermore, the LSM::GBM function doesn't use any member variables or change any state in the object or call any member functions of LSM, so it could be implemented as a free-standing static function inside LSM.cpp. (Unless, of course, you're going to want other code outside the class to call it, in which case it should probably be a static member function of the LSM class.)
const
Nice use of const! So few people use it, so it's really refreshing to see it being used well. Good work!


I think what your better off doing is to have a join on your database call, so that the class data and student data is returned in one object.


You are right about head, it is used to move through the list. previous is a temporary pointer that is needed to perform the delete. You need it because the delete process means taking the next value of the Node to the left, and making it 'skip' the deleted Node and point over to the right of the deleted Node.

The list is linked by each Node having a next pointer. It would look something like:

A -> B -> A -> C -> D ->

Here the first A points to B, which points to a different A, which points to C, and so on.

You would call your method with the pointer to the first A as the argument head. There is no previous ....

So your system starts off looking like:

     A -> B -> A -> C -> D ->
^    ^
P    H

Where H is the Head pointer, and P is the previous.

We add the value A to the HashMap, and advance our pointers:

    A -> B -> A -> C -> D ->
    ^    ^
    P    H

B is not in the HashMap, so move on....

    A -> B -> A -> C -> D ->
         ^    ^
         P    H

A is in the HashMap, so we have a duplicate. This is where P comes in to play....

We make the B (pointed to by previous) point to C....

    A -> B  --->  C -> D ->
         ^      /
         |    A
         |    ^
         P    H

We do that by making the previous's next point to the head's next. We now have a kind of 'fork' in the list, with the second A dangling part way through....

We have now removed the A from the main link chain, and we need to advance the head pointer to C.... Sunce Nothing is pointing to the second A now, it can be garbage collected, etc... and the final result looks like:

    A -> B  --->  C -> D ->
         ^        ^
         P        H

Now, about your other questions.....

This operation is about as fast as it can get. Not much you can do to improve performance.

Additionally, the operation essentially uses no stoage (there is some stack amount, but this is peanuts in the scheme of things....

If this list is able to cover your use cases, then I would say "Great, use it".


There are no glaring security issues I can see in the original code, but I felt it could be improved.

<?php

core::doPage();

class core
{
    public static function doPage()
    {

        // i hate having $_GET littered through my code,
        // it is too easy to mishandle non-sanitized data
        $request_page = isset($_GET["page"]) ? $_GET["page"] : null;

        // why die here, why not use our standard page handling
        if(empty($request_page) || !is_string($request_page)) {
            $request_page = 'index.php';
        }

        // we take .php extenstion off, then tack it back on later, whats the point?,
        // just leave it on
        // if you have 1000's of files glob + in_array test will be a slow way to check
        // give your variables a more descriptive name other then $pages,
        // so that when someone else edits your code,
        // they can tell what you are trying to do
        $pages_whitelist = glob("*.php");

        // test and alter your request_page, just do one include at the end
        if(!in_array($request_page, $pages_whitelist)) {
            $request_page = '404.php';
        }

        // include_once triggers a php warning if the file doesn't exist,
        // why not use file_exists?
        $file = "./_pages/$request_page";

        if (!file_exists($file)) {
            die("404 - File not found.");
        }

        // yay, no more nested if statements
        // a lot cleaner and easier to read (i hope)
        include_once($file);
    }

}


Lotus Domino API - Parsing through NotesItems

You can rewrite the nested ifs and loops with a nice and short LINQ query that will give you all the items first:

var items
    from doc in notedb.AllDocuments.Where(doc => doc.Items != null)
    from item in doc.Items.Where(item => item.Values != null)
    select item;

Then, you loop over the items with a foreach loop:

foreach (var item in items)
{
    SetDocProperty(pdbdoc, item);
}

and call a new helper method that encapsulates the switch:

void SetDocProperty(SomeType pdbdoc, SomeOtherType item)
{
    switch (item.Name)
    {
        //PDB DATA
        case "DocArea": pdbdoc.DocArea = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "DocDisc": pdbdoc.DocDisc = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "DocObject": pdbdoc.DocObject = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "DocOrigin": pdbdoc.DocOrigin = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "DocRef": pdbdoc.DocRef = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "DocRefClient": pdbdoc.DocRefClient = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "DocRevDt": pdbdoc.DocRevDt = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "DocRevNo": pdbdoc.DocRevNo = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "DocTitle": pdbdoc.DocTitle = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "DocUnit": pdbdoc.DocUnit = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "INCABINET": pdbdoc.InCabinet = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        //VDB DATA
        case "VendorDocNm": pdbdoc.DocTitle = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "VendorDocRef": pdbdoc.DocRefClient = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "VendorDocRevNo": pdbdoc.DocRevNo = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "DocUse": pdbdoc.DocObject = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "VendorDocRevDt": pdbdoc.DocRevDt = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "VendorDocClientRef": pdbdoc.DocRef = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
        case "VendorNm": pdbdoc.VendorName = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
    }
}

You could probably parallelize it with Parallel.ForEach but the code isn't complete so I cannot make any other suggestions as I don't know how the pdbdoc works and what it is.


Yes:

CXX       = g++
#
# Notice the +=.  Use CPPFLAGS rather than INC for pre-processor rules.
#
CPPFLAGS += -Iinclude/ -I../tools/
CXXFLAGS += -std=c++0x

#
# Move the backslash
# This will stop it looking like a directory at first glance.
binaries=01sum35              \
     02evenfibs               \
     03largestprimefactor     \
     04largestpallyproduct    \
     05smallestmultiple       \
     06sumsquaredifference    \
     07tenthousandfirstprime  \
     08largestproductinseries \
     09specialpythagtriplet

all: $(binaries)

clean:
    rm -f $(binaries)

# Default rules and dependencies works for all the targets
# except the following which need one more file (dependency)

04largestpallyproduct:      04largestpallyproduct.cc    ../tools/tools.cc
07tenthousandfirstprime:    07tenthousandfirstprime.cc  ../tools/tools.cc
08largestproductinseries:   08largestproductinseries.cc ../tools/tools.cc


I find MODULO() to be jarring, when everything else is written in lowercase.  Be consistent.

To left-justify strings in the output, write it using a * format.  Since you want to write to standard output, you can simplify it by using print instead.

To left-justify numbers in the output, first convert it to a string, then strip leading spaces.

program fizzbuzz
implicit none
integer ::i
character(len=8) :: str

! Loop through integers 1 through 100
! Multiples of 3 print Fort
! Multiples of 5 print Ran
! Multiples of both print FortRan
! 15 is the lowest common multiple of 3, and 5
!    and thus is a shortcut to FortRan

do i=1,100
    if (modulo(i, 15) == 0) then
        print *, 'FortRan'
    else if (modulo(i, 3) == 0) then
        print *, 'Fort'
    else if (modulo(i, 5) == 0) then
        print *, 'Ran'
    else
        write (str, '(i8)') i
        str = adjustl(str)
        print *, str
    end if
end do

end program fizzbuzz


Wrapper for commonly used database classes

First of all, it's unclear to me what exactly you want to achieve with this code. Database access, yes, but what benefits should your code provide? Why don't you want to use SqlConnection (or IDbConnection) and its associated classes directly?

Without knowing what sort of abstraction level you want to provide (and why), I think adherence to SOLID principles is a moot point. But here's what I think:

Overall design

It looks like you're taking the 'S' in SOLID a bit too far. Writing a separate class for each possible operation can be useful in certain situations, but here it only seems to complicate things. It also looks like your code doesn't actually work correctly: the SqlConnection returned by SqlOpenConnection.OConnection is never passed to that SqlCloseConnection instance, so how can it close that connection? And why would you need to create a new object to close an existing connection anyway? That's not intuitive.

Note that using a SqlConnection directly allows you to use a using statement, which would result in cleaner (and correct) code. I don't see any added value in those SqlOpenConnection and SqlCloseConnection classes. A single Database class that offers various methods for storing and retrieving data would be less complicated, and still serve a single purpose (database access).

I don't see any code that's using your interfaces (except inside ExecuteComplexCud.ExecuteCommandWithParams, but that seems to be an implementation detail of your library), so it's hard to tell how useful those interfaces really are - and thus how well you're taking the 'I' in SOLID into account.

Exception handling

You don't need to catch an exception if you're just going to throw it.

The type of an exception is a useful piece of information. SqlException indicates that the problem is related to database access. By wrapping that in a generic Exception, calling code is no longer able to distinguish database related exceptions from other exceptions. Wrapping can be useful, for example if you want to hide implementation details. In that case, your library may want to provide its own exception type, such as DatabaseException. Also think about what information the caller wants or needs in order to handle such exceptions.

Other notes

Use methods instead of properties to validate something. Properties are used to store or retrieve information. Using them otherwise will make your code harder to understand and maintain.

Another reason to remove the ValidateConnectionString and ValidateSqlCommand properties is that there doesn't seem to be any reason to store that information - and certainly not in multiple locations (SqlOpenConnection, SqlCloseConnection, ExecuteComplexCud).

Note that validation implies that the syntax or structure of the connection or command string will be checked. A simple null-or-empty check does not live up to that expectation. Either perform a full validation, or just remove those validation methods and use string.IsNullOrEmpty instead. And since the connection and command strings are passed as arguments, it's better to throw an ArgumentException or ArgumentNullException if they're invalid.

OConnection is not a descriptive name. I assume it's short for OpenConnection? If so, SqlCloseConnection.OpenConnection doesn't make any sense.

You may also want to add documentation. Describe the purpose of each interface and method, what input they consider invalid (and how they will react to that), what edge cases need to be taken into account and which exceptions they can throw.

Regarding '//have one function to Insert,Update and delete', do those methods have their own class or interface, or are they part of one of the interfaces you have shown here?

Conclusion

Without knowing the reasoning behind your design decisions, I'd say this code is overly complicated. It's making writing a correct program harder instead of easier. As for SOLID principles, I think there's too little context shown here to determine how well this code is adhering to them.

I hope you found this helpful. Feel free to add more context or explanation to your post if you want to receive more accurate feedback.


It is fine to read event.target in react. In many cases (e.g. finding out which item was clicked) it's the only way to get the data your code needs.

It is generally considered best practice to not change DOM directly, but let react handle have monopoly on DOM changes -> You're good here, you do not change DOM, you only read from it.

Two things that could be improved:

You store the field name in data-field, and later on read it to find out which div is which field. This is not so clean react code.
You read the entire form from event.target, filtering out all divs.

It may work, and it is efficient: react is only triggered after submit is clicked.
But the code is very dependent on the structure of your form in the real DOM. If there is one div to many in your real DOM, then your code breaks down. And to debug, one also needs to understand the tricky real DOM traversal methods (e.g. that a DOM node is not the same as a DOM element).

I would advise to refactor to a react-only solution, making the following changes:

Give your FormWithValidation component state, which stores an array of inputset values (firstname and lastname)
Pass down a this.valueUpdate method, which individual fields can invoke to update state. The method would receive an index (of the input set), a fieldname, and a new value.
Make a single component for a single input field, which can receive the fieldname as a prop.
Give the input field an onBlur handler. Which calls this.props.valueUpdate.

This refactoring has two disadvantages:

it is a lot more code for these simple tasks
react will do a lot more cycles: every time an input field has changed, react will update state and re-render the form (efficiently and only diffs of course)

The big advantage is that all your code and all your logic lives inside the react structure and lifecycle. Which will make your code easier to maintain.


The flatten function will not handle any element other than integer or list. A better and simpler way of handling it is using a predefined function flatten.

import compiler.ast as cmp
flatten = cmp.flatten

>>> flatten([1,2,[3,[4]]])
>>> [1,2,3,4]

Now the size function can be rewritten as :

def size(lst):
    return len(lst) + sum(
        nested_count(l) for l in lst if isinstance(l,list))

I also noticed that you take care of float in transform function and not in (your) flatten function. Please ensure all cases or add catch Exceptions where you expect it.


Send html with nonce for each script and style tag on each request

I am unsure if this is the correct way to do this (set nonces on each get)

Yes, it is

  Remember that nonces must be regenerated for every page request and they must be unguessable.

In terms of best practises, couple of things I'd recommend:

Move your nonce manipulation into it's own middleware
Cache your page content, don't read it from disk every time

The end result would look something like:

csp.js

const path = require('path');
const fs = require('fs');

const cache = new Map();

const getHtml = path => new Promise((resolve, reject) =>
  fs.readFile(path, 'utf-8', (err, contents) => {
    if (err) return reject(err);

    cache.set(path, contents);
    return resolve(contents);
  }));

const csp = page => async (req, res, next) => {
  const pagePath = path.join(dirViews, page);
  let html = cache.get(pagePath);
  if (!html) {
    html = await getHtml(pagePath);
  }
  html = html.replace(/<script/g, `<script nonce="${nonce1}"`)
    .replace(/<style/g, `<style nonce="${nonce1}"`);
  res.send(newHTML);
}

export default csp;

app.js

app.get('/', limiter.middleware(), csp('index.html'))


Tuple unpacking

width = photo1.size[0]  # define W and H
height = photo1.size[1]

can be

width, height = photo1.size

Use input properly

Don't print here:

print("Output file: ", end="")
output = input()

Instead,

output = input('Output file: ')

Range default start

Don't include the 0 in these calls:

for y in range(0, height):  # counts to 1079
    for x in range(0, width):# counts to 1920

Only call pack once

    data += struct.pack("B", R) + struct.pack("B", G) + struct.pack("B",B)

should become, I think,

data += struct.pack('BBB', R, G, B)


Complex dashboard using presenters and/or service objects

There is a lot here and without diving into the pattern based approach, my first question would be have you considered using rails scopes? Maybe that answer is overly simplistic, but using scopes would get rid of a lot of your reporting methods and make you be able to do something like:

Spendings.last_month
Results.last_month

And speaking of Spendings and Results, it sounds like you may want to create a rails class or model for some of these items (like Results and Spendings and Expenses) instead of just querying them from a dashboard view? I have some tableless models in my apps that are used for reporting purposes. It seems like a much cleaner approach than having a long dashboard controller doing the querying for you. In that same vein, another data / reporting centric approach that isn't rails specific is to create reporting tables (these could be rails models) that are divorced from the transactional data just so you aren't querying reports from the live system which can lead to performance hits for both users on the transactional side and the reporting side.

Rails is very "flat" from a traditional 3rd normal form database architecture, so it isn't much work to create reporting tables.... Just some thoughts. Good luck.


Try tracking the current maximum, otherwise frequent occurrences of 3 will push your run time towards \$\mathcal{O}(n^2)\$.

If you take a closer look at what your input actually means, you will notice that smaller values being pushed onto the stack have actually no significance if a greater value has being pushed previously. So for every fill level of the stack, you already know the corresponding maximum at the time you push onto the stack.

Use that knowledge:

current_max = []
for _ in range(int(input())):
    ins = input().split()
    if ins[0] == '1':
        new_max = int(ins[1])
        if current_max and new_max < current_max[-1]:
            new_max = current_max[-1]
        current_max.append(new_max)
    elif ins[0] == '2':
        current_max.pop()
    elif ins[0] == '3':
        print(current_max[-1])

By storing the maximum instead of the raw value on the stack, you can always access the current maximum directly. Just don't forget to handle the special case when data is empty, so the new value will always be the maximum.


Should I use setters with null or no setter when null value?

First off i'm a little confused by what  you are trying to do, and why you are doing this that way. I don't really grasp the full context of what and why you are doing it that way.

IMO since you are returning the same type of person, you don't need a person factory (update). You would need a person factory class if you were returning different types of People. Have a look at the method of polymorphism employed here: https://gist.github.com/BKSpurgeon/db4f8062569181d871f1565c89103e7e notice how we have different types of cities: LondonCity, SanFranCity - they all supply slightly different behaviour, but they are all cities.
setLastName not instance methods within the person class? Please have a look at the code below for what i mean. You probably should make these method private if you don't intend to call them.
"that's a no-no for OOP diehards"

this is what i mean.

# as OOP programmers we don't want to be doing things like this:

if x == 2 THEN do this
If x == 3 THEN do this
if x  == 4 THEN do this.
# As OOP programmers this is all we want to do:
#
cww = ClassWhichDoesWork.new(x)
cww.DoWork()
#
# and then we use a Factory method and polymorphism to supply the correct behaviour.
# we have no conditionals which say if x == 2 THEN do this. all of that is taken care of by polymorphism.
# if you do it that way you code will be very easy to maintain and to make changes, and to test as well.

Here is a gist which is probably how I would structure the above code given my very limited understanding of what you are trying to do


This way your software is highly coupled. I can see three big responsibilities in it:

Get data from db
Format data in "TableModel way"
Create TableModel

Let's create a class to get data. I don't like the idea of let other classes deal with objects from jdbc api, so this class will format data too:

public class TableData {

    public TableContent getData() {
        Vector<String> headers = new Vector<String>();
        Vector<Vector<String>> content = new Vector<Vector<String>>();

        try {
            Connection conn = DriverManager.getConnection("");
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery("Select * from table");

            headers = buildHeaders(rs);
            content = buildContent(rs);

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return new TableContent(headers, content);
    }

    private Vector<String> buildHeaders(final ResultSet rs) throws SQLException {
        Vector<String> headers = new Vector<String>();

        int col = rs.getMetaData().getColumnCount();
        for (int i = 1; i <= col; i++) {
            headers.add(rs.getMetaData().getColumnName(i));
        }
        return headers;
    }

    private Vector<Vector<String>> buildContent(final ResultSet rs) throws SQLException {
        Vector<Vector<String>> content = new Vector<Vector<String>>();

        while (rs.next()) {
            int col = rs.getMetaData().getColumnCount();
            Vector<String> newRow = new Vector<String>(col);

            for (int i = 1; i <= col; i++) {
                newRow.add(rs.getString(i));
            }
            content.add(newRow);
        }
        return content;
    }
}

I've created TableContent just to wrap the result:

public class TableContent {

    private final Vector<String> headers;
    private final Vector<Vector<String>> content;

    public TableContent(final Vector<String> headers, final Vector<Vector<String>> content) {
        this.headers = headers;
        this.content = content;
    }

    public Vector<String> headers() {
        return headers;
    }

    public Vector<Vector<String>> content() {
        return content;
    }
}

Now, the TableModel. That way you don't need to extend the class DefaultTableModel, you can simply instantiate one:

TableContent data = new TableData().getData();
new DefaultTableModel(data.headers(), data.content());

The class TableData still has a problem, the ideal would be to receive the Connection by the constructor, because without it, it's not possible to test the class with unit tests. I didn't wanna make the solution more difficult.


Running code snippets in a background thread

Sorry, didn't have time to look at the issue of preventing the infinite loops, but here is a way to address the printing issue.

Enforce thread-local printing

As you've found, because each thread shares sys.stdout there isn't a good way to redirect printing from distinct threads to distinct streams.
As you discovered, and as is documented, contextlib.redirect_stdout does not work in threaded applications, and has no effect on the output of subprocesses.
However, because you're using Python 3 print is a function, and because Python is a dynamic language, we can (ab)use that.

Consider the following function signature:

def print(*objects, sep='', end='\n', file=sys.stdout, flush=False)

An astute reader may notice that this is Python 3's print function. Suppose we changed it just a little bit, to not use
sys.stdout as the default stream and instead use a thread-local stream. Now we may be tempted to use the builtin threading.local function,
however that will make it hard to recover the output after the fact. Let's start by making a mechanism for getting a thread-local output stream.

thread_local_data = {
    'stdout': {},
    'stderr': {}
}

def register_thread(thread_ident=None):
    """Register a thread with the monitor."""

    thread_ident = thread_ident or threading.get_ident()

    thread_local_data['stdout'][thread_ident] = io.StringIO()
    thread_local_data['stderr'][thread_ident] = io.StringIO()

def unregister_thread(thread_ident=None):
    """Unregister a thread with the monitor."""

    thread_ident = thread_ident or threading.get_ident()

    thread_local_data['stdout'][thread_ident].close()
    thread_local_data['stderr'][thread_ident].close()

def get_thread_stdout(thread_ident=None):
    """Get output stream for a thread."""

    thread_ident = thread_ident or threading.get_ident()
    return thread_local_data['stdout'][thread_ident]

def get_thread_stderr(thread_ident=None):
    """Get error stream for a thread."""

    thread_ident = thread_ident or threading.get_ident()
    return thread_local_data['stderr'][thread_ident]

original_print = print
def print(*objects, sep='', end='\n', file=None, flush=False):
    if file is None or file is sys.stdout:
        file = get_thread_stdout()
    if file is sys.stderr:
        file = get_thread_stderr()

    original_print(*objects, sep=sep, end=end, file=file, flush=flush)

You can test a simplified version of it right from the REPL - notice that we now have a print function in our globals() dict,
where there was not one previously. Then we can see

>>> old_print=globals()['__builtins__'].print
>>> old_print("test")
test
>>> def print(): old_print("I WIN")
...
>>> import pprint
>>> pprint.pprint(globals())
{'__annotations__': {},
 '__builtins__': <module 'builtins' (built-in)>,
 '__doc__': None,
 '__loader__': <class '_frozen_importlib.BuiltinImporter'>,
 '__name__': '__main__',
 '__package__': None,
 '__spec__': None,
 'old_print': <built-in function print>,
 'pprint': <module 'pprint' from 'C:\\Users\\dobermil\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\pprint.py'>,
 'print': <function print at 0x02BD5198>}
>>> exec("print()", globals())
I WIN

Now that we have the mechanism to print as we want to, you just need to make sure you register the thread before starting it. That will setup the thread-local stdout.


Use .format

Using % is considered old style, so:

print("  %5i | %6.3f |  %s  | %i".format(
    (num, time.time() - start, "ox"[ist == mod.SOLL], ist)))

Be generous with long variables names

For example ist is impossible to understand for me, solution is more natural

Don't abuse Code-Golf techniques

The line:

"ox"[ist == mod.SOLL]

is a well known Code-Golf trick that relies on implicit boolean to integer conversion that is equivalent to:

"x" if ist == mod.SOLL else "o"

please use the latter.

Use argparse

C-Style arguments such as sys.argv[1] should be avoided, I suggest argparse (help to get started here: https://stackoverflow.com/questions/7427101/dead-simple-argparse-example-wanted-1-argument-3-results)

Don't shadow built-ins

def run(file = "input/18.dat"):
    # Parse File
    with open(file) as fid:

file is a built-in, you should use file_ in your code.

Explode long lines

Divide the following lines in two please.

 tri = [[int(num) for num in line.split(' ')] for line in fid.read().split('\n')]


KISS (Keep it simple, stupid)
You could've done this way simpler than that by just writing:
string.count(substring)

Wrapping this into a function for later use would look like:
def count_substrings(my_string, my_substring):
    return my_string.count(my_substring)

if __name__ == '__main__':
    print(count_substrings('dexter is dexter lala dext dexter', 'dexter'))

Which will print the desired result:

3

About your code:

You should always have a space around operators (i=0 should be i = 0).
Python is not C. You have way too many parentheses and you shouldn't use ;.

There's something called PEP8 which is the recommended style-guide for Python. I'd strongly recommend you read it.
Your code would look like this if we'd respect the above:
string = input()
substring = input()

count, i = 0, 0
while i < len(string) - len(substring):
    if string.find(substring, i, len(string)) >= 0:
        count += 1
        i = string.find(substring, i, len(string)) + 1
    else:
        break
print(count)

More, I'd let the user know what's about to be entered so I'd write:
my_string = input('Please enter the string: ')
my_substring = input('What substring are you looking for? ')

You should also wrap your code within a function for later use, and add the if __name__ == '__main__' construction, which will allow you you to have that code execute only when you want to run the module as a program, and not have it execute when someone just wants to import your module and call your functions themselves

Anyway, the first solution does not work for overlapping matches (which I saw it was a requirement after reading the challenge), so you might consider doing it like you did, but a bit different / simpler:
def count_substrings(my_string, my_substring):
    count = start = 0
    while True:
        start = my_string.find(my_substring, start) + 1
        if start > 0:
            count += 1
        else:
            return count

The above might be even faster since it does the comparing in C.

Bear with the fact that I've only commented on your actual code, and not the entire challenge. You might wanna add some constraints which are clearly specified there (e.g: 1 <= len(my_string) <= 200)


List all repeated substrings with a fixed length

Styling and readability
You are using a variable length. It is unclear what this variable is, or does, without looking at your explanation in the question. It appears that length is a number which represents the length of the substrings you want to find. I would recommend changing the name of this variable to better represent what it is.
You are using a variable str. When reading this, I expect this variable to be a string, but from your description this function accepts "anything that can be converted into a string". To avoid confusion I would recommend renaming this variable to something that better represents what it contains, such as source.
You are using a variable x which does not describe what it contains.
You check the validity of length, but you do not do this for str. You can check the validity of str with str.toString !== undefined. Instead of a cryptic TypeError (variable.toString is not a function) you can give a better error description.
Javascript processes variable declarations in a context before executing the code. This process is called variable hoisting. This means that when you declare variables in the middle of a function, they are moved to the top. To avoid confusion why variables are defined before you declare them, or why local variables are used when you expected global variables to be used, I would recommend declaring all variables at the beginning of the context.
You are dropping the variable piece into the global scope by forgetting to declaring it with var. This is another reason to declare them at the top!
Logic errors
You have an if-statement in your code that seems to serve no purpose other than causing the result to be incorrect. If the substring you want to find is larger or equal to the length of the data passed, you cannot find repeated substrings. You should remove this if-clause.
if(length > (copy.length / 2))
{
    length = Math.ceil(copy.length / 2);
}

You use the .toString() method on a variable of an unknown type. The result is a string. At a later stage, you request the length of str, which is still of an unknown type. This causes the code to be incorrect when str is not actually a string. This error is likely caused by using a variable name that does not represent the type, which is a good argument why you should use a better name for that variable.
var copy = str.toString();
//...
for(var i = str.length - length - 1; i > 1; i--)

If your string contains reserved words with length length, your code will fail as you experienced. You can work around this by prepending a character such as # in keys. You'll need to remove that character again when you use the key. As far as I am aware, no reserved properties beginning with a # exist in javascript/ES.
Your implementation has two off-by-one errors in the following line. With a length length and a string s, you start your loop at length + 1 before the end of the string, causing you to ignore the last character in s. Your code fails to produce the right result for the string "test.........test", with a substring length of 4. You end your loop with i > 1, and this will cause the code to produce the incorrect result when the substring starting at 0 and the substring starting at 1 are the same. Your code will fail for the string "11111...........". You can safely ignore the substring starting at index 0, because indexOf will always be 0.
for(var i = str.length - length - 1; i > 1; i--)

Note: You use !x[piece], which would fail if it contained a falsy value. Since it contains a value that is guaranteed >= 1 this is not an issue in this case.
Note: Your algorithm will find repeating substrings even if the substrings overlap. I am assuming this is intended behaviour. When substrings overlap copy.split(piece).length - 1 will not be equal to the amount of times the substring appears in the string.
Performance
Your performance tests give a skewed result. The data you passed is highly repetitive, causing more than 99% of your code to skip the indexOf test. If indexOf was implemented in a very naive way, the worst case would need to do (n * n) / 2 comparisons. indexOf seems to be implemented slightly better, but only slightly.

var str = Array(10000000).join("1");
var lookup1 = "2222222222222222";
var lookup2 = "1111111111111112";

console.time( "Lookup 1" );
str.indexOf( lookup1 );
console.timeEnd( "Lookup 1" );
console.time( "Lookup 2" );
str.indexOf( lookup2 );
console.timeEnd( "Lookup 2" );
console.log( "Some lookups are handled quite fast" );

If I execute your code on 10 random string of 100.000 alphanumeric characters, finding substrings of 9 characters, it costs about 2.959 ms per string to find all repetitions. Executing your code on 10 random strings of 200.000 alphanumeric characters, finding substrings of 9 characters, it costs about 11.815 ms. This is significantly worse than "twice as long".
Your code can be easily improved by using hashmaps. Browser vendors use hashmaps to store properties of objects1. Using an object to store found substrings will cost more memory, but will improve performance significantly. For 10 random strings of 100.000 alphanumeric characters, finding substrings of 9 characters, it costs about 126 ms per string to find all repetitions. For 10 random strings of 200.000 alphanumeric characters, finding substrings of 9 characters, it costs about 313 ms per string to find all repetitions. For 10 random strings of 1.000.000 alphanumeric characters, finding substrings of 9 characters, it costs about 1.659 ms per string to find all repetitions.
Testing on your fixed strings will make the improved versions perform worse, because two lookups have to be done instead of one. The difference for random strings is between seconds and several hours.

function getRepetitions(source, substringLength) {
  var copy;
  var piece;
  var output;
  var i;

  if (isNaN(length)) {
    throw new TypeError('length must be a number');
  }

  if (substringLength < 1 || substringLength > 2147483647) {
    throw new RangeError('length must be between 1 and 2147483647');
  }
  if (source.toString === undefined) {
    throw new TypeError('must be able to convert source to string via toString method');
  }

  copy = source.toString();
  output = {};

  for (i = copy.length - substringLength; i > 0; i--) {
    piece = copy.substr(i, substringLength);
    if (!output[piece] && copy.indexOf(piece) !== i) {
      output[piece] = copy.split(piece).length - 1;
    }
  }

  return output;
}

function getRepetitions2(source, substringLength) {
  var copy;
  var piece;
  var output;
  var i;
  var foundSubstrings;

  if (isNaN(length)) {
    throw new TypeError('length must be a number');
  }

  if (substringLength < 1 || substringLength > 2147483647) {
    throw new RangeError('length must be between 1 and 2147483647');
  }
  if (source.toString === undefined) {
    throw new TypeError('must be able to convert source to string via toString method');
  }

  copy = source.toString();
  output = {};
  foundSubstrings = {};

  for (i = copy.length - substringLength; i >= 0; i--) {
    piece = copy.substr(i, substringLength);
    if (!foundSubstrings[piece]) {
      foundSubstrings[piece] = true;
    } else if (!output[piece]) {
      output[piece] = copy.split(piece).length - 1;
    }
  }

  return output;
}

function getRepetitions2WithoutKeywords(source, substringLength) {
  var copy;
  var piece;
  var output;
  var i;
  var foundSubstrings;
  var key;

  if (isNaN(length)) {
    throw new TypeError('length must be a number');
  }

  if (substringLength < 1 || substringLength > 2147483647) {
    throw new RangeError('length must be between 1 and 2147483647');
  }
  if (source.toString === undefined) {
    throw new TypeError('must be able to convert source to string via toString method');
  }

  copy = source.toString();
  output = {};
  foundSubstrings = {};

  for (i = copy.length - substringLength; i >= 0; i--) {
    piece = copy.substr(i, substringLength);
    key = "#" + piece;
    if (!foundSubstrings[key]) {
      foundSubstrings[key] = true;
    } else if (!output[key]) {
      output[key] = copy.split(piece).length - 1;
    }
  }

  return output;
}

function test() {
  //https://stackoverflow.com/a/1349426/2209007
  var possibleChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ';
  var str = '';
  var nrOfTests = 10;
  var strLength = 100000;
  var i;
  var testNr;
  var substrLength = 9;

  console.log('== Testing random strings ==');
  for (testNr = 1; testNr <= nrOfTests; testNr++) {
    str = '';
    console.time('Test ' + testNr + ': Generating string');
    for (i = 0; i < strLength; i++) {
      str += possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
    }
    console.timeEnd('Test ' + testNr + ': Generating string');

    console.log('Test ' + testNr + ': Working with string "' + str.substring(0, 100) + '...\"');

    console.time('Test ' + testNr + ': Default repetitions');
    getRepetitions(str, substrLength);
    console.timeEnd('Test ' + testNr + ': Default repetitions');

    console.time('Test ' + testNr + ': Improved repetitions');
    getRepetitions2(str, substrLength);
    console.timeEnd('Test ' + testNr + ': Improved repetitions');

    console.time('Test ' + testNr + ': Improved repetitions without keywords');
    getRepetitions2WithoutKeywords(str, substrLength);
    console.timeEnd('Test ' + testNr + ': Improved repetitions without keywords');
  }

  console.log('== Testing fixed string ==');
  str = Array(1000001).join("123456789");
  console.log('Test ' + testNr + ': Working with string \"' + str.substring(0, 100) + '...\"');

  console.time('Test ' + testNr + ': Default repetitions');
  getRepetitions(str, 9);
  console.timeEnd('Test ' + testNr + ': Default repetitions');

  console.time('Test ' + testNr + ': Improved repetitions');
  getRepetitions2(str, 9);
  console.timeEnd('Test ' + testNr + ': Improved repetitions');

  console.time('Test ' + testNr + ': Improved repetitions without keywords');
  getRepetitions2WithoutKeywords(str, 9);
  console.timeEnd('Test ' + testNr + ': Improved repetitions without keywords');
}

test();


Fastest sum of absolute values of 32 differences

We can try to optimize the subtraction by looking at the result table and finding a bit level hack that gives us the right result after which a modified bitcount will produce the result.

The table when viewed for each bit pair is:

        00 01 10 11
        0  1  2  3

00 0    0  1  2  3
01 1    1  0  1  2
10 2    2  1  0  1
11 3    3  2  1  0

a^b is almost the right result, only for a=1 and b=2 does this give the wrong result (3 instead of 1).

So that need to be detected and dealt with.

That means that if a&b == 0 and a^b == 3 and both a and b are not 0 then the result should be 1 which we can do by xoring the high bit of the result.

long result = a^b;
long is3 = result & result << 1; //high bit per pair will contain whether the pair is 3
is3 &= 0xaaaa_aaaa_aaaa_aaaal; //extract the high bit per pair
long is0 = a&b;
is0 = ~(is0 | is0 << 1);//high bit per pair will contain whether the pair is 0
is0 &= 0xaaaa_aaaa_aaaa_aaaal; //extract the high bit per pair
long notBoth0 = (a|a<<1) & (b|b<<1);
notBoth0 &= 0xaaaa_aaaa_aaaa_aaaal; //extract the high bit per pair
result ^= is3 & is0 & notBoth0; // only invert the bits set in is3, is0 and notBoth0

The other selection possibility is when the bits in a are not equal:

long result = a^b;
long is3 = result & result << 1; //high bit per pair will contain whether the pair is 3
is3 &= 0xaaaa_aaaa_aaaa_aaaal; //extract the high bit per pair
long isEq = a^(a<<1);
isEq &= 0xaaaa_aaaa_aaaa_aaaal; //extract the high bit per pair
result ^= is3 & isEq0; // only invert the bits set in is3 and isEq0

The modified bitcount would be something like:

result = (result & 0x3333_3333_3333_3333l) + ((result >>  2) & 0x3333_3333_3333_3333l);
result = (result & 0x0f0f_0f0f_0f0f_0f0fl) + ((result >>  4) & 0x0f0f_0f0f_0f0f_0f0fl);
result = (result & 0x00ff_00ff_00ff_00ffl) + ((result >>  8) & 0x00ff_00ff_00ff_00ffl);
result = (result & 0x0000_ffff_0000_ffffl) + ((result >> 16) & 0x0000_ffff_0000_ffffl);
result = (result & 0x0000_0000_ffff_ffffl) + ((result >> 32) & 0x0000_0000_ffff_ffffl);

note: I use underscores in the hexadecimal literals to make it clearer (they are legal in java 7 I believe) however in java 6 you will need to remove them.


Worst case runtime analysis of a string partitioning algorithm

From looking at your code, I'd think it would be \$O(n^2)\$ or \$O(n^3)\$. I got this by:

backTrack() is called n times
backTrack() has a for loop, which is executed m-n times
In that for loop, isPalindrome() is called, which has the complexity of \$O(\frac{r-l}2)\$

Putting it together, I get:

$$O(\frac{n(n+1)(2n+1)}6)$$

I am not sure if I'm right; correct me if I'm wrong.

Since 1, 2, 4, and 6 are not significant, we can remove them, to get:

$$O(n^3)$$

I can't think of a better algorithm, but maybe there is one. I will concentrate on the naming of your variables, and other conventions.

Formatting

All right, time to complain about how bad your formatting is, part by part...

List<List<String>> resultLst;
ArrayList<String> currLst;
public List<List<String>> partition(String s) {
    resultLst = new ArrayList<List<String>>();
    currLst = new ArrayList<String>();
    backTrack(s,0);
    return resultLst;
}
public void backTrack(String s, int l){
    if(currLst.size()>0 //the initial str could be palindrome
        && l>=s.length()){
            List<String> r = (ArrayList<String>) currLst.clone();
            resultLst.add(r);
    }
    for(int i=l;i<s.length();i++){
        if(isPalindrome(s,l,i)){
            if(l==i)
                currLst.add(Character.toString(s.charAt(i)));
            else
                currLst.add(s.substring(l,i+1));
            backTrack(s,i+1);
            currLst.remove(currLst.size()-1);
        }
    }
}
public boolean isPalindrome(String str, int l, int r){
    if(l==r) return true;
    while(l<r){
        if(str.charAt(l)!=str.charAt(r)) return false;
        l++;r--;
    }
    return true;
}

First of all, extra newline between methods. This allows easier readability.

Now, to the first section:

List<List<String>> resultLst;
ArrayList<String> currLst;

public List<List<String>> partition(String s) {
    resultLst = new ArrayList<List<String>>();
    currLst = new ArrayList<String>();
    backTrack(s,0); // Line 7
    return resultLst;
}

My suggestions:

Line 7: Space after comma

Well.. that was easy. Next...

public void backTrack(String s, int l){
    if(currLst.size()>0 //the initial str could be palindrome
        && l>=s.length()){
            List<String> r = (ArrayList<String>) currLst.clone();
            resultLst.add(r);
    }
    for(int i=l;i<s.length();i++){ // Line 7
        if(isPalindrome(s,l,i)){
            if(l==i)
                currLst.add(Character.toString(s.charAt(i)));
            else
                currLst.add(s.substring(l,i+1));
            backTrack(s,i+1);
            currLst.remove(currLst.size()-1);
        }
    }
}

Line 1: Space before brace

Line 2: Space after if
Line 2: Space before and after >, or any other operator, for that matter
Line 2: Usually, though optional, there is a space after // in end-of-line comments

Line 3: It is recommended to use two tabs, or 8 spaces, for a continued line.
Line 3: Again, space before and after all operators.

Line 4-5: Here, it should be 4 spaced.

Line 7: Space after for
Line 7: Space before and after operators, twice
Line 7: Space after semicolons
Line 7: Space before brace

Line 8: Space after if
Line 8: Space before brace
Line 8: Space after commas

Line 9: Space after if
Line 9: Space before and after operators
Line 9: ALWAYS put braced for if statements. I explain it here.

Line 11: Again, ALWAYS put braced for if statements, including else.
Line 11: Space after comma
Line 11: Space before and after operators

Line 12: Space before and after operators
Line 12: Space after comma

Line 13: Space before and after operators
Line 13: Space after comma

Line 14: Space before and after operators

Now that was quite a bit. Notice that most of my suggestions appear over and over and over again.

Next...

public boolean isPalindrome(String str, int l, int r){
    if(l==r) return true;
    while(l<r){
        if(str.charAt(l)!=str.charAt(r)) return false;
        l++;r--;
    }
    return true;
}

Line 1: Space before brace (hey, I just realised it rhymes!)

Line 2: Space after if
Line 2: Space before and after operators
Line 2: Here, I do see a reason why you made it a one-liner. I would usually not do so, but I wouldn't complain if I saw it.

Line 3: Space after while
Line 3: Space before and after operators
Line 3: Space before brace

Line 4: Space after if
Line 4: Space before and after operators
Line 4: Again, I do see a reason why you made it a one-liner.

Line 5: Separate into two lines. I would never put two statements on one line, no matter how related.

Done! Result after formatting:

List<List<String>> resultLst;
ArrayList<String> currLst;

public List<List<String>> partition(String s) {
    resultLst = new ArrayList<List<String>>();
    currLst = new ArrayList<String>();
    backTrack(s, 0);
    return resultLst;
}

public void backTrack(String s, int l) {
    if (currLst.size() > 0 // the initial str could be palindrome
            && l >= s.length()) {
        List<String> r = (ArrayList<String>) currLst.clone();
        resultLst.add(r);
    }
    for (int i = l; i < s.length(); i++) {
        if (isPalindrome(s, l, i)) {
            if (l == i) {
                currLst.add(Character.toString(s.charAt(i)));
            } else {
                currLst.add(s.substring(l, i + 1));
            }
            backTrack(s, i + 1);
            currLst.remove(currLst.size() - 1);
        }
    }
}

public boolean isPalindrome(String str, int l, int r) {
    if (l == r) return true;
    while (l < r) {
        if (str.charAt(l) != str.charAt(r)) return false;
        l++;
        r--;
    }
    return true;
}

Naming

Most of your variable names are not exactly good. Names say what the variable is for, and is not just there to identify a from b. I would suggest:

resultLst -> result
currLst -> currentList
resultLst -> result

In partition():

s -> string or toPartition

In backtrack():

s -> string or toPartition
l -> len or length
r -> list or toAdd

In isPalindrome():

str -> string
l -> from
r -> to

Result:

List<List<String>> result;
ArrayList<String> currentList;

public List<List<String>> partition(String string) {
    result = new ArrayList<List<String>>();
    currentList = new ArrayList<String>();
    backTrack(string, 0);
    return result;
}

public void backTrack(String string, int length) {
    if (currentList.size() > 0 // the initial str could be palindrome
            && length >= string.length()) {
        List<String> list = (ArrayList<String>) currentList.clone();
        result.add(list);
    }
    for (int i = length; i < string.length(); i++) {
        if (isPalindrome(string, length, i)) {
            if (length == i) {
                currentList.add(Character.toString(string.charAt(i)));
            } else {
                currentList.add(s.substring(length, i + 1));
            }
            backTrack(string, i + 1);
            currentList.remove(currentList.size() - 1);
        }
    }
}

public boolean isPalindrome(String string, int from, int to) {
    if (from == to) return true;
    while (from < to) {
        if (string.charAt(from) != string.charAt(to)) return false;
        from++;
        to--;
    }
    return true;
}

Misc

Declare all lists at List<Type>
result and currentList should be private


Why you can't just hardcode cache path calculation?

>>> _hash = '743a0e0c5c657d3295d347a1f0a66109'
>>> def hash2path(_hash):
...     return "%s/%s/%s/%s" % (_hash[0], _hash[1:3], _hash[3:6], _hash)
...
>>> hash2path(_hash)
'7/43/a0e/743a0e0c5c657d3295d347a1f0a66109'

UPDATE: If you really need to pass level array there is a little bit faster version:

def hash2path(_hash, levels):
    prev = 0
    parts = []
    for level in levels:
        parts.append(_hash[prev:prev + level])
        prev += level
    parts.append(_hash)
    return "/".join(parts)


how to properly expose an ES class function residing inside a module?

I'm not aware of any best practice here, so this answer is my own hunch.

I would stick with using an uppercase 'C' for the exported member name.

In JavaScript, the usual protocol is to use an uppercase name for a function that should be new from, rather than called directly e.g.

function Config()

to show that the function should be used with a new call, to treat it as a constructor. e.g.

var config = new Config();

As you are exposing a class from your module, in other words a function that can be new'd up from, then I would stick with using a capital C.


Correctness

1 is not a prime factor:

>>> find_prime_factors(25)
[5, 5, 1]

Performance

Primality testing is expensive.  You call is_prime() twice on every iteration of the main loop of find_prime_factors().  Furthermore, is_prime() performs trial division in much the same way that find_prime_factors() does, resulting in redundant work.


In the code below you must realise that score is a variable that is shared between the threads. Which means that it requires synchronization, as you have omitted this synchornisation you will have undefined behaviour (incorrect result most likely).

for (int i = 1; i <= MAXPLAYER; i++)
    score += player(playersDarts);

OpenMP is not a magic box that will automatically make everything faster. You still need to think about synchronisation and proper algorithms. Also starting a thread does have some overhead and if the work done by the thread is small in comparison to the overhead, then you're slowing the program down.

There are plenty of resources on parallel programming on the internet, I recommend starting with doing your threading manually until you know how it works and then start using tools like OpenMP.


Saving WPF DataGrid changes to Entity Framework

Other issues...

C# variable naming convention is camelCase. And definitely don't start a local's name with an underscore, as underscores are understood to prefix instance variables.
There's no separation of concerns here. Your UI code is talking to the database. That's not the responsibility of the UI.
I assume ApplicationDbContext inherits from DbContext which is implements IDisposable. You're not disposing it. Use it in a using block. (I know nothing about Entity Framework so don't know if there's a good reason not to do so.)


Project Euler #4 - Largest Palindrome Product

The function is_palindrome converts num to a string twice. You might consider:

def is_palindrome(n):
   """Return True if n is a palindrome; False otherwise."""
   s = str(n)
   return s == s[::-1]

And then for the main loop I would write:

from itertools import product
max(x * y for x, y in product(range(1000), repeat=2) if is_palindrome(x * y))

This runs in less than a second so I think it is not worth putting lots of effort into optimizing it.


Convert binary tree to doubly linked list

Naming

I personally prefer a class named Convert for such a task. This would also be more natural because the NET provided converting methods live in a Convert class too.
to be consistent with the NET naming I also would prefer the method be named ToDoubleLinkedListNode()
instead of shortening the name of the node to be returned to res, name it convertedNode
you should name the node which is returned by the recursive calls leftNode or rightNode.

General

by extracting the search for the last Next node which is not null to a separate method, the if..else if..else can be removed.
if you use a guard claus for root.Right == null you save horizontal spacing.
the method should be static, because it doesn't depend on any internal state of the class itself. This makes the constructor obsolete.

Refactoring

After all for above is applied the refactored code looks like

public class Convert
{
    public DoubleLinkedListNode ToDoubleLinkedListNode(TreeNode root)
    {
        if (root == null) { return null; }

        DoubleLinkedListNode convertedNode = new DoubleLinkedListNode { Index = root.Index };

        if (root.Left != null)
        {
            var leftNode = ToDoubleLinkedListNode(root.Left);
            leftNode.Previous = convertedNode;
            convertedNode.Next = leftNode;
        }

        if (root.Right == null) { return convertedNode; }

        var rightNode = ToDoubleLinkedListNode(root.Right);

        DoubleLinkedListNode lastNextNode = FindLastNextNode(convertedNode);
        rightNode.Previous = lastNextNode;
        lastNextNode.Next = rightNode;

        return convertedNode;
    }
    private static DoubleLinkedListNode FindLastNextNode(DoubleLinkedListNode node)
    {
        while (node.Next != null)
        {
            node = node.Next;
        }
        return node;
    }
}


Return all pairs from a list of integers that contributes to a given sum

I see that you are overriding Object.equals(Object) without overriding Object.hashCode(). By doing this, you violate the contract of Object.hashCode() (see the last paragraph in the description of Object.equals(Object)). In fact, the HashSet<Pair> created in your findPairs method might not operate properly due to this.
Since the values of x and y of a Pair instance never change, you could make x and y final, thereby making Pair an immutable class and preventing accidental tampering with the values of x and y.
I don't know if you've considered this, but your code would treat {2,3} and {3,2} as two distinct pairs. Due to how the findPairs method works, it doesn't matter, since it will never create two pairs that only differ in the order of the two numbers, but I thought I'd point it out in case you were not aware of that.
The null check in Pair.equals(Object) is redundant, since null instanceof X, with X being the name of class, will always return false.
if (o instanceof Pair) {
    Pair other = (Pair) o;
    if (other.x == this.x && other.y == this.y) {
        return true;
    }
}
return false;

can be written more concise as:

if (o instanceof Pair) {
    Pair other = (Pair) o;
    return other.x == this.x && other.y == this.y;
}
return false;

new StringBuilder().append("{")

can also be shortened:

new StringBuilder("{")

You don't actually need a Map<Integer, Integer> in findPairs. The mapping of integers to their complement serves no purpose, because the complement of an integer can be simply calculated by subtracting it from the target sum. A Set<Integer> would suffice, since you just use the map to determine whether the complement of a number has already appeared in the sequence of numbers. So findPairs can be re-written as:

public static Set<Pair> findPairs(int inputs[], int targetSum) {
    Set<Pair> results = new HashSet<>();
    Set<Integer> pastNumbers = new HashSet<>();

    for (int number : inputs) {
        int remainingSum = targetSum - number;

        if (pastNumbers.contains(remainingSum)) {
            results.add(new Pair(number, remainingSum));
        } else {
            pastNumbers.add(number);
        }
    }
    return results;
}


If you are careful about it, instead of creating a new PDO instance on every invocation of your script, you can use a persistent connection. Make sure you resolve all transactions through a commit() or rollBack().

To make your connection persistent, just include PDO::ATTR_PERSISTENT => true in your options array when constructing your PDO object.

And now, for a review of your code:

Storing database keys directly in your PHP file is considered bad practice. Generally it's better to put it somewhere outside your web root and require it in, or on Apache, to set appropriate php_values in your .htaccess. Alternatively, and again on Apache, use SetEnv in your httpd.conf.
$utf8 is a misleading name. It actually stores your PDO options. If you extend your options to include PDO::ATTR_PERSISTENT, then the variable name will no longer make sense.
Your query is inefficient. ORDER BY RAND() is slow enough as it is, and you're using it twice! (The third time is over two rows, so that's not a big issue.) Here's an excellent article on quickly selecting random rows in MySQL.
You're doing a SELECT *. It's better to explicitly mention what columns you're using.
If my assumptions are correct, homemade and user_generated have the same columns. I'm not sure this is a good idea; I think it would be better to put them in the same column. Note: as it is, your code will have 50% of picking a user generated pair of values, and 50% of picking a "homemade" pair, regardless of the ratio of user generated to homemade. You'll need to account for that if that's the desired behaviour.
Minor stylistic points: be consistent in spacing around parentheses. Also, catch is typically placed on the same line as the precending }.


You have the right basic idea - pass a list of conditions - but the implementation is wrong.

Yes, you should avoid eval; it is a dangerous source of potential error (and performs poorly as a non-bonus).  You might put anything in there.  You might not even notice a typo which caused nasty side effects, since Python has a very tolerant definition of truth and will be happy as long as the expression evaluates to something.  Instead, why not pass a list of lambda functions? Then you just call each function in turn.  Much safer.

For example, you could build a list of tuples (condition, error message) like this:

conditions = [(lambda: not placeToGo, "Enter a positive integer in the text box"),
(lambda: int(placeToGo) <= 0, "I need a positive integer in the text box please"),
(lambda: not DataStore.DBFILENAME, "There is no data available in the table")]

And then iterate through the list, calling each function in turn.

If you are not familiar with functional programming (in Python or any other language), take a look at this short tutorial


Security: Credentials in ENV

It is less than ideal to store your credentials in environment variables, as they may easily leak.

phpinfo for example will print all environment variables.

Of course, you don't want to allow access to phpinfo to just anyone either, but it may still leak, and not everyone who should be allowed to see phpinfo should be allowed to see the FTP credentials.

Security: Directory Traversal which may lead to Information Leak and Limited DOS

An attacker can delete arbitrary .docx files in arbitrary locations because you never check the input for directory traversal. The problematic code is this:

$forms = Input::get('documents');
[...]
foreach($forms as $doc) {
    unlink("temp/files/$doc.docx");
}

The impact of this is rather small, but depending on what you store on your server, there may be some damage from this.

As you actually know what files are acceptable, you can easily use a whitelist approach here. At a minimum, you should check if the normalized path is inside the root dir.

Alternatively, if you do decide to cache filenames locally (see below), you could simply pass ids to the user instead of filenames, avoiding the problem altogether.

The same problem also exists here:

$forms = Input::get('documents');
[...]
foreach($forms as $doc) {
    ftp_get($ftp_conn,"temp/files/$doc.docx",getenv('FTP_DIRECTORY') . "/$doc.docx",FTP_BINARY);
    $mergeDocs[] = "temp/files/$doc.docx";
}

An attacker could read .doxc files outside of the FTP_DIRECTORY (if the FTP server allows this, and if the local server is writable at the given directory, both rather big ifs, but I would still protect against this).

Security: SSL

Your FTP connection will not be encrypted, meaning that a theoretical man in the middle can intercept your FTP credentials or the transfered files.

This may or may not be a problem for your use-case.

An alternative would be ftp_ssl_connect or using sftp (see also here).

Security/Funktionality: DOS & Performance

From what I can tell, each time I visit the website containing the form that lists files I can join, you open an FTP connection and  retrieve a list of all the files (which may be quite a lot).

A user (or multiple user) may accidentally or on purpose reload the form a bunch of times, causing performance problems.

I would definitely profile this and see what strain it puts on your server. It may make sense to cache the list of docs locally (if it doesn't change that often).

Usability / Bug / Security: File Listing

Your mechanism will hide all files which contain a dot in their filename, which may lead to hard to trace bugs.

Your current mechanism may also have security implications, as files with no extension (for example secret) are listed as well, even though they shouldn't be.

Instead, I would probably use an approach such as this:

Filter out all files that do not have the docx extension
Remove the .docx extension

Naming

You use forms in multiple places as variable name where it doesn't really make sense. The variable doesn't contain multiple forms, but actually multiple document names. This naming also leads to the odd to read foreach($forms as $doc) loop. Instead, you should name name these variables $docs (in mergeDocument, generateForm, and in the view).


main()
You should use if __name__ == "__main__":, like this:
if __name__ == "__main__":
    main()

This will prevent your code from automatically running if you ever import this module into another module.
Methods
I like how you split play_again() into a separate method.  However, you should use more methods, including a unique method to play the game, and perhaps a method to input a guess from the user.
Recursion
Recursion here is not good.  If the user plays the game enough times, you could have a stack overflow exception:
if play_again():
    main()
else:
    print('Bye!')

If you split the game up into multiple methods that you can call, each method could finish and get removed from the stack before it returns control to the caller, so you never have a stack overflow.
An example of this would be to have something like this:
def play_again():
    # code here

def game():
    # play game here

def main():
    print('Welcome to the number guess game!', end='\n\n')

    play_game = True
    while play_game:
        game()
        play_game = play_again()

if __name__ == "__main__":
    main()


updateBuildChart method with a lot of dependencies

The function is named updateBuildChart,
but building a chart seems a very tiny part of all its responsibilities.
If we kept only what its name implies and removed everything else:

function updateBuildChart(ChartBuilder) {
    var currentReports = $scope.$parent.reports;
    if (currentReports.length > 0) {
        ChartBuilder.buildChart(currentReports);
    }
}

However,
without seeing all your code,
it's hard to advise.
Mainly,
it's not clear if the statements in the function have side effects or not.
So I'm just going to go over line by line and ask you some questions that might help you clean up this thing.

The function starts with using Filter and ends with using Filter,
and it doesn't use it anywhere in between:

Filter.clearFilters();

// ...

Filter.setReports(self.currentReports);

Does this ordering matter?
Will your program still work if you move the Filter.setReports call right after Filter.clearFilters?
If not, then these calls will be good to group together.

It will be even better if you move them to a dedicated function whose responsibility is to clear filters and set the reports,
perhaps something like resetFilters(Filter).

And move the call to this new function outside of updateBuildChart,
where it really doesn't belong.

What is this for?

this.currentReports = $scope.$parent.reports;

Is it just to be a shortcut for $scope.$parent.reports in the rest of the function, or will this have a side effect outside this function?
If it's the first case, then it would be better to use var currentReports = instead.

PagerFactory is only referenced in one place:

$scope.pager = PagerFactory.Create({
    items: this.currentReports
});

Similar to the treatment of Filter earlier,
it would be better to move this into a dedicated function,
say updatePager, and call it outside of this function.

What is this for?

this.originalReports = angular.copy(this.currentReports);

Since this.originalReports is not referenced again within the function,
it would seem that this produces a side effect outside the function.
Or else, it's pointless and should be deleted.

The only references to LimitsManager:

LimitsManager.calcFteLimits();

What is it doing there in the middle of the function?
Does it need to be in the middle?
Can it be at the start or at the end?
Or does it have a side effect that makes a difference for the code that appears before or after it?

If the code dealing with ChartBuilder is moved out to its own method,
then this part can be simplified:

if (this.currentReports.length > 0) {
    $scope.showGraph = true;
    ChartBuilder.buildChart(this.currentReports);
} else {
    $scope.showGraph = false;
}

To this:

$scope.showGraph = this.currentReports.length > 0;

If I make the optimistic and possibly completely false assumption that the statements in the function produce no side effects,
I would replace it with this code:

function updateCharts(ChartBuilder) {
    var currentReports = $scope.$parent.reports;
    if (currentReports.length > 0) {
        ChartBuilder.buildChart(currentReports);
        $scope.showGraph = true;
    } else {
        $scope.showGraph = false;
    }
}

function updateFilters(Filter) {
    Filter.clearFilters();
    Filter.setReports($scope.$parent.reports);
}

function updatePager(PagerFactory) {
    $scope.pager = PagerFactory.Create({
        items: this.currentReports
    });
}

function updateLimits(LimitManager) {
    LimitsManager.calcFteLimits();
}

Once again,
this decomposition is only useful if these functions really don't have side effects, which only you can tell.
If they have side effects, then the order in which you call them might matter.
In that case, you should at least document it.
A better solution would be to reorganize the code to convert the side effect to direct effect, visible in the code.


String s = "-9846032";
char[] ch = s.toCharArray();
int len = s.length();
int val = atoiFunc(s,ch,len);

How come you chose to do it this way? In general, you shouldn't pass every permutation of a value into a function. If the function wants s.toCharArray, it can call it itself.

Imagine if we did the following:

String s = "-9846032";
char[] ch = "abcdef".toCharArray();
int len = "lololololololololol".length();
int val = atoiFunc(s,ch,len);

What does that even mean? To protect yourself from such nonsense and to make your API easier to understand, we should remove them. If you remove them, it means that your function can be called as such:

int val = atoiFunc("12345678")

which is much more preferable.

//If the length is 0,the function returns 0;
if(l==0){
    return 0;
}

What happens if l is -1? Or any other negative number? What happens if l is e.g. 12? Can you convert a 12 digit number to an int?

Importantly: How does someone differentiate atoiFunc("0") from atoiFunc("") ?

//variable to store the result
int res = 0;
//variable to check for the sign.Initially,initially with positive 1.
int sign = 1;

"variable to" is superfluous -- we already know they're variables :)

// try/catch block to check the bounds of Integer datatype.
try{
    int check = Integer.valueOf(str);
}
catch(NumberFormatException e){
    System.out.println("Number is going out of bounds of integer
           datatype.");
    System.exit(0);
}

What is the use in this?

Integer.valueOf converts a string to an integer. It does exactly what you're already trying to do!

So therefore I assume this exercise is some kind of study/homework? In which case relying on Integer.valueOf is a massive cop-out, and probably against the spirit of the code. I can see you're using it as a bounds check. But there are other, better ways to do that that will actually a) teach you something and b) not rely on a function that already does what your function is trying to do :)

If we go back to this comment you made:

  I have written this code to check all the edge cases in the implemention of an atoi() function.Please review.

Then we can see that you haven't checked anything! checkInt does it all for you! It's basically cheating :P So please remove that part of the code and try to think up a proper way to check the conditions checkInt is catching.

(Note: If this isn't a study piece, then the entire program should be replaced by a call to Integer.valueOf or even Integer.parseInt :))

for(int i=0; i<l; i++){

almost all style guides ask for a bit of space around binary operators:

for (int i = 0; i < l; i++){

It's hard to critic the loop, as I would like to say things such as "What happens if a character is a letter?", but it's hard to say that because of the checkInt cheat in the way, which protects you. So I'll comment more after you've fixed the code to remove that!

Here are some more tests for your function, however:

 assert 1234 == atoiFunc("1234")
 assert -1234 == atoiFunc("-1234")
 assert 0 == atoiFunc("0")

 atoiFunc("") # should raise an error
 atoiFunc(null) # should raise an error
 assert 0 == atoiFunc("+0")
 assert 0 == atoiFunc("-0")

 atoiFunc("1234abc") # should raise an error
 atoiFunc("abc1234") # should raise an error
 atoiFunc("12    34") # should raise an error
 assert 1234 == atoiFunc("+1234")
 atoiFunc("+12+34") # should raise an error
 atoiFunc("12-34") # should raise an error
 atoiFunc("1234+") # should raise an error
 atoiFunc("-1234+") # should raise an error
 atoiFunc("+1234-") # should raise an error
 atoiFunc("1234-") # should raise an error
 atoiFunc(" 1234 ") # should maybe raise an error. up to you.

 int x = atoiFunc("4294967296") # I'll let you figure this one out :)
 int y = atoiFunc("4294967297") # I'll let you figure this one out :)
 int z = atoiFunc("-4294967296") # I'll let you figure this one out :)
 int w = atoiFunc("-4294967297") # I'll let you figure this one out :)


Switch statement decreases adaptability of a function

I fixed it by myself by introducing abstract classes, see below:
class Product {
    private int $id;
    private string $name;
    private int $price;
    private Category $category;

    public function __construct(int $id, string $name, int $price, Category $category) {
        $this->id = $id;
        $this->name = $name;
        $this->price = $price;
        $this->category = $category;
    }
    public function getId(): int
    {
        return $this->id;
    }
    public function getName(): string
    {
        return $this->name;
    }
    public function getPrice(): int
    {
        return $this->price;
    }
    public function getCategory(): Category
    {
        return $this->category;
    }
}

here it goes
abstract class Category {
    abstract public function calculateTax(int $price): float;
}
class CategoryFurniture extends Category {
    public function calculateTax(int $price): float {
        return (float)($price / 100 * 21);
    }
}
class CategoryFood extends Category {
    public function calculateTax(int $price): float {
        return (float)($price / 100 * 9);
    }
}

//$product = new Product(200, 'Bread', 200, new CategoryFood);
$product = new Product(100, 'Chair', 5000, new CategoryFurniture);

$taxForChair = calculateTax($product);
var_dump($taxForChair); // float 1050
exit;

function calculateTax(Product $product): float {

    $price = $product->getPrice();

    $category = $product->getCategory();
    return $category->calculateTax($price);
}


Your CountPrimes function wrongly returns 3 (instead of the correct answer 0) when given the input {982081, 988027, 994009}. Can you see why?

Once you get down into dozens-of-milliseconds time ranges, it makes sense to increase the size of your test case so that you can distinguish real algorithmic improvements from noise. I recommend using 10,000,000 integers in your vector instead of 100,000, so that your runtimes are back up in the whole numbers of seconds instead of faster-than-human-reaction-time. A change that takes your runtime from 3.5 seconds to 1.5 seconds is vastly more likely to be a real optimization than a change that takes your reported runtime from 75 milliseconds to 20 milliseconds.

seed_seq seed{ 2016 };
default_random_engine generator{ seed };
uniform_int_distribution<int> distribution(100000, 999999);

Global variables are evil. In this case, these variables are used only by main; so you should make them local to main. (If you still wanted them to be statically allocated instead of stack-allocated, you could qualify them with static; but protip: there's no reason to do that.)

int CountPrimes(unique_ptr<vector<int>> const &samples)

Stylistically, most C++ programmers would write this as

int CountPrimes(const std::unique_ptr<std::vector<int>>& samples)

(having internalized the advice that using namespace std; is a bad habit, and finding const X& easier to read than X const &). Your mileage may vary.

However, definitely you should not be using unique_ptr here. You have three indirections here where only one is needed:

The actual data is in a buffer on the heap...
which is pointed to by a pointer wrapped in a std::vector...
which is pointed to by a pointer wrapped in a std::unique_ptr...
which is pointed to by the reference argument to CountPrimes.

Instead of all this indirection, I recommend either the "standard" two levels of indirection:

int CountPrimes(const std::vector<int>& samples)

or if you can use the C++ Core Guidelines support library, you could dispense with one more level:

int CountPrimes(gsl::span<int> samples)

Anyway, get rid of that unique_ptr. It's not buying you anything. And as a good rule of thumb: passing any kind of smart pointer by reference is just as much of a code smell as passing a core-language pointer by reference. If you find yourself doing it, something is probably wrong with your design!

int numPrimes{};

is IMHO a needlessly convoluted way to write

int numPrimes = 0;

Likewise,

int n{ 2 };
if (sample % n == 0)
{
    isPrime = false;
}

is IMHO a needlessly complicated way to write

if (sample % 2 == 0) {
    continue;
}

When you know the input isn't prime, any further work you do after that point is wasted. Don't spend time looping on m if you're just going to throw that work away in the end.

If I were writing this code, I'd make a helper function bool IsPrime(int x) that just returns true if x is prime; and then my CountPrimes function could be

int CountPrimes(const std::vector<int>& v)
{
    int result = 0;
    for (auto&& x : v) {
        if (IsPrime(x)) ++result;
    }
    return result;
}

Notice the complete lack of goto, break, or continue in this program; that is, I'm enabling the use of structured programming by breaking my code down into subroutines.

The only reason not to arrange your program logically in this way is if you expect to get some benefit from logically arranging the computations a different way. For example, maybe we could exploit SSE vectorized instructions to do the computation four times faster, something like this:

int CountPrimes4x(const int *abcd)
{
    // use some _mm_... intrinsics or something
}

int CountPrimes(const std::vector<int>& v)
{
    int result = 0;
    assert(v.size() % 4 == 0);
    for (size_t i=0; i < v.size(); i += 4) {
        result += CountPrimes4x(&v[i]);
    }
    return result;
}

Problem is, there's no fast integer division instruction on x86, so we might not come up with anything better than the plain old (slow) (non-vectorized) integer division we started with.


PHP function to evaluate comparisons between two values, with debug logging

given your function's purpose is to return the calculation result, I would return the expression result right away, especially given return makes break unnecessary as well

private function performComparison($operator, $value_allowed, $value_entered)
{
    switch($operator) {
        case '>':
            return ($value_entered >  $value_allowed);
        case '>=':
            return ($value_entered >= $value_allowed);
        case '<':
            return ($value_entered <  $value_allowed);
        case '<=':
            return ($value_entered <= $value_allowed);
        case '=':
            return ($value_entered == $value_allowed);
        default:
            throw new InvalidArgumentException("Invalid operator");
    }
}

The code above is both concise and readable, it takes one no problem to gist the function's meaning and purpose.

Whereas any debugging should be done elsewhere. If you need any debugging for this function, create another one encapsulating the current function's call.

    private function debugPerformComparison($element, $operator, $value_allowed, $value_entered)
    {
        $result = $this->performComparison($operator, $value_allowed, $value_entered);
        $dateformat = 'n/j/Y';
        $debug = [
            'element' => $element,
            'operator' => $operator,
            'value allowed' => is_a($value_allowed, 'DateTime') ? $value_allowed->format($dateformat) : $value_allowed,
            'value entered' => is_a($value_entered, 'DateTime') ? $value_entered->format($dateformat) : $value_entered,
            'result' => $result,
        ];
        echo '<pre>'.var_export($debug,1).'</pre>';
        return $result;
    }

Regarding anonymous function-based version, a concise version shouldn't be less readable in the first place. Any code improvements should improve the readability, by means of removing unnecessary parts, not worsen it. And the said version is extremely hard to read.


Printing chessboard with *(asterisk) and .(dot)

Your current code limits the number of rows/columns to a single integer. Is this desired behavior?

For clarity sake, I would probably generate the even/odd rows and then print each until you have printed enough rows

Function to specify the input

def get_int_digits(l):
    try:
        inp = input()
    except SyntaxError:
        print "You did not enter anything"
        return 0
    if type(inp) != int:
        print "You did not enter an integer."
        return 0
    if l is not None and len(str(inp)) != l:
        print "You did not enter the correct number of digits."
        print "{} digits expected.".format(l)
        return 0
    return inp

Function to output the "board"

def print_board(row, column):
    even_string = ("*." * (column // 2 + 1)) [0:column]
    odd_string = (".*" * (column // 2 + 1)) [0:column]

    for i in xrange(row):
        print odd_string if i % 2 else even_string

Driver

if __name__ == __main__:
    cases = get_int_digits(None)
    for i in xrange(cases):
        row_col = get_int_digits(2)
        print_board(row_col // 10, row_col % 10)


Caesar and Vigenère ciphers in Haskell the simple way

My issue with both your ciphers is that they don't preserve whitespace. Even for a lower-case only string, the following property does not hold:

unCaesar n (caesar n xs) == xs

Indeed, only the following property holds:

let xs' = unwords (words xs) in unCaesar n (caesar n xs') == xs'

But that might be your design, so let us ignore that for now. Instead, let us have a look at your first cipher.

Caesar

The nice property about Caesar is that you can encrypt the same way you decrypt. If you move a character n characters forward, how many characters do you need to move it to get back the original one? 26 - n.

With that in mind, we can heavily reduce the size of unCaesar:

unCaesar :: Int -> String -> String
unCaesar n = caesar (26 - n)

We could also use caesar (-n) since we're using mod, but that's not important. It would fail if we used rem, though.

Now that we've reused unCaesar, let us have a look at caesar:

caesar :: Int -> String -> String
caesar n s = unwords $ map (map chr) coded
  where
    coded = map (map helper) $ words s
    helper = (+) base . flip mod 26 . (+) n . flip (-) base . ord . toLower
    base = ord 'a'

Point-free programming isn't always best practices. It's clever, but you really don't want to fix something like that in the middle of the night. Compare your code to

caesar :: Int -> String -> String
caesar n s = unwords $ map (map chr) coded
  where
    coded    = map (map helper) $ words s
    helper c = (ord (toLower c) - base + n) `mod` 26  + base
    base     = ord 'a'

It is even shorter. It is easier to read than the point-free version, too. No flip. But if we want to preserve whitespace, it is still not optimal. Since we're handling a single character in helper either way, let us just keep spaces and handle all other characters:

caesar :: Int -> String -> String
caesar n = map helper
  where
    helper ' ' = ' '
    helper c   = chr $ (ord (toLower c) - base + n) `mod` 26  + base
    base       = ord 'a'

We've lost all applications of unwords and words, and instead of the map (map …) we only have a single map.

Being able to advance a lower-case ASCII character seems somewhat important, so let us refactor that:

caesar :: Int -> String -> String
caesar n = map helper
  where
    helper ' ' = ' '
    helper c   = asciiAdvance n c

asciiAdvance :: Int -> Char -> Char
asciiAdvance n c = chr $ (ord (toLower c) - base + n) `mod` 26  + base
  where
    base = ord 'a'

We will revisit Caesar later.

Vigenère

First of all, let us apply the point-free to non-pointfree conversion and use pattern-matching in assign:

vigenere :: String -> String -> String
vigenere k s = unwords $ map (map chr) coded
  where
    coded      = zipWith (zipWith helper) (words s) (words $ assign s 0)
    helper x y = base + mod (diff (toLower x) + diff (toLower y)) 26
    base       = ord 'a'
    diff c     = ord c - base

    assign ""     _ = ""
    assign (x:xs) i
        | x == ' '  = ' '      : assign xs i
        | otherwise = (k !! i) : assign xs (mod (i + 1) (length k))

Hm. assign just cycles through k and skips spaces. We can implement it without length and !! if we hand it two lists: our secret, and our cycled key:

vigenere k s = unwords $ map (map chr) coded
  where
    coded      = zipWith (zipWith helper) (words s) (words $ assign s (cylce k))
    …
    assign ""     _      = ""
    assign (x:xs) (y:ys)
        | x == ' '  = ' ' : assign xs (y:ys)
        | otherwise = y   : assign xs ys

But for a second, let us again say that you want to keep the whitespace. How would that look like?

vigenere :: String -> String -> String
vigenere k s = map chr coded
  where
    coded          = zipWith helper s (assign s (cycle k)
    base           = ord 'a'
    diff c         = ord c - base

    helper ' ' ' ' = ' '
    helper x   y   = base + mod (diff (toLower x) + diff (toLower y)) 26

    assign ""     _ = ""
    assign (x:xs) i
        | x == ' '  = ' '      : assign xs i
        | otherwise = (k !! i) : assign xs (mod (i + 1) (length k))

Hm. zipWith helper and assign have the same type. Maybe we can fuse them?

vigenere :: String -> String -> String
vigenere k s = map chr $ helper (cycle k) s
  where
    base   = ord 'a'
    diff c = ord c - base

    helper _      []     = []
    helper (y:ys) (x:xs)
      | x == ' '  = ' '          : helper xs (y:ys)
      | otherwise = modify x y   : helper xs ys

    modify x y = base + mod (diff (toLower x) + diff (toLower y)) 26

In order to share code between vigenere and unVigenere, we need one last step. Let us change modify's type to Char -> Char -> Char:

vigenere :: String -> String -> String
vigenere k s = helper (cycle k) s
  where
    base   = ord 'a'
    diff c = ord c - base

    helper _      []     = []
    helper (y:ys) (x:xs)
      | x == ' '  = ' '          : helper (y:ys) xs
      | otherwise = modify x y   : helper ys     xs

    modify x y = chr $ base + mod (diff (toLower x) + diff (toLower y)) 26

If we rewrite unVigenere the same way, we'll notice that it looks very similar:

unVigenere :: String -> String -> String
unVigenere k s = helper (cycle k) s
  where
    base   = ord 'a'
    diff c = ord c - base

    helper _      []     = []
    helper (y:ys) (x:xs)
      | x == ' '  = ' '          : helper (y:ys) xs
      | otherwise = modify x y   : helper ys     xs

    modify x y = chr $ base + mod (diff (toLower x) - diff (toLower y)) 26

Note that I've used the properties of mod again, just as in Caesar.

Everything is the same. Except for the modification. In unViginere, we subtract the key, and in vigenere we add it. So let us move that into another function:

withKey :: (Char -> Char -> Char) -> String -> String -> String
withKey f k s = helper (cycle k) s
  where
    helper _      []     = []
    helper (y:ys) (x:xs)
      | x == ' '  = ' '   : helper (y:ys) xs
      | otherwise = f y x : helper ys     xs

vigenere :: String -> String -> String
vigenere = withKey modify
  where
    modify k v = asciiAdvance (ord k - ord 'a') v

unVigenere :: String -> String -> String
unVigenere = withKey modify
  where
    modify k v = asciiAdvance (26 - (ord k - ord 'a')) v

And we're done.


Removing image records if no physical file exists

The mysql_* functions are deprecated.  Use mysqli or PDO instead.

Each query that you issue has a rather large overhead: you have to communicate the query to the server; the server has to parse, plan, and execute the query; the results have to be returned to your application.  Therefore, you want to avoid running any query in a loop.  You're much better off executing fewer complex queries than many simple queries.

First, note that your $query1 has a bug: AND has higher precedence than OR, so you need parentheses.  Also, you eventually ignore any column named …backup, so you might as well filter those out immediately.

SELECT TABLE_NAME AS table_name, COLUMN_NAME AS image_col
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE
        TABLE_SCHEMA = 'schemaname'
        AND TABLE_NAME NOT LIKE '%backup%'
        AND (COLUMN_NAME LIKE '%image%' OR COLUMN_NAME = 'video');

Let's clarify the naming.

Your $row1[0] is what I call table_name
Your $row1[1] is what I call image_col

Notionally, you want to execute this query for each result returned by that $schema query.

UPDATE `$schema['table_name']`
    SET `$schema['image_col']` = ''
    WHERE
        `$schema['image_col']` != '' AND `$schema['image_col']` IS NOT NULL
        AND `$s['image_col']` NOT LIKE '%facebook%'
        AND NOT file_exists('$img_root/$schema['image_col']')

Of course, there are two problems with that idea:

There is no file_exists() function in MySQL (and furthermore, if such a function existed, it would be wrong to run it on the database server rather than on the application server, since they could be on different machines with different filesystems).
You have to execute many UPDATEs, not just one.  Furthermore, the UPDATE queries are dynamic — the table and column names vary.

This is a strong indication that your database schema is poorly designed.  There should not be a proliferation of tables!  You should also not be doing version control or backups by creating tables named …backup.  I encourage you to follow up with these issues on http://dba.stackexchange.com.

A solution to the first problem is to create a temporary table that lists all images on your website's filesystem, then write the UPDATE with an anti-join.

$db = new mysqli(…);
$db->query('CREATE TEMPORARY TABLE fs_images ( filename VARCHAR(128) PRIMARY KEY );');
$ins = $db->prepare('INSERT INTO fs_images VALUES (?)');
$file_it = new RecursiveDirectoryIterator($img_root);
foreach (new RecursiveIteratorIterator($file_it) as $f) {
    $ins->bind_param('s', basename($f));
    $ins->execute();
}
$ins->close();

A solution to the second problem is to use a stored procedure with a loop that executes dynamically composed SQL queries with a cursor.

DELIMITER $$
CREATE PROCEDURE clear_images()
BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE table_name VARCHAR(64);
    DECLARE image_col VARCHAR(64);

    DECLARE schema_cursor CURSOR FOR
        SELECT TABLE_NAME AS table_name, COLUMN_NAME AS image_col
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE
                TABLE_SCHEMA = 'schemaname'
                AND TABLE_NAME NOT LIKE '%backup%'
                AND (COLUMN_NAME LIKE '%image%' OR COLUMN_NAME = 'video');
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    OPEN schema_cursor;
    schema_loop: LOOP
        FETCH schema_cursor INTO table_name, image_col;
        IF done THEN
            LEAVE schema_loop;
        END IF;

        PREPARE stmt FROM CONCAT(
            'UPDATE `', @table_name, '`',
            '    SET `', @image_col, '` = ''''',
            '    WHERE',
            '        `', @image_col, '` != '''' AND `', @image_col, '` IS NOT NULL',
            '        AND `', @image_col, '` NOT LIKE ''%facebook%''',
            '        AND `', @image_col, '` NOT IN (SELECT filename FROM fs_images);'
        );
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END LOOP;
END$$
DELIMITER ;

Anyway, this solution is rather nasty (and untested!) — all as a result of your poor database schema design.


Using generator for buffered read of large file in Python

You called it unbuffered, but these lines:

with open(infile) as f:
    lines = f.readlines()
    f.close()

slurp the entire file into memory, while your 'buffered' version only pulls in a line at a time, returning chunks.

I note that you're not doing anything with the entire chunk, just the lines starting with 'productNumber:', so I think a rework of your 'unbuffered' code will actually be fastest, as well as clearest:

def get_products_unbuffered(infile):
    products = []
    with open(infile) as f:
        for line in f:
            if line.startswith('productNumber:'):
                 productNumber = line[len('productNumber:'):].strip().rstrip(';').strip('"')
                 products.append(productNumber)
    return products

as this will read the file a line at a time and only keep desired info (productNumbers) in memory..


Better way to un-define a set of defines based on version numbers in C++?

While it's somewhat uncertain whether you'll like it (some compilers warn about doing so) it's entirely permissible to #undef a value that wasn't defined to start with, so you can consolidate these down to something like:

#if OPENGL_TARGET_VERSION < 44
    #undef GL_VERSION_4_4
#endif

#if OPENGL_TARGET_VERSION < 43
    #undef GL_VERSION_4_3
#endif

#if OPENGL_TARGET_VERSION < 42
    #undef GL_VERSION_4_2
#endif

#if OPENGL_TARGET_VERSION < 41
    #undef GL_VERSION_4_1
#endif

While this does (or at least sort of might) answer the question you asked, from a code review standpoint, I'd probably prefer the code as it's written in the question. It's longer, but:

it's almost certainly hidden in a header almost nobody really reads through very often
it's simple repetitions of a simple pattern, so reading it isn't much work,
eliminating the #ifdef will give warnings with some compilers

While I think that's a pretty stupid warning, eliminating the warning is still worth more than reducing the line count.


6174 is Kaprekar Constant, I don't know why you're using it as an
input argument  while it should be within the method. So, you'll only
need to pass one int argument.
there is no need to call ToString to get the length of the integer.
You can check the integer range instead. So, this num.ToString().Length != 4 can be converted to num >= 1000 && num <= 9999.
using LINQ is fine, but in your case, I don't see a need of that. As you have fixed input length (4 digits), you can simply converted to string, then just do str[index] where the index would be a range of 0 to 3.
why are you using while(true) while you could enforce kaprekar's
constant condition by using while(diff != 6174).
No need for recursive method.

here is a standard version :

int KaprekarsConstant(int num)
{

    // zero == zero
    if (num == 0) { return 0; }

    // if num is not between 1000 and 9999 throw exception
    if(num >= 1000 && num <= 9999) { throw new ArgumentException(); }

    // will be used inside the loop
    var diff = num;

    // number of repeatation
    var numberOfRepeatation = 0;

    do // do it at least once.
    {
        //to array
        var digitsAsc = new int[4];

        for (var x = 0; x < 4; x++)
        {
            digitsAsc[x] = diff % 10;
            diff /= 10;
        }

        // sort the elements in the array to ascendent order
        Array.Sort(digitsAsc);

        //now, digitsAsc array is in ascedent order, we will resorted into descendent order
        var digitsDesc = new int[4];

        for (var x = 0; x < 4; x++)
        {
            digitsDesc[x] = digitsAsc[3 - x];
        }

        // convert them to int
        var asce = int.Parse(string.Join(string.Empty, digitsAsc));

        var desc = int.Parse(string.Join(string.Empty, digitsDesc));

        diff = desc - asce;

        numberOfRepeatation++;

    }
    while (diff != 6174);

    return numberOfRepeatation;
}

if you're into LINQ, here is LINQ version :

int KaprekarsConstant(int num)
{
    // zero == zero
    if (num == 0) { return 0; }

    // if num is not between 1000 and 9999 throw exception
    if(num >= 1000 && num <= 9999) { throw new ArgumentException(); }

    // will be used inside the loop
    var diff = num;

    // number of repeatation
    var numberOfRepeatation = 0;

    do // do it at least once.
    {
        //to ascedent array
        var digitsAsc = Array
            .ConvertAll(diff.ToString().ToCharArray(), x => (int)char.GetNumericValue(x))
            .OrderBy(x=>x)
            .ToArray();

        //now, digitsAsc array is in ascedent order, we will resorted into descendent order by calling Reverse;
        var digitsDesc = digitsAsc.Reverse().ToArray();

        // convert them to string (this is similar to string.Join)
        var asce = digitsAsc
            .Aggregate(new StringBuilder(), (x, y) => x.Append(x.Length == 0 ? string.Empty : string.Empty).Append(y))
            .ToString();

        var desc = digitsDesc
            .Aggregate(new StringBuilder(), (x, y) => x.Append(x.Length == 0 ? string.Empty : string.Empty).Append(y))
            .ToString();

        diff = int.Parse(desc) - int.Parse(asce);

        numberOfRepeatation++;

    }
    while (diff != 6174);

    return numberOfRepeatation;
}