Am I approaching this ASP.Net MVC/Entity Framework pattern incorrectly?

Here is a link to the "official" tutorial on basic CRUD operations in ASP.NET MVC and EF.

The main difference is the validation checking, and the exception handling.  I recommend adding in the validation, and possibly the exception handling if you need it.  Don't randomly swallow exceptions and show the user some generic error message.

Other than that, they use a slightly different way of letting EF know about the entity to be updated, but I think they're accomplishing the same thing. I think the functional difference is that you are only posting back the necessary data to be updated, and having EF get the entity and update it with those changes for you. With their method, I think that they are posting back the entire entity, and having EF "reattach" the entity and mark it as modified.

So I think the differences in the update code boil down to partial vs. full entity updates.

Side Note 1

I like your way better.  In their case they are relying on the end user to postback the entire entity.  While that is a basic demo, using this method blindly opens up your application to vulnerabilities where people can update any field they want, even if the field doesn't appear in the HTML form (Think of an "IsAdmin" flag). I believe that this is known as a Mass Assignment vulnerability that bit Rails and Github last week! (Source: https://github.com/blog/1068-public-key-security-vulnerability-and-mitigation)

Side Note 2

About the comments and the LINQ syntax... I also like the expression syntax a little more, at least for short, small queries.  But when doing joins in the past, I've gone with the query syntax.  Just a personal preference.  Here is what the code would look like with the LINQ expression syntax (as opposed to the query syntax):

