Determinant calculation of a matrix of any degree

The first thing is to learn proper indentation.

//;;PushForEach put element elem into a heads of all lists of L:
(defun PushForEach (elem L)
    (if (null L) nil (cons (cons elem (car L)) (PushForEach elem (cdr L)))
    )
)

What's wrong with the code layout?

Common Lisp has built-in documentation features. A documentation string can be placed inside the function and can be retrieved with the DOCUMENTATIONfunction.
trailing parentheses are a big DON'T DO THAT. It just wastes space without adding much information. Your editor will count parentheses or will show the corresponding parentheses.
put constructs, when they are too long on a line, over several lines.
don't use CamelCase, use hyphens

Let's do the editing step by step:

(defun PushForEach (elem L)
  "put element elem into a heads of all lists of L"
    (if (null L) nil (cons (cons elem (car L)) (PushForEach elem (cdr L)))
    )
)

(defun PushForEach (elem L)
  "put element elem into a heads of all lists of L"
    (if (null L) nil (cons (cons elem (car L)) (PushForEach elem (cdr L)))))

Now we get the version which is best readable:

(defun push-for-each (elem L)
  "put element elem into a heads of all lists of L"
  (if (null L)
      nil
      (cons (cons elem (car L))
            (push-for-each elem (cdr L)))))

Above function has a documentation string and useful code layout.

Next: can we write it better? You can bet that basic recursion in Lisp has been provided as a higher-order function. Applying a function over all items in a list is called mapping. The basic mapping function is MAPCAR.

(defun push-for-each (element list)
  "adds element as head of all sublists of list"
  (mapcar #'(lambda (item)
              (cons element item))
          list))


Find longest sequence of zeroes in a binary representation of an integer

Unless performance is somehow critical, you'd do far better by just making use of String.Split on '1' after getting a binary representation. Then you can search for the longest string in that array. The current implementation is very low level and hard to easily understand.

A programmer who sees the code as it is now would have to invest time to understand how it works, whereas relying on (even if slower) a few library calls can make an algorithm easier to understand for programmers, thus being of more value than the faster, low level algorithm. It's also faster to write such things and less likely to contain bugs because most of the actual work is done by the standard libraries, which are thoroughly tested by other programmers.


The values at the top of your script are constants so, per the style guide, should be UPPERCASE_WITH_UNDERSCORES:

BINS = [40, 50, 60]
DAYS = 25
GAUSS = True  # distribution can be gaussian or lognormal
ITERATIONS = 1000
START_PRICE = 50
STD_DEV = 2

Note that I've also made some of the names a little more meaningful, and added more Pythonic whitespace to the list. I've also ordered them alphabetically, although there may be a more sensible grouping.

It would be nice to add a comment explaining BINS - the rest are fairly obvious, but it took me a few reads to figure out that they're the top of each bin, and an additional higher bin will be automatically added. Consider adding a module docstring covering this.

Currently, all of the code is just in the body of the script. Instead (as it makes it easier to import and reuse this functionality elsewhere), it is conventional to define an "entry point" function (conventionally named main) and call that when the script is invoked directly:

# imports, constants, etc.

def main():
    # do your thing

if __name__ == '__main__':
    main()

Rather than specify two distributions within the body of the code, I would extract the distribution function as a parameter to the simulation. In this case the functions would be:

def gaussian(std_dev):
    """Apply the Gaussian distribution."""
    return random.gauss(0, std_dev)

def lognormal(std_dev):
    """Apply the log-normal distribution."""
    return random.choice((1, -1)) * random.lognormvariate(0, std_dev)

Now if you wrote a function to do one iteration, it would be very simple:

def simulate(days, start_price, std_dev, distribution):
    """Simulate the asset for the specified number of days."""
    price = start_price
    for _ in range(days):
        price = max(0, price + distribution(std_dev))
    return price

You can then create more distribution functions in the future, and pass whichever you want to simulate; all it requires is a function that takes a single argument and returns a number.

Note that I have made the constants explicit parameters to these functions - this, again, makes reuse of the code easier. main would now look like:

def main():
    results = [0] * (len(BINS) + 1)
    dist = gaussian if GAUSS else lognormal
    for _ in range(ITERATIONS):
        final_price = simulate(DAYS, START_PRICE, STD_DEV, dist)
        ...
    ...
    print(final_results)  # you could return final_results instead

You could also abstract the binning of results into a function. I would avoid using the identifier bin, as this shadows a built-in function


The first change I'd make would be to get rid of most of the 9s you currently have sprinkled throughout the code.

static const int rows = 9;
static const int cols = 9;

This way if you decide you want a 10x10 grid (or 8x11, etc.) it should be pretty easy to do that.

The second possibility would consider would be a (probably somewhat misplaced) attempt at optimization. In particular, instead of copying the rows up after each turn, I'd keep track of which row is the current starting point at any given time. Each update would just advance that, modify the row that's now the "bottom", and re-draw.

Honestly, as long as you're only dealing with an 9x9 grid, that's probably not going to gain enough to notice. For a game that (for example) was drawing 2D graphics instead, it would probably make a rather more meaningful difference.

I'd probably define names for the 80, 75 and 77 in the main loop as well:

enum {LEFT = 75, RIGHT = 77, DOWN = 80 };

// ...

