Random bits with a specified density (Bernoulli Trials)

For what I can see, the code fills an array with a given amounts of true values (the rest being false) in random order. I'd rather initialize first p*N elements to true, and then random_shuffle the array.

That said I don't understand why you need this array at all. Can we see how your application uses it?


Make your menus more uniform, then you won't have to do the ng-switch-ing.  So something like

$scope.menus = [
  {
    title: 'Startsida'
  },
  {
    title: 'Messages',
    items: ['Inkorg', ...]
  },
  {
    title: 'My Pages',
    items: ['Mina kurser', ...]
  },
  ...
];

Then check whether you have the items field and if so, render the items:

{{menu.title}}

{{subitem}}

It might be worthwhile to split the URLs from the titles as well.

This approach will break down somewhat at a point when the nesting level of your menu gets too deep, because you have to add more nested lists, but until then this will keep working.


To understand what recursion is, you must first understand recursion

Usually we write recursive functions with the exit condition all by itself:

void writeLine(const char c, const int8_t num)
{
  if (num > 0)
  {
    std::cout << c;
    writeLine(c, num - 1);
  }
}

I would normally write this as:

void writeLine(const char c, const int8_t num)
{
  if (num <= 0)
  {
      return;
  }

  std::cout << c;
  writeLine(c, num - 1);
}

No real reason apart from tradition I suppose. But it does show tail recursion more clearly. The compiler can easily optimize tail recursion into a loop for you. But it also makes it obvious to the human eye where tail recursion is.

A static member of a recursive function!!!