db.centres
    .Join(...)
    .Where(c => c.id == id)
    .Select(new CentreViewModel
        {
            CentreId = c.id,
            CentreName = c.Name,
            etc...
        };


This looks like something that can get optimized to a mathematical function.

Let's run it pass by pass and try to interpret the result.

  N = 12

  Doors #1 through #12

Pass 1:  1 1 1  1 1 1  1 1 1  1 1 1 //All opened
Pass 2:  1 0 1  0 1 0  1 0 1  0 1 0 //2, 4, 6, 8, 10, 12 closed
Pass 3:  1 0 0  0 1 1  1 0 0  0 1 1 //3 and 9 closed, 6 and 12 opened
Pass 4:  1 0 0  1 1 1  1 1 0  0 1 0 //4 and 8 opened, 12 closed
Pass 5:  1 0 0  1 0 1  1 1 0  1 1 0 //5 closed, 10 opened
Pass 6:  1 0 0  1 0 0  1 1 0  1 1 1 //6 closed, 12 opened
Pass 7:  1 0 0  1 0 0  0 1 0  1 1 1 //7 closed
Pass 8:  1 0 0  1 0 0  0 0 0  1 1 1 //8 closed
Pass 9:  1 0 0  1 0 0  0 0 1  1 1 1 //9 opened
Pass 10: 1 0 0  1 0 0  0 0 1  0 1 1 //10 closed
Pass 11: 1 0 0  1 0 0  0 0 1  0 0 1 //11 closed
Pass 12: 1 0 0  1 0 0  0 0 1  0 0 0 //12 closed

It's a factor detector!

It detects whether for each positive integer \$N\$ or lower whether its divisible an even or uneven amount of times by its possible factors.

That is, 12 can be factorized as \$1\times 12\$, \$2\times 6\$, \$3\times 4\$, \$4\times 3\$, \$6\times 2\$, \$12\times 1\$. That's even, so the door ends up at 0, which is closed. 9 can be factorized as \$1\times 9\$, \$3\times 3\$ and \$9\times 1\$. That's uneven, so the door ends up at 1, which is opened.

Now, for any factorization \$x\times y\$ of a number, there exists an inverse factorization: \$y\times x\$. Unless \$x\$ equals \$y\$. If that's the case, then there is no inverse factorization because the inverse is the same!

So it's a square root detector! (Any number that has a positive integer as a square root has an uneven number of factorizations, the rest have an even number).

Now, this doesn't implement the algorithm that your problem statement describes, but it does end up with the same result:

public static void printDoorsOpened(final int passes)
{
    int j = 1;
    for(int i = 1; i <= passes; i++)
    {
        if(j*j == i){
            j++;
            System.out.println("The door number "+i+" is Opened");
        } else {
            System.out.println("The door number "+i+" is Closed");
        }
    }
}


Linked list that support modifications during iteration

I haven't done much Kotlin, however something looked wrong and I was curious, so I wrote some tests.  I had a couple of failures, so you may have issues, or it may be that I'm expecting the wrong behaviour.  There's three scenarios to consider.  I've defined a list of string to make it easy to test.
val list = ListenersList<String>()

clear
You've said that you want the code to be tolerant of adding/removing items during iteration.  I assumed that it would therefor also be tolerant of clear being called (it seems equivalent to calling remove on every item).  So, I would expect it to iterate up to the point of the clear being called.  This isn't what happens.  Instead, it iterates past the end of the list.  So, for example:
@Test
fun clearMiddleWorks() {
    list.add("a")
    list.add("b")
    list.add("c")

    var items = ""

    for (item in list) {
        if(item == "a")
            list.clear()
        items += item
    }

    assertEquals("a", items)
}

This test fails, because instead of exiting the loop after "a", it continues building up the string, and fails on "a" != "abcnull"
end removal
This issue exists in the code you've posted, however it looks like you've cleaned it up in your latest github version.  Removing the last item in the list during iteration, fails to terminate as expected:
@Test
fun removalOfEndWorks() {
    list.add("a")
    list.add("b")
    list.add("c")

    var items = ""

    for (item in list) {
        if(item == "b") {
            list.remove("c")
        }
        items += item
    }

    assertEquals("ab", items)
}

This fails with "ab" != "abnull"
remove and add conflict
This may actually be expected behaviour, however it seems odd to me.  If I remove an item from the list, whilst I'm iterating over it, then add an item with the same value, I'd expect that item to be treated the same was as if I'd added a new item, however it isn't.  So, this test passes:
@Test
fun removalAdditionOtherInMiddleWorks() {
    list.add("a")
    list.add("b")
    list.add("c")

    var items = ""

    for (item in list) {
        if(item == "a") {
            list.remove("b")
            list.add("d")
        }
        items += item
    }

    assertEquals("acd", items)
}

And this test fails:
@Test
fun removalAdditionOfMiddleWorks() {
    list.add("a")
    list.add("b")
    list.add("c")

    var items = ""

    for (item in list) {
        if(item == "a") {
            list.remove("b")
            list.add("b")
        }
        items += item
    }

    assertEquals("acb", items)
}

It fails because the added in "b" is ignored, so "acb" != "ac".  Is this expected?


At least as it stands right now, quite a bit of your code accomplishes nothing.

template<typename T, typename H>
class tree;

template<typename T, typename H>
class tree : public std::unordered_map<T, std::shared_ptr<tree<T, H>>, H> { };

When the declaration immediately precedes the definition like this, the declaration isn't really accomplishing anything--the definition by itself will do the same, so we can consolidate this down to just:

template<typename T, typename H>
class tree : public std::unordered_map<T, std::shared_ptr<tree<T, H>>, H> { };

Likewise, your declaration of the stream insertion operator:

template<typename T, typename H>
std::ostream& operator<<(std::ostream& s, const tree<T, H> &t);

...can be eliminated with no loss. For these declarations to be meaningful/helpful, you'd do something like putting them in a header, with the definitions in a separate file. For most purposes, the class definitions need to be in a header as well though, so the utility of the class declarations may be open to some question. There are cases such things are used (e.g., <iosfwd> contains just "forward" declarations of the iostreams classes) but they're not very widely used (e.g., when was the last time you wrote code that used #include <iosfwd>?)

Another obvious issue is that you're publicly deriving from a standard container. The standard containers aren't really intended to be used as base classes, so this usage is somewhat fragile. Public derivation means it's trivial to assign the address of Tree object to a pointer an unordered_map. If the object is destroyed this way, you get undefined behavior because the base class doesn't declare its dtor as virtual.

// Note that we don't have a cast or anything like that indicate that we're doing
// something dangerous here.
std::unordered_map<T, H> *base = new Tree<T, H>;
// ...
delete base; // undefined behavior here.

...and there's basically nothing you can do from inside the class to prevent a user from doing this--by using public inheritance, you've told the world (and the compiler) that this usage should be perfectly fine, so the compiler doesn't require an explicit cast to do the conversion.


Design: The design is pretty bad. Think more on how you plan to use it.
Currently, it is prone to deadlocks.
Say, you create two ramfile_disk_t instances in two different places in your code of the same file. The second instance will be blocked until first is finished. Is this really what you want? Is this the only way you want the code to be used?
At least add options like:

"shared usage" - if you only want to read, there is no reason to disable access from several places. Also user may want to manage read/write safety themselves instead of relying on crude methods.
"try open" - return false if locked.
"open" - throw if locked.
"wait for open" - waits until unlocked if locked.
"lock on usage" - lock/unlocks the mutex upon read/write instead of creation/destruction of the class.

Technical Issues:

Avoid #include "../win_xept.hpp". Imagine there is another win_xept.hpp file somewhere and user added an include path that results in loading the wrong win_xept.hpp. This leads to build corruption. If anything you'd better make an extra folder for all your code files just to be extra safe. So you always include #include "my_codebase/current_project/win_xept.hpp". As a bonus your code will be organized better.

Frequently one makes a static create function for abstract classes that will instantiate the implementation depending on user's request. This way, user at no point needs to include implementation's headers.

ramfile_t is a class with virtual functions. Therefore, it is ought to have a virtual destructor (virtual ~ramfile_t() = default). This is especially true for purely abstract classes. Also, do you really think you'll have more that one implementation of the class, why even bother with the interface?

ramfile_disk_t has data-racing issues with the static member file_locks. You ought to guard it with a mutex each time you access it.

I am not 100% sure, but most likely
std::vector< std::byte >( std::istreambuf_iterator< std::byte >( file ),
                          std::istreambuf_iterator< std::byte >( ) );

is a very slow method to read the file. Consider using more low-level functions like fread or read of the iostream instead of the iterator-based approach. At least make some tests.

It is a bit nitpicky, but is there any reason to pass std::size_t const & off = 0 as const reference in the overwrite method? Just pass it by value std::size_t off; not only passing by reference is slower, it becomes nuisance once you attempt to schedule the function in an asynchronous thread.


This is awesome code,

I would have added an s to var trigger since you are counting on more than 1 trigger.


Quoting

Some recommended double-quotes were missed here:

cut -d' ' -f1 /proc/mounts | grep -Fxq $(realpath "$1") && die "$1: is mounted"

Should be like this:

cut -d' ' -f1 /proc/mounts | grep -Fxq "$(realpath "$1")" && die "$1: is mounted"

This will break for example if $outfile contains spaces:

exec dd $ddflags $outfile

You could make it safe by using an array:

ddargs=(conv=nocreat,fsync oflag=dsync bs=1M status=progress "of=$1")

exec dd "${ddargs[@]}"

Safety tip

set -eu is a nice safeguard, I also like to add -o pipefail:

set -euo pipefail

Cosmetic issues

There is an unnecessary trailing ; in exit 1;


Application that processes XML based on configuration

Pardon my lack of Python knowledge, but I think a function something like this might work:

def fatal_error(message):
    log.error(message)
    app_exit(1)

And now your catch cases look more like this:

try:
    root = get_root(xmlfile)
except ET.ParseError as e:
    fatal_error("Error while parsing {0}: {1}".format(xmlfile, e))
except IOError as e:
    fatal_error("I/O error({0}): {1}".format(e.errno, e.strerror))

log.info('Getting configuration of XML {}.'.format(xmlfile))
try:
    cfg = get_cfg(xmlfile)
except IOError as e:
    fatal_error("I/O error({0}): {1}".format(e.errno, e.strerror))


Indexing and searching an list of rectangles to see if they contain a point

One way to solve the problem with trees
A simplified look at binary trees

the rectangles are static

[the rectangles] should never overlap

As such we can build a simple tree.
Before looking at 2d points we can look at a solution for 1d points.
Say we have the following line segments. Beginnings are inclusive ends are not.

A: 0 - 2
B: 2 - 3
C: 3 - 4
D: 4 - 8

We could describe the values as a really simple binary tree.

With the example I gave we can reduce the amount of leaf nodes to just 4.

We do need to assign multiple leaves to the same node at times.
For example if we had the following line segments:

A: 0 - 3
B: 3 - 8

An algorithm for the above
As such we can just use a simple binary tree.
With two major changes:

We need to make the intermediary nodes when building the leaves.
We may need to add multiple leaf nodes to account for the end of the rect.

As such we can build a simple algorithm:

When building the nodes we need to know the index of the node.
Each node has a range for the values the children can be.
In our above 8 leaf node tree, the the values for node 4 can range from 0-8.
Where the 2 node's range is 0-4 and the 5 node's range is 4-6.

If the range of the line segment is greater than the range of the node we can stop recursing.

Otherwise we need to recursively append to the left or right child node. (Can be both.)

If the start of the line segment's range is less than the node's index we recurse left.
If the end of the line segment's range is greater than the node's index we recurse right.

Before recursing:

Build the child node if one doesn't exist.
The index will be:
Left: (node's index + node's start) // 2
Right: (node's index + node's end) // 2

We also need to adjust one of the start or end of the child node's range.
Left: The end of the child node's range is the current node's index.
Right: The start of the child node's range is the current node's index.

We then recurse into the children.

Here is an example implementation of such a binary tree in Python:
from __future__ import annotations

import dataclasses
import textwrap
from typing import Iterator, Optional, TypeVar, Generic

T = TypeVar("T")

@dataclasses.dataclass
class Node(Generic[T]):
    index: int
    left: Optional[Node[T]] = None
    right: Optional[Node[T]] = None
    value: Optional[T] = None

    def get_point(self, point: int) -> Optional[T]:
        if self.value is not None:
            return self.value
        child = self.left if point < self.index else self.right
        return child.get_point(point)

    def add_range(
        self,
        value: T,
        range_start: int,
        range_end: int,
        node_start: int,
        node_end: int,
    ) -> None:
        if range_start <= node_start and node_end <= range_end:
            self.value = value
            return
        if range_start < self.index:
            if self.left is None:
                self.left = Node((self.index + node_start) // 2)
            self.left.add_range(value, range_start, range_end, node_start, self.index)
        if self.index < range_end:
            if self.right is None:
                self.right = Node((self.index + node_end) // 2)
            self.right.add_range(value, range_start, range_end, self.index, node_end)

    # So I can show the code works
    def tree_format(self, join="──", top="  ", bottom="  ") -> Iterator[str]:
        if self.left is not None:
            for value in self.left.tree_format("┌─", bottom="│ "):
                yield top + value
        if self.value is None:
            yield f"{join}{self.index}"
        else:
            yield f"{join}{self.value}"
        if self.right is not None:
            for value in self.right.tree_format("└─", top="│ "):
                yield bottom + value

class Tree(Generic[T]):
    _size: int
    _root: Node

    def __init__(self, size: int) -> None:
        self._size = size
        self._root = Node(size // 2)

    def __str__(self) -> None:
        return "\n".join(self._root.tree_format())

    def add_range(self, value: T, start: int, stop: int):
        self._root.add_range(value, start, stop, 0, self._size)

    def get_point(self, point: int) -> Optional[T]:
        try:
            return self._root.get_point(point)
        except AttributeError:
            return None

if __name__ == "__main__":
    print("Tree1:")
    tree_1 = Tree(8)
    tree_1.add_range("A", 0, 2)
    tree_1.add_range("B", 2, 3)
    tree_1.add_range("C", 3, 4)
    tree_1.add_range("D", 4, 8)
    print(tree_1)
    print(3, "==", tree_1.get_point(3))

    print("\nTree2:")
    tree_2 = Tree(8)
    tree_2.add_range("A", 0, 3)
    tree_2.add_range("B", 3, 8)
    print(tree_2)
    print(3, "==", tree_2.get_point(3))

    print("\nTree3:")
    tree_3 = Tree(8)
    tree_3.add_range("A", 0, 3)
    tree_3.add_range("B", 4, 8)
    print(tree_3)
    print(3, "==", tree_3.get_point(3))

Tree1:
    ┌─A
  ┌─2
  │ │ ┌─B
  │ └─3
  │   └─C
──4
  └─D
3 == C

Tree2:
    ┌─A
  ┌─2
  │ │ ┌─A
  │ └─3
  │   └─B
──4
  └─B
3 == B

Tree3:
    ┌─A
  ┌─2
  │ │ ┌─A
  │ └─3
──4
  └─B
3 == None

We can abstract the binary tree (1D) to a quad tree (2D) and perform the same algorithm.
The quad tree will have a top-left, top-right, bottom-left and bottom-right but otherwise would work the same way.
Problems
The above solution isn't just rainbows and sunshine

The tree's size must never change.
If the tree ever needs to resize you must build one from scratch again.

Currently the tree cannot have overlapping boxes.
Adding the capability doesn't seem impossible however.

You would need to change Node.value to a list and append to the list in Node.add_range.
Adjust Node.get_point to not eagerly exit and return the children's values (if applicable) along with the current node's values.

Your tree can have lots of cruft leaf nodes because of bad index selection.
(node_end + self.index) // 2

Say you want to put 9 equally sized squares into a 3x3 grid, you won't have a nice 9 leaf nodes.
You'd have 36 leaf nodes.
We see a less severe version of the problem in "Tree2".
Had we selected 3 to be the first index to split on, rather than 4, we'd only have 2 nodes not 4.
  ┌─A
──3
  └─B

To solve the issue I'd move the index generation code out into a separate binary or quad tree.
For example we could abstract the index generation as:
class IndexNode:
    def __init__(self, index, start, end):
        self.index = index
        self.start = start
        self.end = end

    def left(self):
        start, end = self.start, self.index
        return Node((start + end) // 2, start, end)

    def right(self):
        start, end = self.index, self.end
        return Node((start + end) // 2, start, end)

We can now easily change the index generation for the 3x3 grid without having to mangle the other tree.
We could also manually define the tree.
But you'd have to manually build the entire tree.
Or have a hybrid where you define the top nodes and let the class generate the rest.

Maintainability

I'm aiming for maintainability over performance

As you can probably see using a tree can get you better performance.
Since the tree could find the rects in \$O(\log(n))\$ time.
To improve the performance and to get good memory usage may require more thought; depending on the intricate patterns you use.
However do you really get much from building an intricate quad-tree?
Even my simple binary tree is double your line count.
If you have come on CR without caring about speed then I can't imagine your current solution is performing poorly.
As such the cost to maintainability doesn't really seem worth the gain in speed at the moment.


Three variations on a Webpack build script

I would say a very big "no" to Version 3. Instantiating an object should not have a side-effect of emptying a directory and kicking off a build — that's very surprising behavior. In OOP, the methods should be the verbs. Here, your noun has gone rogue and is doing all kinds of activities.

Version 2 adds verbosity with questionable benefits. If you want to define functions, then the functions should accept parameters and return results. Here, the functions act on inputs that are essentially global variables, so you still have to read the code within each function to understand what it does.

Version 1 is good, and I would say that the added comments are probably beneficial.

All four of the scripts lack decent error handling. If an error occurs, I would expect the entire script to abort, rather than printing a message and trying to continue.


Ok, here are some things I noticed:

First of all, while the code seems easy enough to follow as it is, a couple of comments here and there certainly couldn't hurt.

tag = do manyTill anyChar . try $ lookAhead tagStart
         char '<'
         name <- many $ noneOf " "

It seems weird that you first use tagStart to find until where to match, but then don't use it to actually match the tag start.

junk = optional . many $ oneOf "\n\r\t\\/"

Since many can already match the empty string, making it optional doesn't change anything.

tagName = string "rect"
          <|> string "polygon"
          <|> string "polyline"
          <|> string "circle"
          <|> string "path"
          <|> string "g"
          <|> string "svg"

That looks a bit repetitive. I'd define a helper function which matches one of a list of strings:

-- Takes a list of strings and returns a Parser which matches any of those strings
oneStringOf = choice . map (try . string)

tagName = oneStringOf ["rect", "polygon", "polyline"] -- etc

By adding the try we also made it so that it actually works correctly now (thanks to Joey Adams for pointing out that fix).

As for why your alternative definition for property doesn't work: I'm not sure whether it's the only thing that keeps it from working, but one mistake is that you wrote tagName when you meant propName.


I would actually avoid the attempt to mimic C++ syntax. It makes things more complex and exposes unnecessary details.

For me it would be equally object-oriented with the following C interface:

#ifdef __cplusplus
#extern "C" {
#endif

typedef struct XCFString_
{
    char unused__;
} XCFString;

XCFString* XCFString_Init();
XCFString* XCFString_InitFromCString(char const* sz);
size_t XCFString_Length(XCFString const* xcfs);
char const* XCFString_Value(XCFString const* xcfs);
void XCFString_Release(XCFString* xcfs);

#ifdef __cplusplus
}
#endif

The above interface hides the details while allowing polymorphism; you could e.g. keep the "vtable" implementation (but hidden) and provide different init-functions.

I really don't follow all that macro voodoo but having a mutable shared state - the "pointer to current class" - seems susceptible to race conditions.


Python multi-threaded kubernetes watcher

Restructuring and consolidation

Dealing with API client instanceInstead of generating a new client.AppsV1Api instance in each separate thread - create the instance in the main thread and pass shared API client to your threads constructors:

if __name__ == '__main__':
    ...
    v1 = client.AppsV1Api()
    thread.start_new_thread(watch_deployments, (v1,))
    thread.start_new_thread(watch_daemonsets, (v1))
    ...

Both target functions watch_deployments and watch_daemonsets perform essentially the same set of actions and differ only in specific v1.list_... routine.To eliminate duplication the common behavior is extracted into a separate function say _gather_watched_metadata that will accept a particular v1.list_... function object as callable:

def _gather_watched_metadata(list_func):
    w = watch.Watch()
    last_seen_version = list_func().metadata.resource_version
    while True:
        for item in w.stream(list_func, pretty="pretty", resource_version=last_seen_version):
            metadata = item["object"].metadata
            _ = {metadata.name: [item["object"].kind, metadata.namespace,
                                 metadata.resource_version,
                                 metadata.annotations]}
            depl_lst.put(_)

As can be seen in the above function, to avoid repetitive indexing of nested attributes like item["object"].metadata it is worth to extract it into a variable at once.

Now, both target functions become just as below:

def watch_deployments(v1):
    _gather_watched_metadata(v1.list_deployment_for_all_namespaces)

def watch_daemonsets(v1):
    _gather_watched_metadata(v1.list_daemon_set_for_all_namespaces)

That can be shortened even further: both watch_... functions can be eliminated and you may run just with _gather_watched_metadata function and specific API routines passed as an argument :

...
v1 = client.AppsV1Api()
thread.start_new_thread(_gather_watched_metadata, (v1.list_deployment_for_all_namespaces,))
thread.start_new_thread(_gather_watched_metadata, (v1.list_daemon_set_for_all_namespaces,))

But to apply the last "shortening" - is up to you ...

Consuming depl_lst queueInitiating for loop with range in this context:

while True:
    for i in range(depl_lst.qsize()):
        ...

is redundant as it's enough to check if queue is not empty:

while True:
    if not depl_lst.empty():
        current_obj = depl_lst.get()


Your code is correct, but the problem you proposed can be solved in a less complicate manner, starting from your example these are some steps of my algorithm making comparisons between elements of the two arrays:
x = [1, 4, 7, 8, 10} , y = [2, 3, 9] step0 : comparing 10, 9
                  ^               ^

x = [1, 4, 7, 8, 9} , y = [2, 3, 10] step1 : 10, 9 swapped
                 ^                ^

x = [1, 4, 7, 8, 9} , y = [2, 3, 10] step2 : comparing 9, 3
                 ^            ^

x = [1, 4, 7, 8, 3} , y = [2, 9, 10] step3 : 3, 9 swapped
                 ^            ^

x = [1, 3, 4, 7, 8} , y = [2, 9, 10] step5 : reordered x with swaps, comparing 8, 9
                 ^            ^

This means that if you start from the right of the two arrays, if the x array element is greater than the array y element, the swap will be done and after you will reorder the x array swapping adiacent elements if one element is smaller than previous element in the array.
With the help of a method to swap elements between the two arrays like this below:
private static void swap(int i, int j, int[] arr1, int[] arr2) {
    int tmp = arr1[i];
    arr1[i] = arr2[j];
    arr2[j] = tmp;
}

Your method  mergeRunner can be rewritten like below:
private static void mergeRunner(int[] x, int[] y) {
    final int maxIndex = x.length - 1;

    for (int j = y.length - 1; j >= 0; --j) {

        if (y[j] < x[maxIndex]) {

            swap(maxIndex, j, x, y);

            for (int i = maxIndex; i > 0 && x[i - 1] > x[i]; --i) {

                swap(i, i - 1, x, x);
            }
        }
    }
}


Python implementation of the longest increasing subsequence

from random import randrange
from itertools import islice

def randomSeq(max):

The python style guide recommend that you use space_with_underscores for function names

  while True: yield randrange(max)

def randomList(N,max):
  return list(islice(randomSeq(max),N))

I suspect that's not a really efficient way to produce a random list. I think the following may be a better option:

return [randrange(max) for x in range(N)]

I've not done any benchmarking so I may be wrong.

## Returns the longest subsequence (non-contiguous) of X that is strictly increasing.
def subsequence(X):
    L = 1     ## length of longest subsequence (initially: just first element)
    M = [0]   ## M[j] = index in X of the final member of the lowest subsequence of length 'j' yet found
    P = [-1]

Consider using names instead of these single letter variables.

    for i in range(1,X.__len__()):

Don't use x.__len__() use len(x)

        ## Find largest j <= L such that: X[M[j]] < X[i].
        ## X[M[j]] is increasing, so use binary search over j.

This whole bit about the binary search would do well in a seperate function so as not the clutter the subsequence implementation. Actually python already provides a binary search function in the bisect module.

        j = -1
        start = 0
        end = L - 1
        going = True
        while going:
            if (start == end):

You don't need those parens

                if (X[M[start]] < X[i]):
                    j = start
                going = False

Use break. break isn't pretty when you can avoid it, but setting booleans flags is worse.

            else:
                partition = 1 + ((end - start - 1) / 2)

Notice how you only use start + partition? Calculate the middle element instead. It'll make this whole section a bit neater.

                if (X[M[start + partition]] < X[i]):
                    start += partition
                    j = start
                else:
                    end = start + partition - 1

        if (j >= 0):
            P.append(M[j])
        else:
            P.append(-1)

        j += 1
        if (j == L):
            M.append(i)
            L += 1
        if (X[i] < X[M[j]]):
            M[j] = i

    ## trace subsequence back to output
    result = []
    trace_idx = M[L-1]
    while (trace_idx >= 0):
        result.append(X[trace_idx])
        trace_idx = P[trace_idx]

    return list(result.__reversed__())

use reversed(list)

l1 = randomList(15,100)


Munkres algorithm in Python: calculating maximum profit

I just want to point out two sources of inefficiency:

1) The counting functions, e.g.:

def get_no_of_vowels(str):
    return sum(str.lower().count(c) for c in "aeiuoy")

This will loop over str 6 times, which is 5 more times than is necessary. A more efficient approach is:

def get_no_of_vowels(str):
    return sum(1 for s in str if s.lower() in "aeiouy" else 0)

We are creating a generator that will convert each character into a 1 or a 0, and then just sum them. That way, we just do one iteration. Also, "y" is not a vowel.

2) Your line-splitting code here:

        names = line.strip().split(';')[0].split(',')
        items = line.strip().split(';')[1].split(',')

You are splitting line twice. That's extra work. Prefer:

names, items = line.strip().split(';')
names = names.split(',')
items = items.split(',')

Hope that helps.


You may be visiting nodes more than once, because you only check if l.node not in visited when adding nodes to to_visit. The node may be in to_visit already. The correct place for the check is right after to_visit.pop(0).
to_visit should perhaps be a collections.deque to benefit from the efficient popleft() function
The comment says you use str(l) to ensure compatibility somehow. I'm not sure what you mean. I'm concerned because str(l) becomes page.node which is used to index graph again, which may not work depending on the original type of l.


Only one argument needed
First of all, your third argument reverseListHead should be a local variable because it is never used before being set.
Next, if you change your algorithm slightly, you don't need the second argument either:
public static Node reverseList(Node head)
{
    // Empty list or list with one element.
    if (head == null || head.next == null) {
        return head;
    }

    Node second = head.next;
    Node reversedList = reverseList(second);

    // The second node is now the tail of the reversed list,
    // so when we append head to it, head becomes the new tail.
    second.next = head;
    head.next   = null;

    return reversedList;
}


Python functions to determine if a given ticker symbol is an ETF

Any time you're dealing with structured data, use a proper parser for it.

url = 'http://finance.yahoo.com/d/quotes.csv?s=%s&f=%s' % (symbol, tag)

In this case, you want urllib.parse.

Please use a context manager for:

request = Request(url)
response = urlopen(request)

eg.

with urlopen(Request(url)) as response:
    ...

Context managers are good. It's a shame they're so under-used. On older Pythons, you should use contextlib.closing instead.

I would generally merge these lines into a long return:

content = response.read().decode().strip().strip('"')
return content

Consider that in

ticker = ticker.upper()
return True if get_name(ticker) != 'N/A' else False

True if some_bool else False is just some_bool, so write

return get_name(ticker.upper()) != 'N/A'

instead.


So you want a variation of dict.update that recursively update inner dicts; and you want it to record changes as you go.

I’m afraid that your solution is way too complicated for that:

compare_object has two for loops (for key in D and for key in d) that mainly perform the same kind of task. The former being an initialization to the outer loop of the latter.
compare_object copies its N parameter which is never modified and modify record in place (thus there is no need in returning it); which is at best misleading, at worse a bug.
record_change seems to be only an extremely verbose and convoluted way of calling setInDict while ensuring that each level of nesting will actually contain a dictionary.

As for the actual coding style:

Always specify the kind of exception you’re expecting in an except clause; as in you probably don't expect to catch IndexError when calling record_changes.
Raising Exception is also worth noting. You should either declare your own exception or raise a more specific one.
Iterating over keys in a dictionary and repeatedly calling d[key] reads poorly: it's better to iterate over the pairs of keys and values returned by items or iteritems (Python 2): for key, value in d.iteritems():.
As already stated around here AssertionErrors are not meant to control the flow of execution. If I run your code in optimized mode (-O switch on the command line), your code breaks.

Now before getting back to the algorithm, let me introduce you to dict.setdefault: it works pretty much the same than dict.get but instead of just returning the default value in case the key does not exist, it set the key to that default value if it doesn't exist before returning the value.

With that information in mind, let's take an empty file and build a function that update a dictionary and recursively update inner dictionaries.

The name should convey (at least part of) this:

def update_inner(orig, update):

The function should return values that actually changed:

    change = {}
    ...
    return change

The function should update values of the original dict with values from the update dict (and still record changes):

    change = {}
    for key, value in update.iteritems():
        if value != orig.get(key):
            orig[key] = change[key] = value
    return change

The function should recurse to update inner dictionaries:

def update_inner(orig, update):
    change = {}
    for key, value in update.iteritems():
        try:
            # Consider value is a dict, so recurse
            changed = update_inner(orig, value)
        except AttributeError:
            # We were wrong, value is not a dict, backup to simple update
            if orig.get(key) != value:
                orig[key] = change[key] = value
        else:
            # We were right, record the changes
            change[key] = changed
    return change

Wait no, there is something wrong… We are not keeping track of the keys used to go deeper into orig when doing the recursion… Find out why I talked about setdefault now?

Proposed improvements

def update_inner(orig, update):
    change = {}
    for key, value in update.iteritems():
        try:
            # Consider value is a dict, so recurse
            changed = update_inner(orig.setdefault(key, {}), value)
        except AttributeError:
            # We were wrong, value is not a dict, backup to simple update
            if orig[key] != value: # Direct access is OK thanks to setdefault above
                orig[key] = change[key] = value
        else:
            # We were right, record the changes
            change[key] = changed
    return change

You use it like so:

>>> record = {'a':{'b':2, 'q':0}, 'f':9}
>>> new = {'a':{'b':1, 'q':0}, 'c':5}
>>> update_inner(record, new)
{'a': {'b': 1}, 'c': 5}
>>> record
{'f': 9, 'a': {'q': 0, 'b': 1}, 'c': 5}


Iterator based version of quicksort, allowing user defined pivot-selection-strategy

One thing that is missing is selecting a custom comparison function. This is usually done by adding a std::less like type to the template and passing that on to the partition

template<typename It, typename Compare>
It Partition(It begin,It end,It pivot, Compare comp)
{
    std::swap(*begin, *pivot);
    pivot = begin;
    It i{ begin }, j = std::next(begin, 1);
    for(;j != end; j++)
    {
        if(comp(*j, *pivot))
            std::swap(*j, *++i);
    }
    std::swap(*pivot, *i);
    return i;
}


JavaScript image-Carousel with using IIFE

A carousel is an enhancement, a different way of displaying the same data. Without the carousel effect, a carousel is just a list of images. If JS was turned off or for some reason the script blew up, one would still expect to see the images, albeit in a broken layout.

In this case, I would format it to become a list.

    <button type="button" class="my-carousel__control my-carousel__control--prev"> << </button>
    <button type="button" class="my-carousel__control my-carousel__control--next"> >> </button>

In addition, I just popped in a few classes for styling. You can, by default, hide the buttons and show all images. When JS runs, it shows the controls and hides all but one image.

.my-carousel{...}                   # Widget style
.my-carousel__deck{...}             # Deck
.my-carousel__slide{...}            # Default slide style
.my-carousel__slide--hidden{...}    # Styles when a slide is hidden
.my-carousel__controls{...}         # Default controls styles
.my-carousel__controls--active{...} # Controls when active

Your carousel looks simple, just showing one image, no sliding effect etc. We can improve that even further. Since we moved out the image sources away from the JS, we can focus on just the effect.

;(function(images, controls, prevButton, nextButton){

  const imageHiddenClass    = 'my-carousel__slide--hidden';
  const controlsActiveClass = 'my-carousel__controls--active';
  let currentSlide = 0;

  function setActiveSlide(index){
    // Hide all images
    images.forEach(image => image.classList.add(imageHiddenClass));
    // But then show the one we want shown
    images[index].classList.remove(imageHiddenClass);
  }

  prevButton.addEventListener('click', function() {
    currentSlide = (currentSlide - 1) % images.length;
    setActiveSlide(currentSlide);
  });

  nextButton.addEventListener('click', function() {
    currentSlide = (currentSlide + 1) % images.length;
    setActiveSlide(currentSlide);
  });

  // Show the controls that are hidden by default
  controls.classList.add(controlsActiveClass);

  // Set the first slide as active
  setActiveSlide(currentSlide);

})(
   Array.prototype.slice.call(document.querySelectorAll('.my-carousel__slide')),
   document.querySelector('.carousel__controls'),
   document.querySelector('.carousel__control--prev'),
   document.querySelector('.carousel__control--next')
);

In the above, the script is a bit longer but it takes an alternate approach. The major difference is that instead of changing srcs of the image, since the images are all in the markup, what the script does now is toggle the my-carousel__slide--hidden class, adding it to hide images not in focus.


Marking duplicate entries in a numpy array as True

As mentioned in the comments of another answer, you should use sets for membership tests whenever possible. Combinig this with building up uniques instead of cutting it down, we get this really simple implementation:
def duplicates(numbers):
    uniques = set()
    result = []

    for num in numbers:
        result.append(num in uniques)
        uniques.add(num)

    return result

This implementation of duplicates is concise, easy to read and runs in O(n) instead of O(n^2), which is a major difference. One-liners are a fun exercise that can teach you some interesting aspects of Python, and I understand their appeal, but they're often not the best way to go. It's not worth sacrificing readability and performance for the sake of writing less lines of code.

EDIT: Performance testing
As requested in the comments I tested the performance of three different approaches:
def duplicates_set(numbers):
    uniques = set()
    result = []

    for num in numbers:
        result.append(num in uniques)
        uniques.add(num)

    return result

def duplicates_list(numbers):
    result, uniques = [], []
    for elem in numbers:
        if elem in uniques:
            result.append(True)
        else:
            result.append(False)
            uniques.append(elem)

    return result

def duplicates_oneliner(numbers):
    return [elem in numbers[:i] for i, elem in enumerate(numbers)]

Note that the following approach for duplicates_list should be avoided in any case, since it checks for elem membership in uniques twice.
def duplicates_list(numbers):
    result, uniques = [], []
    for elem in numbers:
        result.append(elem in uniques)
        if elem not in uniques:
            uniques.append(elem)

    return result

Here is my code for performance testing using the timeit module. All the provided outputs were produced by this code.
num_range: (int, int)
random_nums: int
executions: int

np.random.seed(100)
a = np.random.randint(*num_range, random_nums)

from timeit import timeit

print(f"{executions} executions with {random_nums} random numbers in range {num_range}")
print("duplicates_set:", "\t" * 2, timeit(stmt=lambda: duplicates_set(a), number=executions))
print("duplicates_list:", "\t" * 2, timeit(stmt=lambda: duplicates_list(a), number=executions))
print("duplicates_oneliner:\t", timeit(stmt=lambda: duplicates_oneliner(a), number=executions))

Starting out with 100_000 executions with the parameters from the original question we get this result:
100000 executions with 10 random numbers in range (0, 5)
duplicates_set:          0.22261620000000001
duplicates_list:         0.18974730000000006
duplicates_oneliner:     2.9783912

We can clearly see that the list implementation performs the best for a small amount of numbers and a small range of random numbers. The one-liner is already at a huge disadvantage.
Upping the length of the random number array to 1_000, we get this result:
1000 executions with 1000 random numbers in range (0, 5)
duplicates_set:          0.1603748
duplicates_list:         0.13001250000000003
duplicates_oneliner:     3.1837349

It seems the length of the array alone does not really affect the relative performance of duplicates_set and duplicates_list. As long as the range of numbers is small, the list comes out on top. Relative performance stayed the same up until 1_000_000 elements, which makes sense since the size of uniques is capped by the range of numbers.
Once we start increasing num_range, the set implementation really starts to shine, since it simply does not care about the size of uniques when it comes to runtime:
1000 executions with 1000 random numbers in range (0, 10)
duplicates_set:          0.15972010000000003
duplicates_list:         0.15932980000000002
duplicates_oneliner:     3.1950098

For a range of (0, 10), set and list implementation perform about the same.
At a range of (0, 1_000) the list implementation is already outperformed by the one-liner:
1000 executions with 1000 random numbers in range (0, 1000)
duplicates_set:          0.15644170000000002
duplicates_list:         3.4406095
duplicates_oneliner:     3.1854200999999995

The one-liner however is immediately out of the competition once the input gets larger, even at small number ranges:
10 executions with 100000 random numbers in range (0, 10)
duplicates_set:          0.1576303
duplicates_list:         0.24761889999999998
duplicates_oneliner:     30.1282213

The final result is exactly what would be expected:

duplicates_list really starts to struggle once the number of unique numbers goes up, since if elem in uniques gets increasingly expensive.
duplicates_oneliner completely breaks down with long input lists, since elem in numbers[:i] gets expensive really fast.
duplicates_set is only outperformed at a low number of unique numbers, but at scale it outperforms both other implementations by a huge margin, since if elem in uniques can be checked in constant time.


Disclaimer: I will not address the actual FibonacciHeap itself, just the c# code.

I explicitly write the private keyword on those methods and properties, so they are indented roughly the same as the public ones. A matter of preference, I guess.

These _name variables are odd, I suggest using the de facto standard of PascalCase.

_count seems to be a duplication of Root.count. I would remove it.
However, ExtractMin adds items to the Root and does not increment count! This seems like a bug, but perhaps it's not. If it is, it is a strong justification for removing _count; if not, it could use a quick comment there to signal why _count is not updated.

Because I like my variables very strongly typed, I don't like var. I changed most of its uses to an explicit type.

You can if-chain if-elses better if you do not use parenthesis around the else that takes an if inside:

if (Min == null) {
    Root.Clear();
    Min = item;
} else if (Comparer<TKey>.Default.Compare(item.Key, Min.Key) < 0) {
    Min = item;
} // else if() { } else if() { } etc

A Node does not seem to make sense without a Key and a Value, so I would add a constructor that takes those two.

You overrode Node.ToString. I assume that was for debugging purposes? I would use the DebuggerDisplay attribute in the class, instead.

Here is a proposal of reviewed code, with some highlights in comments:

public sealed class FibonacciHeap<TKey, TValue>
{
    private readonly List<Node> Root = new List<Node>();
    // TODO: is this not a duplication of Root.Count? Remove it.
    private int _count;
    private Node Min;

    public void Push(TKey key, TValue value)
    {
        Insert(new Node(key, value));
    }

    public KeyValuePair<TKey, TValue> Peek()
    {
        if (Min == null)
            throw new InvalidOperationException();
        return new KeyValuePair<TKey, TValue>(Min.Key, Min.Value);
    }

    public KeyValuePair<TKey, TValue> Pop()
    {
        if (Min == null)
            throw new InvalidOperationException();
        var min = ExtractMin();
        return new KeyValuePair<TKey, TValue>(min.Key, min.Value);
    }

    private void Insert(Node node)
    {
        _count++;
        Root.Add(node);
        if (Min == null)
        {
            Min = node;
        } else if (Comparer<TKey>.Default.Compare(node.Key, Min.Key) < 0)
        {
            Min = node;
        }
    }

    private Node ExtractMin()
    {
        var result = Min;
        if (result == null)
            return null;
        foreach (var child in result.Children)
        {
            child.Parent = null;
            // TODO: shouldn't _count be updated?? Same in Consolidate();
            Root.Add(child);
        }
        Root.Remove(result);
        if (Root.Count == 0)
        {
            Min = null;
        } else
        {
            Min = Root[0];
            Consolidate();
        }
        _count--;
        return result;
    }

    // Here be FibonacciHeap dragons.
    private void Consolidate()
    {
        var unlabeledBag = new Node[UpperBound()];
        for (int i = 0; i < Root.Count; i++)
        {
            Node item = Root[i];
            int itemChildren = item.Children.Count;
            while (true)
            {
                Node child = unlabeledBag[itemChildren];
                if (child == null)
                    break;
                if (Comparer<TKey>.Default.Compare(item.Key, child.Key) > 0)
                {
                    var swap = item;
                    item = child;
                    child = swap;
                }
                Root.Remove(child);
                i--;
                item.AddChild(child);
                child.Mark = false;
                unlabeledBag[itemChildren] = null;
                itemChildren++;
            }
            unlabeledBag[itemChildren] = item;
        }
        Min = null;
        for (int i = 0; i < unlabeledBag.Length; i++)
        {
            var item = unlabeledBag[i];
            if (item == null)
                continue;
            if (Min == null)
            {
                Root.Clear();
                Min = item;
            } else if (Comparer<TKey>.Default.Compare(item.Key, Min.Key) < 0)
            {
                Min = item;
            }
            Root.Add(item);
        }
    }

    private int UpperBound()
    {
        // Here be dragons.
        // Also, if _count is NOT Root.Count, it ought to at least have a more meaningful name.
        double magicValue = Math.Log(_count, (1.0 + Math.Sqrt(5)) / 2.0);
        return (int)Math.Floor(magicValue) + 1;
    }

    [DebuggerDisplay("{Key}, {Value}")]
    private class Node
    {
        public TKey Key;
        public TValue Value;
        public Node Parent;
        public List<Node> Children = new List<Node>();
        public bool Mark;

        public Node(TKey key, TValue value)
        {
            Key = key;
            Value = value;
        }

        public void AddChild(Node child)
        {
            child.Parent = this;
            Children.Add(child);
        }
    }
}


CSS Styling: Should I specify the element type?

It depends what you mean by "better".

Because of the way the style system matches rules, #style1 is faster than div#style1 (and the same goes for classes). For this reason, conventional wisdom is that the former, less-qualified selector is better.

However, it may be that div#style1 is more easily understood by the next person1 editing the CSS than #style1 (in the specific case you give, probably not - but, for example, the meaning of a selector like a.external is immediately obvious to anyone reading it in a way that a bare .external isn't).

In cases like that, you have to decide which is more important: making your CSS as straightforward as possible to maintain, or making it (perhaps only very slightly) faster to render.

1 Maybe you in eighteen months, maybe someone else entirely.


Drawing a Thue-Morse pattern recursively

Is there any way that I can improve my program?

Yes :)
A good cue to see if your program can be improved is when there is lot of repetition in the code. There are usually ways to avoid repetition, although they can sometimes get pretty complex. However, avoiding repetition is useful for two very important reasons :

Copy/paste usually leads to "dumb" bugs
If you want to change a thing you need to change it in a billion places, making it more likely you'll forget one.

I'll be very honest, I'm reading your code as much as I can, but I don't understand what's happening in there, so it's going to be hard to provide a review of what you're doing, but it's also an indication that the code isn't clear enough to be understood by someone trying to understand it (me, in this case).
What can be done about this?

Use comprehensive names (That goes for methods, variables, everything really)
Spacing the code properly (Have you ever read a complicated paper/book where all the text was cramped up? Have you ever read another one where the was good spacing? It makes a world of difference!)
Avoiding commented code (Why is it there? Is it a mistake? Should it be uncommented? How long has it been commented? Why?)
Finally, when none of those tips are enough, you should comment your code, but be cautious not to "overcomment". Comments should be just long enough so that someone can understand why you coded the way you did. There's no need to explain things such as "I'm changing the pen color" over StdDraw.setPenColor(StdDraw.BOOK_BLUE);

Now, there's one thing that I think would help tremedously with the readability of the code. Right now, your code both computes the "pattern" and prints it. What if you first generated a binary 2D array that fit the problem at hand, and you had another function that printed this array?
Taking an example of the N=4 case you gave, the array could look like this :
0110
1001
1001
0110

Separating the algorithm from the printing will also let you see how you can improve your code.
For example, we can notice that there's symmetry between the \$row_i\$ and \$col_i\$, meaning that we only need to find the value of half the grid in order to find all the values (that would be a valuable optimisation for a problem with a big N value).
Now, if I take a look at the link you gave us, I see that :

Amazingly, the Thue-Morse sequence can be generated from the substitution system :
0 -> 01 and 1 -> 10, recursively.

Let's look at this with the first row of the N=8 example you gave us. We'll need  \$log_2(8)=3\$ iterations of this substitution sequence : 0->01->0110->01101001. Let's fill our 2D array with this :
0 1 1 0 1 0 0 1
1 X X X X X X X
1 X X X X X X X
0 X X X X X X X
1 X X X X X X X
0 X X X X X X X
0 X X X X X X X
1 X X X X X X X

Now, let's fill the second row, knowing that the first value is 1 : 1 -> 10 -> 1001 -> 10010110
0 1 1 0 1 0 0 1
1 0 0 1 0 1 1 0
1 0 X X X X X X
0 1 X X X X X X
1 0 X X X X X X
0 1 X X X X X X
0 1 X X X X X X
1 0 X X X X X X

For completion, let's do the third row, and I'll leave the rest to you 10 -> 1001 -> 10010110
0 1 1 0 1 0 0 1
1 0 0 1 0 1 1 0
1 0 0 1 0 1 1 0
0 1 1 X X X X X
1 0 0 X X X X X
0 1 1 X X X X X
0 1 1 X X X X X
1 0 0 X X X X X

I guess you see where this ends. This leads to a pretty performant approach with code that should be pretty simple to understand. Afterwards, you could have a function paintThueMorse, give it this 2D array and paint blue for 1, white for 0 or the inverse.


Nope. Let's walk through it from a hypothetical attackers point of view.

  Okay. It's sending an identification cookie. It's hex. 32 digits long.
  Probably an md5 hash. I wonder what's hashed? I'll throw it in
  oclHashcat to check. I can make a billion guesses a second, so if it's
  a hash of something simple, I'll find out.

  <3 seconds later>

  Huh. It's a number. Lemme grab another session and see if that's a
  number too.

  Yep.

  It looks like these are all 6 digit numbers. I'll grab 10 more to
  check.

  Okay, 6 digits AND they can be positive or negative.

  That's a keyspace of about 2^21. If there are 8 sessions going right
  now, then it costs, on average,

  2^(21 - 1 - 3) requests * 1 KB per request * 0.08 $/GB
  ...
  =1.01 cents to crack a session.
  Alright, I'll start on that and see what I have in the morning.

So: Add more entropy.


I took the liberty of adding your code to a Fiddle Here so that we could see what it being displayed and test it in different browsers.

I tried to set my Browser to IE 8 and less and apparently it doesn't play nice with JSFiddle.  but in IE 9 mode it showed up very nicely, exactly the same as in Chrome.

I like that you created a CSS class button-primary so that you didn't repeat the code you were going to use in all the buttons. and so you didn't have to write so many :hover statements.

Overall I would say that this is some pretty clean code.

But, there is one thing that I would suggest that you do.

Terminate every tag

This

<link rel="stylesheet" href="css/main.css">

Becomes

<link rel="stylesheet" href="css/main.css" />

Notice the /> at the end.  if there is no closing tag you should still "close the tag"

these are called Self closing Tags.

some Tags are self closing tags and some are not. HTML5 is a little blurry on this, or I am a little blurry on HTML5

either way you should make sure that these tags

<input />
<area />
<link />
<meta />

and some others.   This Answers Lists some more

XHTML allows you to Self Close any tag, this isn't really good practice, mostly because most tags are meant to be containers and leaving them empty would be really silly.

This more recent answer from BoltClock explains a little bit better about closing tags.

I recommend always closing your tags, even if the Doctype tells you that you don't have to. it is better practice.


Calculation of lexicographic permutations

LOOP syntax violation

There is a LOOP syntax violation: your LOOP starts with a WHILE clause and FOR clauses follow. This is not allowed according to the ANSI CL LOOP syntax. WHILE is a main clause, which follow after the variable clauses.

WHILE is not needed

The while...for... is just a for.

LOOP iterations in the sub-LOOPs are creating side-effects

I would propose to rewrite the sub-LOOPS to return values. That would make it easier to refactor them into functions.

My version of your code

I tried to keep the main loop small and remove the side-effects.
If the function calls are too much overhead, we could let Lisp inline them with a INLINE declaration.

Each of the sub-functions have a purpose and can be described and tested separately.

(defun lexicographic-permutation% (order n &aux (len (1+ order)))
  "Returns the Nth permutation of integers from 0 upto order."
  (labels ((iota (n)
             (loop :for i :upto n :collect i))
           (compute-i (permutation order)
             (loop :for i :downfrom order
                   :when (< (aref permutation (1- i))
                            (aref permutation i))
                   :do (return i)))
           (compute-j (permutation len i)
             (loop :for j :downfrom len
                   :when (> (aref permutation (1- j))
                            (aref permutation (1- i)))
                   :do (return j)))
           (swap-ij (permutation i j)
             (rotatef (aref permutation i) (aref permutation j)))
           (swap (permutation i j)
             (loop :for i1 :from i :and j1 :downfrom j
                   :while (< i1 j1)
                   :do (swap-ij permutation (1- i1) (1- j1)))))
    (let ((permutation (make-array len :initial-contents (iota order))))
      (loop :for count :from 1 :upto n
            :for i = (compute-i permutation order)
            :for j = (compute-j permutation len i)
            :do
            (swap-ij permutation (1- i) (1- j))
            (swap    permutation (1+ i) len))
      permutation)))


Implementation of a Fraction class in Java

I'm not going to repeat the basics which Ronan has covered fairly comprehensively. I'd just add: why use -1*a when you could use -a?

However, I have some design questions:

Reduction

I have a Rational class which I have used for about 15 years. It always reduces, and I've never found this to be a problem. Why would you want unreduced fractions?

In addition, consider that being reduced or not is not really an property of the number: it's a property of how the number is displayed in text. If you have use cases, would they be covered equally well or better by a toString method which takes a desired denominator?

Among the advantages of using reduced numbers are i) it simplifies equality testing; ii) it reduces the risk of overflow (or improves memory usage and speed, if using BigIntegers for numerator and denominator).

Mutability

Whether you keep unreduced numbers or not, make them immutable. In fact, I would recommend making every class in your CAS immutable, and using the builder pattern if you think this makes it too hard to instantiate matrices.

int vs BigInteger

Why are the numerator and denominator stored as ints? They will easily overflow, especially given that adding two rationals requires multiplying numerators and denominators. If you do stick with ints to keep memory usage low then you should cast to longs in the arithmetic methods and then reduce before casting back to ints, but I would recommend using BigInteger.

A final note

Well done for considering the special cases around zero and negative numbers in the constructor.


Generic method for checking database integrity on soft delete

I don't think this is the route you should travel. As an assumption of me, you will, if any dependent Items are found, show a message somehow which shows all the dependent items in a messagebox/label so the user knows which items should/need to be deleted first.

IMO this isn't really userfriendly because the user will need to delete each item individually and will have to remember the items to be deleted. If one of the subitems has dependent items as well another message will be shown which results in another delete marathon...and so on.

Maybe it would be better, if a to be deleted item has subitems to provide a possibility to delete all items at all by showing some kind of form where the user can decide if all items should be deleted or not.

You should add a method which returns the dependent items, if there aren't Any(), go on and delete the desired item. If ther are Any(), return them to the user asking if all of these should deleted as well.

Now comming to review the code in question

Omitting braces {} although they might be optional is a dangerous decision. This can lead to bugs which are hard to find. I would like to encouracge you to always use them.
usually I tend to use well named variables myself, but if it is obvious I wouldn't bother with them, resulting in less lines of code. What I mean here is the isAny. Having isAny won't give you much/any benefit in this small method. I would just write

public void ItemDependant<TEntity>(Guid id,
    Expression<Func<TEntity, bool>> condition,
    Expression<Func<TEntity, string>> select) where TEntity : BaseModel
{
    var foundItems = _dbContext.Set<TEntity>().Where(x => x.IsDeleted == false).Where(condition);

    if (foundItems.Any())
    {
        throw new Exception($"You must first delete these dependent items: {foundItems.Select(select).ToList().Aggregate((i, j) => i + ", " + j)}");
    }
}

but I would use a variable to store the result of foundItems.Select(select).ToList().Aggregate((i, j) => i + ", " + j)} because it will increase the readability (IMO). Using C# 6 features is a good thing but you could do it to much.
By looking at the condition parameter at the call to ItemDependant() inside the Delete() method I wonder why you didn't place the x => x.IsDeleted == false in there as well like so