switch (ch) {
    case LEFT:
        if(player == 0) continue;
        if(map[1][player-1] == 'X')
        {
            crash = true;
            break;
        }
        map[0][player] = ' ';
        player--;
        map[0][player] = 'v';
        break;

The name player should probably also be changed to something like horizontal_position or current_column (at least I think that's what it represents).

You might also consider re-casting the code to be a map class, with reset (sounds more accurate than restart to me), draw, slide, and info as member functions. If you're going to do this, you might also consider getting rid of the reset completely. Instead, do that initialization in the constructor, and when you want to clear the grid, you just create a new map object.

One other minor detail: if(crash == true) should normally be written just as if (crash) instead.


Hackerrank: Fraudulent Activity Notifications

Yes, deciding for each day in isolation is easy enough. And produces reusable and well-defined abstractions.
Unfortunately, it costs you. Specifically, it needs too long. Use a running-total, thus each day needs only subtracting one trailing day, adding the last day, and comparing to that day. The cost is pretty independent of the number of trailing days considered. It is easily adapted to streams.
Additionally, you really should avoid floating-point, not necessarily due to its runtime cost, but its design cost. Or do you have the time and inclination to prove conclusively whether your handling of floating point rounding is right?
I won't go into all the bad habits hackerrank encourages, like using <bits/stdc++.h>, using namespace std;, all the useless copies, ...
If you are interested, it's repeated enough times already.


Conventions

According to coding conventions, Java class names should start with an uppercase letter. myStack should be MyStack.

Variable names

Whenever you have a comment after declaring a variable, rename the variable to comment itself.

int n1;     //result of 1st popping

Can be renamed to make the variable name "comment itself".

int poppingResult1;

If this, then do nothing, else do something

if (ch == ' ') {
} else {

To achieve the same effect, and make the code cleaner, write instead:

if (ch != ' ') {

Integer.parseInt

Now, it's not clear which datatype you get from list.pop(). If it is an int (or Integer), then variable = list.pop() will be sufficient.

If it is an Object, instead use Integer.parseInt(String.valueOf(list.pop()))

Anyway, if possible, change the values you store in your list to always be of the same type (Integer, preferably). This would make your code cleaner as you don't have to use Integer.parseInt every time you pop something of the list.


Handling an openFileDialog in the View of my MVP WinForms project

In the big if you have the following:

Path.GetExtension(openFileDialog1.FileName) == ".txt" || Path.GetExtension(openFileDialog1.FileName) == ".csv")

Why? You already put openFileDialog1.FileName in a fileName variable. Just use that.

The next thing I would do is define a list of valid extensions:

public readonly string[] ValidExtensions => new string[] { "txt", "csv" }

Then simply:

if (result == DialogResult.OK && ValidExtensions.Contains(Path.GetExtension(fileName).Substring(1)))

We use the .Substring(1) to remove the period.

That way, if you add support for a different file type, you just add it to ValidExtensions.


VBA - If error return '0' else execute code

This is easily handled with a simple function that checks for a potential error instead of triggering an error. Code first, and then an explanation:

Public Sub MultiplyValues()
    '
    ' MultiplyValues Macro
    '
    ' =IFERROR(IF(A2="NULL",B2*C2,A2*B2*C2),0)
    ' Forumala is in D

    Dim Target As Range

    ' The line below implicitly uses the ActiveSheet. If this is intended, qualify your range with `ActiveSheet.Range`, otherwise
    ' you will want to identify the proper sheet.
    Set Target = Range("A2", Range("A2").End(xlDown))
    Dim Cell As Range
    For Each Cell In Target.Cells
        ' No need to use an error handler. Avoiding errors is always preferred over relying on the error handler. In this case, let's use a function.
        Cell.Offset(0, 3).Value = GetFormulaValue(Cell)
    Next Cell
End Sub

Private Function GetFormulaValue(ByVal InputCell As Range) As Double
    If Not IsNumeric(InputCell.Value) Then
        ' Be sure to explicitly access the value property of the range object.
        GetFormulaValue = InputCell.Offset(0, 1).Value * InputCell.Offset(0, 2).Value

    ' I am adding this in case you want to run a separate calculation if the cell-value is 0).
    ' ElseIf InputCell.Value = 0 Then
        ' Your code here
    Else
        ' While order of operations would automatically calculate X * Y and then XY * Z, I prefer using parentheses
        ' to make my code even clearer.
        GetFormulaValue = (InputCell.Offset(0, 0) * InputCell.Offset(0, 1)) * InputCell.Offset(0, 2)
    End If
End Function

Public vs Private

First I would like to note the use of a Public subroutine along with a Private function. This basically just means that the MultiplyValues subroutine is accessible by other routines/the macro's list. On the other hand, the function is only seen by other code in the same module (so we don't risk the wrong code using it, and potentially returning a bad value). This is a little bit more advanced compared to where you are, but it is a good practice to get into early.

Variable Declarations

I noticed that you were using Hungarian Notation (HN). I would venture to assume we all go through this phase in the SO VBA community, but the sooner you break that habit, the better. It is far better to properly name variables than to use HN to denote the types. For this purpose, the names were easy. For larger projects it can be a bit more complicated. The sooner you avoid the habit though, the better.

The Good Stuff

Avoiding Errors Before They Happen

Error handling in VBA is not very robust. It works, but oftentimes it is misused. I am of the mindset that error handling (in the line label sense) should be avoided at all costs. The best way to accomplish this is to use logic to your advantage, and to wrap repeated operations in a single function.

In this case, the appropriate method was easy. The function takes an input cell, and returns a value based on the contents of the cell. While you initially checked for Null the function checks for IsNumeric since this will catch Null as well as anything else that isnt a number (since XYZ isn't Null but will throw an error if multiplied by a number).

Why Use Functions?

I like to think of functions as magical creatures that really are under-appreciated by newer programmers. Maybe I am hyping them up a bit. Maybe not. What I can say for sure is I used to avoid them. Then, someone came along (cough ThunderFrame cough) and lightly-reprimanded my avoidance of using single-functions for repeated steps (I had the same Format(X, Y) command in numerous places. He reminded me that, should that command ever change, I would then have to find every single place it lived and fix it. Simple advice, simple reminder, but it changed my approach to using Functions.

I tend to ramble, so the point here is this: When you have some operation that needs to be done in multiple places (or on multiple conditions) you should strongly consider a function. That way, should the operation change, you can fix it in the function, and not in all of the places that you are calculating the operation manually. Functions also allow you to return different types of values. Declare a Function as a Variant and you can return a vbNullString a 0 a "ThisIsABadValuePleaseIgnoreIt". Whatever you want to do. They allow greater control over the flow of your code.

Final Tidbits

As I do in many of my CR posts, I recommend using RubberDuck, especially when you're starting out. You can find it here: http://rubberduckvba.com/. It helps for finding those little things you do without knowing it (Implicit reference to ActiveWorksheet and .Value for example) and help you learn better habits. Over time, these small changes in habits can make or break a programmer.

Best of luck on this.


It's bizarre that you are calling mysql_escape_string() and mysql_error() for code that has nothing to do with MySQL.  Why are you calling arbitrary escaping functions?  You should always know why you are escaping a string.

The most severe problem is that you don't validate the $_POST['Dir'].  If the file path contains ../, then the script will overwrite any file of the attacker's choosing, subject only to the permissions of the webserver process.

The space/no-space scheme is baffling.  Why are you doing that?  You should either eliminate all characters that fall outside a safe set (e.g. A-Z, a-z, 0-9, dot, hyphen, and underscore), or diligently apply percent-encoding to URLs.


Reduce one for loop to decrease time complexity

The second loop can be eliminated by creating a 2D array by tiling the self.x array with the np.tile method. The removal of elements in de 1D array with np.delete can than be replaced with a boolean mask (unfortunately this results in a 1D array which needs to be reshaped).
The calculation of the 2D array can be done outside the first loop, as can be the calculation of lower as they do not depend on x.
See my rewrite of the __call__ method:
def __call__(self,x):

    y_interp = np.zeros(len(x))

    n = self.degree + 1
    mask =  ~np.eye(n, dtype=np.bool)

    tiled = np.tile(self.x, (n,1))
    masked = np.reshape(tiled[mask], (n, n-1))

    lower = np.prod(self.x[:,np.newaxis] - masked, axis=1)

    for i in range(len(x)):

        upper = np.prod(masked -x[i], axis=1)

        y_interp[i] = np.sum((upper/lower) * self.y)

    return y_interp


Code seems repeated, except for the callback function

You don't need the local funcGetOffers variable. Just call util.funcGetOffers directly.

You may extract the options to a var outside the request handlers, since it's the same in both places.

After that, there's not really any repetition left. Sure, the 2 request handlers each call utils.funcGetOffers, but the callbacks are so different that it'd be more complex to generalize them.

However, you can skip the callback function expression for the /api/get_offers handler, and simply use res.json directly.

var options = { top_sort: true }; // maybe call this offersOptions to make it clearer

app.get('/offers/', function(req, res){
  utils.funcGetOffers(function(offers){
    res.render('offers', { offers:offers });
  }, options);
});

app.get('/api/get_offers', function(req, res){
  utils.funcGetOffers(res.json, options);
});

I don't think it's necessary to do anything more elaborate than that.

And again, in utils.funcGetOffers you don't need all those local variables (you can access models.offer directly, and where isn't even used), and you can skip the success-callback, and just use the given one directly

var funcGetOffers = function(callback, opt) {
  var order = [['updatedAt', 'DESC']];
  if(opt && opt.top_sort) {
    order.unshift(['flag_top', 'DESC']);
  }
  models.offer.findAll({order:order}).success(callback);
}

In general, I'd recommend a bit more consistency. You obviously have a column named updatedAt (camelCase), but you apparently also have one called flag_top (underscored). Pick one way of naming things, and stick with it (for JavaScript, the convention is to use camelCase).

This extends to the options object (or opts, but there's no need to shorten it: Just call it options). There you have a key called top_sort, which should probably be camelCased - especially since you're not using it directly, but "translating" it to mean flag_top. In fact, it might be smarter to simply use the actual column name, rather than the - pretty ambuiguous - name top_sort.

And it'd be wise to handle errors too - not just success.

Lastly, there's really no need for the func prefix. If something's called getOffers it's implied that it's a function.


Validating initial inputs then a joint validation test

You should write a function that takes care of asking the user for input. It should be able to assign a type and validate the input. This way you can continue asking for a valid input for each of the variables independently. It also allows you to validate the second variable using the value of the first.
def ask_user(message, type_=str, valid=lambda x: True, wrong_type="Wrong type!", invalid="Invalid!"):
    while True:
        try:
            x = type_(input(message))
        except (TypeError, ValueError):
            print(wrong_type)
            continue
        if valid(x):
            return x
        else:
            print(invalid)

Which you can use like this:
if __name__ == "__main__":
    r_x = 0.15
    r_y = 0.21
    w_x = ask_user("Enter the weight of stock x in your portfolio: ",
                   type_=float,
                   wrong_type="Please enter the weight using numbers",
                   valid=lambda w_x: 0 <= w_x <= 1,
                   invalid="Please enter the number as a decimal. Remember, your maximum investment is 100%.")
    w_y = ask_user("Enter the weight of stock y in your portoflio: ",
                   type_=float,
                   wrong_type="Please enter the weight using numbers",
                   valid=lambda w_y: 0 <= w_x + w_y <= 1,
                   invalid="Remember, the total weight of the portfolio is 100%. The weights should add to 1.")
    r_p = r_x * w_x + r_y * w_y
    print(f"The total return on your portoflio is {r_p:.2%}")

I also used the newer f-strings for string formatting, with the % format code, which takes care of that multiplication by one hundred. I also added a if __name__ == "__main__": guard to allow importing from this script without the code being run.
Python has an official style-guide, PEP8. It recommends using spaces around = when using it for assignment, but not when using it for keyword arguments. Similarly, operators like + and * should generally also be surrounded by spaces.

If you want to be able to input n weights, I would add another function:
def ask_n_weights(message, n, type_=str, wrong_type="Wrong type!", invalid="Invalid!"):
    weights = []
    for i in range(1, n + 1):
        weights.append(ask_user(message.format(i),
                                type_=type_,
                                wrong_type=wrong_type,
                                valid=lambda w: 0 <= w + sum(weights) <= 1,
                                invalid=invalid))
    return weights

This uses the fact that sum([]) = 0 to also be correct for the first variable. In order not to loose the ability to know which weight you are entering I made it so that message should have one placeholder:
ask_n_weights("Enter weight {}: ", 4, type_=float)
# Enter weight 1: 0.25
# Enter weight 2: 0.25
# Enter weight 3: 0.25
# Enter weight 4: 0.25
# [0.25, 0.25, 0.25, 0.25]

You could also take an iterable of variable names instead of n.


Generating Cartesian product of strings in R

Your approach is an example of good R code. However, there is a base function that allows creating a cartesian product of strings, interaction. This function creates a factor, and the levels are equivalent to the cartesian product.

Furthermore, instead of paste(..., sep = "") you can use paste0(...).

If you use these functions, your code will be much shorter:

combine <- function(..., prefix = "", sep = "_") {
  paste0(prefix, levels(interaction(..., sep = sep)))
}

Examples:

s1 <- c('europe', 'asia')
s2 <- c('co2', 'temperature')
s3 <- c('min', 'max')

combine(s1)
# [1] "europe" "asia"
combine(s1, s2)
# [1] "europe_co2"         "europe_temperature" "asia_co2"           "asia_temperature"
combine(s1, s2, s3)
# [1] "europe_co2_min"         "europe_co2_max"         "europe_temperature_min"
# [4] "europe_temperature_max" "asia_co2_min"           "asia_co2_max"
# [7] "asia_temperature_min"   "asia_temperature_max"


First up calls to .ToList() are not inherently slow - it's only when each element in the list is slow to compute that .ToList() appears slow.

So then, what makes the time to compute each element slow?

Well, you're querying votes twice in each query - and computing TotalVotes for each iteration of the foreach loop.

After the query you are then sorting all the candidates by daily votes and then searching through the candidates and picking the first candidate image that hasn't previously won. The search for the winner uses Count, Contains, and ElementAt - all of which can cause the list to be enumerated each time.

All of this is surrounded by a foreach loop to iterate through each date.

Lots of nested iterating - and most of which is unnecessary.

I've got a solution which I've timed to be 135 times faster.

Here it is:

var query =
    from image in _images
    join tvote in votes on image.ID equals tvote.ItemId into tvs
    let TotalVotes = tvs.Count()
    join vote in votes on image.ID equals vote.ItemId
    join date in dates on vote.Date.DayOfYear equals date.Date.DayOfYear
    group vote by new
    {
        image,
        date.Date,
        TotalVotes,
    } into dvs
    let Date = dvs.Key.Date
    let Image = dvs.Key.image
    let DailyVotes = dvs.Count()
    orderby DailyVotes descending
    orderby Date
    group new
    {
        Image = dvs.Key.image,
        dvs.Key.TotalVotes,
        DailyVotes = dvs.Count(),
    } by Date;

var winners = query.Aggregate(new ImageWinnerVotes[] { }, (iwvs, gs) =>
{
    var previousWinners = iwvs.Select(iwv => iwv.ID).ToArray();
    var winner = gs
        .Where(g => !previousWinners.Contains(g.Image.ID))
        .Select(g => new ImageWinnerVotes
        {
            ID = g.Image.ID,
            Image = g.Image.ImagePath,
            Thumbnail = g.Image.ThumbnailImagePath,
            Title = g.Image.Name,
            Url = GetFriendlyUrl(g.Image.ID),
            Date = g.Image.CreatedDate,
            WinnerDateString = gs.Key.ToString("dd/MM"),
            WinnerDate = gs.Key,
            TotalVotes = g.TotalVotes,
            Name = g.Image.Fields["Name"].ToString(),
            Votes = g.DailyVotes,
        })
        .FirstOrDefault();
    return winner == null ? iwvs.ToArray() : iwvs.Concat(new [] { winner, }).ToArray();
}).ToArray();

This is purely a LINQ solution. It's a good idea not to mix LINQ & non-LINQ.

Now, if you didn't have the requirement to eliminate previous winners then I have a solution that is twice as fast again:

var query =
    from image in _images
    join tvote in votes on image.ID equals tvote.ItemId into tvs
    let TotalVotes = tvs.Count()
    join vote in votes on image.ID equals vote.ItemId
    join date in dates on vote.Date.DayOfYear equals date.Date.DayOfYear
    group vote by new
    {
        image,
        date.Date,
        TotalVotes,
    } into dvs
    group new
    {
        Image = dvs.Key.image,
        dvs.Key.TotalVotes,
        DailyVotes = dvs.Count(),
        } by dvs.Key.Date into gxs
    let winners =
        from x in gxs
        orderby x.DailyVotes descending
        select x
    let winner = winners.First()
    let image = winner.Image
    let winnerDate = gxs.Key
    orderby winnerDate
    select new ImageWinnerVotes
    {
        ID = image.ID,
        Image = image.ImagePath,
        Thumbnail = image.ThumbnailImagePath,
        Title = image.Name,
        Url = GetFriendlyUrl(image.ID),
        Date = image.CreatedDate,
        WinnerDateString = winnerDate.ToString("dd/MM"),
        WinnerDate = winnerDate,
        TotalVotes = winner.TotalVotes,
        Name = image.Fields["Name"].ToString(),
        Votes = winner.DailyVotes,
    };

var winners = query.ToArray();

Let me know if these help and/or if you need more info.


Compute max population given a list of people's birth and death year

Your approach isn't bad if you want to do multiple analyses of the population over time. For programming puzzles I often find it useful to focus in on exactly what's being requested and leave the other interesting stuff for another day.

persons.flatMap(p => Seq((p.birthYear, 1), (p.deathYear, -1)))
       .sorted
       .foldLeft((0,0,0)){case ((mxYear,mxPop,curPop), (thisYear,dif)) =>
         if (curPop+dif > mxPop) (thisYear, curPop+dif, curPop+dif)
         else (mxYear, mxPop, curPop+dif)
       }._1  //res0: Int = 2000

In this case the data is

traversed once - to attach a 1 or -1
sorted - to get all the years in order
traversed a 2nd and final time - to count the population changes and save the maxes


LeetCode 862: Shortest Subarray with Sum at Least K

Passing by reference or value
Currently,
std::vector<int> nums

forces callers to pass a copy of the entire vector by value. You could argue that this is actually useful, since your algorithm needs to mutate it (or a copy of it) in-place. My preference is usually to make this copy-step explicit instead:

Pass a const & reference, not a mutable copy
Make a local copy of the vector explicitly, invoking the copy constructor
Mutate your copy.

Spelling
deque_indicies -> deque_indices


Scaling and incrementing non-zero elements of a NumPy matrix

This is a typical use case for numpy.where:

cPrime = np.where(C, C * 30 + 1, C)

This is about twice as fast as (30 * C + 1) * (C != 0) and generalizes more easily to other conditions.


Find all the numbers within a range whose digits add up to a certain target

Just a idea...

There are 7 sets of digits that can constuct numbers that add up to 5.

a = [1, 1, 1, 1, 1]
b = [2, 1, 1, 1]
c = [2, 2, 1]
d = [3, 1, 1]
e = [3, 2]
f = [4, 1]
g = [5]

Then:
let r be the sets in (a...g) that has size < log(max)

Pad each set in r with zeroes so that all set sizes are log(max)

The answer is permutations of the sets that are in the range min - max.


Your code is pretty clear and readable. Congratulations!

Here are some suggestions:

Stop using sleep! Unless this is for a Hollywood hacker movie, it just slows things down. Nobody thinks delays are cool after the first three times you run something.
Take command-line arguments instead of prompting for everything. It's a lot easier to just put stuff into a command line than it is to respond to it at the keyboard. Something like:

ingest -t $HOME/media -b SONY -p "My Project"

There are plenty of SO answers on how to do this.
Add some more functions! Anything you find yourself doing twice should be a function. Also, anything that you have to "break the flow" in order to do should be a function. Here are some examples:

while [[ -z "$target_directory" ]]
    do
        echo -e "Path of target directory?"
        read target_directory
    done

while [[ -z "$brand" ]]
    do
        echo -e "\nBrand Prefix?"
        read brand
    done

That's twice! Write a function to do this:

target_dir=$(prompt_for_variable target_dir 'Path of target directory?')"
brand="$(prompt_for_variable brand 'Brand Prefix?')"

Now consider this:

while true;
do
    read -p "Additional rsync options? [y/n] " rsync_add
    case $rsync_add in
        [Yy]* )

Right in the middle of "construct_rsync" you stop and loop forever prompting the user for a y/n answer. Write a function for that!

if get_yn 'Additional rsync options?'
then
     read -p "Enter the additional options: " rsync_options
fi

Don't lie to anybody, especially yourself. You have a function called construct_rsync but what does it do? It runs the command. Either change the name, or change the function.
Beware of $?. In your log function you refer to it several times. But $? is updated each time a command is run. So if you're going to make decisions based on the value, you should either capture the value into a separate variable (status=$? ... if $status) or make a single decision right up front (if $? ... else ... fi)


Optimized computation of pairwise correlations in Python

What is the reason for this poor performance? And how can I optimize the algorithm?

You mentioned that sites=100 is a "fast" run, and sites=400 is a "slow" six-hour run, without posting profiling data. I don't know what "fast" is, but if it's around 22 minutes then you're just looking at quadratic growth of your data. I'm going to guess "fast" was less than 22 minutes, and then I'll speculate about your cache size. Perhaps you blew out your L3 (or L2) last-level cache. Which would suggest looking for a divide and conquer approach on overlapping neighborhoods, so each sub-problem is conveniently small enough to fit within cache.

Other than that, perhaps you can "cheat" by changing the problem, approximating results. Consider a fixed budget of 10^4 pairs for which you're willing to compute correlation coefficients. In the sites=400 case, could you maybe rank order pairs so the ones with negligible contribution sort to the bottom of the list, outside of budget? Then they would simply never be considered.


My question: Is borrowed_ptr silly? Is it a faux pas? Does it feel like a code smell?

It seems a bit overengineered to me (YMMV).

  Do you feel I should rather do 1., 2. or something else altogether?

Something else. Consider this alternative:

class Master {
private:
    std::vector<std::unique_ptr<Child>> children;
    ...
public:
    // an observed ptr is not modified in any way by client code
    typedef Child const * const ObservedChildPtr;

    ObservedChildPtr get_child(int index) const;
};

This has the following advantages:

the semantics for an observed (i.e. not modified) pointer became part of the class' API
it is explicit and self-explanatory (like your borrowed_ptr)
it is minimalistic (you don't define/need the extra class)
it provides a natural expansion point, in case you actually do need the extra class (see line above) - if you need to expand it, replace Child const * const with a class definition.
client code can be written in terms of Master::ObservedChildPtr (which you can change later without having to update client code).


Given a search string, fetch all movies results from the api

I think it's cool that you fetch the pages in parallel.

A minor miss of the spec

The description says to not return from getMovieTitles,
but the implementation does that.

I agree the early return makes sense when there is a single page of results.
I would have extracted to a function the code that fetches results.
Then the caller could simply call sortAndPrintResults on the returned array.

Things I find weird

return sortAndPrintResults(matches) is weird because sortAndPrintResults is void.

sortAndPrintResults joins the results before printing to console,
which doubles the memory used by the results.
It would have been better to call console.log in a loop.

I find the name fillRange misleading.
Basically it creates a sequence of numbers.
That's not what I would guess from the name.

It's a pity to construct an array of numbers just to loop over them.

These two issues could be fixed by implementing a range function as an async generator.

It's not 100% clear if the functions were given or only the first one.
Many of them would be better inlined.


Creating a webtrend function to remove duplication using js apply and call

There is not much you can do,
the only thing I would suggest is to use concat instead of push, this way you can keep re-using commonLogs, and maybe have 1 commonLogs per group.

So

  var commonLogs = [ [] ];
  commonLogs[1]  = ["DCSext.common1","common1"];
  commonLogs[2]  = commonLogs[1].concat( ["DCSext.common2","common2"] );
  commonLogs[3]  = commonLogs[2].concat( ["DCSext.common3","common3"] );

Then you can

(function(){

  $("#a", "#main").bind("mouseover", function(){
          var id1 = $("#one").text(),
              args = commonLogs[2].concat( ["DCSext.title","one", "DCSext.ti", id1] );
          dcsMultitrack.apply(this, args);
  });

  $("#b", "#cool").bind("click", function(){
       var id2 = $("#two").text(),
           args = commonLogs[2].concat( ["DCSext.title", "two", "DCSext.some", id2] );
       dcsMultitrack.apply(this, args);
  });

  $("body").delegate("a", "click", function(){
     var args = commonLogs[2].concat( ["DCSext.new", "what", "DCSext.where", "us"] );
     dcsMultitrack.apply(this, args);
  });

}());


Apart from the five cases you have to distinguish, there is a more
severe problem with the code as it is: It misses some sums. In your
example of sums adding up to 5 it is the sum 3+1+1 that is missed. The
higher the number, the more sums will be missed.

The reason is that your algorithm greedily "schmears" down one from
the first number whenever possible. However, this should only happen
if the rest of the sum can not be schmeared anymore. So in your
example you have 3+2 and you try to reduce the 3 instead of splitting
up the 2 first.

If you fix that, an important consequence is that it is not sufficient
to modify the sum by schmearing alone, but you have to "reset" parts
of it it occasionally. If you go from 3+2 to 3+1+1, you cannot reach
2+2+1 anymore by schmearing.

A better strategy is trying to schmear the tail first and only if this
is not possible anymore, reduce the first number and reset the tail to
the most compact form not violating your invariants. This is what
uniformSum does in the following listing. Lets say your total is 10
and you reduce the first number to 3, then it sets the sum to 3+3+3+1.

type Sum = List[Int]

def sums(n: Int): Stream[Sum] = schmearStream(List(n))

def schmearStream(sum: Sum): Stream[Sum] =
  sum #:: (schmear(sum) map (schmearStream(_)) getOrElse Empty)

def schmear(nums: Sum): Option[Sum] =
  if (nums.isEmpty || nums.head == 1) None
  else schmear(nums.tail) match {
    case Some(schmearedTail) => Some(nums.head :: schmearedTail)
    case None => Some(uniformSum(nums.sum, nums.head - 1))
  }

def uniformSum(sum: Int, num: Int): Sum = {
  val rest = sum % num
  List.fill(sum / num)(num) ::: (if (rest == 0) Nil else List(rest))
}

You also see that it is sufficient to distinguish fewer cases because
you don't need a lookahead of 2. As long we don't have an
unschmearable sum (empty or starts with 1), we only care if we can
schmear the tail or not.

I tried to write it in a very compact form. If you think a function
should be more verbose for the sake of better readability, please let
me know.


Find the smallest triangular number with more than 500 factors

Instead of
        if len(a) > 498:
            return True
        else :
            a.clear()
            return False

you could just
        return len(a) > 498

as there's no point in clearing a.
The n-th triangle number is \$\frac{n(n+1)}{2}\$, so you could factor both n and n+1 and combine their factorizations.
Takes less than a second:
from collections import Counter
from math import prod
from functools import cache

@cache
def factorize(n):
    factorization = Counter()
    d = 2
    while d * d <= n:
        while n % d == 0:
            factorization[d] += 1
            n //= d
        d += 1
    if n > 1:
        factorization[n] += 1
    return factorization

n = triangle = 0
while True:
    n += 1
    triangle += n
    factorization = factorize(n) + factorize(n + 1) - factorize(2)
    divisors = prod(power + 1 for power in factorization.values())
    if divisors > 500:
        print(triangle, divisors)
        break


The problem

Both examples you show have issues.

Example 1 violates DRY. You have three instances of the same "failure" outcome (in this case ResetLine()). Imagine if the failure outcome requires multiple steps. Now imagine you need to change the failure logic. You'd have to make the same change three times, or you'd end up with unexpected behavior.

Example 2 solves the DRY issue, but it actually fails to properly null check. If zoomEventArgs_ is null, you're going to run into a null reference exception when you try to access zoomEventArgs_.focus. Note that the as conversion returns null when it cannot convert the object to the chosen type.

There is an easy fix for this:

if(zoomEventArgs_?.focus != null)

Note the ?. operator. It is the null propagation operator that will prevent nullreferences from being thrown (and instead returns null). In other words, your if evaluation will be false if either zoomEventArgs_ or zoomEventArgs_.focus is null

The solution

The second example is closer to what you want, but it's not leveraging the best syntax. It can be cleaned up further, without introducing nesting:

if(eventArgs is OnZoomEventArgs zoomEventArgs && zoomEventArgs.focus != null)
{
    SetLine(zoomEventArgs.focus.GetComponent<AssemblyLine>());
} else
{
    ResetLine();
}

eventArgs is OnZoomEventArgs zoomEventArgs will cast the object when it can (and return true), and will pass false if it cannot (thus directing you to the else). Notice that you are able to use this casted object immediately in the same evaluation (zoomEventArgs.focus != null).

I also removed the _ suffix as it does not conform to any convention I've ever heard of.

Your question

  My question is should I instead check for null reference this many times?

Should you check for nulls? Of course, it's part of the validation logic. But you should avoid writing individual failure clauses when the failure logic remains the same in all cases.

  should I instead try to not pass a null reference

Never return null unless you intend to deal with it yourself.

When you intentionally throw a null, you are required to handle the potential nulls being returned. This is the honeytrap of developers. It's very easy to "just return null" and not write any proper handling, but it simply shifts the problem towards the caller, who now has to deal with nulls.
Dealing with nulls, as trivial as it may seem, requires the caller to know if and when nulls are being returned, and it burdens them with the task of dealing with it.

Avoiding wanton null returning as a good practice is further confirmed by the coming update of C#8, where nullable reference types are added specifically to address this "just return null" behavior. The name is a bit confusing, what it actually does is that it makes all reference types non-nullable, unless you explictly allow them to be nullable.

This is analogous to how you today can already choose to use int and int?, for example. This behavior is simply going to be extended to reference types.

  I tried to replace [...] with ternaries but I cannot as both SetLine() and ResetLine() have void as return type.

Don't abuse ternaries as "shorter ifs". If you want to shorten the line count of your if, simply remove the braces (I'm not opposed to that, but this may clash with some style guides who enforce the use of brackets).

Ternaries should only be used in cases where you are assigning a value and would end up with a needlessly bulky if block for what amounts to a simple assigning of a value.

Note that ternaries do not improve code readability on non-trivially readable code.

isActive ? "active" : "inactive" is readable because it is simple (and using an if structure here would be needlessly bulky.
(eventArgs is OnZoomEventArgs zoomEventArgs && zoomEventArgs.focus != null) ? "passed" : "failed" is considerably less readable because it's no longer a trivially readable piece of logic.


Project Euler: #36 Binary and Base 10 Palindromes

Are there any such other optimizations that I have missed that I can use to reduce runtime and in general make my code more useful.

Yes. You're thinking about the problem backwards. As far as I can tell, your solution may be as fast as you can do in Python solving the problem directly. That is, something like:

sum(filter(satisfies_problem, xrange(1, 1000000))

But we can do way better. Palindromes are fairly sparse, so rather than go through a million numbers and checking them to see, we can actually just generate all the palindromes in one base and just check if they're a palindrome in the other base. Basically, for every number from 1 to 1000 we can just add its reverse with or without duplication (e.g. 146 can become the palindromes 14641 and 146641). That is:

def make_palindrome(p, repeat):
    result = p
    if not repeat: p //= 10
    while p > 0:
        result = result * 10 + p % 10
        p //= 10
    return result

Then we can just generate all the right palindromes, base 10, and check if they match base 2:

total = 0
cap = upper_limit / 10 ** (math.log10(upper_limit)/2)
for p in xrange(int(cap) + 1):
    for repeat in (True, False):
        pal = make_palindrome(p, repeat)
        if pal & 1 and lower_limit <= pal <= upper_limit:
            as_bin = bin(pal)[2:]
            if as_bin == as_bin[::-1]:
                total += pal

return total

Timing comparison, this is 100x faster:

Brute Force Search    0.3477s
Palindrome Generator  0.0030s


Make a command line application with parameter

Parameter validation is sorely missing. For example, if you call this with -o as last argument (no more arguments), the program will crash with an array index out of bounds exception and a stack trace. Getting a lengthy stack trace for invalid output is not very UNIX-y ;-)

The finally in the exception handling is not necessary and a bit confusing. I suggest simply moving the break after the catch.

The indenting is a bit strange. I suggest to use an IDE to reformat nicely.

In any case, instead of worrying your own, I suggest using a library. Recently I tried Argparse4j, and I'm happy to say I really like it, works very well for me.


Systems management using SSH for my school

As suggested in the comments, I would strongly suggest looking at a proper configuration management tool such as Ansible or Puppet (both free) instead of rolling your own. That will probably save you a lot of time, once you’ve done the initial ramp-up.

Here are some comments on the code presented:

There aren’t any comments or documentation. It’s hard to tell if this script is behaving correctly, because it’s not written anywhere. (Although the description on the question is good, it would be better if it was embedded in the script itself.)
Use full names in variables; don’t skimp out with abbreviations. It makes the code much easier to read, and characters are cheap. For example: remove_duplicates instead of rem_dupl.

Speaking of that function, here’s a cleaner way to write it:

def remove_duplicates(sequence):
    return list(set(sequence))

In the while run: loop, rather than having the sentinel variable run, it would be nicer to use break statements to get out of the loop. Something like:

while True:
    x = ...
    if x == 'done':
        break
    elif x == 'all':
        ...
        break
    else:
        ...

This is one less variable to understand and track (for the human reading your code, that is!)
In Python 2, range() already returns a list, so

nums = [x for x in range(1, 70)]

can be reduced to

nums = range(1, 70)

I suspect you probably meant

nums = [str(x) for x in range(1, 70)]

because then nums is always a list of strings, however it gets populated.
Rather than creating addresses as an empty list and populating it one-by-one, you could use a list comprehension:

addresses = ["192.168.0." + str((int(i) + 10)) for i in set(nums)]

Note that in this case, we can just deduplicate with set() – we don’t even need to recast to a list to put it in our list comprehension.
It’s not clear what the temp variable is being used for, as we never seem to do anything with the hosts file.
Rather than using the f = open(path); ...; f.close() paradigm, it’s better to use the with statement like so:

with open('hosts.txt', 'w') as f:
    f.write('\n'.join(addresses))

This ensures that the file will always be closed correctly, even if something goes wrong while you’re trying to write to it.

(For example, your file.close is missing the parentheses to actually call the close() method, so this file will never be closed.)

Note also that it’s generally considered bad practice to use a builtin as a variable name. This can be a source of fun and weird bugs, so avoid it unless absolutely necessary.

And an ancillary thought:

As presented, the hosts will be written in the order supplied. Would it be better to sort the output, so that you can easily skim the list and spot missing entries? Not a must, just an idea.


Depending on when you want to make the ajax request, you'll need to modify the first line of my example. Currently it just gets all of them. You might want to change it so that it gets only the div that was clicked, or whatever. Anyways here's one way you could do that:

$('div[id*="carousel"]').each(function() { //The *= selector gets all the divs with an id that contains carousel anywhere in the id.
    var $this = $(this), //Here we select the right div
        id = $this.attr('id'); //And grab the id of the div

    $.ajax({
        url: 'json/' + id,
        //You don't need to set type: GET, the GET is the default.
        success: function(data) {
            //blah blah blah...
            $this.append(d); //Boom done!
        }
    });
});

The way you have your success function set up, you're appending and changing the DOM each time that for loop goes around, and it goes around for every image. That's not good because DOM manipulations are quite expensive performance wise. So if you have 100 images, you're append one at a time - 100 times. The better way to do that would be do all your stuff and save to a variable, string, or object, then append once outside the loop.

Here's an example of what  I mean:

var totalPictures = data['totalPictures'],
    d = ""; //We add "d" outside

for (var i=0; i<totalPictures; i++) {
    if(i<1){
        d = "
";
        d += "";
        d += "";
        d += "";
        d += "
";
    } else {
        d += "
"; //Added a += here so that it'll add onto the first picture
        d += "";
        d += "";
        d += "";
        d += "
";
    }
}

$('#carousel1b').append(d); //Here we append a single time outside the loop
//This cuts our appends down from totalPictures to 1.
//What may seem like a small change will make a huge difference

$("a[rel^='prettyPhoto']").prettyPhoto(); //I assume you'll need this outside since it depends on the appended content


Rock-Paper-Scissors with the revealing module pattern

I like your question,

I think if you are going to export one function, and then immediately execute it, then you are better served with a self executing query.
You are writing a game, I would use a revealing pattern for the model, the controller, and the view.

View would export

An alert function
An input function

Controller would export a

init or start function
It would have a lot of internal functions calling view and model

Model would export a

Getter/setter for victories
comparePlays function

Always consider if you can replace control structures with data structures:

// Display a message depending on round result
function privateAlertRoundResults(results) {
  var resultsMessages = [ 'Draw !', 'You lose !','You win !'];
  alert( resultsMessages[ results ];
}

instead of

// Display a message depending on round result
function privateAlertRoundResults(results) {
  switch (results) {
    case 0:
      alert('Draw !');
      break;
    case 1:
      alert('You lose !');
      break;
    case 2:
      alert('You win !');
      break;
  }
}

For extra points, consider how you can convert this into a data structure:

    if (robotPlay == 1 && humanPlay == 3 || robotPlay == 2 && humanPlay == 1 || robotPlay == 3 && humanPlay == 2) {

Consider wellnamed variables or constants instead of magic numbers, your code would be so much more readable if you had upfront

var DRAW = 0,
    LOSE = 1,
    WIN  = 2;

and then later

function privateUpdateDB(check) {
  switch (check) {
    case LOSE:
      privateGameCount++;
      break;
    case WIN:
      privateGameDB++;
      privateGameCount++;
      break;
  }
}

of course in this particular case, I would not have gone for a case but an if:

function privateUpdateDB(check) {
  if( check == LOSE ){
      privateGameCount++;
  } else if ( check == WIN ){
      privateGameDB++;
      privateGameCount++;
  }
  //We don't increase privateGameCount for Draws (?)
}

I like your adjusting prompt in case the user provides a bad number
On the whole, prefixing your private functions with private is not a great idea because it interrupts the reading flow. I would not prefix at all, but if you insist on prefixing I would prefix with _, most developers will know what you mean (and frown because they also don't like prefixing ;)


The only even prime number is two, so with a little extra coding you can ignore even numbers in the for loop.  For even more speed use a sieve, though maybe save that for when you get a 'TLE' failure.

A more formal code layout would be good as well, your if statements need expanding to include {...}.  More vertical space (blank lines) a well as explanatory comments help.  When you come back to your old code six months later you will thank yourself.

I prefer to set 0 and 1 as FALSE and TRUE to make code easier to read YMMV.

int is_prime(int num) {
  if (num <= 1) {
    return FALSE;
  }

  // Even numbers.
  if (num % 2 == 0) {
    return num == 2;  // 2 is the only even prime.
  }

  // Odd numbers.
  // Start loop at 3 and step 2 to skip even divisors.
  for (int i = 3; i * i <= num; i += 2) {
    if (num % i == 0) {
        return FALSE;
    }
  }
  return TRUE;
}


Thread-safe wrapper around WCF ServiceModel.ClientBase subclass

The code in the OP seems thread-safe to me, but may not be the best solution.
If the channel has many concurrent users, and if using the channel takes for example 100 msec, then 100 concurrent users would queue for up to 10 seconds before being able to use the (single) channel one after the other. A 10-second delay is unacceptable (web users abandon the session).
If the channel is to a payment processor, authorizing a customer transaction might take longer than 100 msec (not 100++ msec of CPU time for your ASP.NET server, but rather a 100++ msec delay waiting for a network response from the payment processor).
Wenlong Dong's Blog article, "Performance Improvement for WCF Client Proxy Creation in .NET 3.5 and Best Practices" (2007) says,

A common pattern of using ClientBase styled proxies is to perform
creation/disposing on each call:
foreach (string msg in myList)
{
    // You may add try/catch block here ...
    HelloWorldProxy proxy = new HelloWorldProxy("MyEndpoint", new EndpointAddress(address)))
    proxy.Hello(msg);
    proxy.Close();
    // Error handling code here ...
}

This article is not ASP.NET-specific, but it states that concurrent instances of a channel are normal.
This article also warns that, creating and destroying proxies can be very expensive, gives advice on how to minimize the cost, mentions a performance improvement (implicit cacheing) made in .NET 3.5, and warns what behaviour (i.e. specifying an endpoint) will disable that cacheing.
A follow-up article titled A Sample for WCF Client Proxy Pooling gives advice on how to implement a pol of proxies.

See also here and here for warnings about how to close and dispose a WCF channel safely:

It should be closed before it's disposed
If there has been a communication error the Close could throw an exception
In an exception is thrown you should call Abort before trying to Dispose the channel


I would propose rearranging and simplifying the code down to this:

Sub LaunchTMAP()
    '' let user know the workbook is downloading so they dont think Outlook froze
    Dim infoBox As New UserForm2
    Call infoBox.Show

    ''  open excel, open the workbook, run the subroutine, then close excel
    Dim xl As New Excel.Application
    Dim wb As Excel.Workbook
    Set wb = ExApp.Workbooks.Open("Z/TMAPAddIn.xlam", ReadOnly:=True) 'Z is a network drive
    Call xl.Run("Module1.example")
    Call xl.Quit

    ''  hide the userform
    Call infoBox.Hide
End Sub

This should not make your code run any faster, but it should make it feel more responsive. By moving the infoBox dim and show to before the new excel window is openned, you make the infoBox appear earlier. This is because the 5 second delay comes from opening excel. I've added a quit call to make sure that you are closing out the excel window when oyu are done with it. I've also gone switched you away from having the CreateObject call, as you appear to already be using the "Microsoft Excel XX.0 Object Library" reference. I also used Dim ... As New .. notation where posible to reduce the number of lines.


I can make some general suggestions. Having code completely rewritten is offtopic here though.

In play_game, you import random from within the function. PEP8 notes though that:

  Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

It's conceivable that you may want to have an import conditionally happen inside of a function if the import is expensive, and would only rarely be used. That certainly isn't the case here though.

changed_list = [char for char in changed_word]

This just creates a copy of changed_word in a verbose way. You would be better off doing what you did before:

changed_list = changed_word[:]

You use far too many global variables. For clarity, those variables making up the state of the game should be explicitly passed to each function that needs them. You could use a dataclass to hold the data, and then pass the state object around.

Having everything as global with complicate testing, and makes your program harder to understand.

You have a loop that's written in a confusing way:

while True:
    guess = input("Input a letter: ")
    if len(guess) != 1:
        print("You should print a single letter\n")
        continue
    if guess != guess.lower() or not guess.isalpha():
        print("It is not an ASCII lowercase letter\n")
        continue
    break

You continue in two branches, then break at the bottom. You might as well just use an elif and else to set it up so you only break if both checks were false:

while True:
    guess = input("Input a letter: ")
    if len(guess) != 1:
        print("You should print a single letter\n")
    elif guess != guess.lower() or not guess.isalpha():
        print("It is not an ASCII lowercase letter\n")
    else:
        break

"\n%s\nYou guessed the word!\nYou survived!" % hidden_word

In more modern Python, this can be written more cleanly using f-strings like you use later:

f"\n{hidden_word}\nYou guessed the word!\nYou survived!"

if setting == "check_lives":
    if lives != 0:
        if lives < 5: # HINT CONDITION
            if hint_flag:

You don't have an else case for any of those checks, so you might as well just and them:

if setting == "check_lives" and 0 < lives < 5 and hint_flag:

That will cut down on a lot of nesting.

list((len(chosen_word))*"-")

Would make a lot more sense as just:

len("chosen_word") * ["-"]

for _ in range(len(changed_list)):
    guess = changed_list[_]

Don't call something _ unless you don't use it. If you use it, give it a good, descriptive name. Here though, you should just iterate the word directly:

for letter in changed_list:
    guess = letter  # Which mostly gets rid of the need for guess


Using py.test with scenarios

Instead of using unittest, I prefer using pytest. There are few reasons:

no need for using test classes
test cases are easy to write as very simple functions
any inputs to test can be parametrized and easily fed by fixtures or parametrization
very easy to have one test case run for one combinations of parameters - makes easier to identify
how large is the share of failing cases.

Here is my rewrite to pytest (all put in one file test_it.py:

Imports:

import pytest
from land_selling import Offer, Seller

Function generating scenarios:

def gen_scenarios(mode):
    assert mode in ["greedy", "dynamic"]

    offers1 = [
        Offer(0, 6, 2),
        Offer(1, 2, 4),
        Offer(3, 5, 1),
        Offer(5, 9, 3),
        Offer(7, 10, 2),
        Offer(10, 20, 5),
        Offer(34, 2, 1)
    ]
    offers2 = [
        Offer(6, 10, 4),
        Offer(1, 5, 2),
        Offer(7, 20, 3),
        Offer(2, 7, 1),
        Offer(14, 30, 2),
        Offer(3, 6, 3),
        Offer(8, 15, 2),
        Offer(20, 35, 5),
        Offer(25, 5, 3)
    ]
    offers3 = [
        Offer(17, 1, 12),
        Offer(7, 2, 10),
        Offer(17, 2, 8),
        Offer(20, 3, 6),
        Offer(3, 11, 4),
        Offer(22, 12, 2)
    ]

    # input list
    offers_list = [offers1, offers2, offers3]

    if mode == "greedy":
        greedy_answers = [4, 3, 2]
        return zip(offers_list, greedy_answers)
    elif mode == "dynamic":
        dynamic_answers = [13, 12, 16]
        return zip(offers_list, dynamic_answers)

Parametrized tests:

@pytest.mark.parametrize("scenario", gen_scenarios("greedy"))
def test_greedy(scenario):
    offers, ans = scenario
    seller = Seller(offers)
    seller.set_up()
    assert len(seller.accepted_offers()) == ans

@pytest.mark.parametrize("scenario", gen_scenarios("dynamic"))
def test_dynamic(scenario):
    offers, ans = scenario
    seller = Seller(offers)
    seller.sort_offers_by_finish()
    assert seller.maximum_profit() == ans

Run it by:

$ py.test -sv test_it.py

I cannot provide sample output as I do not have access to the imported code, but there you will see
another beauty of py.test - really well readable test output.


A few abstract notes about game engines and going with the times:
Choice of UI-Framework
You have chosen Swing as your UI Framework. This is a decision I frankly cannot understand. Swing has been officially deprecated in favor of JavaFX. Not only that, Swing is slow.
It's not getting easier by virtue that I know of no way to load textures in Swing. Also there's no proper integration for OpenGL (let alone any other render engine) into Swing.
These problems could easily be remedied by instead working with JavaFX, which is the new official UI framework and has acceptable, if not good integration for OpenGL through javafx.scene.canvas.Canvas
Raw AWT
Working on raw AWT to integrate free drawing with java.awt.Canvas is a royal pain and actually just a workaround for the lack of proper support in Swing. You shouldn't have to work against your UI Framework. Instead work with it and use it to your advantage. Leverage it.
Design mistakes and OOP violations
Making your GMEngine an abstract class is probably a good move. Making the stuff I need for drawing inaccessible from subclasses probably isn't.
Note that most graphics engines are expected to work on a different basis than your "Engine". This comes back to favouring Composition over Inheritance. The point I'm trying to make is that an Engine should help a programmer get work done in significantly less steps than it needed before.
It should boil down to loading Textures, positioning them and then calling something like render() repeatedly after updating the texture positions. This is simply speaking impossible with your current design, because I as "user" of your Engine have to write the code to do that myself anyways. It would've been easier for me to just write those 200-ish lines here myself, because then I have the full control over what I render and only insignificantly more work.
I think you should revisit your motivations for this class and get a clearer idea for what it should actually do to make life easier for you (and other programmers).


Outputting an inverted index to a text file

In main add:

std::ios_base::sync_with_stdio(false); //   do not keep the C and C++ streams synced.
                                       //   No extra works make this quicker.

The quickest way to flush one stream into another is:

stream << otherStream.rdBuf();

So rather than this:

out_stream.write(output_buffer.str().c_str(), output_buffer.str().size());

// prefer
out_stream << output_buffer.rdBuf();

The other things that slows things down is excessive flushing. Don't flush your stream until you really want the output (so its not good practice to flush the stream while you are writing to it). Do it explicitly afterwords.

out_stream << object << std::flush;

But I see no reason for copying all the data into one stream then re-copying the data into another stream.

std::ostream& operator<<(std::ostream& out_stream, const InvertedIndex& rhs)
{
    auto& rhs_index = rhs.GetIndex();
    for(auto map_elem : rhs_index) {
        out_stream << map_elem.first;
        auto& cur_postingset = map_elem.second;
        for(auto set_elem : cur_postingset) {
            out_stream << " <" << set_elem.GetDocumentId() << ' ' << set_elem.GetTokenFrequency() << ">";
        }
        out_stream << '\n';
    }
    return out_stream;
}


Since a method has to be executed to get this color, you cannot declare the color as constant. A static readonly field is what comes closest to a const.

private static readonly Color DefaultColor = Color.FromArgb(224, 224, 224);

private int GetOleFromHTML(string stringRep)
{
    Color c;
    if (string.IsNullOrWhiteSpace(stringRep))
    {
        c = DefaultColor
    }
    else
    {
        try
        {
            c = ColorTranslator.FromHtml(stringRep);
        }
        catch
        {
            c = DefaultColor
        }
    }

    return ColorTranslator.ToOle(c);
}

Another approach would be to directly store the OLE color as int.

const int DefaultOleColor = 14737632; // R=224, G=224, B=224

private int GetOleFromHTML(string stringRep)
{
    if (string.IsNullOrWhiteSpace(stringRep))
    {
        return DefaultOleColor;
    }
    try
    {
        return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));
    }
    catch
    {
        return DefaultOleColor;
    }
}

Or calculated explicitly:

const int DefaultOleColor = 256 * (256 * 224 + 224) + 224;

Or with bit shift operations

const int DefaultOleColor = 224 << 16 | 224 << 8 | 224; // My preferred variant.

These expressions can be used to initialize the constant as they can be fully evaluated at compile time.

You can test these variants easily in the Immediate Window of Visual Studio. You must qualify the names with the namespaces for the first variant (System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(224, 224, 224))).

Avoiding repetition is not the only reason for having constants. Constant declarations give a name to otherwise "magic" values. See Magic number (programming) (Wikipedia).

This variant avoids the repetition by restructuring the code, but still uses a constant.

const int DefaultOleColor = 224 << 16 | 224 << 8 | 224;

private int GetOleFromHTML(string stringRep)
{
    if (!String.IsNullOrWhiteSpace(stringRep))
    {
        try
        {
            return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));
        }
        catch
        {
        }
    }
    return DefaultOleColor;
}


Space Complexity

This is quite inefficient in terms of the storage space it uses.

Assuming the bisection works as we'd hope, and the vector is cut exactly in half every time, the recursive call copies half the input vector. If, for example, we started with an array of a million items, the first recursive call will copy half a million items. The second recursive call will copy a quarter of a million items.

Since the first call also passed the input array by value, we expect that our search of one million items ends up copying about two million items (in addition to the original vector the user passed).

Time Complexity

Copying those items takes a fair amount of time as well. To be more specific, it takes linear time.

Summary

We normally expect a binary search to have complexity of about \$O(log N)\$, and only descend to \$O(N)\$ in relatively rare worst cases. In this case, we get \$O(N)\$ in about the best case, and \$O(N^2)\$ in the bad cases.

This violates the normal expectations of a binary search badly enough that it effectively only barely qualifies as a binary search at all. In many cases, we can expect its performance to be substantially worse than a simple linear search.

Recommendation

You really don't want to pass the vector by value. Either pass it by reference, along with a pair of indexes into the vector giving the current upper and lower bounds of the part you want to search, or else pass a pair of iterators (there are probably other options as well, but in any case you want to pass an indication of the data to search rather than copying all the data you're going to search).

There are other parts of the code that could use changing as well, but that set of changes is likely to render many (most?) of them obsolete anyway, so I'm not going to get into other areas for now.


You can't currently play with the numbers on the numpad of a keyboard - they have different keycodes to the numbers along the top.

It's normal to camelCase function names rather than snake_case.

Avoid abbreviations e.g. the gen in gen_single_digit_expression.

function number_from_keycode(keycode) { - keycode isn't a keycode at all, it's an event.

Try to remember your semicolons - it's not required but many people (myself included) prefer to see them. There are a couple of very subtle edge cases that can cause problems if you omit them.

eval is evil. You really don't need to invoke the interpreter to do a simple sum!

Here's an example of a simple constructor function (and usage) to show you a way of doing it without eval.

var MathExpression = function(left, operator, right) {
    this.evaluate = function () {
        switch (operator) {
            case '+':
                return left + right;
            case '-':
                return left - right;
            case '*':
                return left * right;
        }
    };
};

var e1 = new MathExpression(1, '+', 8);
console.log(e1.evaluate()); // 9

You don't need to brute force expression generation either. Choose the operator first, then choose the LHS and finally choose a number for the RHS that is within the allowed range.

'+' (addition)
Choose LHS: 1 <= LHS <= 8
Choose RHS: 1 <= RHS <= 9 - LHS

LHS choose 5.
RHS can be 1, 2, 3 or 4 to yield a single digit answer.

You can do the same for the other operators:

'*' (multiplication)
Choose LHS: 1 <= LHS <= 4
Choose RHs: 1 <= RHS <= 9/LHS (rounded down).

LHS choose 4.
RHS can be 1 or 2 to yield a single digit number. (9/4 = 2.25 -> 2)

I'll leave '-' for you to do.


This looks fine to me.

I only have 2 minor points:

You could assign the .text() once in the var statements so that your string concats look like customMessages.email = "'" + label + "' has an invalid email address."; This way you are not repeating text() all over the place.
var customMessages = [{}]; looks odd, because you are afterwards assigning straight to the array instead of the empty object. Simply replacing that with var customMessages = {};  works in the fiddle.


As you are no doubt aware, one-time pads are cryptographically secure according to Kerckhoff's principle, assuming the key is sufficiently random and secret. From a brief glance, your implementation of OTP looks correct. (But I might of course have missed something.)

However, whether the program itself has any vulnerabilities would not be relevant as long as you write the key to a file. Anyone with access to your memory or harddisk would be able to intercept the file, and therefore the key. This means the question boils down to "Is my implementation correct?", and the answer to that is "Yes", as far as I can tell.

I might be wrong, however, because your program is not very readable. Some of the things you can do to clean it up are:

1: Improve variable names. Several of your variable names are single letters. plaintext_length is way more readable than f3.

2: Split your code into logical units. Refactor into functions, and group code that logically belongs together by separating such groups with a single empty line.

3: Why on earth are you doing this?!

if os.path.exists(f2):
    f1 = file(f2, "w")
    f1 = open(f2, "w")
    f1.write(key)
    f1.close()
else:
    f1 = file(f2, "w")
    f1 = open(f2, "w")
    f1.write(key)
    f1.close()

As far as I can see, the two blocks are identical, and one of them will be executed regardless. And as Anthon points out, the first two lines in each block do the same.


Can I simplify my Restaurant MenuCard program?

MenuCard should have two variables, courses_list and menu_date. In my opinion, the method add_course should take in a Course object as parameter instead of taking in the name of the course.
def add_course(self, new_course: Course):
    self.__courses_list.append(new_course)

Course should have two variables, name and dishes_list. The add_dish method should take in a Dish object as parameter and append it to the dishes_list.
Dish seems alright. You should probably change if self.__veggy == bool(1): to if self.__veggy is True:.


Your usage (and your code) is actually fine, which means there isn't much to review.

The only tip I would give is that having only the mean of the cross validation scores is not enough to determine if your model did well. Imagine, for instance, that you have 4 cv that gave the following accuracy scores : [0.01, 0.90, 0.90, 0.90] / 4 = 0.677 vs another set of hyper-parameters that gave [0.77, 0.79, 0.76, 0.80] / 4 = 0.78. That's a fairly crazy example, because such a big gap in the first cv scores is unrealistic, but it's only an example. The mean isn't very robust to outliers, that's what I mean. In order to have more information, it's great to also keep tracking of the standard deviation. You can also plot it using errorbar in matplotlib.


Is my logic correct checking for a newer remote file?

Well, if it works, it works. There is not much to say about this small part of the code without any context. You should know this by yourself, because you should have some tests.

For the code:

The first catch is not suitable. If it happens, you will get a NullPointerException for the following if.

Avoid abbreviations. There are a lot of bad examples in this code, the most noticeable one is String e = s + " | Status Code: " + i;

Reduce indentation levels:

if (serverLastMod.after(fileLastFetched)) {
...
} else {
    Log.e("DS", "NO! Don't do anything... Wait until next check...");
}

could be:

if (!serverLastMod.after(fileLastFetched)) // or last <= current
{
    log...
    return
}
... rest of code...

and so on.
The part ...rest of code... could probably have its own method update..., so the purpose is clear.


Laravel controller for form validation skinny

Check out Dwight Watson's Validating Trait. I like to use it with:

protected $throwValidationExceptions = true;

Validation of Eloquent models occurs automatically according to the rules defined on the model and if it fails, a ValidatingException is thrown that you can catch further up the application stack. For example, I might put the following exception handler somewhere like app/global/start.php

App::error(function (\Watson\Validating\ValidationException $exception)
{
    Log::error($exception);
    // I prefer 'success' => 'false' to be expressed in the response code
    return Response::json([
        'message' => $exception->getErrors()->first(),
    ], 422); // Unprocessable entity
});

Them my controllers end up looking more like this:

public function create()
{
    $input = Input::all();
    // Validation occurs automatically during object creation
    $post = $this->post->create($input, Auth::user()->id);
    $html = View::make('posts.post', ['post_id' => $post->id])->render();

    // I prefer "success" to be expressed by the 200 OK response code
    return Response::json([
        'message' => 'Your post has been successfully posted!',
        'post_html' => $html
    ]); // not specifying a response code implies 200 OK

}

But it's really just a matter of personal preference at this point. Your code looks good to me.

tl;dr +1 would pull & merge


Map with case insensitive get, remove and containsKey

You can't do that with HashMap. Use a TreeMap instead:

new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER)

For highly concurrent version, use ConcurrentSkipListMap:

new ConcurrentSkipListMap<String, String>(String.CASE_INSENSITIVE_ORDER)

Since you don't care about actual ordering, the String.CASE_INSENSITIVE_ORDER is fine for this. If locale-sensitive ordering is required, you need to supply a Collator instead, e.g.

Collator.getInstance(Locale.forLanguageTag("es-ES"))


Instead of providing you a "better" solution, I will try to give you some feedback the code.

Block indentation

  function vowelsAndConsonants(s) {
var strConsonants = "";
var strVowels = "";
var i;
// ..

To work with code it is important that it is formatted in a readable way. There are some style guides out there for example from google

function vowelsAndConsonants(s) {
  var strConsonants = "";
  var strVowels = "";
  var i;
  // ..

Type Embedded in Name

var strConsonants = "";
var strVowels = "";

In this variable names the type is embedded in the name

  Avoid placing types in method names; it's not only redundant, but it forces you to change the name if the type changes.

Array iteration and for...in

For your task is the order important:

  Input string, output vowels and consonants to log, separately but in order

You can read on MDN about the for..in loop,that it do not guaranties a traversal in order:

  Note: for...in should not be used to iterate over an Array where the index order is important. [...]

  [...] iterating over an array may not visit elements in a consistent order. Therefore, it is better to use a for loop with a numeric index (or Array.prototype.forEach() or the for...of loop) when iterating over arrays where the order of access is important.

Make the Else-Statement Implicit

  if (s.charAt(i) == "a" ||
    s.charAt(i) == "e" ||
    s.charAt(i) == "i" ||
    s.charAt(i) == "o" ||
    s.charAt(i) == "u") {
  strVowels += s.charAt(i);
} else if (s.charAt(i) != "a" ||
           s.charAt(i) != "e" ||
           s.charAt(i) != "i" ||
           s.charAt(i) != "o" ||
           s.charAt(i) != "u") {
  strConsonants += s.charAt(i);
}

Currently the if-else statement tries to express: If you are a, e, i, o, u do something, else if you are not from a, e, i, o, u do something.

This is semanticly the same as: If you are a, e, i, o, u do something, else do something.

Additional we can wrap the condition of the vowels into its own method to make the code more readable.

function isVowel(letter) {
    return letter === "a" ||
           letter === "e" ||
           letter === "i" ||
           letter === "o" ||
           letter === "u"
}

The if-statement could now look like

var letter = s.charAt(i)
if (isVowel(letter)) {
  strVowels += letter;
} else {
  strConsonants += letter;
}

String Concatenation..

  strVowels += letter

  Every time Strings get merged by + a new String gets created, because Strings are immutable, that means that for each concatenation new memory space gets allocated.

Better would be to use an array instead of a string an push into it.

vowels.push(letter)

Example Refactoring

function isVowel(letter) {
    return letter === "a" ||
           letter === "e" ||
           letter === "i" ||
           letter === "o" ||
           letter === "u"
}

function vowelsAndConsonants(s) {
    var consonants = [];
    var vowels = [];

    for (var letter of s) {
        if (isVowel(letter)) {
            vowels.push(letter)
        } else {
            consonants.push(letter)
        }
    }

    for (var vowel of vowels) {
        console.log(vowel);
    }

    for (var constant of consonants) {
        console.log(constant);
    }
}

and from here you can still use some methods like forEach or using the ternary operator to shorten an if-else

function isVowel(letter) {
    return letter === "a" ||
           letter === "e" ||
           letter === "i" ||
           letter === "o" ||
           letter === "u"
}

function print(x) {
    console.log(x)
}

function vowelsAndConsonants(s) {
    var consonants = [];
    var vowels = [];

    for (var letter of s) {
        isVowel(letter)
            ? vowels.push(letter)
            : consonants.push(letter)
    }

    vowels.forEach(print)
    consonants.forEach(print)
}


Making events not trigger so often on a datatable with dc.js

What is ineficient here is always running RefreshTable 5 times. Even if no filters where applied to any charts.

Make a new function that only resets filters from charts that have a filter.

function filterAll_performance(){
    var chartlist=[chart_year, chart_genre, chart_runtime, chart_globalscore]
    count=chartlist.length;
    for (var i=count; i--;) {
        if(chartlist[i].filters()!=0) {
            chartlist[i].filterAll();
        }
    }
}

and replace

dc.filterAll();

with

filterAll_performance();

This will still refresh the datatable more than once sometimes but it's still better.


Getting the max value from a list of sums

You've got logic mixed in with your view.

Move as much of the code out of your button handler as you can, and into a separate function (and preferably a separate class).

A button handler should do just that, handle button presses. It should not then perform calculations.

Your spacing could use some work. For example:

    int element;
    List<int> finalResult = new List<int>();
    do
    {
        bag = txtBag.Text;
    }
    while (!int.TryParse(bag, out goal));
    input = txtGenerate.Text;
    string[] elementsText = input.Split(' ');
    List<int> elementsList = new List<int>();
    foreach (string elementText in elementsText)
    {

        if (int.TryParse(elementText, out element))
        {
            elementsList.Add(element);
        }
    }
    Solver solver = new Solver();
    List<List<int>> results = solver.Solve(goal, elementsList.ToArray());
    int closestValue = 0;
    foreach (List<int> result in results)
    {
        count++;
        int totalValue = result.Sum(x => Convert.ToInt32(x));

        if (totalValue >= closestValue)
        {
            closestValue = totalValue;
            finalResult = result;
            txtSum.Text = closestValue.ToString();

        }
    }

Would be a lot more readable like this:

    int element;
    List<int> finalResult = new List<int>();

    do
    {
        bag = txtBag.Text;
    }
    while (!int.TryParse(bag, out goal));

    input = txtGenerate.Text;
    string[] elementsText = input.Split(' ');
    List<int> elementsList = new List<int>();

    foreach (string elementText in elementsText)
    {

        if (int.TryParse(elementText, out element))
        {
            elementsList.Add(element);
        }
    }

    Solver solver = new Solver();
    List<List<int>> results = solver.Solve(goal, elementsList.ToArray());
    int closestValue = 0;

    foreach (List<int> result in results)
    {
        count++;
        int totalValue = result.Sum(x => Convert.ToInt32(x));

        if (totalValue >= closestValue)
        {
            closestValue = totalValue;
            finalResult = result;
            txtSum.Text = closestValue.ToString();

        }
    }

Use var when it is obvious from the RHS of a declaration what the type of the variable is, and always use var in foreach loops.

e.g.

    int element;
    var finalResult = new List<int>();

    do
    {
        bag = txtBag.Text;
    }
    while (!int.TryParse(bag, out goal));

    input = txtGenerate.Text;
    var elementsText = input.Split(' ');
    var elementsList = new List<int>();

    foreach (var elementText in elementsText)
    {

        if (int.TryParse(elementText, out element))
        {
            elementsList.Add(element);
        }
    }

    var solver = new Solver();
    List<List<int>> results = solver.Solve(goal, elementsList.ToArray());
    var closestValue = 0;

    foreach (var result in results)
    {
        count++;
        int totalValue = result.Sum(x => Convert.ToInt32(x));

        if (totalValue >= closestValue)
        {
            closestValue = totalValue;
            finalResult = result;
            txtSum.Text = closestValue.ToString();
        }
    }

Avoid Hungarian notation in C#, and prefer public properties over public fields. Additionally, public collections should be readonly, and you don't need to intiialize an integer as 0. Its default value is 0.

    private readonly List<List<int>> results

    public List<List<int>> Results
    {
        get
        {
            return results;
        }
    }

    public int ClosestValue {get; set;}


Project Euler Problem #6 - sum square difference

Here are a few comments that may help you improve your code.

Use only necessary #includes

The #include <cmath> line is not necessary and can be safely removed.

Avoid "magic numbers"

Since the constant 100 is used several times within the code, it makes sense to create a constant instead.  This also helps with troubleshooting since you can quickly change it to small values (e.g. 10) for which you already know the answer:

const int maxnum = 100;

Avoid abusing using namespace std

Don't abuse using namespace std

Especially in a very simple program like this, there's little reason to use that line.  Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Eliminate function prototypes by ordering

If you put the sum and sqsum implementations above main in the source code, you don't need the function prototypes.

End the last console output with a newline

The output to the program is a little neater on most machines if you output a newline character after the last of the program's console output.

Avoid unnecessary function calls

It doesn't make a huge difference in this code, but the code dosn't need to make two calls to sum().  Instead, the main routine might look like this:

int main()
{
    const int maxnum = 100;
    unsigned square_of_sum = sum(maxnum);
    square_of_sum *= square_of_sum;
    std::cout << square_of_sum - sqsum(maxnum)-a << '\n';
}


Taking n lines from a file which contains m lines, repeating the file lazily if necessary

Even though module Main is implied when no header is given, I'd write it.
return . read =<< getLine = read <$> getLine = fmap read getLine is a worse version of readLn. read <$> getLine is basically return (error msg) when the parse fails. This passes the bottoming value into the "pure" part of your code. readLn badstr crashes at a well defined time—upon its execution—and if you actually wanted to handle the error you'd use Text.Read.readMaybe or readEither.
concat . repeat is cycle. Gets your point across better, doesn't it?
putStrLn . unlines is a bug. It causes an extra newline in the input: unlines creates a trailing newline and putStrLn creates another. Use putStr.
I don't hate the "expression" style here, but once we replace the =<< return . read =<< getLine with =<< readLine you may as well bring it to the front and use >>=, and at that point let's just use a do.
x? Really?

So:
module Main (main) where -- not my style of spacing; but fine
import System.IO (readFile)

main = do
    wanted <- readLn
    contents <- readFile "file"
    putStr $ unlines $ take wanted $ cycle $ lines contents

Though I'd also take
main = do
    wanted <- readLn
    putStr . unlines . take wanted . cycle . lines =<< readFile "file"

Or, if you're attached
main = readLn >>= (\wanted -> putStr . unlines . take wanted . cycle . lines =<< readFile "file")

As to your concern about laziness; this is perfectly fine. readFile is lazy, and so is lines. cycle is actually better than concat . repeat; the latter keeps allocating (:)-cells as long as take consumes them, while cycle will simply connect a pointer that cycles back to the beginning of the output list, which should make it faster. Also, it errors instead of potentially looping forever on an empty input. take is of course lazy, and we've eliminated the excess laziness that would cause any parse errors to be triggered in it. Passing an infinite input (am on a *nix, so I used yes(1) and mkfifo(1)) into this program doesn't break it, which is a good litmus test for laziness.
Now, as to the functionality of this program: the wanted number should really be an argument, and so should the file (which should be optional and default to stdin). That's done with getArgs. This is complicated enough to move into new definitions. Let's get that readMaybe going, too. (Hoogle the new names to find the imports.)
dieWithUsage :: IO a
dieWithUsage = do
    name <- getProgName
    die $ "Usage: " ++ name ++ " lines [file]"

parseArgs :: [String] -> IO (Int, Handle)
parseArgs [] = dieWithUsage
parseArgs (wanted : rest) = (,) <$> getWanted <*> getHandle
    where getWanted = maybe dieWithUsage return $ readMaybe wanted
          getHandle = case rest of
              [] -> return stdin
              [path] -> openFile path ReadMode
              _ -> dieWithUsage

leaving
main = do
    (wanted, input) <- parseArgs =<< getArgs
    putStr . unlines . take wanted . cycle . lines =<< hGetContents input


I agree with forsvarir's answer, that you should lose the continue by inverting the condition.  But you can do one better than that: lose the loop!

var scores = students.Select(student => GetScore(student));
int count = scores.Count(score => !excludeZeros || score != 0);
int total = scores.Sum();

Done. No loop needed.

Or equivalently:

var scores = from student in students
             let score = GetScore(student)
             where !excludeZeros || score != 0
             select score;
int count = scores.Count();
int total = scores.Sum();

You know what is really nice about doing it this way? First, the code looks like what it means; it's closer to the "business domain" of the code. Second, it is super easy to extract more statistics:

int maximum = scores.Max();
int average = scores.Average();
var sorted = scores.OrderBy(x=>x);
var bottomTen = sorted.Take(10);

and so on.


Filter then map instances from a stream and other Java 8 hiccups

What I can suggest is putting the subsequent filter()/map() steps into an extraction method of sorts:

@SuppressWarnings("rawtypes")
private static Optional<Type> extractMyType(Field field) {
    return Optional.of(field.getGenericType())...;
}

You can also put the filter()/map() steps as a single method:

private static <T, R> Optional<R> filterAndMap(T obj, Predicate<? super T> filter,
        Function<? super T, ? extends R> mapper) {
    return Optional.of(obj).filter(filter).map(mapper);
}

For convenience, you can create a cast() method that calls filterAndMap() to handle safe-casting:

private static <T, R> Optional<R> cast(T obj, Class<R> clazz) {
    return filterAndMap(obj, clazz::isInstance, v -> (R) obj);
}

Then, the meat of extractMyType() effectively becomes three flatMap() operations:

@SuppressWarnings("rawtypes")
private static Optional<Class> extractMyType(Field field) {
    return Optional.of(field.getGenericType())
            .flatMap(v -> cast(v, ParameterizedType.class))
            .flatMap(v -> filterAndMap(v,
                            v1 -> v1.getRawType() == MyTypeWrapper.class,
                            v1 -> v1.getActualTypeArguments()[0]))
            .flatMap(v -> cast(v, Class.class));
}

Finally, your collectMyTypes() method will just do a simple filter on the resulting Optional wrapper instances:

@SuppressWarnings("unchecked")
static Stream<Class<? extends MyType>> collectMyTypes(Object o) {
    return Reflection.lineage(o.getClass())
            .flatMap(c -> Arrays.stream(c.getDeclaredFields()))
            .map(YourClass::extractMyType).filter(Optional::isPresent)
            .map(Optional::get);
}


You should reduce the use of explicit type declaration as much as possible.

A function isn't of much value if it just prints its calculated result. You should return the result to let it be up to the client to handle it.

But you can't break out from a loop via an if-statement in F#. You can overcome that by wrapping the outer for-loop in a seq {...} statement and then yield the one and only result and then take the first element from that sequence. But that is inefficient in that it iterates through all the cities even if the first is the one searched for.

Below I've refactored your algorithm according to the above in order to be able to return the result from the function:

let SumByTown town input =
    let rows = (string input).Split('\n')
    seq { for row in rows do
            if (row.Contains(town)) then
                let months = row.Replace(town + ":" , "").Split(',')
                let sequence = seq { for j in months do yield j.Remove(0,4) |> double } |> Seq.sum
                yield sequence
    } |> Seq.head

But this still doesn't look very functional IMO.

For inspiration is here a version that uses the built in higher order functions in a more functional manner:

let calculateCity city data =
    let sum values = values |> Array.sum
    let avg values = values |> Array.average
    let mean values = (values |> Array.sort).[values.Length / 2]

    let handleCity cityText =
        let values = Regex.Replace(cityText, "[^0-9,.]+", "").Split(',') |> Array.map float
        (sum values, avg values, mean values)

    (string data).Split('\n') |> Seq.find (fun s -> s.StartsWith(city)) |> handleCity

let printCityData (sum, avg, mean) = printfn "Sum: %.2f, Average: %.2f, Mean: %.2f" sum avg mean

Usage:

printCityData (calculateCity town data)

Update

Antoher way to use Regex is to match numbers instead of removing non-numeric chars:

let calculateCity1 city data =
    let sum values = values |> Seq.sum
    let avg values = values |> Seq.average
    let mean values = (values |> Seq.sort).ElementAt((values|> Seq.length)/ 2)
    let extractValues text = Regex.Matches(text, "\d+.\d+").Cast<Match>() |> Seq.map (fun m -> m.Value)

    let handleCity cityText =
        let values = cityText |> extractValues |> Seq.map float
        (sum values, avg values, mean values)

    (string data).Split('\n') |> Seq.find (fun s -> s.StartsWith(city)) |> handleCity

let printCityData (sum, avg, mean) = printfn "Sum: %.2f, Average: %.2f, Mean: %.2f" sum avg mean

This requires an open System.Linq at the top of the module


Switched

Let's start with the obvious things we can improve. A return statement terminates the current function. Therefore, all your

case XY: return AB; break;

can be rewritten as

case XY: return AB;

However, you don't have any default cases in both switch statements. What happens if you use conv0to19(100)? Well, it's not obvious, because it's undefined behaviour.

For the sake of simplicity, let's use an assert for unhandled cases. But before we do that, let's have a closer look at your switch:

    case 0:return "";
    case 1:return "one ";
    case 2:return "two ";
      ...
    case 18:return "eighteen ";
    case 19:return "nineteen ";

Hm. You have a continuous range of integer values. So let's use that to our advantage:

std::string conv0to19(uint64_t a) {
    static char const * const numbers[20] =
      {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
      "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
      };

    assert(0 <= a && a < 20);

    return numbers[a];
}

You can do the same for conv_dec. Note that I've removed the suffix space from the string. More on that later.

While we're at it and using an array, your name should:

have a better name (especially not name, since it's a collection of several ones)
be const, so that you don't change it by accident:

const std::string numberNames[] = {"", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion"};

By the way, did you notice that I've added whitespace to separate the arguments? Remember code is written for humans (and for machines). If you want to remove a word later, it should be easy to do so, and whitespace makes it a lot easier to mark text with Ctrl+Shift (or whatever your operating system/editor uses).

Back to the beginning

int container[7];                       /// every element contains a number between 0 and 999

That is a code smell. It's a global variable, which isn't constant. And the description is, well, no really helpful. Just remove it.

Also, the 7 seems like a magic number. Why is it 7? Why not 10?

Either way, you should include cstdint instead of stdint-gcc.h, or — if your compiler is too old — stdint.h. Also, I recommend you to typedef your used number type, e.g.:

typedef uint64_t number_type;

That way you can replace the type easily, if you want to support even larger numbers later.

And using namespace std… well, it's considered bad practice for large programs, especially in headers, but you're writing only a single file here. It's up to you, but I wouldn't use it.

Using logic to reduce if-complexity

Your convert1to999 is too complex. If we didn't enter the following block:

    if (a>0&&a<20)
        return conv0to19(a)+name[i];

we're guaranteed that a is larger then 20. Why? Because a isn't 0. Since it is a non-negative number, it must be then greater than zero, so a>0 holds, so a < 20 must not hold. We don't need to repeat that in the next condition:

    if(a>20&&a<100&&a%10!=0)
       ^^^^

And again, your code is neigh unreadable, since you don't use any whitespace. What is easier to read:

a>=20&&a&&a<100&&a%10==0

or

a >= 20 && a && a < 100 && a % 10 == 0

I guess you now see the superfluous a in the condition, which will always be true at that point.

Next, this function should do one job. It should get a number from 0-999 and return its name, not add the suffix. So let's get rid of that and fix the if complexity. And while we're at it, let's add another function for 0-99:

std::string conv0to99(number_type a)
{
    assert(0 <= a && a < 100);

    if(a == 0) {
        return "";
    } else if (a <= 20) {
        return conv0to19(a);
    } else {
        return conv_dec(a / 10) + "-" + conv0to19(a % 10);
    }
}

std::string convert1to999(number_type a)
{
    assert(0 <= a && a < 1000);

    if(a == 0) {
        return "";
    } else if (a <= 100) {
        return conv0to99(a);
    } else {
        return conv0to19(a/100) + " hundred " + conv0to99(a % 100);
    }
}

Both functions are rather simple and easy to check. The hurdles of the <=20 are now (almost) entirely hidden in conv0to99, which is still easy enough to understand quickly.

As I said, get rid of fillContainer. You use it only in convert, so let's only have it there. Also, handle the easy case first:

std::string convert(uint64_t a)
{
    if(a == 0) {
        return "zero";
    }

    std::string output;
    int container[7];

    for(int i = 0; i < 7; ++i) {
        container[i] = a % 1000;
        a = a / 1000;
    }

    for(int i = 6; i>=0; i--) {
        if(container[i] != 0) {
            // we add the name now here instead of in convert1to999
            output += convert1to999(container[i]) + " " + name[i] + " ";
        }
    }

    // if your compiler doesn't have `output.back()`, use your old check
    while(output.back() == ' ') {
        output.pop_back();
    }

    return output;
}

You can also get rid of container if you build the number from the back.

Last words

Make sure to format your code. Either use an editor which supports automatic formatting, or use a program that formats your code, especially if you want to share your code.