void writePyramid(const char c, const int8_t h)
{
  static int count;
  count++;

That's a bit strange. You normally pass all values as parameters between iterations. If you need a defaulting starting value then you can either use a wrapper function that calls your recursive function and provides the initial value. Or have a parameter that defaults to the start value but internally you increment it (I choose the second here).

void writePyramid(const char c, const int8_t h, int count = 0)
{
  if (h <= 0)
  {
    return;
  }

  writeLine(' ', (2 * h - 1) / 2);
  writeLine(c, (2 * count - 1));
  std::endl(std::cout);
  writePyramid(c, h - 1, count + 1);
}

I know that Static storage duration objects are zero initialized. But how many of your peers know this. It would have been nice to give them a hint.

static int count = 0;

Going back to your wrapper code:

All the switch statements contain the same bit of code:

  std::cout << "Enter number of rows: ";
  std::cin >> rows;
  std::cout << "Enter number of columns: ";
  std::cin >> cols;
  std::cout << "Enter character to build with (*): ";
  type = getSanitizedChar();

Keep it DRY. Either move this into a separate function (called from each case). Or move it to before the switch intirally.


A storage bin thingy for Repl.it projects

Few optimization tips

verify_password function

avoid bare except: clause - at least use except Exception: (though it's also broad, check which exception class is most appropriate in that context)
a set of statements:

try:
    if check_password_hash(user["password"], password):
        return True
except: return False
return False

is an overloaded and verbose version of a more explicit logic:

@auth.verify_password
def verify_password(username, password):
    user = db.retrieve(f"users/{username}")
    try:
        return check_password_hash(user["password"], password)
    except Exception:
        return False

don't overuse (or avoid entirely) multiple statements one-liners like if <condition>: <long statement>
avoid writing duplicated lengthy db statements like:

if request.is_json: db.store(f"users/{user}", { "password": generate_password_hash(request.get_json()['password'])})
else: db.store(f"users/{user}", { "password": generate_password_hash(request.form['password'])})

To fix that determine request data source beforehand. Optimizing register function:

@app.route('/regester', methods = ['POST'])
def register():
    data = request.get_json() if request.is_json else request.form
    user = data['username']
    if db.retrieve(f"users/{user}"):
        return False

    db.store(f"users/{user}", {"password": generate_password_hash(data['password'])})
    return make_response(user, 201)

Apply this optimization technique to all remaining functions with a similar issue.


There's no docstring. What does travel do? What arguments does it take? What does it return?
The meaning of the data structure queue is far from clear. It seems to be a deque whose elements represent paths, each path being represented by a list of pairs (v, e) where v is the vertex on the path, and e is None if this is the first vertex on the path, or an iterable of edges by which v could be reached from the previous vertex of the path. This kind of complex data structure is hard to understand, and would be clearer if it had its own class, for example using collections.namedtuple.
It would be a good idea to generate the paths one at a time using the yield statement, so that if a consumer is processing the paths one at a time then the whole list of paths does not have to be stored in memory.
Generating the paths would also allow us to omit the count argument and keep generating paths forever. If the caller wants at most 1000 paths, they can use itertools.islice:

islice(travel(graph, start, dests), 1000)

The test if at in dests: takes time proportional to the number of destinations. This would run in constant time if dests were converted to a set.
It would be reasonable to insist on the graph having a key for every vertex (whose corresponding value is an empty dictionary if the vertex is a sink); this would allow you to write graph[at] instead of graph.get(at, {}) which creates and throws away an empty dictionary.
The implementation stores path + [item] in the queue, taking time and space proportional to the length of the path, on each iteration. This is unnecessary: many paths will share the same initial prefix, so a data structure which stored only the last item on the path, together with a reference to the previous data structure on the path, would take constant time on each iteration. The whole path could be reconstructed when the destination is reached by following the references.

2. Revised code

from collections import deque, namedtuple

# Node in the breadth-first search with fields:
# vertex -- the current vertex in the search
# edges -- iterable of edges from previous vertex (or None)
# prev -- previous Search node (or None)
SearchNode = namedtuple('SearchNode', 'vertex edges prev')

def travel(graph, start, dests):
    """Generate paths in graph beginning at the vertex start and ending at
    any of the vertices in dests.

    The graph must be represented as a mapping from vertex to a
    mapping from neighbouring vertex to an iterable of edges.

    """
    dests = set(dests)
    queue = deque([SearchNode(start, None, None)])
    while queue:
        at = queue.popleft()
        if at.vertex in dests:
            edges = []
            prev = at
            while prev.edges is not None:
                edges.append(prev.edges)
                prev = prev.prev
            for path in product(*reversed(edges)):
                yield ''.join(path)
        for v, e in graph[at.vertex].items():
            queue.append(SearchNode(v, e, at))


Created my first wordpress plugin template page, need comments

First of all, your plugin is not translation ready, see l18n. In the plugin header, you should add

* Text Domain: your-textdomain
* Domain Path: /languages

Create the language files in wp-content/plugins/your-plugin/languages with PoEdit. And make all relevant strings translatable with:

add_menu_page( __('Plugin title','your-textdomain'), ...
// and
<?php _e('Options saved','your-textdomain'); ?>

There's a big issue: you're printing your styles and scripts all over the admin area. It's essential that you always target the correct page.

add_action( 'admin_menu', 'my_first_plugin_add_page' );
function my_first_plugin_add_page()
{
    $hook = add_menu_page(
        'plugin title',
        'plugin title',
        'manage_options',
        'my_first_plugin',
        'my_first_plugin_do_page'
    );
    add_action( "admin_print_scripts-$hook", 'my_first_plugin_scripts' );
}

You don't need to close and open PHP tags if you're not swapping between PHP and HTML:

*/
?>
<?php
function my_first_plugin_init(){

Get rid of the very last ?> too.
See Why do some scripts omit the closing php tag ?>.

It's easier to have a general picture if you declare first the hooks and then the callbacks.

add_action('first_hook', 'prefix_first_callback');
add_action('second_hook', 'prefix_second_callback');
add_filter('third_hook', 'prefix_third_callback');
function prefix_first_callback() {}
function prefix_second_callback() {}
function prefix_third_callback() {}

It's important to prefix everything, function names, meta data and $_POSTed data. But for function names this quickly turns into hard to read code. Encapsulating everything in a class avoids this. And also allows us to start-up our plugin in a safe point: plugins_loaded, see Best way to initiate a class in a WP plugin?.

The following is a clean version of Plugin Class Demo, by toscho◆. Please, go to the source for the full documented class.

add_action(
    'plugins_loaded',
    array ( PREFIX_My_Plugin::get_instance(), 'plugin_setup' )
);

class PREFIX_My_Plugin
{
    protected static $instance = NULL;
    public $plugin_url = '';
    public $plugin_path = '';

    public static function get_instance()
    {
        NULL === self::$instance and self::$instance = new self;
        return self::$instance;
    }

    public function plugin_setup()
    {
        $this->plugin_url    = plugins_url( '/', __FILE__ );
        $this->plugin_path   = plugin_dir_path( __FILE__ );
        $this->load_language( 'plugin_unique_name' );
        // Your stuff: register actions and filters
        add_action( 'admin_init', array( $this, '_admin_init' ) );
    }

    public function _admin_init()
    {
        // your_stuff();
    }

    public function __construct() {}

    public function load_language( $domain )
    {
        load_plugin_textdomain(
            $domain,
            FALSE,
            $this->plugin_path . 'languages'
        );
    }
}


Writing an HTTP POST body that has new lines

Iterating over a list

Using an Iterator to iterate over a list is very old-fashioned.
It's better to use the for-each syntax when possible:

for (String record : records) {
    // ...
}

I noticed that the last element is treated differently from the others:
a \n character is not appended after the last record.
Is that really necessary?
I doubt it. Trailing \n characters should not make the JSON invalid.
Although the implementation may be correct to not print a trailing \n,
it seems a bit pedantic.

If for some reason you need to keep the special treatment of the last line,
you can still use the for-each technique with twist:

if (!records.isEmpty()) {
    output.write(records.get(0).getBytes(Charset.forName("UTF-8")));
    for (String record : records.subList(1, records.size())) {
        output.write('\n');
        output.write(record.getBytes(Charset.forName("UTF-8")));
    }
}

That is, instead of treating the last item specially,
we treat the first item specially,
and then use .subList to effectively work with the tail of the list.
Note that .subList does not copy the content of the list,
so it's not inefficient.

And if you can use Java 8, then an even more compact solution is possible using String.join:

output.write(String.join("\n", records).getBytes(Charset.forName("UTF-8")));

try-with-resources

You used try-with-resources when writing to the output stream, but not when reading from the input stream. It's always good to use it whenever possible:

StringBuilder response = new StringBuilder();
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
}


I would probably put it right in your __init__ method, which simplifies it every time a fraction is created (which includes after any operation).

I disagree with Jaime's answer that you should do the simplification as part of the operation, as you'll have to copy/paste that code for every new operation.

I’d write something like:

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

class Fraction(object):
    def __init__(self, numer, denom):
        cancel_factor = gcd(numer, denom)
        self.numer = numer / cancel_factor
        self.denom = denom / cancel_factor

A few other comments:

Per PEP 8 on class names, I'm using Fraction instead of frac.

Also from PEP 8, I would put spaces around your multiplication operators.
New style classes should inherit from object (as I've done above).
I think numer and denom are better attribute names than a and b.
The convention is to use other as the variable name in a method that takes two inputs, rather than x. For example:

def __add__(self, other):
    new_numer = self.numer * other.denom + self.denom * other.numer
    new_denom = self.denom * other.denom
    return Fraction(new_numer, new_denom)

I disagree with your use of __repr__. As a rule of thumb, __repr__ should be something you can eval() to get back to that object; __str__ is the human-readable object. See difference between __str__ and __repr__ for more.

Here's what I'd write:

def __repr__(self):
    return "Fraction(%s, %s)" % (self.numer, self.denom)

def __str__(self):
    return "%s / %s" % (self.numer, self.denom)


SQL Query that pulls rows in current table based on parent id optimization

The sub-query as a concept is not a problem... you need to do that work, and this is a decent way to do it.

It would be better if it was expressed as a direct lookup... like:

WHERE `po`.`object`='EVENTS'
   OR exists (
      SELECT `sub`.`id`
      FROM `permission_objects` `sub`
      WHERE `sub`.`object`='EVENTS'
        and `sub`.`id` = `po`.`parent_id`
)

This sub-select is better because it can do an indexed lookup in the table in the sub-select based on the id column.

Apart from that, I don't see a better, or neater way to do it.


My approach is to have two indexes. The i index starts at the left and the j index starts at the right of the array. For a length of 4, we would do these comparisons in this order.
(0, 3), (0, 2), (0, 1), then (1, 3), (1, 2), then, (2, 3) This is basically a pairwise comparison. (Note the initialization part of the for loop is empty)

int frontIndex = 0;
int endIndex = sequence.length - 1;
for( ; frontIndex < endIndex; frontIndex++)
{
    for(int i = endIndex ; i > frontIndex; i--)
    {
    //stuff here
    }
}

Once a match is found, we start counting the max length, with one index moving to the left and one to the right. The while condition makes sure we don't go out of bounds. Once we break out of that loop, we may update the max length.

while(frontIndex + currentLength < sequence.length && i - currentLength >= 0)
{
    if(sequence[frontIndex + currentLength] == sequence[i - currentLength])
    {
        currentLength++;
    }
    else break;
}
if (currentLength > maxLength) maxLength = currentLength;
currentLength = 0;

This is the entire class

public class Mirrors
{
    public static void main(String[] args)
    {
        int maxLength = 1;
        int currentLength = 0;
        int[] sequence = {1, 2, 1, 2, 1};
        int frontIndex = 0;
        int endIndex = sequence.length - 1;
        for( ; frontIndex < endIndex; frontIndex++)
        {
            for(int i = endIndex; i > frontIndex; i--)
            {
                if(sequence[frontIndex] == sequence[i])
                {
                    currentLength++;
                    while(frontIndex + currentLength < sequence.length && i - currentLength >= 0)
                    {
                        if(sequence[frontIndex + currentLength] == sequence[i - currentLength])
                        {
                            currentLength++;
                        }
                        else break;
                    }
                    if (currentLength > maxLength) maxLength = currentLength;
                    currentLength = 0;
                }
            }
        }
        System.out.print("Max length is " + maxLength);
    }
}


Here you are using a few structures which I feel are not the right tool for the job.

Firstly, you are given an array of int, but you are returning a List<Integer>. I dislike List<Integer>, but even worse than using a List for primitives, is using a mixture of them. Be consistent!

The dueue is a confusing concept. It is worse because you use a for-loop in a non-traditional way, with the loop-variable declared outside the loop, and you reuse it later. You don't have any comments explaining how you use it.

At this point, I have looked through the requirements, I have figured out how I would do it. I can see that your strategy may have some advantages, if it does what I think it does, but it is complicated, and hard to read. So, I am giving up....

Code Review not successful, not commented enough, not enough background information.


Finding travel distance between airports

First, let's download some data similar to yours (I assume). This csv available online has almost 7,000 airports:

url <- "https://commondatastorage.googleapis.com/ckannet-storage/2012-07-09T214020/global_airports.csv"
library(RCurl)
txt <- getURL(url)
data <- read.csv(textConnection(txt), stringsAsFactors = FALSE)

For illustration purposes, we will use a small sample: the six airports in Jamaica.

dat <- subset(data, country == "Jamaica",
              c("city", "country", "name", "latitude", "longitude"))
dat
#              city country               name latitude longitude
# 1745    Ocho Rios Jamaica           Boscobel 18.40425 -76.96902
# 1746     Kingston Jamaica Norman Manley Intl 17.93567 -76.78750
# 1747  Montego Bay Jamaica      Sangster Intl 18.50372 -77.91336
# 1748 Port Antonio Jamaica          Ken Jones 18.19881 -76.53453
# 1749     Kingston Jamaica         Tinson Pen 17.98856 -76.82376
# 5878       Negril Jamaica   Negril Aerodrome 18.34000 -78.33556

Now let's have a look at your code. I will not review the math in earth.dist, I'll assume it is correct. One beautiful thing about that function is that it is vectorized, i.e., you could give it n-long vectors as inputs and it will compute n distances in a single call. Unfortunately, the rest of your code does not take advantage of it. Instead, your double loop only calls earth.dist with scalars at each time...

Instead of a double loop, you should be using the outer function. Have a look at the doc (?outer) if you are not familiar with it. The typical usage is outer(X, Y, FUN) where X and Y are vectors and FUN is a vectorized function. The output is a matrix Z where Z[i, j] is the result of FUN(X[i], Y[j]). But what's brilliant about outer is that it does not call FUN as many times as there are entries in Z (length(X) * length(Y)). No, it calls is only once. How? Because FUN is vectorized (a requirement) and outer knows how to take advantage of it.

So, here is how we can massage your data a bit so we can use outer. First, remember that outer loops on the pairwise combinations from two vectors. In our case, we could use the names of the airports:

airport.names <- dat$name

so we will be calling outer(airport.names, airport.names, FUN = airport.dist). All that is left is to write airport.dist: a vectorized function that will take as inputs two vectors of airport names and return their distances. We could first put the important data in a matrix with airport names as row names for easy access:

dat.mat <- as.matrix(dat[, c("latitude", "longitude")])
rownames(dat.mat) <- airport.names

Then define:

airport.dist <- function(name1, name2, data = dat.mat) {
    lon1 <- data[name1, "longitude"]
    lat1 <- data[name1, "latitude"]
    lon2 <- data[name2, "longitude"]
    lat2 <- data[name2, "latitude"]
    return(earth.dist(lon1, lat1, lon2, lat2))
}

Then run outer:

dist.mat <- outer(airport.names, airport.names, FUN = airport.dist)

and attach names to the columns and rows:

dimnames(dist.mat) <- list(airport.names, airport.names)

#                     Boscobel Norman Manley Intl Sangster Intl Ken Jones Tinson Pen Negril Aerodrome
# Boscobel             0.00000           55.58311     100.33081  51.30027   48.75737        144.54554
# Norman Manley Intl  55.58311            0.00000     134.79830  39.68379    7.02926        169.83797
# Sangster Intl      100.33081          134.79830       0.00000 149.58621  128.67955         48.17112
# Ken Jones           51.30027           39.68379     149.58621   0.00000   38.52863        191.03056
# Tinson Pen          48.75737            7.02926     128.67955  38.52863    0.00000        164.62138
# Negril Aerodrome   144.54554          169.83797      48.17112 191.03056  164.62138          0.00000

If you need to convince yourself that earth.dist was called a single time, you could add a cat("HELLO\n") somewhere inside its body (I did!). earth.dist having been called only once, there is no need to say how fast the computation will be.

Finally, if you want to store the distances in a three column (airport1, airport2, distance) data.frame rather than a matrix, you can do:

d <- dist.mat
dist.df <- data.frame(airport1 = rownames(d)[row(d)],
                      airport2 = colnames(d)[col(d)],
                      distance = c(dist.mat))

I hope it helps! Don't hesitate to comment below if you have questions.


Assign a value to combobox depend upon other combobox value

I think you might be able to eliminate creating the distinct list and the nested ifs by first checking for the All() condtions, then later check for Any()

    var items = list_of_combobox.ToList();

    if (items.All(str => str.Equals("Finding")))
    {
       // assign final comboxbox
    }
    else  if (items.Any(str => str.Equals("Finding")))

Also, you might want to try creating an enum of the possible values, adding these values to the ComboBox, then getting/setting the SelectedItem property rather than dealing with indexes.


First things first, the convention is to use uppercase-initial for class names.

All modules, functions, classes and methods should have docstrings.

According to their API documentation, if limit is not specified, the default is 100 and by default convert is 'USD'. Your coins_arr() method is returning 100 coins, not 10, which I think is due to an incorrect formatting of the placeholder in the URL you are passing to requests.get(). You are splitting each coin and concatenating it to coinsData, which is not necessary since you just need to append it to the list.

The coins_dict() method is also returning 100 coins, not 10.

There is also some repetition in the two methods, which you could avoid.

Here I would write the class, like so:

import requests

class Coins:
    """This is a class for cryptocurrencies."""

    def __init__(self, url, limit=10):
        self.url = url
        self.limit = limit
        self.data = requests.get(self.url.format(self.limit)).json()

    def get_coins(self):
        """Return a sorted list of cryptocurrencies."""

        coins = sorted(v for obj in self.data
                       for k, v in obj.items() if k == 'id') # sorted() returns a list

        return coins

    def get_coins_prices(self):
        """Return a dictionary of cryptocurrencies and their prices."""

        coins_prices = {obj[k]: obj['price_usd'] for obj in self.data
                        for k, v in obj.items() if k == 'id'}

        return coins_prices

if __name__ == '__main__':
    url = 'https://api.coinmarketcap.com/v1/ticker/?limit={}'

    obj_a = Coins(url)
    print(obj_a.get_coins())

    obj_b = Coins(url)
    print(obj_b.get_coins_prices())

    obj_c = Coins(url, limit=5) # Setting limit to 5 results
    print(obj_c.get_coins_prices())

The Python version used to test the above code is 3.6.

Hope that helps.


It's opinion-driven, but general points:

You return large strings. Use try/catch for custom errors and warnings.
Manage specific messages separately from your OOP (for example, language files).
Separate layers, such as presentation, application, business logic, etc.

About the further structure: correct, but you didn't post serious logic.

There are many patterns to solve problems, such as Model-View-Controller (separating responsibilities), Adapter pattern, Factory pattern, etc. Read more here.


Checking whether one string is a permutation of another

For both strings, generate a dictionary containing distinct characters of the string as keys and their respective counts as values.

If the two dictionaries are equal, the strings are permutations of each other.

Instead of manually counting characters using a dict, you can utilize the collections.Counter class. To save time in case the strings are of different length, you can compare their lengths first.

from collections import Counter

def checkPermutation(str1, str2):
    return len(str1) == len(str2) and Counter(str1) == Counter(str2)

This is a \$O(n)\$ time and approximately \$O(1)\$ space solution. Approximately because – presumably – the less distinct characters there are in the input strings, the less space is occupied by the counters.


One way is to use multiplication. Multiplying a String by a Fixnum will produce a new String where the original String appears the Fixnum of times.

"-" * @title.length #=> "---------------"

Documentation for String#*

Warning: Make sure you put the String first or else you will get a TypeError: String can't be coerced into Fixnum since that would be calling Fixnum#* instead of String#*.


First, you should follow the Java naming conventions.

Second, don't shorten names just because you can. Example, what does "Proc" stand for? Procedure? Processor? Even if names become longer, the readability is worth it!

static String db_host = null;

Your members should not be static, and should ideally be qualified with something else than package-private, like protected or private to show the intent clearly.

In order to read the required arguments I need some kind of state machine.

Is that a requirement you've been given or is that an assumption you had? Because that's not true at all. Overall, your system is completely unnecessarily complex without an obvious reason or benefit. Neither does it seem like a state-machine at all, it's just an overly complex chain of function calls.
A state-machine for your command-argument parsing would be something like this:
for (int index = 0; index < args.length; index++) {
    String arg = args[index];

    if (arg.equals("-p") && databaseHost == null) {
        arg = args[++index];

        databasePort = arg;
    } else if (databaseHost == null) {
        databaseHost = arg;
    } else if (databaseUsername == null) {
        databaseUsername = arg;
    } else if (databasePassword == null) {
        databasePassword = arg;
    } else if (inputFile == null) {
        inputFile = arg;
    }
}

And even that is oddly complex.
What you want is the most simplest solution that works, and that would be a hardcoded extracting of arguments:
if (args[0].equals("-h")) {
    printHelp();
    return;
}

int portProvidedOffset = 0;

if (args[0].equals("-p")) {
    databasePort = args[1];

    portProvidedOffset = 2;
}

databaseHost = args[portProvidedOffset + 0];
databaseUsername = args[portProvidedOffset + 1];
databasePassword = args[portProvidedOffset + 2];
inputFile = args[portProvidedOffset + 3];

Which is, of course, not pretty, but the most simplest solution you can get away with. Of course, the length of the array should be checked beforehand, whether it is 4 elements or more. Afterwards you'd check whether all parameters are set, if not, exit with an error.
If you want a more sophisticated solution, you'd need to write yourself a complete argument parser, a not-so-trivial exercise.


I think binary search will be super fast too (without divisions):

public static long intSqrtBinarySearch(long number) {
    long l = 0L, r = Integer.MAX_VALUE;
    while (l < r) {
        long mid = (l + r + 1L) / 2L; // div 2 - bitwise operation
        if (mid * mid <= number) {
            l = mid;
        } else {
            r = mid - 1L;
        }
    }
    return l;
}

Also, your implementation of intSqrt2() may produce overflow error.
Test:

Failed number : 383100999
Bad answer    : 383100999
Correct       : 19572


Fetching data from nested JSON using jQuery and displaying in table

You may take advantage of reduce() and map() functions to have no loop at all, like this:

$('#data').append(
  resp.DATA.reduce((table, obj, index) => (
    table + (
      !index ? (
        Object.keys(obj).reduce((header, key) => `${header}<th>${key}`, '
')
      ) : ''
    ) + $.map(obj, v => v).reduce((row, value) => `${row}<td>${value}`, '
')
  ), '
') + '
'
);

I also used some tagged strings, so more reducing the size of the code.
Additionally it works a bit faster than the original version, as you can observe with the following snippet.

var resp= {
  "ERROR": [],
  "DATA": [{
    "CustomerID": "234",
    "BranchID": "1",
    "LocationID": "26",
    "FirstName": "Lakshmi "
  }, {
    "CustomerID": "235",
    "BranchID": "1",
    "LocationID": "6",
    "FirstName": "Arora "
  }, {
    "CustomerID": "236",
    "BranchID": "1",
    "LocationID": "68",
    "FirstName": "S.K.Raman "
  }, {
    "CustomerID": "237",
    "BranchID": "1",
    "LocationID": "38",
    "FirstName": "Vidya Rao "
  }, {
    "CustomerID": "238",
    "BranchID": "1",
    "LocationID": "18",
    "FirstName": "Raju "
  }, {
    "CustomerID": "239",
    "BranchID": "1",
    "LocationID": "49",
    "FirstName": "K.B.Hebbar "
  }],
  "META": {
    "currentPageNumber": "1",
    "totalPages": "11",
    "rowcountCurrentPage": "10",
    "rowcountTotal": "107"
  }
}

var begTime = performance.now();var content = '
';
var heading = "
";
var data = "";
$.each(resp.DATA[0], function(ke, va) {
  heading += '' + ke + '	';
});
$.each(resp.DATA, function(key, value) {
  data += "
";
  $.each(value, function(k, v) {
    data += '' + v + '	';
  });
  data += "
";
});
heading += "
";
content += heading + data + "
";
$('#data').append(content);
$('#data').append(`<h3>OLD: ${performance.now() - begTime} ms</h3>`);

var begTime = performance.now();
$('#data').append(
  resp.DATA.reduce((table, obj, index) => (
    table + (
      !index ? (
        Object.keys(obj).reduce((header, key) => `${header}<th>${key}`, '
')
      ) : ''
    ) + $.map(obj, v => v).reduce((row, value) => `${row}<td>${value}`, '
')
  ), '
') + '
'
);

$('#data').append(`<h3>NEW: ${performance.now() - begTime} ms</h3>`);
<!DOCTYPE html>

    <title>COnsuming rest webservice</title>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Consuming REST api

    </script>

NOTE: in your version as well as mine, we never take care of the keys in nested objects: they work only if they appear always in the same order!


Overall, I think the code looks good.  Here are a few sugestions that may help you improve your code.

Check for overflow

As you know, terms of the Fibonacci sequence get very big very quickly.  For this reason, it's easy to overflow the numerical range.  I'd suggest addressing this by throwing an exception in iterator& operator++():

if (b_ < a_) {
  throw std::overflow_error("Exceeded range of underlying type");
}

Use an unsigned type

None of the terms of the Fibonacci sequence are negative, so I'd suggest that perhaps unsigned or even unsigned long might be more appropriate base types.

Use a template

It may make sense to turn this into a templated function to allow different types to be used as the base type.  This would be one way to extend the range, such as with the GNU Multiple Precision Arithmetic Library.

Consider a different operator++ implementation

The current implementation of the operator++ is this:

iterator& operator++() {
  ++i_;
  b_ = b_ + a_;
  a_ = b_ - a_;
  return *this;
}

I would suggest, especially if you decide to implement templates, that this might be more efficient:

iterator& operator++() {
  ++i_;
  std::swap(a_, b_);
  b_ += a_;
  if (b_ < a_) {
      throw std::overflow_error("Exceeded range of underlying type");
  }
  return *this;
}


Unbounded Sieve of Eratosthenes in Swift

1 is not a prime number!

By definition, a prime number is an integer greater than one which has
no (positive) divisor other than 1 and itself.

Both the UnboundedSieve
iterator and the sieveOfEratosthenes function – correctly – produce 2 as the first prime. But then in PrimeSequence, the number 1
is inserted and I see no reason to do so.

From the description and naming of the max parameter in the

/// Construct a sequence of primes up to a max.
/// ...
public init(max: Int)

constructor I would assume that it produces a sequence of all primes
up to and including max, but that is not true: It produces all
primes below max because

private func sieveOfEratosthenes(n: Int) -> [Int]

returns all primes below n. That might be unexpected. I would
suggest to change the function so that the upper limit is included,
and give the parameters a more descriptive name:

/// Creates a sequence of primes up to (and including) `limit`.
public init(upTo limit: Int) {

I don't see the benefit of the terms parameter in

public init(terms: Int? = nil)

because  PrimeSequence(terms: numberOfTerms)
can be replaced by PrimeSequence().prefix(numberOfTerms),
using the prefix() method from the Swift standard library.
I would suggest to remove that parameter.

That leaves us with only two cases: creating a finite sequence
(using the sieve of Eratosthenes), or an infinite sequence
(using a priority queue), and the PrimeSequence definition
can be simplified to

public struct PrimeSequence: Sequence {
    private let iterator: AnyIterator<Int>

    /// Creates a sequence of primes up to (and including) `limit`.
    public init(upTo limit: Int) {
        self.iterator = AnyIterator(sieveOfEratosthenes(upTo: limit).makeIterator())
   }

    /// Creates an "infinite" sequence of prime numbers.
    public init() {
        self.iterator = AnyIterator(UnboundedSieve())
    }

    public func makeIterator() -> AnyIterator<Int> {
        return iterator
    }
}

struct UnboundedSieve looks like a clean implementation of the
priority queue-based algorithm from https://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf to me. However,

sieve.enqueue(PrimeCounter(prime: counter, composite: counter + counter))

can be improved to

sieve.enqueue(PrimeCounter(prime: counter, composite: counter * counter))

since all primes less than counter have already been found.
This reduced the execution time of my test (code below) from
2.26 sec to 1.17 sec.

A possible further improvement is to treat the only even prime 2
separately and then handle only odd numbers:

private struct UnboundedSieve: IteratorProtocol {

    var sieve: PriorityQueue<PrimeCounter>
    var counter = 2

    init() {
        sieve = PriorityQueue { $0.composite < $1.composite }
    }

    private struct PrimeCounter {
        let prime: Int
        var composite: Int
        func next() -> PrimeCounter {
            return PrimeCounter(prime: prime, composite: composite + 2 * prime)
        }
    }

    mutating func next() -> Int? {
        if counter == 2 {
            counter = 3
            return 2
        }

        while let catcher = sieve.peek(), catcher.composite == counter {
            while let catcher = sieve.peek(), catcher.composite == counter {
                sieve.replaceTop(with: catcher.next())
            }
            counter += 2
        }
        defer {
            sieve.enqueue(PrimeCounter(prime: counter, composite: counter * counter))
            counter += 2
        }
        return counter
    }
}

The reduced the execution time of the test code to 0.58 sec.

In sieveOfEratosthenes() the same improvement as mentioned above
applies: If a prime number is found then "crossing out multiples"
can start at the square of that prime:

private func sieveOfEratosthenes(upTo n: Int) -> [Int] {
    var numbers = [Int](2...n)
    for i in 0...n-2 {
        let prime = numbers[i]
        guard prime > 0 else { continue }
        for multiple in stride(from: prime * prime-2, through: n-2, by: prime) {
            numbers[multiple] = 0
        }
    }
    return numbers.filter { $0 > 0 }
}

The reduced the execution time for my test code from
0.37 sec to 0.28 sec.

The numbers array in this function holds redundant information,
memory can be saved by replacing it a by an array of booleans
which marks all numbers which have been found to be composite:

private func sieveOfEratosthenes(upTo n: Int) -> [Int] {
    var result = [Int]()
    var composite = [Bool](repeating: false, count: n + 1)
    for i in 2...n {
        if !composite[i] {
            result.append(i)
            for multiple in stride(from: i * i, through: n, by: i) {
                composite[multiple] = true
            }
        }
    }
    return result
}

In my test this also turned out to be faster: 0.13 sec.

You could also implement the Eratosthenes sieve as an iterator,
which makes it non-eager and removes the results array:

private struct EratosthenesIterator: IteratorProtocol {
    let n: Int
    var composite: [Bool]
    var current = 2

    init(upTo n: Int) {
        self.n = n
        self.composite = [Bool](repeating: false, count: n + 1)
    }

    mutating func next() -> Int? {
        while current <= self.n {
            if !composite[current] {
                let prime = current
                for multiple in stride(from: current * current, through: self.n, by: current) {
                    composite[multiple] = true
                }
                current += 1
                return prime
            }
            current += 1
        }
        return nil
    }
}

The corresponding init method in struct PrimeSequence then becomes

    /// Creates a sequence of primes up to (and including) `limit`.
    public init(upTo limit: Int) {
        self.iterator = AnyIterator(EratosthenesIterator(upTo: limit))
   }

The execution time for the test code is now 0.12 sec.

Benchmarking code for the infinite generator:

Calculate the sum of the first 10,000 primes:

let numPrimes = 10_000
do {
    let startTime = Date()
    let sum = PrimeSequence().prefix(numPrimes).reduce(0, combine: +)
    let endTime = Date()
    print(sum, endTime.timeIntervalSince(startTime), "sec")
}

Benchmarking code for the Eratosthenes generator:

Calculates the sum of all primes below 10,000,000:

let N = 10_000_000

do {
    let startTime = Date()
    let sum = PrimeSequence(upTo: N).reduce(0, combine: +)
    let endTime = Date()
    print(sum, endTime.timeIntervalSince(startTime))
}

The tests were done on a MacBook, with the program compiled in Release mode.


A few short comments:

Don't use namespace std:

It's bad for a few reasons, but in short: You can have big name conflicts if you are using namespace std;. For more information: Why is using namespaec std considered bad practice?

Break conditions:

well lookie here:

while (bottle > 0)
{
    //print the lyrics
    if (bottle == 1)
    {
         break;
    }
}

This could be much simpler:

while (bottle > 1)
{
     //print the lyrics
}

Naming:

bottle is a crap name for a counter. Make it bottleCount, leftBottles or about anything else, but don't name it bottle. Because it isn't a bottle...


Optimization - open excel file from VB.NET using interop

Interop is surely enough for this purpose. To manipulate workbooks, fill in 10.000th of cells then I usually use SpreadsheetLight (http://spreadsheetlight.com/), a free, MIT licensed .NET library that works on the XML level of the Excel files and is incredibly fast compared to the Application.Excel object.

From the point of code review, I think you could dive a bit more into VB.NET, your code still has the feeling of being VB6 or VBA. Why don't you switch to try/catch error handling for example? I assure you, you are going to like it. And as a rule of thumb, never compile any path/file names into your application, put them into app.config (especially if this is a standalone application) or into start parameters (especially if this application is called from within an enterprise database application).


Python implementation for contains pattern in text

PEP8 and readability

You have a few great docstrings, there is no need for block-comments and docstrings.
In contains you have this assert isinstance(text, str) but don't use it.

Code changes

Your contains(text, pattern) could be a lot more simplified. Because contains checks whether a pattern occurs in text and returns a boolean indicating .

def contains(text, pattern):
    """Return a boolean indicating whether pattern occurs in text."""
    # If our pattern index is equal to our pattern length
    # then we found a match and we can return True
    # If our current text character is not our pattern character
    # and if we were checking for a pattern
    # If we have not found our pattern then we return False

    text_index = 0
    pattern_index = 0

    text_length = len(text)
    pattern_length = len(pattern)

    while text_index < text_length:
        if text[text_index] == pattern[pattern_index]:
            pattern_index += 1
        elif pattern_index > 0:
            pattern_index = 0
            continue
        if pattern_index + 1 > pattern_length:
            return True
        text_index += 1
    return False


Creating a user profile from an omniauth hash

The "default to empty string" bit should probably be done in the model. I.e. in a before_validation callback or similar.

You can also use Hash#slice to pluck out certain keys:

user = find_or_create_by(auth_hash.slice(%w(uid provider)))

user.assign_attributes(auth_hash['info'].slice(%w(name email nickname))
user.avatar = auth_hash['info']['image']

user.access_token = auth_hash['credentials']['token']

extra = auth_hash['extra']['raw_info']

user.assign_attributes(extra['raw_info'].slice(%w(location company)))
user.member_since = extra['raw_info']['created_at']

Alternatively, you could rewrite the keys (e.g. in a loop or using transform_keys) before using assign_attributes:

translations = { # could be a constant somewhere
  'image' => 'avatar',
  'token' => 'access_token',
  'created_at' => 'member_since'
}

attributes = auth_hash['info'].slice(%w(name email nickname image))
attributes.merge!(auth_hash['extra']['raw_info'].slice(%w(location company created_at)))
attributes['token'] = auth_hash['credentials']['token']

attributes.transform_keys! { |key| translations[key] || key }

user.assign_attributes(attributes)


Largest common multiple equal or lower than max

Looping is generally not recommended in R.
And it's not really needed here.

As @vnp pointed out in a comment,
all you need is simply calculate the least common multiple of the values in the input vector, let's call it lcm, and apply the formula lcm * (max // lcm) (with integer division).

The pracma library already has an implementation of the least common multiple. If installing that library is not an option for you, you can use this instead:

gcd <- function(a, b) {
  stopifnot(is.numeric(a), is.numeric(b))
  if (a > b) gcd(b, a)
  else if (a == 0) b
  else gcd(b %% a, a)
}

Lcm <- function(a, b) {
  stopifnot(is.numeric(a), is.numeric(b))
  a / gcd(a, b) * b
}

To calculate the least common multiples for a vector of numbers:

Lcm.many = function(values) {
  stopifnot(values)
  if (length(values) == 2) {
    Lcm(values[1], values[2])
  } else {
    Lcm.many(c(Lcm(values[1], values[2]), tail(values, -2)))
  }
}

Then with these helper functions the implementation of your function becomes much simpler:

LCMLthan = function(ms, max) {
  lcm <- Lcm.many(ms)
  lcm * (max %/% lcm)
}

Update

As @flodel pointed out in a comment,
there's actually no need for Lcm.many at all,
the call to it can be simply replaced with Reduce(Lcm, ms):

LCMLthan = function(ms, max) {
  lcm <- Reduce(Lcm, ms)
  lcm * (max %/% lcm)
}


Rock-Paper-Scissors game for learning purposes

Choice representation

You're using numbers to represent choices (rock/paper/scissors). That's a reasonable choice, but as it stands, you have the mapping between choices and numbers smeared all across your program. So you have to know when reading it that 1=rock, 2=scissors---no, wait, 2=paper---you can see how easy it is to make a mistake.

If you start off your program with something along the lines of:

ROCK = 1
PAPER = 2
SCISSORS = 3

then you can write code like:

if user == ROCK and comp == PAPER:
   # user loses

which is much easier to read.

The all-uppercase names are used by convention to indicate constants; python doesn't treat them differently.

Also note that this isn't really the best way to do this; what I'm describing is a clumsy way of doing an enumerated type; there are cleaner approaches in all versions of Python, and proper support for enums in Python 3. I'm suggesting a lightweight approach to suit where I've guessed your skill level to be.

Choice output

At the moment, you have lots of conditionals of the approximate form:

if choice == 1:
    print "Chose ROCK!"
elif choice == 2:
   print "Chose PAPER!"

You could define this mapping once at the top of your program:

names = { 1: "ROCK", 2: "PAPER", 3: "SCISSORS" }

and then refer to it later:

print "Chose {}!".format(names[choice])

Note that it would make sense to replace those literal numbers with the enumerated constants above; I'm just showing the literal numbers to avoid excessive coupling within this answer.

Data-driven victory conditions

You have a huge chunk of code:

if user == comp:
    # tie
elif user == 1 && comp == 2:
    lose()
elif user == 1 && comp == 3:
    win()
#...etc.

Even if we write it using named constants for the choices, it's still unwieldy, and the interaction between the conditional branches makes it easy to write bugs.

It would be easier to read and understand if you described those relationships in data:

outcomes = {
    ROCK: {PAPER: lose, SCISSORS: win},
    PAPER: {ROCK: win, SCISSORS: lose},
    SCISSORS: {ROCK: lose, PAPER: win}
}

and then just looked them up:

if user == comp:
    # tie
else:
   outcomes[user][comp]()

In that example, you have to declare outcomes after win() and lose(), as you're storing references to those functions in the dictionary; you could also choose some other way of representing the outcome (strings, a boolean, etc), although then you'd have to interpret it rather than just calling the function returned from the lookup.

Obviously, that outcomes data structure is rather redundant, as it encodes the rules both ways round: for a problem this size, that's probably simplest; if you had a larger, more complex game, I would suggest something like a relation:

beats = {(ROCK, SCISSORS), (PAPER, ROCK), (SCISSORS, PAPER)}

and then compute the symmetric closure of that. But don't worry too much about that in your context.


I don't see any unnecessary reflection in your code.

One think that could be simplified is your check for string.Empty:

if (fieldValue == null || fieldValue as string == string.Empty)


Everyone has had good ideas, but since you're asking about OOP, I'd suggest refactoring it altogether.

void Main()
{
    var formula = new Formula(new[] {
        new Ingredient("Flour, AP", 100m, true),
        new Ingredient("Water, Warm", 70.15m, false),
        new Ingredient("Salt", 3.04m, false),
        new Ingredient("Yeast", .24m, false),
        new Ingredient("Pate fermentee", 2.53m, false)
    });
    var weights = formula.GetWeights(10000m);
}

class Ingredient
{
    public string Name { get; private set; }
    public decimal Percentage { get; private set; }
    public bool IsFlour { get; private set; }

    public Ingredient(string _Name, decimal _Percent, bool _IsFlour)
    {
        this.Name = _Name;
        this.Percentage = _Percent;
        this.IsFlour = _IsFlour;
    }
}

class Formula
{
    private IEnumerable<Ingredient> Ingredients { get; set; }
    public decimal SumPercentages { get; private set; }

    public Formula(IEnumerable<Ingredient> _Ingredients)
    {
        this.Ingredients = _Ingredients;
        this.SumPercentages = _Ingredients.Sum(x => x.Percentage);
    }

    public Dictionary<Ingredient, decimal> GetWeights(decimal weightTotalDough)
    {
        return Ingredients.ToDictionary(k => k, v => (v.Percentage / this.SumPercentages) * weightTotalDough);
    }
}

By doing it this way, you separate the formula (which is basically just Ingredient/Percentage pairs) from each application of it.  You can use the same Formula object to calculate the weights for 10000g of dough or 50000g of dough - simply call GetWeights() with a different value.

Notice how many fewer properties you need on each class, and the question of "late setting" of some of them is entirely irrelevant.  Effectively, weight is not an intrinsic property of an ingredient, because it varies based on the total weight, so Weight shouldn't be a property of Ingredient.


Answering Questions.

I need to allocate n-dimensional arrays of type T, currently I am using the following functions. Is there a better way to do this?

Yes. Create a class that wraps the 2/3 D array in such a way that memory management is done correctly in an exception safe manner.
You may need the raw pointer for interfacing with other libraries but that does not need to mean you should actively manage the pointer. You need to wrap these in a class so all the memory management for you but provide access to the RAW pointer for situations when you need it.
Example:
template<typename T>
class Array3D
{
    private:
    static T*** allocate_3d_array(std::size_t nx, std::size_t ny, std::size_t nz)
    {
        T*** A = new T**[nx];
        for(std::size_t i = 0; i < nx; ++i)
        {
            A[i] = new T*[ny];
            for(std::size_r j(0); j < ny; ++j)
            {
                A[i][j] = new T[nz];
                for(std::size_t k(0); k < nz; ++k)
                {
                    A[i][j][k]= 0.;
                }
            }
        }
        return A;
    }
    static void release_3d_array(T*** A, std::size_t nx, std::size_t ny, std::size_t nz)
    {
        for (std::size_t i = 0; i < nx; ++i)
        {
            for (std::size_t j = 0; j < ny; ++j)
            {
                delete[] A[i][j];
            }
            delete[] A[i];
        }
        delete[] A;
    }
    T*** data;
    std::size_t  xSize;
    std::size_t  ySize;
    std::size_t  zSize;
public:
    Array3D(std::size_t xSize, std::size_t ySize, std::size_t zSize)
        : data(allocate_3d_array(xSize, ySize, zSize)
        , xSize(xSize)
        , ySize(ySize)
        , zSize(zSize)
    {}
    ~Array3D()
    {
        release_3d_array(data, xSize, ySize, zSize);
    }

    // Disable Copy for now
    Array3D(Array3D const&)            = delete;
    Array3D& operator=(Array3D const&) = delete;

    // Disable Move for now
    Array3D(Array3D&&)                 = delete;
    Array3D& operator=(Array3D&&)      = delete;

    // Allow access to the underlying data when calling C function.
    operator T***()
    {
        return data;
    }
};

Now you can create a 3D array where the memory is correctly managed at all times (so no leaks). When you pass the data to a C function it will convert itself to a T*** so that it can be used (I am assuming that the C functions are non owning and will thus not destroy the array and the object is in the same thread and will thus live as long as the function call).
If you want to use operator[] to access the object See below were I have linked to a stackoverflow article.
Copy is probably not something you want with a 3D array. But if you need it you will need to implement the appropriate functions above.
Move is an advanced form of copy. don't use until you understand move semantics. Again you will need to implement the above functions.

Also, ideally I would like to allocate a 1-D array and access that as a N-D array but I could not figure out a better way of doing that.

Yes this would makes memory usage more effecient so would be the preferred technique to implement a multidimensional arrya. I refer you to an article I have written on SO that points you in the correct direction.
See: How to overload array index operator for wrapper class of 2D array? for an example.

Using existing matrix library is not an option as I want access to raw pointers.

To be honest I am bit surprised by this statement. In my mind this is a requirement of any library that wants to interface with C libraries. Not having this ability is shocking. Maybe you missed it. What library were you thinking of using?
Your current style is definitely lacking in relation to C++. The way you have implemented this provides no benefits to using C++ over C.
Generic Review
I see no need for the template type Ti
template <class T, class Ti>
T*** allocate_3d_array(Ti nx, Ti ny, Ti nz){

In my mind this is always an integer type. Pick one. If you did this for some specific reason that I have not deduced then this should be pointed out in the comments of the code (if it is not obvious to me then I don't think anybody else got it).
Use zero initialization.
new T;  // Alocates memory for T but does default initialization.
        // for POD types this means nothing is done and the value is
        // indeterminate.

new T();// Allocates memory for T but does zero initialization.
        // for pod types it means the values have zero.

            A[i][j] = new T[nz];
            for(Ti k(0); k < nz; ++k){
                A[i][j][k]= 0.;
            }

            // Can be replaced with:
            A[i][j] = new T[nz]();


It is not technically wrong. In OOP languages you can encounter this sort of thing (a private method apparently only used once) especially in loops. Or if you want a specific part of the algorithm to not be overrideable, etc. Generally spoken however, I see no reason to do it in your example. The code was clear and now has way more clutter.
Whenever you repeat yourself in a class, whenever you use copy paste from another class, is most oftentimes an indication that you could abstract the code to a set of smaller functions / objects.
With regards to the tool reporting a high ABC rank: those tools do not IMHO replace common sense. You should never sacrifice readability and conciseness for the sake of a better score. This is a case where your code quality tool might have too rigid settings, or perhaps there is more code in the inspected scope that is better suited or in more need of refactoring.


You might consider using the trick of extending your array by one on both ends, ie. to include indices 0 and n+1, and assign:

ratings[0] = ratings[n+1] = 0
candies[0] = candies[n+1] = 0

and then go 1 and go n will be handled by the other clauses.

Also, you can eliminate the boundary assignments in go with:

candies = listArray (0,n+1) $ [0] ++ [go i | i <- [1..n] ] ++ [0]

Finally you can use these definitions to make the guards more succinct:

go i | incL && incR  = 1 + max cL cR
     | incL          = 1 + cL
     | incR          = 1 + cR
     | otherwise     = 1
  where incL = (ratings!(i-1)) < (ratings!i)
        incR = (ratings!i) > (ratings(i+1))
        cL   = candies!(i-1)
        cR   = candies!(i+1)


Creating connections and executing queries/updates

You've written a wrapper around JDBC that automatically connects/disconnects, and swallows exceptions.  Don't do that.

JDBC wants you to establish connections explicitly because it's a high-overhead activity.  Connecting involves a TCP handshake, authentication, opening the requested database, and some work to set up a session (which includes some locale settings, for example).  You have just taken a good design decision of JDBC (and all other database APIs) and made it worse.

Furthermore, if every query/update is in its own connection, then you can't execute multiple statements in a transaction.  (MySQL users often don't appreciate the value of transactions.)

Finally, SQLException exists for a reason: they allow your code to gracefully handle failures.  You merely swallow the exceptions after printing a stack trace.  You might as well be writing your data to /dev/null if you don't care whether your writes succeeded.  Also, returning null instead of propagating an exception does not make your caller's code any simpler.

I strongly recommend discarding your entire MySQLManager class and using JDBC as is.


Shortest code to generate a full mesh of elements

If I get it correctly, the shortest way that I can think of is by using itertools.combinations. Basically, you want all unique combinations, so:

from itertools import combinations

def mesh(L):
    return ["->".join(map(str, comb)) for comb in combinations(L, 2)]

Which will return:

['1->2', '1->3', '2->3']

For: mesh([1, 2, 3])

If you then want to print them as above, just:

for x in mesh([1, 2, 3]):
    print(x)


There are some optimizations from the original algorithm that can be included here: the base iteration of the prime p before the sieve is filled with its multiples can start with p = 2 and subsequently with odd numbers only (2, 3, 5, ..., upper_limit). Another useful refinement is that starting from 3, we only need to set the indices of the sieve with a step by 2 p. So for p = 3, we'd only have to clear (9, 15, 21, 27, ...). The rest of the review will be focused around idiomatic Rust, while integrating these optimizations.

In function nth, matching on a boolean value is something awkward to do, since if statements are also expressions and are more readable. Even better here is to turn it into another match clause for the error. Values of type u32 cannot be negative, so testing for 0 is enough.

match x {
    0 => Err("invalid input".to_string()),
    1 => Ok(2),
    2 => Ok(3),
    3 => Ok(5),
    4 => Ok(7),
    5 => Ok(11),
    x if x < 1000 => Ok(trial_div(x)),
    x => Ok(sieve(x)),
}

To create a String out of a &str, you can also use the to_string() or to_owned() methods. "invalid input".into() would also work here because the program already expects a String for the error type and String implements From<&str>.

We can see multiple uses of indexing operations over the prime_indices vector (e.g. prime_indices[i.pow(2) + (counter * i)] and if prime_indices[i]). While these uses are not necessarily wrong, the operation is bound-checked at run-time and it isn't guaranteed that the compiler will optimize them out. The preferred way of manipulating collections and other sequences of data is with the Iterator API. The use of iterators can become tricky when dealing with mutable collections, since there cannot be multiple borrows to the same vector. Nevertheless, we can remove most of these uses, resulting in better optimized and more idiomatic code, potentially less prone to indexing mistakes that could lead to a panic.

At the beginning of sieve, line 42, we have one of these cases where it is best to leave the ranged iteration alone, because the inner loop will modify the same content the outer loop is attempting to read. When filling the sieve for each multiple of i, we can rethink this operation over the vector as a stepped iteration starting from i.pow(2) (this can be replaced with i * i) with a step i. The step_by iteration adaptor is unfortunately not stable yet, but there is an equivalent Itertools#step method in the itertools crate. The result:

for i in 2..upper_limit {
    if prime_indices[i] {
        for p in prime_indices.iter_mut().skip(i * i).step(i) {
            *p = false;
        }
    }
}

Or even better, with the aforementioned optimizations:

for p in prime_indices.iter_mut().skip(4).step(2) {
    *p = false;
}
for i in (3..upper_limit).step(2) {
    if prime_indices[i] {
        for p in prime_indices.iter_mut().skip(i * i).step(2 * i) {
            *p = false;
        }
    }
}

Then, we want the xth prime number from the vector. We can achieve the same outcome as your loop with the following sequence of adaptors, commented one by one for clarity:

let prime_x = prime_indices.into_iter()
    .enumerate()           // keep track of original indices
    .skip(2)               // start at number 2
    .filter(|&(_, p)| p)   // primes only
    .map(|(i, _)| i)       // discard boolean
    .nth((x - 1) as usize) // take the xth prime (1-indexed minus 2 skipped)
    .unwrap_or(1);         // default to 1

My final advice is to consider running the rustfmt tool to format the entire code, as I've seen some irregular indentations. Here is the full result in a Rust Playground.


Checking the GridColumnType using a switch statement

The only possible solution I can come up with, to shorten/simplify your code, is to extract the redundant code and place it in a separate method TryAddFilter for example:

private void TryAddFilter(FilteringNode node)
{
    if (filterColumnType != typeof(node))
        filters.Add(columnFilter);
}

And then call this method from the switch-statement:

switch (gridColumnDataType)
{
    case "System.String": TryAddFilter(RuleTextNode); break;
    case "System.DateTime": TryAddFilter(RuleDateNode); break;
    case "System.Boolean": TryAddFilter(RuleBoolNode); break;
    default:
        if (gridColumnType.IsNumericType())
            TryAddFilter(RuleNumberNode); break;
}


This is a reasonable first attempt but there are many ways to make it better:

public class RockPaperScissors {
    final static int ROCK = 1;
    final static int PAPER = 2;
    final static int SCISSORS = 3;

Consider using an enumerated type to hold related constants.

System.out.println("Start By Entering A number");

Your capitalization is not standard English.
Tell the user how to quit.

int human = input.nextInt();
System.out.println("ROCK IS 1 :: PAPER IS 2 :: SCISSORS 3");

Put the explanation before fetching input!
Why is there no "is" for the scissors case?

int computerScore = 0, humanScore = 0, computer;
while (human != -1) {

Consider refactoring the main method so that it more clearly reflects what is happening, and extracting state to an object.  I'd prefer to see your main look like this:

public static void main(String[] args) {
    initialize();
    Game g = new Game();
    g.printStartingText();
    while(!g.finished())
      g.playRound();
    g.printEndText();
}

Can you structure your program like that? It will be more clear if you do.

        String h = human == 1 ? "ROCK" : human == 2 ? "PAPER" : "SCISSORS";
        String c = computer == 1 ? "ROCK" : computer == 2 ? "PAPER" : "SCISSORS";

You've replicated some code here; it would be better to make a map from integer to the enumerated value and do two lookups in the map here.

    if ((human == ROCK && computer == SCISSORS) || (human == PAPER && computer == ROCK) || (human == SCISSORS && computer == PAPER)) {

Instead of doing this work twice, write a method that returns PLAYER_1, PLAYER_2 or TIE:

    Winner w = getWinner(human, computer);

That will let you simplify the logic that follows, and it will be easier to read.

            System.out.println("Something Went Wrong Try Again:( ");

This should never happen. A better choice would be to assert that the condition is impossible.

    System.out.println("Human Race Is saved! We Won!");

Why are the humans "we"? The message is being produced by a computer! It should be "The human race is saved; you won and we computers lost." :)


There is one thing missing: iteration.

There is no way for the user code to get all items stored in the list without doing get(int) for each item which will result in O(n^2) time complexity.

Building the ListIterator without remove support is simple enough you just need to have it keep a reference to the current node.


Neatest way of including a header and footer on every page

If you are working in PHP use a framework that has MVC such as Laravel(up and coming and popular), Symphony, Yii, Codeigniter(defunct), etc.

Each of them will enable you to use some reuse mechanism.

Laravel itself uses a template PHP called blade. There are several other template mechanism such as Twig that enables you to template your views to even add more granular way and cleaner.

If its a single file system that you must what you are doing is fine because you are using require_once it enables you to call other files and you can modify that file and it will reflect any other files that references it.


You can speed up your code by replacing the for loop with more efficient (vectorized) functions. Your code can then be reduced to a simple one-liner:

closestSequence2 <- function(a, b) min(colSums(abs(combn(b, length(a)) - a)))

Looking at it step-by-step:

combn is applied directly to b rather than 1:b. The output is a matrix where each column is a length(a)-long sub-sequence of b.
combn() - a takes advantage of R's recycling rules to compute, for each item in each sub-sequence, the signed distance to the corresponding element of a.
abs() converts to absolute (unsigned) distances.
colSums summarizes each column into a single value: the total distance from a for that sub-sequence.
min picks the minimum total distance across all candidates.

However, as pointed, an exhaustive search will not work well for large input vectors. A much faster approach is indeed to use dynamic programming. Here is a tentative implementation:

closestSequence2 <- function(a, b) {
  La <- length(a)
  Lb <- length(b)
  d <- abs(outer(a, b, FUN = `-`)) # matrix of all distances

  # x[1 + i, 1 + j] will hold the optimal distance between
  # the i first elements of a and the best sub-sequence
  # within the i+j first elements of b.
  x <- matrix(NA, La + 1, Lb - La + 1)
  x[ 1,  ] <- 0                             # init case where i = 0
  x[-1, 1] <- cumsum(d[cbind(1:La, 1:La)])  # init case where j = 0
  for (i in 1:La) {
     if (Lb > La) for (j in 1:(Lb - La)) {
        x[1 + i, 1 + j] <- min(x[1 + i, j],
                               x[i, 1 + j] + d[i, i + j])
     }
  }
  min(x[La + 1, ]) # min value on the last row
}


Python function to hash a python function

Looking at the source code for ast.get_docstring your code more or less does what it does. Here is their code for reference:

def get_docstring(node, clean=True):
    """
    Return the docstring for the given node or None if no docstring can
    be found.  If the node provided does not have docstrings a TypeError
    will be raised.
    """
    if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
        raise TypeError("%r can't have docstrings" % node.__class__.__name__)
    if not(node.body and isinstance(node.body[0], Expr)):
        return
    node = node.body[0].value
    if isinstance(node, Str):
        text = node.s
    elif isinstance(node, Constant) and isinstance(node.value, str):
        text = node.value
    else:
        return
    if clean:
        import inspect
        text = inspect.cleandoc(text)
return text

A couple of the things they mention are only a concern for Python 3+ like AsyncFunctionDef. Also, it seems Constant is a grammar rule introduced in Python 3+. (However, you may want to account for this in the future.)

You seem to be also removing docstrings from ClassDef, I am not one hundred percent sure, but you may also want to add Module as well.

There is also a ast.NodeTransformer. However, I find it rather weird stylistically compared to your current method of looping. So... I'm not confident in making any comments about whether you should be using it or not. Nevertheless, I'm putting it out there so you are aware in case you weren't.


You have quite a large bug with how you handle kwargs.

You don't care about the value, only that the key exists.
You care about the order of the keywords.
You don't care about default keywords.

To test this, we can make a simple function to see what your keys are.
With some simple tests.

def test(*args, **kwargs):
    return (*args, None, *kwargs)

print(test(a=1)) # (None, 'a')
print(test(a=2)) # (None, 'a')
print(test(a=1, b=2)) # (None, 'a', 'b')
print(test(b=2, a=1)) # (None, 'b', 'a')

And so you should instead sort your kwargs.items().
However to correctly change args and kwargs to a single standard that the function will take is a little bit more complex.
The simplest way to do this is to use inspect.signature to get something like:

def test(fn):
    signature = inspect.signature(fn)
    def call(*args, **kwargs):
        bind = signature.bind(*args, **kwargs)
        bind.apply_defaults()
        return bind.args, tuple(sorted(bind.kwargs.items()))
    return call

def fn1(a, b, c=1, *, d=2, **kwargs):
    pass

def fn2(a, b, *args, c=1, d=2, **kwargs):
    pass

# Checking that it works as intended
for fn in (fn1, fn2):
    t = test(fn)
    print(t('a', 'b'))
    print(t('a', 'b', 'c'))
    print(t(a='a', b='b', c='c'))
    print(t(b='b', c='c', a='a'))
    print(t('a', 'b', d='d'))
    print(t('a', 'b', test='test'))
    print(t('a', 'b', t1='t1', t2='t2'))
    print(t('a', 'b', t2='t2', t1='t1'))

And so I'd use:

from collections import OrderedDict
from functools import wraps
from inspect import signature

def lru_cache(maxsize=None):
    def decorator(func):
        func_sig = signature(func)
        cache = OrderedDict()
        @wraps(func)
        def decorated(*arg, **kwargs):
            bind = func_sig.bind(*args, **kwargs)
            bind.apply_defaults()
            args, kwargs = bind.args, bind.kwargs
            key = (arg, tuple(sorted(kwargs.items())))
            try:
                val = cache[key]
                del cache[key]
            except KeyError:
                val = func(*arg, **kwargs)

            cache[key] = val
            if maxsize and len(cache) > maxsize:
                cache.popitem(last=False)

            return val

        return decorated
    return decorator

Adding typed is also fairly easy and comes down to making more tuples with an extra value of type. Which I'm fairly sure you're capable of doing.


I like this. Your code is clean and pretty readable. I recommend using rustfmt, if only because it will stop annoying people on the internet from recommending you use rustfmt. But the minor code formatting differences are not something to be overly concerned about, if you have a style and stick with it.
I have two major suggestions:

Don't populate the cache with a sentinel value (zero) and then test whether each value is zero or not. Instead, make the vector start small and grow as you populate it. To avoid reallocation, you can initialize it with a large capacity and small length. You can further simplify the logic by (a) using push to add a value to the cache when you know the length is n; and (b) initializing the cache to [0, 1], which will play into the next point:

Split fib into two functions: one that takes a cache as argument, and one that creates the cache inside itself (and calls the first one to do the heavy lifting). If you expose both of these in an API, then the user can decide whether reusing the cache is appropriate or not.

Here's the main code with both suggestions implemented:
fn fib_cached(n: u32, memo: &mut Vec<u64>) -> u64 {
    if (n as usize) < memo.len() {
        memo[n as usize]
    } else {
        let ret = fib_cached(n - 2, memo) + fib_cached(n - 1, memo);
        // At this point we know that memo.len() is at least n, because
        // fib_cached(n - 1, memo) will have populated memo[n-1]. Furthermore, if
        // memo.len() had been greater than n, we would have taken the other
        // branch of the if. There are no other functions capable of modifying
        // memo because we hold a &mut reference to it, so memo.len() is exactly n
        // and push(ret) will make memo[n] = ret.
        memo.push(ret);
        ret
    }
}

fn fib(n: u32) -> u64 {
    let mut cache = Vec::with_capacity(n as usize);
    cache.extend(&[0, 1]);
    fib_cached(n, &mut cache)
}

Here are some more observations, in no particular order:

Even this modified version is somewhat fragile, since it's easy to call fib_cached with a too-small cache, which may panic. If you were writing a library for others to use, I would suggest making a wrapper type around Vec<u64> so you can insist on correctly-initialized caches. This would be a start:
struct FibCache {
    data: Vec<u64>,
}

impl FibCache {
    fn with_capacity(n: usize) -> Self {
        let mut data = Vec::with_capacity(n);
        data.extend(&[0, 1]);
        FibCache {data}
    }
}

fn fib_cached(n: u32, memo: &mut FibCache) -> u64 {
    if (n as usize) < memo.data.len() {
        memo.data[n as usize]
    } else {
        let ret = fib_cached(n - 2, memo) + fib_cached(n - 1, memo);
        memo.data.push(ret);
        ret
    }
}

fn fib(n: u32) -> u64 {
    let mut cache = FibCache::with_capacity(n as usize);
    fib_cached(n, &mut cache)
}

This means nobody can call fib_cached without creating a FibCache object with a constructor you define. It also lets you make backwards-compatible changes to the type of cache -- you could use a HashMap, as 6005 suggests, or another data structure, without changing the outward-facing API of the library.

n as usize is another source of fragility. Casting between integer types can have surprising results, so you're usually well-advised to use usize::try_from(n).unwrap() instead, which will panic if the conversion can't be done. In this code, I don't regard this as a major issue because u32 is losslessly convertible to usize on virtually all Rust targets and because any n that would overflow a usize, on any target, is already too large for this algorithm. Just be aware you should normally use the conversion traits instead of casting.

Changing fib to use internal static state is pretty simple, using lazy_static or once_cell. I'll use lazy_static here, and assume the FibCache API above:
fn fib(n: u32) -> u64 {
    use lazy_static::lazy_static; // 1.4.0
    use std::sync::Mutex;
    lazy_static! {
        static ref CACHE: Mutex<FibCache> = Mutex::new(FibCache::with_capacity(10));
    }
    fib_cached(n, &mut *CACHE.lock().expect("Could not lock static cache"))
}

Whether this is a good idea or not is rather up for debate. Ultimately it's replacing contention for one resource (the heap) with contention for another resource (the lock). Neither is necessarily the best choice, which is why it's important to expose fib_cached as well so your users aren't stuck with your choice of implementation for fib. Making access to FibCache lock-free could make static memory much more appealing by removing the contention aspect.

Don't use str as the name of a variable, since it's also the name of a built-in type. It will mess with syntax highlighting (as it does on this very site).

Obviously, this is a slow and wasteful algorithm for calculating Fibonacci numbers. So I assume what you're looking for is feedback on the general shape and style of the solution, not the choice of algorithm, and I've written this review based on that assumption. Peter's review deals with algorithmic improvements.


Since you are using matrices, I don't think that you need the runtime polymorphic behaviour offered by virtual but that you created virtual functions so that you could call methods of the derived class from methods of the base class. If this is the case, you could use static polymorphism instead, thanks to the Curiously Recurring Template Pattern idiom (CRTP).

In other words, make DenseBase take a Derived template parameter which corresponds to the type of the derived class:

template <typename T, std::size_t M, std::size_t N, typename Derived>
class DenseBase
{
    // ...
}

Then make the derived classes feed their own type to this template parameter:

template <typename Parent, typename T, std::size_t N>
class Rowview : public DenseBase<T, 1, N, Rowview<Parent, T, N>>
{
    // ...
}

Now, add a couple of methods to DenseBase to make a downcast when needed. Since you know the derived type at compile time thanks to the template parameter Derived, you can make a safe downcast with a static_cast:

Derived& derived() { return static_cast<Derived&>(*this); }
const Derived& derived() const { return static_cast<Derived&>(*this); }

Now you can rewrite the coeff methods in DenseBase so that they don't need to use virtual anymore to call the coeff methods from the derived class:

T& coeff(std::size_t row, std::size_t col) { return derived().coeff(row, col); }
const T& coeff(std::size_t row, std::size_t col) const { return derived().coeff(row, col); }

T& coeff(std::size_t index) { return derived().coeff(index); }
const T& coeff(std::size_t index) const { return derived().coeff(index); }

That way, you have some of the benefits of polymorphism without having to pay the cost of runtime polymorphism which I feel you won't need for such a class. That's a little bit tricky to understand and use at first, but it has clear benefits.


Finding N partitions of number M with min and max partitions sizes

The way you have done your algorithm, you could just apply the same operation to your sum variable, rather than reducing the entire array.

  while (sum > number) {
    for (i = 0; i < result.length; i++) {
      if (result[i] > min) {
        result[i]--;
        sum--
        if (sum === number) {
          break;
        }
      }
    }
    sum = result.reduce(add, 0);
  }

Additionally, the last sum = result.reduce is not needed here, as any change in the result array is subsequently reflected in the sum variable a row lower.

  while (sum > number) {
    for (i = 0; i < result.length; i++) {
      if (result[i] > min) {
        result[i]--;
        sum--
        if (sum === number) {
          break;
        }
      }
    }
  }

Lastly, keep in mind if you were to feed your code an impossible situation ("stuff 5 people into 1 house where each house can only contain 3 people at most"), you will get an infinite loop. It's up to you to decide how to handle this.


Optimizing mcrypt encryption class further

You can actually refactor most of the code into a separate function:

static function encryptdecrypt($text)
{
    $td = mcrypt_module_open(self::CIPHER, "", self::MODE, "");
    mcrypt_generic_init($td, self::KEY, 0);
    $text = mcrypt_generic($td, $text);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $text;
}

static function encrypt($plaintext)
{
    return base64_encode(encryptdecrypt($plaintext));
}

static function decrypt($ciphertext)
{
    return encryptdecrypt(base64_decode($ciphertext));
}


I'm surprised nobody mentioned the code being vulnerable to SQL injection attacks:

(XKCD source)

Using string formatting and string concatenation to construct SQL queries is, first of all, unsafe and also, fragile - you will have to handle the argument types, balancing and escaping quotes yourself manually.

Instead, you should parameterize your queries - this way, you are not only protected from SQL injections, but also let the database driver worry about the python-to-database type conversions, sample:

query = """
    SELECT column1
    FROM table
    WHERE column2 = ?"""
cursor.execute(query, (data, ))

Note how parameters are passed in a separate argument to execute().

On the other hand, it feels like you may be reinventing the wheel in a certain way - please check if switching to an ORM like SQLAlchemy or peewee would help to avoid re-writing boilerplate code.


Javadoc on every method would be nice.

Change signature to <T extends Comparable<T>> void sort(T[] a).

public static void sort(Comparable[] a) {

Standard method to specify ranges is from inclusive to exclusive.

  quicksort(a, 0, a.length - 1);
}

private static void quicksort(Comparable[] a, int lo, int hi) {

Why not "high" and "low"?

  if (lo >= hi) {

Your code never invokes quicksort with lo > hi. You'd better throw an IllegalArgument exception in this case.

    return;
  }
  int pi = partition(a, lo, hi);
  quicksort(a, lo, pi - 1);
  quicksort(a, pi + 1, hi);
}

private static int partition(Comparable[] a, int lo, int hi) {
  int i = lo + 1;
  int j = hi;

You choose the first element as pivotal. Choosing as a pivot the element at a constant position allows construction of an antitest, an array on which your sort works in O(n^2). In your particular case, the antitest is pretty simple - an array in descending order, e.g. (5, 4, 3, 2, 1).

  while (i <= j) {
    if (a[i].compareTo(a[lo]) <= 0) {
      i++;
    } else if (a[j].compareTo(a[lo]) > 0) {
      j--;
    } else if (j < i) {
      break;
    } else {
      exchange(a, i, j);
    }
  }
  exchange(a, lo, j);
  return j;
}

It's better to name it swap.

private static void exchange(Object[] a, int i, int j) {
  Object tmp = a[i];
  a[i] = a[j];
  a[j] = tmp;
}


Have a look at the reshape function. To use the jargon, your data is in "long" format and you want to turn it to a "wide" format. Before using reshape, you will need to add a column of 1, 2, 1, 2, etc. so it can be used as the "time" column. You can do that on the fly using the transform function. In all:

new_scores <- reshape(transform(all_scores, i = 1:2),
                      idvar = "match", timevar = "i", direction = "wide")

#   match team.1 count.1 points.1 team.2 count.2 points.2
# 1     1    ARG      11       21    ENG       9       19
# 3     2    CAN       8       15    USA       8       17
# 5     3    FRA       7        7    NZL       8       36


The best way to optimize that is store indexes directly in the source data. So, the int public Property in the ADataModel. It's rather faster to refill indexes there with O(n) complexity than with O(n2) using Converter.
The code can be a bit optimized: it's better to use bindings to pass the data to Converter. But it's not possible to pass a data to ConverterParameter using Binding. The MultiBinding+IMultiValueConverter is the solution.
<CollectionView ItemsSource="{Binding ACollectionView}">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="{x:Type ADataModel}">
            <Label BackgroundColor="Black" Style="{StaticResource ListLabels}" TextColor="WhiteSmoke" >
                <Label.Text>
                    <MultiBinding Converter="{StaticResource IndexConverter}">
                        <Binding Path="."/>
                        <Binding Path="ItemsSource" RelativeSource="{RelativeSource AncestorType=CollectionView}"/>
                    </MultiBinding>
                </Label.Text>
            </Label>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

Alternative Binding to the Colletion as an option.
<Binding Path="DataContext.ACollectionView" RelativeSource="{RelativeSource AncestorType=CollectionView}"/>

Avoid giving names to controls where possible, it would give more flexibility for the future UI improvements.
public class IndexValueConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values[1] is IList list ? list.IndexOf(values[0]) + 1 : -1;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException("Converting index of the List back is not supported");
    }
}

Avoid throwing Exception in converters if you don't want to crash the app. Don't build the app's logic on Exceptions in general.


Is calling a overridden function from overriding function a bad practice? Is there a better way to write this code?

If you are adding serialization support to an existing class hierarchy, then what you are doing is A-O-K.

However, if you are in the process of designing that structure, then it's indirectly considered bad practice.

The whole "subclass to extend" design pattern is frowned upon in general by modern design sensibilities.

If you want to be "modern", then your virtual functions should be pure in the base class, and your class hierarchy should rarely go beyond a single inheritance depth.

The mantra is "prefer composition to inheritance, unless you need type erasure". However, this doesn't mean that everything is fair game as soon as type erasure is needed. You should still strive to limit your use of hierarchy to the minimum required in order to achieve erasure, i.e: Base classes should be pure interface classes, nothing more.

The details on how best to do that really depends on the project, so I can't really go into details here.

Edit: As requested, a more in-depth explanation of composition vs inheritance.

Disclaimer: It's a fairly subtle, almost academic, subject.

The theory goes like this:

Apart from type erasure, there is nothing gained by inheritance that cannot be accomplished through composition.
Composition is more flexible. Primarily because you don't run the risk of running into clashing namespaces, but also because diamond patterns are easier to work with.

A good example of this is shared_ptr<> vs having a RefCounted base class at the bottom of your hierarchy.

With shared_ptr<>, which is composition-based, you get a few major benefits:

You can apply the feature to anything, even base types.
You won't run into a diamond pattern if you need to inherit from two interfaces.
You don;t pay for the feature until  you are actually using it.


Exporting objects in various formats while reporting progress

I would suggest moving the actual export(s) into their own class.  We can create an interface for exports.  Something along the lines of
public interface IExport<T>
{
    Task SaveAsync(string fileName, IEnumerable<T> items, IProgress<int> progress = null);
    string ExportType { get; }
}

Then each export type can implement this interface.
public class ExportItemsToText : IExport<Item>
{
    public Task SaveAsync(string fileName, IEnumerable<Item> items, IProgress<int> progress = null)
    {
        throw new NotImplementedException();
    }

    public string ExportType => "txt";
}

Then in your constructor of ExportWindow
public ExportWindow(IEnumerable<IExport<Item>> exports)
{
    // if using DI otherwise could just fill in dictionary here
    ExportStrategy = exports.ToDictionary(x => x.ExportType, x => x);
}

Instead of a switch statement you can now just look up the key in the dictionary to find what export should be ran and if not found would be the same as your default case.
IExport<Item> exporter;
if (ExportStrategy.TryGetValue(ext.ToLower(), out exporter))
{
    await exporter.SaveAsync(exportDialog.FileName, items, new Progress<int>(updateProgress))
}
else
{
    throw new Exception("Specified export format not supported.");
}

Now in the future if adding support for more types you just implement the interface and update your DI container.  Or if not using DI then would need to add it to the constructor of your ExportWindow.
I don't think this is a great idea but If you really don't want to create a class per export, which I think you should, you could make the dictionary IDictionary<string, Action<string>> then just put your methods in there and when adding a new type create the method and update the dictionary.


iOS UITableView; saving cell checkmarks to disk

you should read the settings plist once in -viewDidLoad: and save the contents as a dictionary to a property.

As you are doing, it is a huge performance hit as the disk will be accessed every time a cell appears on screen during scrolling.

In -tableView:cellForRowAtIndexPath: and -tableView:didSelectRowAtIndexPath: you then should only work on that dictionary.

Further more you could introduce a singleton-like shared object, that holds the settings and can be accessed in any class.

see my example code for how to do multiple selection and keeping track of the selected contents.


Printing lines in a file, filtering by the first column

For one thing, in a bitmasking expression it reads much more naturally if you put the "variable" on the left and the "constant mask" on the right. In the same way that we write if x == 0 instead of if 0 == x, we also prefer to write if x & mask rather than if mask & x.

def parse(f_loc, flags=0):
    for line in open(f_loc):
        flag, content = line.strip().split('\t')
        if flags & ftd.get(flag, 0):
            yield content

However, your bitflag identifiers POS, NEU, OON, etc., are pretty much unreadable, especially given that you already have English names for them right there in the source file! If I were you, I'd replace the entire function with simply

def parse(f_loc, flags):
    for line in open(f_loc):
        flag, content = line.strip().split('\t')
        if flag in flags:
            yield content

and then call it as

# print all data flagged as 'positive', 'negative', or 'neutral'
flags = ['positive', 'negative', 'neutral']
for entry in parse('file.txt', flags):
    print(entry)

# print all data, no matter the flag
flags = ['positive', 'negative', 'neutral', 'objective', 'objective-OR-neutral']
for entry in parse('file.txt', flags):
    print(entry)

At this point the code is simple enough that you don't even really need the parse function anymore!

If you're concerned about efficiency, and you have the power to change your input file format, consider switching to single-character flags and fixed-width fields so that you don't need to strip or split your lines.

def parse(f_loc, flags):
    for line in open(f_loc):
        if line[0] in flags:
            yield line[:1].rstrip()

# print all data flagged as 'positive', 'negative', or 'neutral'
for entry in parse('file.txt', "+-n"):
    print(entry)

# print all data, no matter the flag
for entry in parse('file.txt', "+-noO"):
    print(entry)

One last thing: IMHO

from parsing import parse
... parse('file.txt', flags) ...

is generally inferior to

import parsing
... parsing.parse('file.txt', flags) ...

This way, when I see the call site, my first question isn't "what is parse?" (could be a local variable, a function in this file, etc. etc.); instead, my first question is "what is parsing?" (which I generally know off the top of my head because it's the name of a module, and it's easy to remember all the modules I'm using). Plus, if I ever need to use any other functions out of parsing, they're all at my fingertips:

from parsing import parse, NEU  # change
... parse('file.txt', NEU) ...  # change

is inferior to

import parsing                  # no change needed
... parsing.parse('file.txt', parsing.NEU) ...  # change


Building Data abstraction for line segments using "objects"

Although your question indicates that you are using a functional paradigm, you are not. You are using a procedural paradigm.

Functional programming is about declaring functions, and then passing those functions in to other places to be used as modifiers and manipulators for other processes. Terms like 'lambdas', and 'closures', 'optionals' or 'monads' are required.

Procedural programming is the act of defining a process to follow, sometimes returning a value, but "I take this data and process it following this defined routine, and I get the results I want."

Procedural programming often has functions declared, but the functions are not used as parameters to other functions.

You do not pass any functions in as parameters, you are not using a "functional paradigm". You are using a "procedural paradigm".

See Wikipedia's comparison between Functional and Procedural programming.

Your code is a very poor implementation of a Functional paradigm.

On the other hand, as a Procedural implementation, it is actually quite good, except for the get_midpoint method, which is implemented on a single line which is too long, and makes it hard to read with all the nested braces on one line.

def midpoint_segment(lineSegment):
    start = start_segment(lineSegment);
    end = end_segment(lineSegment)
    xsums = x_coordinate(start) + x_coordinate(end)
    ysums = y_coordinate(start) + y_coordinate(end)
    return make_point(xsums / 2, ysums / 2)