ItemDependant<ItemB>(id, m => !m.IsDeleted && m.ItemAId == id, s => s.Title);

resulting in ItemDependant looking like so

public void ItemDependant<TEntity>(Guid id,
    Expression<Func<TEntity, bool>> condition,
    Expression<Func<TEntity, string>> select) where TEntity : BaseModel
{
    var foundItems = _dbContext.Set<TEntity>().Where(condition);

    if (foundItems.Any())
    {
        throw new Exception($"You must first delete these dependent items: {foundItems.Select(select).ToList().Aggregate((i, j) => i + ", " + j)}");
    }
}


Storing a version number in a Python project

A better approach is to install your script using a setuptools entry_point and let the argparse handle the parameter parsing.  Your project would look something like:
.
├── myproject
│   ├── __init__.py
│   └── cli.py
└── setup.py

Your setup.py would look like:
import setuptools

import myproject

setuptools.setup(
    name='myproject',
    version=myproject.version,
    description='Does stuff',
    url='https://github.com/me/myproject',
    packages=['myproject'],
    entry_points={
        'console_scripts': ['my-script = myproject.cli:entry_point'],
    },
)

When you install your package using pip, it will install a command line script named my-script somewhere like /usr/local/bin.  The command line script will load your package and any requirements, then run the entry_point function in your cli module.  So let's look at that module:
import argparse
import logging

from . import version

def entry_point():
    parser = argparse.ArgumentParser(
        description='Something ... something short',
        epilog='''Bacon ipsum dolor amet occaecat labore qui, ad
                  veniam boudin capicola flank. Dolore rump jerky magna
                  sirloin pancetta. Voluptate anim non minim nostrud ham.
                  Excepteur kevin turkey officia kielbasa pastrami ad ham
                  nostrud meatball tongue magna t-bone. Chuck salami mollit,
                  fatback pig velit officia ut. Cupidatat nulla jowl, tail
                  chicken occaecat excepteur pig beef salami non. Kevin
                  cupim bresaola filet mignon enim.''')
    parser.add_argument('--verbose', '-v', action='count',
                        help='increase verbosity.  Specify multiple times '
                             'for increased diagnostic output')
    parser.add_argument('--version', action='version',
                        version='%(prog)s {}'.format(version),
                        help='show the version number and exit')

    args = parser.parse_args()
    # do stuff here

if __name__ == '__main__':
    entry_point()

The argparse module handles the --version and --help arguments for you.  Since your code is installed and loaded as a proper package, you can use relative imports.  Of course, you are free to use import myproject as well.
I usually do my __init__.py file a little differently.  I follow the what the standard sys module does:
version_info = (0, 0, 0)
version = '.'.join(str(c) for c in version_info)

This makes it possible to use version_info to compare against the numeric version like version_info > (1, 0) which has some nice benefits.
Here's an example of the package in action:
$ python3.4 -mvenv env
$ env/bin/python setup.py install
$ env/bin/my-script --help
usage: my-script [-h] [--verbose] [--version]

Something ... something short

optional arguments:
  -h, --help     show this help message and exit
  --verbose, -v  increase verbosity. Specify multiple times for increased
                 diagnostic output
  --version      show the version number and exit

Bacon ipsum dolor amet occaecat labore qui, ad veniam boudin capicola flank.
Dolore rump jerky magna sirloin pancetta. Voluptate anim non minim nostrud
ham. Excepteur kevin turkey officia kielbasa pastrami ad ham nostrud meatball
tongue magna t-bone. Chuck salami mollit, fatback pig velit officia ut.
Cupidatat nulla jowl, tail chicken occaecat excepteur pig beef salami non.
Kevin cupim bresaola filet mignon enim. Kielbasa non occaecat flank t-bone ad,
sunt in tail esse deserunt id duis. Ut boudin turducken, pariatur labore
veniam lorem proident culpa laborum. Hamburger swine sunt aliqua, et bacon
shoulder jerky cillum. Meatloaf sed pork belly, dolore corned beef in
consectetur enim ball tip. Fugiat ribeye eiusmod sirloin ground round boudin
shoulder voluptate, reprehenderit tongue landjaeger hamburger. Fatback nisi
occaecat, bacon brisket consequat filet mignon fugiat laboris turducken eu. Ad
tempor frankfurter reprehenderit est corned beef voluptate.
$
$ env/bin/my-script --version
my-script 0.0.0

Then to run myproject/cli.py as a standalone script:
$ python -m myproject.cli --version
cli.py 0.0.0


Cleaning up code for Conway's Game of Life

Ruby convention is to use CamelCase for Classnames (GameOfLife)
Since "size" and "str" are mutably exclusive parameters, using a hash parameter here makes the API confusing
Using flags like "@test" to define object behavior is bad style (antipattern)
Ruby doesn't have tail recursion, so you shouldn't do recursive calls without end conditions

To make this more OOP like and self documenting you can define a base class for the basic initialization:

class GameOfLife
  def initialize(length)
    @length = length # Why not call this "size"?
    @board = []
  end

  def check_board
    # Implemented as above without the "if" statement
  end

  def choose_neighbour_set(index)
    # As above
  end
end

Then you can use subclasses for specific implementations

class RandomGameOfLife < GameOfLife
  def initialize(size)
    super(size)
    (size*size).times do
      @board << [0,1].sample
    end
  end

  def iterate_and_output_board
    while true # Iterate till ^C?
      check_board
      sleep 0.5
      puts "\e[H\e[2J"
      @board.each_slice(@length) {|row| p row }
    end
  end
end

class PredefinedGameOfLife < GameOfLife # Or use a better name here
  def initialize(str)
    super(Math.sqrt(str.length))
    str.each_char {|c| @board << c.to_i}
  end

  def check_board
    # This is just an example how to overwrite method behavior
    # Defining another method using "check_board" might be better here
    super
    @board.join("")
  end
end

Somebody else might cover the efficiency aspect. I don't want to intermix the aspects here and its better to focus on readability first.


Building a flexible upsert statement for SQL

Code like this is bound to be a bit hairy.

However

You aren't using parameters

This is a big security vulnerability. What's that SanitiseForMySql method doing? Is it doing everything by the book? Does it handle every possible obscure corner case? Let ADO the MySQL connector manipulate your query, especially if there's a chance you're handling values supplied by the user.

MySQL can perform the so-called MERGE (also called UPSERT)

You can do it via INSERT ... ON DUPLICATE KEY UPDATE statement. In case you are not aware what that is, it's basically a way to either insert or update in case the INSERT fails because of a duplicate key error. It's for sure faster than making a separate query to retrieve the records that are currently present.

By the way, code like this leaves your code open to race conditions in case another user inserts a record exactly between when you read the current records and the moment you execute your INSERT. This is bad, and you're not currently guarding against it. MySQL can do it for you, take advantage of it.

EDIT

Also

This:

        if (fr.IsGoneaway)
        {
            sqlTargetFlag = sqlTargetFlag + "Goneaway";
        }

are you sure this is correct? Concatenating a column name to the other like that? Are you assuming the column name will be passed in followed by a comma? And anyway, isn't it going to blow up with a syntax error when you do the `UPDATE`? Or will the column name get passed as an empty string? Might be a good idea to check what garbage you are receiving through your parameters, assuming said checks aren't already in place at an upper layer. How can you be sure all callers will remember to pass your arguments exactly the way you expect them? Plus, just my two cents, but if my assumptions are correct, this is not a very fun API to work with.


High school social network query for friends in common

Generic issues

The outline of the query should be made visible at a glance using indentation.  This SELECT has a FROM clause and a WHERE clause.  Within the WHERE clause, there are multiple ANDed conditions.
It is conventional to use ALL CAPS for SQL keywords (though some people dislike that convention and disregard it).
All selected columns should be given their own distinct names.  Otherwise, MySQL will automatically name them, and in this case, you'll get three columns each called name and grade.
Use the same capitalization for table and column names as given in the question, since MySQL identifiers are case-sensitive on some platforms.

Query formulation

SELECT DISTINCT should be avoided wherever possible.  Deduplicating the results could hurt performance, and is a sign of a "wrong" query.  A properly formulated query based on a well designed schema and accurate data should almost never require deduplicating the results.
The a-b and b-c friendship relationships should be symmetrical:

$$\newcommand{rel}[2]{\overset{\mathtt{#1}}{\underset{\mathtt{#2}}{\longleftrightarrow}}}
  \fbox{a} \rel{Friend}{ac} \fbox{c} \rel{Friend}{bc} \fbox{b}
  $$

Therefore, I would expect two Friend tables included in the join on equal footing.
In fact, I'm not convinced that your query is correct.  You have the condition a.id=friend.id1, but there is no mention of friend.id2 at all.  Your query merely specifies that a is not friendless.
It should be possible to formulate the join without so many subselects.

Here's one way to write it:

SELECT a.name AS a_name, a.grade AS a_grade
     , b.name AS b_name, b.grade AS b_grade
     , c.name AS c_name, c.grade AS c_grade
    FROM Highschooler a, Highschooler b, Highschooler c, Likes, Friend ac, Friend bc
    WHERE
        a.ID = Likes.ID1 AND b.ID = Likes.ID2
        AND a.ID = ac.ID1 AND ac.ID2 = bc.ID1 AND b.ID = bc.ID2
        AND a.ID = ac.ID1
        AND b.ID = ac.ID2
        AND c.ID = bc.ID2
        AND NOT EXISTS (
            SELECT *
                FROM Friend ab
                WHERE ab.ID1 = a.ID AND ab.ID2 = b.ID
        );

However, joins would be better written using the INNER JOIN syntax:

SELECT a.name AS a_name, a.grade AS a_grade
     , b.name AS b_name, b.grade AS b_grade
     , c.name AS c_name, c.grade AS c_grade
    FROM Likes
        INNER JOIN Friend AS ac
            ON Likes.ID1 = ac.ID1
        INNER JOIN Friend AS bc
            ON Likes.ID2 = bc.ID2
        INNER JOIN Highschooler AS a
            ON ac.ID1 = a.ID
        INNER JOIN Highschooler AS b
            ON bc.ID2 = b.ID
        INNER JOIN Highschooler AS c
            ON ac.ID2 = c.ID
    WHERE
        ac.ID2 = bc.ID1
        AND NOT EXISTS (
            SELECT *
                FROM Friend AS ab
                WHERE ab.ID1 = a.ID AND ab.ID2 = b.ID
        );


First BDD/RSpec tests, would like some review regarding idioms, conventions and style

A small hint: the count method could clean up one of your test case, more or less as such:

it "should have more than half the tiles be landmass" do
    map = @map_factory.make(40, 40)
    number_of_water_tiles = map.tiles.count{|tile| tile.type == :water}
    number_of_land_tiles = map.tiles.size - number_of_water_tiles
    number_of_land_tiles.should be > (map.tiles.size / 2)
  end
end

Also your map could go in the before section too imho.


ToastUtils - helper class for Android SDK Toast

IMO this class isn't very useful (at least in a current shape).

  In Toast class I often miss the call to show()

Well, it's not a bug, it's a feature. There are many situations when you only want to prepare your Toast using makeText() and show it later with show().  Moreover, you don't fix this "bug" with your class - there is still a makeText() method which does exactly what Toast used to do. And you still can forget to call show().

  Parameter length has type int. So a compiler couldn't detect invalid argument value

I wouldn't say that this is a bug, too. And you're fixing it in a bad way, again:

   public static ToastUtils LONG = new ToastUtils(Toast.LENGTH_LONG);
   public static ToastUtils SHORT = new ToastUtils(Toast.LENGTH_SHORT);

So there can only be single instances of LONG and SHORT at the time. This will make many things complicated.

To sum up, this is usage example of your class:

ToastUtils.LONG.show(context, R.string.greeting);

And this is the same without using your class:

Toast.makeText(context, R.string.greeting, Toast.LENGTH_LONG).show();

It's not a big improvement, is it?


posix_fadvise conveniently provides a POSIX_FADV_SEQUENTIAL macro. Use it instead of a magic 1 and a comment.
The client doesn't know in advance whether the file is malformed or not. Better detect a malformed text file in run time:

    if (begin != buf_end)

A Bugs section of posix_fadvise man page says that

  In kernels before 2.6.6, if len was specified as 0, then this was interpreted literally as "zero bytes", rather than as meaning "all bytes through to the end of the file".

Since you already know the file size, better be safe and call it with fs.st_size instead of 0.
Move #include <iosfwd> to the cpp file. The client code doesn't need it.
fastLineParser can be used in C code; just declare it as extern "C"
I see no reason to use C++ here at all. However, if you do so, do not use namespace std.
Finally, do you have any evidence that this is faster than fgets?


C# greedy algorithm to pick activities that do not clash with each other (corrected)

One of the prevailing rules of C# code development is that your code should be readable by others.  That means the intent of what you are doing should be easily determined by someone else reading your code.

This is not the case with your post.

I can't even begin to comment upon your algorithm without taking lots of time to figure out what you are doing.  Therefore, my reply is about style and structure.

Don't put everything in Main().  Your app wants to do 3 overall things:

Read inputs
Run thru a calculation
Write outputs

Your Main() would be simplified along those division of duties.  Thus your new Main() would:

Call the method that reads and validates inputs
Call the method performing calculations based on the validated inputs
Call the method performing outputs

Choose better names for your objects. a, b, and indx tell me little and are hard to follow.  Especially with indx and this notion of pointing to an indx.  C# has wonderfully modern features like classes.  Something like:

public class Interval
{
    public int Start { get; set; }
    public int End { get; set; }
}

Ditch using pointers to another array.  I see no reason to use a[indx[i], 0].  In conjunction with using a class or struct, there's no reason to have a multi-dimensional array.

Imagine how easy it would be to follow your logic that instead of cryptically using:

last = b[i];

Where it's easy to get lost on b[i] and wonder what last means (e.g. does it mean last element in the array or last value you worked with), that you could instead have a List<Interval> (or if you insist Interval[]) in a variable named intervals and you could use:

largestEnd = intervals[i].End;

It's much easier for someone to follow what you mean.  And once they can follow that, they will be better positioned to comment on the algorithm.


Python set variables to shorter list and list length

There is nothing inelegant about your code.  You are computing the length of each array exactly once, have one test, and assign variables in each of the two paths of the branch.  It is clean, fast, and efficient.

You could make it shorter by combining the assignments into structured assignment statement:

l1, l2 = len(arr1), len(arr2)

if l1 < l2:
    short_arr, long_arr = arr1, arr2
    lshort, llong = l1, l2
else:
    short_arr, long_arr = arr2, arr1
    lshort, llong = l2, l1

but it is debatable whether that is clearer.

I can’t claim this is more elegant, but it is significantly shorter:

short_arr, long_arr = (arr1, arr2) if len(arr1) < len(arr2) else (arr2, arr1)
lshort, llong = len(short_arr), len(long_arr)

And the absolutely wrong way to do it would be:

((lshort, short_arr), (llong, long_arr)) = sorted([(len(arr1), arr1), (len(arr2), arr2)])


Prepend one value to a list 'x' number of times

Is there a reason you use IList? because List has the InsertRange method which uses Array.Copy amongst other optimizations.

If we need to support IList,  we don't want to depend upon implementation details and IList.Insert sounds like your best option.

Another approach is you could check whether the actual implementation is List and use the InsertRange method or fallback to Insert in a loop.

Example of adding the items using InsertRange

var items = Enumerable.Repeat(0, 10);
source.InsertRange(0, items);


I like the idea of this utility class, but there are a few points I would like to mention.

Let's start with naming. I would rename the ConvertorToString class, probably, to one of the following ToStringUtil, ToStringHelper, ObjectToString or ObjectToStringConvertor. The rule of thumb is to put the -or/-er nouns in the end of the class name. Personally, I like the first two. Then come the constant fields which could be shorter. For instance, they could be named as FIELD_NAME_AND_VALUE_SEPARATOR instead of SEPARATOR_BETWEEN_FIELD_NAME_AND_VALUE and FIELDS_SEPARATOR instead of SEPARATOR_BETWEEN_FIELDS. That is, the 'BETWEEN' part is redundant because it's already obvious that a separator separates the one from the other. Two other fields would be better named as FIELDS_START and FIELDS_END, which is more intuitive.

Another thing is that you have two separate methods for adding the field names and values and then you check that there is a corresponding value for each field name in the ConvertorToString.checkState() method. You also check for indexes and arrays' length in the ConvertorToString.Field.checkIndex() method. All these checks are error-prone, but they could be eliminated by enforcing the one-to-one correspondence rule of the field names and values in a single method for adding those fields and their values:

ToStringUtil.addField(String name, Object value);
ToStringUtil.addFields(Map<String, Object> fields);

This way you control the state of your object and have no need in the ConvertorToString.checkState() and ConvertorToString.Field.checkIndex() methods anymore. Moreover, internally I would store the field names and values in one data structure, rather than in two separate arrays. The single structure could be a Map<String, Object> or a List<Field>, the latter one is preferable if you have a Field class. This brings us to the ConvertorToString.Field class.

I think, it would be more practical to encapsulate the field names and values within the ConvertorToString.Field class, which will yield a better OOP-style design. Also, this change will allow you to transform the ConvertorToString.Field class from an inner class to a static nested class, because you don't need the reference to the outer class anymore. After you encapsulate the field name and its value in the ConvertorToString.Field class, the FIELD_NAME_AND_VALUE_SEPARATOR field would naturally belong to the ConvertorToString.Field class. And because the class name is Field, the FIELD_NAME_AND_VALUE_SEPARATOR field could further be renamed to NAME_AND_VALUE_SEPARATOR.

One other opinion on the ConvertorToString constants would be that you don't actually need them because you don't use them anywhere else besides the toString() methods. So, you could just use the string literals instead:

public class ToStringConvertor {
    private final String className;
    private final List<Field> fields;
    ...
    @Override
    public String toString() {
        return String.format(
            "%s(%s)",
            className,
            StringsCombiner.combine(fields, ", ")
        );
    }

    private static class Field {
        private final String name;
        private final Object value;
        ...
        @Override
        public String toString() {
            return String.format("%s=%s", name, value);
        }
    }
}


A recursive web-crawler created using vba

This is quite clean in general. I would probably only add blank lines to visually separate blocks of code and put comments about what is happening in the following block; and, apply the "Extract variable" refactoring method:

With http
    .Open "GET", dynamic_link, False
    .send
    html.body.innerHTML = .responseText
End With

''Extracting movie names
Set movieTitles = html.getElementsByClassName("browse-movie-title")
For Each movie In movieTitles
    ActiveCell.Value = movie.innerText
    ActiveCell.Offset(1, 0).Select
Next movie

''Feeding next page link to the crawler
Set paginationLinks = html.getElementsByClassName("tsc_pagination")(0).getElementsByTagName("a")
For Each link In paginationLinks
    If InStr(link.innerText, "Next") > 0 Then
        yify (main_link & Split(link.href, ":")(1))
    End If
Next link

Application.ScreenUpdating = True

I don't particularly like the way you are getting the next link, but, since I don't see that we can use CSS selectors or XPaths with this html document API.


Reverse a word using string manipulation

In response to your specific questions:

Use a vector. Using a vector you can just append to the end and it will resize itself as necessary.
You can not use printf with strings as printf is a C function and does not know C++'s strings. Either way you should generally avoid printf in C++ code.

General notes on your code:

#include<stdafx.h>
#include<stdio.h>
#include<stdlib.h>

The correct way to include C header files in C++ is to use #include <cheadername>, not #include <headername.h>. Further you should avoid C-functions when there are good C++ alternatives and you should generally not mix C's stdio with C++'s iostream. In this particular program I do not believe you need any of the C headers you include.

string temp[10];

I don't see any reason to have your global storage as a global variable. You should move it as a local variable inside the extract method. And as I already said, you should use a vector instead of a C array.

Also temp is a bad variable name.

void extract(char * c)

Don't mix char*s and strings unless necessary. In this case you can use strings all the way, so you should define extract with const string& sentence as an argument (note that sentence is also a more descriptive name than c).

Further it seems that your extract function is doing too much work: it's extracting words from the sentence into an array, and then printing it in reverse. These two separate steps should be done by two functions: extract (or maybe sentence_to_words which is more descriptive) and print_in_reverse.

You might even want to use 3 steps instead: extract the words, reverse them, then print them. This way your IO code is completely separate from any logic, which is always good. As a bonus point C++ already has a built-in function to reverse an array or vector, so no additional work for you.

Either way you'd need to change your extract function to either return the extracted words rather than void or take a vector into which to store the extracted words as an argument (by reference).

//char *temp = (char *)malloc(sizeof(char));

This code is commented out anyway (and doesn't do anything sensible from the looks of it), but as a general principle I want to point out that there's rarely a reason to use malloc over new in C++.

int ind = 0;
while(*c!= NULL)
{
    if(*c!= ' ') // read all chars in a word and store in temp.
    {
    temp[ind]= temp[ind] + *c;
    c++;

    }
    else if(*c== ' ') // reached end of word
    {
    c++;
    ind++;
    }
}

Using a vector you can get rid of ind as you can just push_back into the vector.

Further if you use strings, you can simplify this part by using find to find the next space and substr take the substring up to that space.

int length = sizeof(temp)/sizeof(temp[0]);

Note that this will only ever tell you the size of an array if the array's size is known at compile time (which is more or less equivalent to: "spelled out in the code"). So if you want the size of the array to be dynamic, you can't use this. If you use a vector, you can just use temp.size().

printf("The reversed string is");

As I already said, you shouldn't mix stdio and iostream. There is no reason to use printf here.

void main()

The correct return value for main is int, not void.

char *c = "seattle is good";

Again this should just be string sentence("seattle is good");. No reason to use char*.

If I were to write this program, I might do it like this:

#include <string>
#include <iostream>
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>

using std::string;
using std::vector;
using std::cout;
using std::endl;
using std::reverse;

// Splits a sentence by spaces into a vector of words
void extract(const string& sentence, vector<string>& words)
{
    size_t pos = 0;
    while(pos != string::npos)
    {
        // Find position of next space
        int next_space = sentence.find(" ", pos);
        // Store everything up to next space in the words vector
        words.push_back( sentence.substr(pos, next_space - pos));

        // Continue at the next character which is not a space.
        pos = sentence.find_first_not_of(" ", next_space);
    }
}

// Prints the strings in the vector separated by spaces
void print_strings(const vector<string>& strings)
{
    for(size_t i = 0; i < strings.size(); i++) {
        cout << strings[i] << " ";
    }
    cout << endl;
}

int main()
{
    string sentence("seattle is good");
    vector<string> words;
    extract(sentence, words);
    reverse(words.begin(), words.end());
    print_strings(words);
}


You can let it derive the  Functor declaration:

data PigLatin a = PigLatin a deriving Functor

foldl mappend mempty <- You want fold.

break implements some of your stuff already.

I wouldn't introduce the types PigLatin a and English a in the first place. They just introduce wrapping without extra type-level structural info.

import Control.Monad (when)
import Data.Char (toLower, toUpper)
import System.IO (hFlush, stdout)
import Control.Cateogry ((>>>)) -- flip (.)

--This turns empty words to yay, but words doesnt send empty words, right?
wordToPig :: String -> String
wordToPig = break (`elem` "aeiou") >>> \(initialConsonants, rest) ->
  rest ++ initialConsonants ++ if null initialConsonants then "yay" else "ay"

-- Your pig latin rules drop the first character of each sentence at the end?
sentenceToPig :: String -> String
sentenceToPig = capitalize . drop 1 . unwords . map wordToPig . words

capitalize :: String -> String
capitalize (x:xs) = toUpper x : map toLower xs
capitalize [] = ""

main :: IO ()
main = do
  putStr "> "
  hFlush stdout
  input <- getLine
  when (input /= "\\q") $ do
    print $ sentenceToPig input
    main


Where to put hidden fields when displaying entities properties in a table?

When you are iterating over the collection of people, it probably does make sense to keep the hidden fields within the loop. I would try to keep them grouped together in that first td, with a hidden field per line, so that they are easily noticeable when scanning the source.

If I weren't iterating (meaning that I was using some field at the top of my model, not in an array), I generally stuff my hidden inputs immediately following the opening  tag.

When iterating, within the td, a hidden element should have no effect on the rendering. You might consider wrapping them in a  or  with display:none applied. I believe there are some (older) browsers that will render white space if you have line breaks between your hidden inputs.


readJSON()

Returning HTTP 404 ("Not Found") is improper, unless you are deliberately sending obfuscatory responses as a kind of security-by-obscurity measure.  If you require a POST, and the client sends anything but a POST, the proper response should HTTP 405 ("Method Not Allowed").  For a body that does not have an appropriate JSON tag, I think that the appropriate response would be a non-specific HTTP 400 ("Bad Request").

In if-else branches, prefer to put the branch with less code first, to get it out of the way and reduce mental load.  Usually, that means putting the error handler first.  As a bonus, you can eliminate one level of indentation.

Instead of the try-finally construct, use a with block for the database cursor.

Assuming that there is an exact correspondence between the JSON tags and the method names of cc(), you could dispatch dynamically.  (Your syncProfile() method doesn't match 'syncprofile', but you could rename your methods accordingly.)

@csrf_exempt
def readJSON(request):
    if request.method != 'POST':
        raise Http405
    json_data = json.loads(request.body)

    # Whitelist allowable function calls for security
    if json_data['tag'] not in ['register', 'syncprofile', … ]:
        raise Http400

    cc_method = getattr(cc(), json_data['tag'])
    with connections['postgres_db'].cursor() as c:
        return HttpResponse(cc_method(c, json_data))

register()

Imports should be listed at the top of the file.  I wouldn't alias bcrypt as bc, as the latter sacrifices clarity just to save a few characters.

There are a lot of columns to be inserted, and a long parameter list.  I think it would be less error prone if you used named placeholders.

import bcrypt

def register(self, c, json_data):
    attr = dict(json_data['data'])
    attr['salt'] = bcrypt.gensalt()
    password = attr['password']
    attr['hash'] = bcrypt.hashpw(password, attr['salt'])
    attr['true'] = True
    try:
        c.execute("""INSERT INTO profiles VALUES (DEFAULT
                         , %(email)s
                         , %(hash)s
                         , %(salt)s
                         , %(date_created)s
                         , %(state_lvl)s
                         , %(true)s
                         , %(first_name)s
                         , %(last_name)s
                         , %(sex)s
                         , %(age)s
                         , %(state)s
                         , %(country)s
                         , %(language)s
                         , %(device_type)s
                         , %(device)s
                         , %(device_width)s
                         , %(device_height)s
                         , %(device_screen_density)s
                     )""", attr);
        json_response = json.dumps({"success": 1, "errors": 0})
    except Exception, e:
        json_response = json.dumps({"success": 0, "errors": 1, "msg": str(e)})
    return HttpResponse(json_response, mimetype="application/json")

It's a bit odd that you let the client specify the profile creation date.  I would just let the database issue a timestamp.

I think that the long parameter list is indicative of a problematic database schema.  If you ever want to add another attribute to the user profile, that would require a schema alteration.  The profiles table should probably be split into an accounts table containing the essentials and an account_attributes table that stores arbitrary key-value pairs.

CREATE TABLE accounts
( id SERIAL PRIMARY KEY
, email TEXT NOT NULL
, hash TEXT NOT NULL
, salt TEXT NOT NULL
, date_created DATE NOT NULL DEFAULT statement_timestamp()
);

CREATE TABLE account_attributes
( account_id INTEGER NOT NULL
, attribute TEXT NOT NULL
, value TEXT NOT NULL
, PRIMARY KEY (account_id, attribute)
, FOREIGN KEY (account_id) REFERENCES accounts (id)
);


Returning a list of the values from the binary tree

There is no docstring for the number method.
There are no test cases. This kind of code would be an ideal opportunity to write some doctests.
The depth property is always 0. This seems useless.
The method name number is misleading. (It does not return a number.) I would call it something like flattened_pre_order because it flattens the tree into a list using pre-order traversal.
The variable name lst is misspelt. Better to call it something like result.
This code:

if self.right is None and self.left is None:
    lst.append(self.item)
else:
    lst.append(self.item)

can be replaced with:

lst.append(self.item)

since it doesn't matter whether the condition is true or false.
There's quite a lot of copying going on in the traversal of the tree: each time you call a.extend(b), Python has to copy out the list b. This copying causes the traversal of a tree with n nodes to take O(n2) time instead of O(n). See below for a way to avoid this copying.
You use recursion to visit the child nodes, which means that traversing a very deep tree will exceed Python's maximum recursion depth:

>>> n = None
>>> for i in range(1000): n = BTNode(i, n)
...
>>> n.number()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr33662.py", line 22, in number
    left = self.left.number()
  [... many lines omitted ...]
RuntimeError: maximum recursion depth exceeded

The way to avoid this is to maintain your own stack, like this:

def flattened_pre_order(self: 'BTNode') -> list:
    """Return a list of items in the tree rooted at this node, using
    pre-order traversal.

        >>> tree = BTNode(1, BTNode(2, None, BTNode(3)), BTNode(4))
        >>> tree.flattened_pre_order()
        [1, 2, 3, 4]
        >>> node = BTNode(9999)
        >>> for i in range(9998, -1, -1): node = BTNode(i, node)
        >>> node.flattened_pre_order() == list(range(10000))
        True

    """
    result = []
    stack = [self]
    node = None
    while stack:
        if node is None:
            node = stack.pop()
        if node is not None:
            result.append(node.item)
            stack.append(node.right)
            node = node.left
    return result