Is this the correct way to create a route to a specific .hbs file?

Somewhere in your code you should be setting the template engine and the base views path, in the likes of
app.set('views', __dirname+'/views/');
app.set('view engine', 'hbs');

(I assume you have that figured out already)
Having said that, you can either reference a view by its location relative to the views setting, therefore:
res.render('Leagues/EnglishDivision/PremierLeague');

(note there's no leading ./ in there)
OR, reference a view by its template file path (without extension). If you do this, the relative path is computed using the base path from which you start your app. Therefore, if your structure looked like:
  /var/www/project
  │
  ├─ packjage.json
  └─ src/
       │
       ├── app.js
       ├── views/
       │   └─── index.hbs
       │   └─── Leagues/
       │       └─── EnglishDivision/
       │           └─── PremierLeague.hbs
       │
       └─── routes/
          └── Pages.js

Moving to /var/www/project and executing node src/app.js means
res.render('./Leagues/EnglishDivision/PremierLeague');

Will look for a template at /var/www/project/Leagues/EnglishDivision/PremierLeague.hbs
Whereas moving to /var/www/project/src and executing node app.js would instead look for /var/www/project/src/Leagues/EnglishDivision/PremierLeague.hbs
If you need to reference the template by its filepath, you should use the absolute path. For example,  __dirname always holds the current folder, regardless of where were you when executing the start script. Which means__dirname called from Pages.js is /var/www/project/src/routes, and therefore
res.render(__dirname+'/../views/Leagues/EnglishDivision/PremierLeague');

Would point to the intended file.


Repetition and potential for bug hiding

try:
    hlwithhtml=article.find('h1')
    hl = hlwithhtml.string
except:
    hl = ''

try:
    pubdatewithhtml=article.find(class_='publication_date')
    pubdate = pubdatewithhtml.getText(' ', strip=True)
except:
    pubdate = ''

try:
    abstractwithhtml=article.find(class_='abstract ')
    abstract=abstractwithhtml.getText(' ', strip=True)
except:
    abstract = ''

try:
    contentwithhtml=article.find(class_='content')
    while contentwithhtml.script:
        contentwithhtml.script.decompose()
    content = contentwithhtml.getText(' ', strip=True)
except:
    content = ''

Potential for bug hiding

except without argument swallows any exception, that is if you mistype for example hlithhtml, h1 will always be empty and you will not be notified of any error.

Repetition

You try an action and if it fails resort to a default value. Also these blocks of code

    pubdatewithhtml=article.find(class_='publication_date')
    pubdate = pubdatewithhtml.getText(' ', strip=True)

    abstractwithhtml=article.find(class_='abstract ')
    abstract=abstractwithhtml.getText(' ', strip=True)

Are very similar only class_ changes.

I suggest you re-organize this code using:

def action_with_default(action, exception, default):
    try:
        return action()
    except exception:
        return default

def find_class(article, class_):
    x = article.find(class_=class_)
    return x.getText(' ', strip=True)

This should save you a lot of duplication.


Testing for divisibility of numbers - follow-up

Precomputed table

I was able to get a much faster result by doing the following:

I precomputed a table which listed for each number, all the permutations of that number.  Only the lowest valid number contained its permutations.  For example, the number 102 contained the permutations: 102 120 201 210.  The entries for 120, 201, and 210 were empty.
I iterated through each number from 1 to MAX.  For each number, I checked whether each divisor divided into at least one of the permutations of the number.  If all divisors divided at least once, then the program was done and the lowest number was found.

When I say I precomputed a table, I mean that I wrote a separate program to dump a table of 1000000 ints into a C file.  I then modified that C file and turned the table into an array of 1000000 ints (a large file > 10MB, but only using about 4 MB at run time), and compiled that huge array into my program.  So I had something that looked like this:

int bigArray[] = {
    -1, -2, -3, -4, ..., -12, 21, -13, 31, ...,
    -102, 120, 201, 210, -103, ..., -999999, -1000000
};

I used negative numbers to denote the start of a new permutation and positive numbers to denote permutations of the entry.  Thus, the -12 and 21 above mean that 12 is the start of a new permutation and 21 is one of the permutations for it.

I have the code to generate the table and the code to use the table, but rather than post them here, I will leave it to the OP to use this idea and create their own code.

The precomputed table version seemed to be about 2x as fast as the previous version, but since the times were so small (0.03 vs 0.06 seconds), it's hard to say whether that measurement was really accurate.


This is reinventing-the-wheel, because the official documentation gives a recipe:

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

By using iterables it tackles the memory-optimization issue effectively.

However, it is possibly not as efficient as it could be because of the way it splits up the work.

To make your code more memory efficient, you could also introduce iterables. I'm assuming that you don't care about the order:

def powerset(A):
    if A == []:
        yield []
    else:
        a = A[0]
        for tail in powerset(A[1:]):
            yield tail
            yield [a] + tail

I've chosen tail to avoid aliasing the built-in set function.

The fastest memory-efficient approach is probably going to be an iterable using a Gray code to create a non-recursive solution which adds or removes a single element to the set between each yield.

Also, FWIW, your code could be more Pythonic.

    rest = []
    for set in incomplete_pset:
        rest.append([a] + set)

could be

rest = [[a] + tail for tail in incomplete_pset]

It's possible that my iterable rewrite of it could also be more Pythonic using a comprehension - I'm open to comments on this point.


Hough transform algorithm - Idiomatic c++

Here are some suggestions for improving the code.

Use all required #includes

The code uses vector but doesn't include the corresponding header.  The code should have

#include <vector>

Use <cmath> instead of <math.h>

The difference between the two forms is that the former defines things within the std:: namespace versus into the global namespace.  Language lawyers have lots of fun with this, but for daily use I'd recommend using <cmath> (and also <cstdio>).  See this SO question for details.

Avoid malloc and free

The old C-style calls still work, of course, but are not recommended.  They are error prone and tend to require more code to do correctly (i.e. checking the return value of malloc for NULL).  Instead, the modern C++ idiom is to use RAII which stand for "Resource Acquisition Is Initialization).  See R.10 and R.1 for details.

Use objects

The 3D array would be much better implemented as an object.  While you could, of course, write one (and I'd encourage you to try that as a learning exercise), there's an even smarter way to do that in the next suggestion.

Know your libraries

The code is already using the OpenCV Mat class, so what would make sense would be to also use that for the Hough space as well.  So this line:

int ***houghSpace = allocate3DArray(image.rows, image.cols, rLen);

would be written instead like this:

int dims[] = { image.rows, image.cols, rLen };
Mat houghSpace(3, dims, CV_8UC(1), Scalar::all(0));

Since that's a properly designed C++ class, it will automatically allocate memory as needed and also de-allocate it when the houghSpace object's destructor is called.  Using it is almost a simple:

houghSpace.at<cv::Vec3i>(y0,x0)[r]++;

Eliminate unused variables

Unused variables are a sign of poor code quality, so eliminating them should be a priority.  In this code, gradient_mag in HoughTransformCircles and r in free3d are unused. Your compiler is probably also smart enough to tell you that, if you ask it to do so.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  It also appears you've got using namespace cv; somewhere as well and it's also not a good idea for similar reasons.

Use variables to clarify your code

The code currently has this nested set of loops:

for (int y = 0; y < image.rows; y++) {
    for (int x = 0; x < image.cols; x++) {
        for (int r = 0; r < rLen; r++)     {
            int x0 = x - (int)(r*cos(gradient_dir.at<double>(y, x)));
            int y0 = y - (int)(r*sin(gradient_dir.at<double>(y, x)));
            if(x0 >= 0 && x0 < image.cols && y0 >= 0 && y0 < image.rows )  {
                houghSpace[y0][x0][r]++;
            }
            x0 = x + (int)(r*cos(gradient_dir.at<double>(y, x)));
            y0 = y + (int)(r*sin(gradient_dir.at<double>(y, x)));
            if(x0 >= 0 && x0 < image.cols && y0 >= 0 && y0 < image.rows )  {
                houghSpace[y0][x0][r]++;
            }
        }
    }
}

Instead, I'd write it like this:

for (int y = 0; y < image.rows; y++) {
    for (int x = 0; x < image.cols; x++) {
        for (int r = 0; r < rLen; r++)     {
            int a = r * std::cos(gradient_dir.at<double>(y, x));
            int b = r * std::sin(gradient_dir.at<double>(y, x));
            int x0 = x - a;
            int y0 = y - b;
            if(x0 >= 0 && x0 < image.cols && y0 >= 0 && y0 < image.rows )  {
                houghSpace.at<cv::Vec3i>(y0,x0)[r]++;
            }
            x0 = x + a;
            y0 = y + b;
            if(x0 >= 0 && x0 < image.cols && y0 >= 0 && y0 < image.rows )  {
                houghSpace.at<cv::Vec3i>(y0,x0)[r]++;
            }
        }
    }
}

In C++11, I'd use a range-for.

Provide complete code to reviewers

This is not so much a change to the code as a change in how you present it to other people.  Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code.  This affects not only code reviews, but also maintenance of the code in the future, by you or by others.  One good way to address that is by the use of comments.  Another good technique is to include test code showing how your code is intended to be used.

Use const where possible

The HoughTransformCircles routine does not  alter the image passed to it, and so it should be declared as taking const Mat& image as an argument.


If she floats then she is not a witch like we thought

There are several small things that you can improve:

double weight = 0; works fine, but double weight = 0.0; would be more pedantic since weight is a double.
By the way, the following line is a good example to illustrate the benefits of literals pedantry:

double volume = ((4/3) * M_PI * pow(obj.radius, 3));

Here, 4/3 performs an integer division and not a floating point one; that expression will yield 1 instead of 1.333333333 (I doubt that you want it to yield 1). You should change it to 4.0/3.0 to get the desired result.
That said, there is another problem with the aforementioned line: M_PI is not standard C++. It is not standard C either. It is a standard POSIX addition to <math.h>. You should rewrite your own constants or use Boost ones for examples if you want your code to be portable.
Speaking of <math.h>... You are using C++, therefore you should use the C++ standard library headers too and not the C ones:

#include <cmath>

And you notably forgot to include the header <ctype.h> for std::tolower.
That said, it is good practice in C++ to fully qualify the names of the functions from the standard library: you should write std::tolower (and thus actually include <cctype> instead  of <ctype.h>). It's not really longer and it may help to prevent name clashes (I doubt that you will have problems with tolower, but it can be worse with some more common names).


Group and send all files to filetype folder

Avoid os.system() by all means. It wastes resources by creating 2 processes per invocation, and is vulnerable to various attacks (at least spell out full paths to the mkdir and mv utilities).

os.mkdir() provide all necessary functionality (don't forget to catch OSError). A combination of os.link() and os.unlink() emulates mv (they are only available on Unix - but you are calling mv anyway).


Why you exactly need the framerate to be constant?
You can use SDL_GetTicks() this way:
const int ms_frame = 1000 / 60;
Uint32 initial_ticks, elapsed_ms;
while(true){
      initial_ticks = SDL_GetTicks();

      //do things

      elapsed_ms = SDL_GetTicks() - elapsed_ms;
      if(elapsed_ms < ms_frame) SDL_Delay(ms_frame - elapsed_ms);
}


Implementation of Prim's Algorithm to find minimum spanning tree

1. Problem

The code in the post does not implement Prim's algorithm! Prim's algorithm constructs a minimum spanning tree. But the code in the post does not construct a tree.

(It could certainly be modified to construct the tree, but you have to actually do it!)

2. Analysis

The key thing to spot about the code in the post is that a node might get added to the queue more than once. This is becasue a node is added to the queue every time a new route is discovered to that node that is shorter than the previously known best route.

In particular, the \$n\$th node to be visited can be added to the queue up to \$n-1\$ times (because a new and better route might be discovered via any of the previous \$n-1\$ nodes to be visited). So the while loop is executed \$O(n^2)\$ times, and on each iteration of the while loop the inner for loop takes \$O(n)\$, giving a runtime of \$O(n^3)\$ overall.

But with an adjacency matrix it is possible to implement Prim's algorithm in \$O(n^2)\$ (see Wikipedia). So you have some work to do!

3. Other review points

There's no docstring. What does prims_mst do? What does it return? What arguments should I pass? I think that if you had stopped and written a docstring then you might have spotted the problem in section 1.
The variables visited and h are global. This means that you can only call prims_mst once — on the second call, the global variables have the wrong initial values. (Or else you have to remember to reset these variables, which is inconvenient and easy to forget.) It also means that the code can't be used from multiple threads.
Names like nd and lv and dst are hard to read. There is no danger of running out of vowels, so nothing will go wrong if you write node and distance instead.
Similarly, instead of importing a module and giving it a hard-to-read alias:

import heapq as hq

consider importing the names you need:

from heapq import heappop, heappush

The variable lv is used only once, so you could just inline its value at the point of use.
Because the graph is given as an adjacency matrix (and because of the enumerate line), we know that the nodes can be labelled with consecutive integers. But the construction of curr_dist uses AP to get the nodes. It would be better to construct it in the way that you use it:

# For each node, the shortest distance from src found so far.
best_distance = [float('inf')] * len(adj_matrix)
best_distance[src] = 0

This avoids the dependency on AP.
The line:

while len(h) != 0:

can be simplified to:

while h:

Instead of representing the set of visited nodes as a dictionary mapping nodes to True, use a set.
This line assigns a variable dst that is not used anywhere:

for nd, dst in enumerate(adj_matrix[src]):

An improvement would be to write:

for node, distance in enumerate(adj_matrix[curr_nd]):

and then you could use distance instead of adj_matrix[curr_nd][nd], saving a couple of indexing operations each time.
The heap entries are data structures of the form:

(distance, (node, parent))

The code for getting data out of these entries is hard to understand because the tuple lookup [1][0] doesn't have any distinctive meaning:

curr_nd = hq.heappop(h)[1][0]

It would be better to use a collections.namedtuple:

HeapEntry = namedtuple('HeapEntry', 'distance node parent')

and then you can write:

current_node = heappop(h).node

which is much easier to understand.


Given a large string, finding the length of the first longest even length sub-string

Firstly, "sub-string" is different than "word". I think "word" is more appropriate in this situation. (A substring can contain non-alphabetical characters).

import sys

You never use this. Get rid of it.

list1 = sentence.split()

This assignment is not terribly necessary.

Your algorithm can be simplified considerably. I think this should be left as an exercise, but here are some things you shouldn't have to do in the new algorithm:

Don't make a copy of the list.
Have some sort of best variable and best_count integer that stores the longest even word found and the length of that word.
After looping through the sentnce, return best.

Using this algorithm you only hit each word once instead of going through the even words again as you do in your algorithm.

The PEP8 style guide states that Python functions use snake_case instead of camelCase so: longestEvenWord -> longest_even_word.


Displaying job status in a jQuery Datatable

First of all, you may benefit from the fact that in Coffee (and in JS, too), the following code

if condition
  variable = value

can be expressed simpler as

variable = condition && value

Therefore, the declaration of the table may be written as

table = $('#dtable').length && $('#dtable').DataTable()

Later in the code, you should not check again for the $('#dtable').length but you should check if the table has a value, possibly with the existential operator. For example, replace the

if $('#dtable').length
    table.cell('#td_5_' + data.job_id).data wait_status

with

table?.cell('#td_5_' + data.job_id).data wait_status

I don't know what the detail_status is but I suppose it is a string selector. Therefore, you don't need to check if it is available in the DOM. JQuery will do nothing if there is no such element, so you can safely call $(detail_status).html wait_status without checking for its length. The same goes for e.g. removeClass method.

You can also use Coffee's string interpolation and replace the "#row" + data.job_id with "#row#{data.job_id}" (and similar).

Last but not least, try replacing multiple conditions like if data.status != "Created" and data.status != "Job Deleted" and data.status != "Scan Complete" with one statement with the in operator, i.e. if data.status not in ['Created', 'Job Deleted', 'Scan Complete'].


Please check out this updated jsFiddle: https://jsfiddle.net/b4mp044z/5/

I've changed your JS code into :

$(document).ready(function () {
    $("#panelSub").hide();

    $("#toggleSubjects").click(function () {
        $("#panelSub").slideToggle("slow");
        $(this).find('i').toggleClass('fa-arrow-circle-down fa-arrow-circle-up')
    });
    return false;
});

and updated your HTML and CSS to hold all your structure and content. It's a good practice to keep things separated (HTML, CSS and JS)


First of all, it is not exactly doing what is expected of detab. The visual appearance of the detabbed text shall remain the same. You need to insert as many spaces as required to reach the next tab stop, not necessarily 4 of them.

For example, a string ab\tc should become

ab  c

(2 spaces inserted) whereas your code produces

ab    c

detab does not zero-terminate the string. It is an (un)lucky coincidence that the code produces meaningful output.
The limit condition is only tested during the tab expansion. A long sequence of ordinary characters will overrun the buffer.


My main problem with this code is that it feels "rambling". Things happen in the right order, but it's all mangled. For instance:

You retrieve hidField on line 6 and then don't use it until line 13.
You retrieve pnl on line 14 and then don't do anything with it until line 33.
You create tbldetails on line 7 but assign its property CssClass only on line 12 (and "table" is IMHO a bad css class name).

Etcetera. Group these assignments so the code become more logical, so there's more of a flow.

Variable altField isn't used at all.

I'm not a big fan of mixing LINQ styles, and I find the SQL-like version often too verbose. Example:

(from q in db.GetTable<priceData>()
where q.ID == rowID
select q).FirstOrDefault();

... can be rewritten as:

db.GetTable<priceData>().FirstOrDefault(x => x.ID == rowID);

priceData is a class name, so why then is it camelCase instead of PascalCase?

Why not use var instead of repeating the class name like here:

TableHeaderRow tblheaderrow = new TableHeaderRow();
TableHeaderCell tblheadercell = new TableHeaderCell();
Table tbldetails = new Table();

Compound words should have a capital at each compounded word, so it should be tblHeaderRow instead of tblheaderrow etc.

Avoid abbreviations. Why hidField and not hiddenField?

This is "old style" C#:

TableHeaderCell tblheadercell = new TableHeaderCell();
tblheadercell.Text = "Details";

These days I'd expect to see this:

var tableHeaderCell = new TableHeaderCell
{
   Text = "Details"
};

Now, WRT your approach: it depends on the volume of data. If this detail table isn't that "heavy" and the main table isn't that big, I would consider filling it up for each row by default and toggling its visibility through client-side code (JavaScript/JQuery + CSS). Not that in this case you should NOT retrieve it ID by ID, but instead in one query.

If that's too much data to send to the browser in one go, then I'd consider your way. There really is no "one size fits all" solution, it all depends on the volume of data and what your users expect from your UI.


Implementation of Generic SQL Data Reader

GetList()

SqlConnection, SqlCommand and SqlDataReader are all implementing the IDisposable interface hence you should either call Dispose()  on that objects or enclosing them in a using block.
You should use var instead of the concrete type if the right-hand-side of an assignment makes the concrete type obvious.
E.g the line SqlConnection con = new SqlConnection(ConStr); we can see at first glance that the concrete type   is SqlConnection and therfor we should use var con = new SqlConnection(ConStr); instead.
Using abbreviations for naming things shouldn't be done because it makes reading and maintaining the code so much harder.
Underscore-prefixed variablenames are usually used for class-level variables. Method-scoped variables should be named using camelCase casing hence list would be better than _list because Sam the maintainer wouldn't wonder about it.
You return an IList<> which is good because coding against interfaces is the way to go.


instead of using ID's you should be using classes. like this

sidebar

 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

then you could change it a little bit more because you have the same exact CSS for 3 & 4 so I would change those to something like this.

#smallLeft {
    float:left;
    width:236px;
    height:167px;
}

    #rtMargin {
    margin-right:5px;
}

same concept for items 2 & 5, and remember that CSS executes top to bottom and will overwrite itself if you change an element with two different selectors in different CSS documents or even on the same document it will overwrite the style, the last one will prevail (in that instance)

Something from my Comment

you should provide all the html, I don't know what is going on with your Headers, but the CSS for them looks wrong. you should apply the width to the outermost element and then 100% the elements inside that you want to be the same width. –  Malachi 1 hour ago


A few comments focused less on line-by-line details and more on how to build
better command-line scripts and on simplifying logic.
How do I use this program? Your input() calls
don't tell me what's going on. Help, please.
Users don't enjoy tedious interactions with computers. Would you rather
type a number, press enter, type an operator, press enter, type a number, press
enter ... OR just enter the darn equation? For example:
reply = input('Enter equation: INT OP INT: ')

Users really don't enjoy tedious interactions with computers. With rare
exceptions, sensible command-line programs don't use input() at all -- or at
least not by default. Learn about sys.argv and let your users run your
calculator directly, without forcing them to become best buddies with their
computer. Here's what a command-line usage might look like:
$ python simple-calculator.py 32 + 10
42

Learn about exception handling. Rather than getting bogged down in creating
a data structure holding every possible bad input (very hard, especially if you
consider all conceivable UTF-8 inputs), just try to do the thing you want to do
-- with a safety net.
while True:
    try:
        # Each of these lines could fail. That's OK. Be optimistic!
        s1, op, s2 = reply.split()
        a = int(s1)
        b = int(s2)
        assert op in '+-*/'
        break                  # Success.
    except Exception as e:
        # The safety net.
        print('Invalid input')

Use data structures to simplify logic. Wouldn't it be cool to get rid of a
pile of if-else checks and instead just do the thing you want to do directly?
In such situations, a data structure can often help. What we need is a way to
take an operator and then use it to get a 2-argument function that will perform
the math we need. In other words, we need a mapping between operators and the
corresponding math functions. Here are 3 ways to achieve that:
import operator

def add(a, b):
    return a + b

ops = {
    '+': add,                    # Define your own functions.
    '-': lambda a, b: a - b,     # Or lambdas.
    '*': operator.mul,           # Or get them from a library.
    '/': operator.truediv,
}

# With that data structure, our code would reduce to this.
answer = ops[op](a, b)     # Wrap in try-except to catch divide by 0.
print(answer)


Definitely separate your PHP from HTML as Alex suggested. You probably don't need to go the full MVC route for something so simple, but simply generating your PHP variables then outputing your HTML would make your code a lot more readable/manageable.

I like your idea of generating a random string and checking it, but Flambino's right, it will never be reliable (by design) - also, imgur probably hates you ;) A simpler approach would be to consume imgur's RSS feed: http://feeds.feedburner.com/ImgurGallery?format=rss

I was bored one morning, so I added something similar to the login page of one of my projects. It pulls one random image from lolcats' RSS feed and inserts it into the page. Here's the code that pulls the image:

$feed = $this->get('feed_parser'); // This is just a SimplePie object
$feed->set_feed_url('http://feeds.feedburner.com/lolcats/rss');
$feed->init();
$items = $feed->get_items();
$item = $items[array_rand($items)]; // Gets one random image, but can modify for more
$item = $item->get_content();

$this->get('feed_parser') is just a fancy way of getting a SimplePie object from the PIMPLE container - you could just instantiate a SimplePie object yourself (if you want code you can't test). After running this code, $item would be a PHP array (or some collection class) containing the details of one image. In my case, I then exposed this as JSON and a REST API endpoint for use by JavaScript, but you could just as easily have PHP output the appropriate HTML.


Randomized response generator for number-guessing game

A standard technique is to setup an array of strings and index it with a random number:

char * answers[] = { "Wrong!", "No", "Try again"};
....
if (guess_is_wrong) {
    int i = random() % (sizeof(answers) / sizeof(answers[0]));
    printf("%s\n", answer[i]);
}


You have one exception for different parameters and I believe it is wrong. You should separate validation of each argument and also use clear message instead of just "something is out of range".

Also I recommend to use ArgumentOutOfRangeException only for arguments that represent single value that is out of range. Length of an array argument is not an argument itself. Some invalid value inside the array is not an argument too.

So define validation methods

private bool IsStairsSizeValid(byte[] stairs)
{
    return stairs.Length >= 1 && stairs.Length <= 50;
}

private bool AreStairsValuesValid(byte[] stairs)
{
    return stairs.All(nextFlight => nextFlight >= 5 && nextFlight <= 30);
}

private bool IsStrideValid(byte stride)
{
    return stride >= 2 && stride <= 5;
}

and then use them

if (!IsStairsSizeValid(stairs))
{
    throw new ArgumentException("Stairs has invalid size.", nameof(stairs));
}

if (!AreStairsValuesValid(stairs))
{
    throw new ArgumentException("Stairs contains invalid value.", nameof(stairs));
}

if (!IsStrideValid(stride))
{
    throw new ArgumentOutOfRangeException(nameof(stride), stride, "Stride is out of range.");
}

Also you should always check arguments of reference type on null in public API:

if (stairs == null)
{
    throw new ArgumentNullException(nameof(stairs));
}

I don't see any reason the numberOfStrides variable should have byte type. You use it within integer calculations so there is no point in byte. Declare it as int and remove casting to byte in the loop.

int numberOfStrides = 0;
foreach (var flight in stairs)
{
    numberOfStrides += flight / stride;

If you have division and remainder calculation for the same values it can be better to use Math.DivRem method:

numberOfStrides += Math.DivRem(flight / stride, out var remainder);
if (remainder != 0)
{
    numberOfStrides++;
}

There is no need to store result of calculations to local variable if you return it immidiately. So you can write just

return (ushort)(numberOfStrides + (stairs.Length - 1) * 2);


I find all those structs tricks a bit old-school now...

There is an alternative implementation using constexpr functions; I also recommend to use if constexpr to make things more readable, but it's doable without it; you just need another overload:

template <typename...>
struct Type_list{};

template <typename... T1s, typename... T2s>
constexpr auto concatenate(Type_list<T1s...>, Type_list<T2s...>) {
    return Type_list<T1s..., T2s...>{};
}

template <template <typename> typename Condition, typename Result>
constexpr auto filter_types(Result result, Type_list<>) {
    return result;
}

template <template <typename> typename Condition, typename Result, typename T, typename... Ts>
constexpr auto filter_types(Result result, Type_list<T, Ts...>) {
    if constexpr (Condition<T>{})
        return filter_types<Condition>(concatenate(result, Type_list<T>{}), Type_list<Ts...>{});
    else
        return filter_types<Condition>(result, Type_list<Ts...>{});
}

template <template <typename> typename Condition, typename... Types>
using filtered_types = std::decay_t<decltype(filter_types<Condition>(Type_list<>{}, Type_list<Types...>{}))>;

template<typename T>
struct is_not_double: std::true_type{};
template<>
struct is_not_double<double>: std::false_type{};

template <typename T>
void print_type() {
    puts(__PRETTY_FUNCTION__);
    }

int main() {
    print_type<filtered_types<is_not_double, double, int, char, float*, double, char*, double>>();
}

I'd rather have this sort of programming: template programming looks like normal programming, rather than have two subsets of the language apart from each other.

Edit: as per request, here's a rewriting of the code without C++ 17 features:

template <typename...>
struct Type_list{};

template <typename... T1s, typename... T2s>
constexpr auto concatenate(Type_list<T1s...>, Type_list<T2s...>) {
    return Type_list<T1s..., T2s...>{};
}

template <template <typename> typename Condition, typename Result, typename T, typename... Ts>
constexpr auto filter_types(Result result, Type_list<T, Ts...>, std::true_type)  {
    return filter_types<Condition>(concatenate(result, Type_list<T>{}), Type_list<Ts...>{});
}

template <template <typename> typename Condition, typename Result, typename T, typename... Ts>
constexpr auto filter_types(Result result, Type_list<T, Ts...>, std::false_type) {
    return filter_types<Condition>(result, Type_list<Ts...>{});
}

template <template <typename> typename Condition, typename Result>
constexpr auto filter_types(Result result, Type_list<>) {
    return result;
}

template <template <typename> typename Condition, typename T, typename... Ts, typename... Us>
constexpr auto filter_types(Type_list<Us...> result, Type_list<T, Ts...> lst) {
    return filter_types<Condition>(result, lst, Condition<T>{});
}

template <template <typename> typename Condition, typename... Types>
using type_filter = decltype(filter_types<Condition>(Type_list<>{}, Type_list<Types...>{}));

As for a variadic, container agnostic, concatenate, here's what you would do with fold expressions:

template <template <typename> typename Type_container, typename... T1s, typename... T2s>
constexpr auto operator+(Type_container<T1s...>, Type_container<T2s...>) {
    return Type_container<T1s..., T2s...>{};
}

template <typename... Type_lists>
constexpr auto concatenate(Type_lists... type_lists) {
    return (type_lists + ...);
}

Without fold expressions you need to provide overloads for calls with 0, 1 and more type lists, as you did with your structs.


You should use map (don't use each to accumulate. Check this page about functional programming):

def users_list
  users.map(&:link_avatar_get).join.html_safe
end


In general, you can use itertools.product to factor out nested loops, and tuple unpacking with * to neatly deal with multiple arguments:

from itertools import product

for keys in product(*Key):
    Decrypt(*keys)

A simple example:

>>> from itertools import product
>>> keys = ["ab", "cd", "ef", "gh"]
>>> for k in product(*keys):
    print k

('a', 'c', 'e', 'g')
('a', 'c', 'e', 'h')
('a', 'c', 'f', 'g')
('a', 'c', 'f', 'h')
('a', 'd', 'e', 'g')
('a', 'd', 'e', 'h')
('a', 'd', 'f', 'g')
('a', 'd', 'f', 'h')
('b', 'c', 'e', 'g')
('b', 'c', 'e', 'h')
('b', 'c', 'f', 'g')
('b', 'c', 'f', 'h')
('b', 'd', 'e', 'g')
('b', 'd', 'e', 'h')
('b', 'd', 'f', 'g')
('b', 'd', 'f', 'h')

Note that for four sets of 20 keys, there would be 160,000 combinations (20 ** 4 == 160000).


Single Validation function, called once per Animation function

You have some possibilities:

1. If you wanna throw and error it's advised to use try...catch to handle the error, also this way the action the user's done will be executed when the condition is matched (when the block is finished animating) if you use finally. try...catch...finally DEMO

$(function(){
  // cache dom
    var $button = $('#button');
  var $block = $('#block');

  // event handlers
    $button.on('click', moveBlock);

  // functions
    function checkAnimationState(){
    if(!$block.hasClass('animating')){
        $block.addClass('animating');
    } else {
        throw Error('Block is already animating... BE PATIENT.');
    }
  }

  function moveBlock(){
    try{
        checkAnimationState(); // check for animation - essentially validation
    }
    catch(e){
        console.log(e);
        return false;
    }
    finally{
      $block.animate(
        {marginLeft:'400px'},
        {
          duration: 3000,
          easing: "linear",
          complete: function(){
            $block.removeAttr('style').removeClass('animating');
          }
        }
      )
    }
  }
});

2. You can use callback inside your checkAnimationState() function to execute or pass the animation command: callback DEMO

$(function(){
  // cache dom
    var $button = $('#button');
  var $block = $('#block');

  // event handlers
    $button.on('click', moveBlock);

  // functions
    function checkAnimationState(callback){
    if(!$block.hasClass('animating')){
        $block.addClass('animating');
      callback();
    }
  }

  function moveBlock(){
    checkAnimationState(function(){
      $block.animate(
        {marginLeft:'400px'},
        {
          duration: 3000,
          easing: "linear",
          complete: function(){
            $block.removeAttr('style').removeClass('animating');
          }
        }
      )
    }); // check for animation - essentially validation
  }
});

3. You can have your checkAnimationState() function return a value wether the condition is matched or not and use an if(...) statement. (I know this one is probably not what the OP wants, but I just wanted to mention it for other people who may stumble upon this question) if (...) DEMO

$(function(){
  // cache dom
    var $button = $('#button');
  var $block = $('#block');

  // event handlers
    $button.on('click', moveBlock);

  // functions
    function checkAnimationState(){
      var isAnimating = !$block.hasClass('animating');
    $block.addClass('animating'); //since jQuery wont add an existing class, no need to check for it's existance before adding
    return isAnimating;
  }

  function moveBlock(){
    if(checkAnimationState()){ // check for animation - essentially validation
      $block.animate(
        {marginLeft:'400px'},
        {
          duration: 3000,
          easing: "linear",
          complete: function(){
            $block.removeAttr('style').removeClass('animating');
          }
        }
      )
    }
  }
});


Style

A few things can be easily detected/improved in your code regarding the style. If you want, you'll find various tools to perform checks automatically : pep8, pyflakes, pychecker. They'll give you a great deal of interesting information, from imported module xxx is not used, to bad indentation via missing documentation, wrong spacing and invalid constant name. Also, it might be good for you to know that in Python, there is a style guide called PEP8 and it's definitely worth a read.

After fixing everything to make the tools happy, your code looks like:

"""Module docstring"""

NAMES = {
    'a': 'awesome',
    'b': 'bold',
    'c': 'curious',
    'd': 'delightful',
    'e': 'emotional',
    'f': 'fearless',
    'g': 'gifted',
    'h': 'helpful',
    'i': 'imaginary',
    'j': 'joyful',
    'k': 'kindhearted',
    'l': 'lovable',
    'm': 'memorable',
    'n': 'naughty',
    'o': 'open',
    'p': 'playful',
    'q': 'quarrelsome',
    'r': 'reliable',
    's': 'serious',
    't': 'thoughtful',
    'u': 'unique',
    'v': 'victorious',
    'w': 'wise',
    'x': 'xerox copy',
    'y': 'yummy',
    'z': 'zealous'
}

def main():
    """Main function"""
    i = j = 0
    user = raw_input("What is your name?: ")
    print ""
    while i < len(user):
        while j < len(NAMES):
            if user[i] == NAMES.keys()[j]:
                print " " + user[i] + ' = ' + NAMES.values()[j]
            j = j + 1
        while j != 0:
            j = 0
        i = i + 1

if __name__ == '__main__':
    main()

Loops

Your are going through your containers (user and names) with a while loop. This is a bit impractical but if you really want to do so, it is clearer to initialise the variable you are going to loop with before the loop so that you not have to try to reset it after the loop.

i = 0
while i < len(user):
    j = 0
    while j < len(NAMES):
        if user[i] == NAMES.keys()[j]:
            print " " + user[i] + ' = ' + NAMES.values()[j]
        j = j + 1
    i = i + 1

Even better, the range function can generate the values your are looking for so that you do not need to do the incrementation yourself :

for i in range(len(user)):
    for j in range(len(NAMES)):
        if user[i] == NAMES.keys()[j]:
            print " " + user[i] + ' = ' + NAMES.values()[j]

but Python provides you an even better way to iterate over containers :

for c in user:
    for j in range(len(NAMES)):
        if c == NAMES.keys()[j]:
            print " " + c + ' = ' + NAMES.values()[j]

Also, because you are using a dictionary, there is no need to loop over NAMES.  You could lookup keys in the dict naturally:

for c in user:
    if c in NAMES:
        print " " + c + ' = ' + NAMES[c]


JavaScript tournament scheduling (fixture generation) algorithm

I have 10 teams to match up. Each team will play 9 matches in a fixture such that all teams play with a separate competition at every round.

Let's build a schedule for 10 teams. I intuitively came up with the following circulant 10x10 matrix A with entry A[i, j] denoting the opponent of team i in round j:

Each row represents the schedule for a single team. We note that for each round j teams are partitioned into pairs playing against each other - i.e. A[A[i, j], j] = i.

However, there is a flaw: According to above schedule, there is a round j for each team where it has to play against itself (the red squares) - i.e. A[i, j] = i.

That's because a correct schedule for 10 teams can only have 9 rounds, not 10. To fix this, we first slice the main diagonal of A - all matches against team 9 - and end up with:

Now, we re-introduce the matches against team 9 wherever a team would have to play against itself (the red squares). We also have to fix the opponents of team 9 to reflect these changes. This practically means that for each round j we swap A[9, j] with A[i, j] where i denotes the self-matched team (the red square):

This is the resulting correct schedule with all swapped matches highlighted in red. This schedule is identical to the one you compute and pretty simple to generate:

Create a circulant 10 x 9 matrix where each row is a circular shift of [0,1,2,3,4,5,6,7,8].
For each round or column, replace the self-match with a match against team 9 and let team 9 play against the self-matched team.

While there are exactly 945 different ways to partition 10 teams into pairs and thus many more ways to generate a correct schedule, I could not come up with a simpler or more intuitive schedule.

  While it works fine i would like to know if my calculations could be
  simplified any further.

I think that by closely following the above recipe, you can avoid the more obscure arithmetic and come up with a simpler and more intuitive 'generative' algorithm. The scheduling is encapsulated in the round(n, j) function:

// Schedule single round `j` for 'n' teams:
function round(n, j) {
  let m = n - 1;
  let round = Array.from({length: n}, (_, i) => (m + j - i) % m); // circular shift
  round[round[m] = j * (n >> 1) % m] = m; // swapping self-match
  return round;
}

// Schedule matches of 'n' teams:
function fixture(n) {
  let rounds = Array.from({length: n - 1}, (_, j) => round(n, j));
  return Array.from({length: n}, (_, i) => ({
    id: "Team_" + i,
    matches: rounds.map(round => "Team_" + round[i])
  }));
}

// Example:
console.log(fixture(10));


Efficient Traversal and Manipulation of the DOM with Native JavaScript Using For/In Loop

You should not iterate over an array or array-like object using a foreach loop,
you should use a good old-fashioned for loop instead:

var items = document.querySelectorAll('.item');
for (var i = 0; i < items.length; ++i) { ... }

Yes, this sequential for loop doesn't look as elegant as a foreach loop,
but unfortunately, using a foreach loop for arrays in JavaScript is incorrect.

As for this:

var items = document.querySelectorAll('.item');
for (var i = 0; i < items.length; ++i) {
  var item = items[i];
  var link = item.querySelector('a');
  var img = item.querySelector('img');
}

Having two .querySelector lookups in each iteration is not really a problem,
because the lookups are done on a small object, a tiny subset of the entire document.

I wrote the loop body slightly differently from your original:

I put the value of items[i] in a local item variable.
This is to avoid duplicating item[i].
It's good to eliminate duplications,
because if you ever need to change something, you need to do it in all duplicates,
which is potentially error-prone.
I declared link and img on two lines.
This is slightly more verbose, but a bit clearer.


The actual creation of the pos mask looks perfect to me. You can streamline the rest of the code into a single-liner as:

a = np.concatenate((a[pos], a[~pos]))


Dynamic Official Receipt increment algorithm

A few notes on the use of exceptions:

You're catching the non-specific Exception. That's bad, because it hides real programming errors. You should be specific what exception to catch (like except POS_settings.DoesNotExist:).
There are too many try-except blocks overall. You may need to rethink what you're trying to do, and with the previous point in mind, what exceptions you're trying to catch. Django queries may often return an empty queryset instead of raising an exception, which may be better suited.
The overarching try-except is really bad. Firstly, that catches anything that isn't caught in the inner block, and secondly, it makes it hard to read where it starts and ends. Try-except blocks should be short, concentrated around the code code (one or a few lines at most) that might raise the exception
If you use else: pass in an try-except clause (or in an if-clause), it's cleaner to just leave off the else branch. There's no use for it. The same goes for finally: pass.
You're catching the overarching exception, then printing it, then returning it. That has two problems:

when run inside a proper server, print very likely causes problems (from my experience using Apache). Use the Django logging provided.
there is absolutely nothing to gain by returning an exception. Re-raise it, or perform a cleanup action (and possibly still re-raise it after that). Return is for actual values, not exceptions.


Allocating a contiguous block of memory for an array

Of course this in not a true 2d array, just a 1d array indexed using arr[i * col + j].

This is an OK approach.  When able, I prefer an array of pointers to an array of ints, as it is usually more flexible to the tasks I tackle.  YMMV.

Modest extreme case: sizeof *arr * row * col is multiplied in the right order.  When row or col is int/unsigned, good to use sizeof *arr first as that is type size_t and the subsequent multiplication will then happen at least using size_t math.   The concern being that with unsigned row, col, row*col  calculated first could overflow using unsigned math, but not size_t math.

Pedantically, even sizeof *arr * row * col can overflow.  Should code need to detect this, the reasonable approach is to use the widest unsigned types like unsigned long long or uintmax_t.  (Other more pedantic methods exist.)

assert(1LLU * sizeof *arr * row * col < SIZE_MAX);

Suggest using size_t for row, col, i, j instead of any other type.  size_t is the Goldilocks type for array indexes - not too narrow, not too wide.
Error messages are better sent to stderr.  2 advantages: will not get lost in code's typical stdout output and the stderr stream is flushed ensuring output is not mixed after later input.
Idea: Using a arr = 0; after the free(arr); has merit when the free'd variable is still in scope for a long time.  Although not needed, a decent compiler will optimized it out, but errant subsequent use is easier to detect when arr == NULL than arr = some_freed_value.
Minor: printf("%d ",arr[k]); in a loop is sometimes a problem when trying to print more than some environmental limit number (e.g. 4095) of characters on the same line.  Liberal use of fflush(stdout); or including a '\n' in the text usually solves this.
A key comment missing is: is this array row or column major?  With some analysis, that is discernible, but from a header only interface, knowing which dimension moves in the smallest steps is important in how higher level code will want to use this array for cache hit efficiency.
Coding style:  No need to introduce a variable until ready for assignment.  Consider the 2nd style.

// int *arr;
// ... many lines
// arr = malloc(sizeof *arr * row * col);

... many lines
int *arr = malloc(sizeof *arr * row * col);


Generating histograms from "chunked" large data streams

var currentTree = tree;
foreach (var item in chunk)
{
     currentTree = currentTree.Add(item);
}
currentTree.Count++;

That function shouldn't need to know how to traverse a tree. That functionality belongs to Tree, not to the invoking site.

A simple tree.Add(chunk); is much cleaner in this context. The complexity of building and traversing the tree should be hidden entirely hidden inside the Tree class:

public void Add(IEnumerable<T> path)
{
    var node = this;
    foreach (var item in path)
    {
        node = node.GetChild(item);
    }
    node.Count++;
}

There is no longer a need to expose the original Tree::Add publicly, as the only legit caller is now inside the same class:

private Tree<T> GetChild(T value)
{
    Tree<T> node;

    if (!Branches.TryGetValue(value, out node))
    {
        node = new Tree<T>();
        Branches.Add(value, node);
    }
    return node;
}

The second occurrence where the functionality should have been encapsulated inside Tree is getAllCurrentTreeReversedPaths. This function requires specific knowledge about how the storage is implemented, so it's inseparable from it.

This also raises concerns regarding the visbility of Tree::Count and Tree::Branches. These properties don't need to be exposed, if the methods belonging to Tree are actually moved into that class.

For the invoking side, only the capabilities of storing, counting, and reciting stored paths are of interest. Nothing else, especially not how the tree is implemented. Not even the fact that it is implemented as a tree at all.

foreach (var subBranch in getAllCurrentTreeReversedPaths(branch.Value))
{
    yield return new HistogramItem<T>(
      subBranch.Count,
      subBranch.Path.Concat(new[] { branch.Key })
    );
}

This doesn't look right. You are essentially recreating and discarding HistogramItem instances over and over again, while you are technically only appending to the Path property.

HistogramItem::Path should either be mutable, or simply add the current path suffix as a parameter to getAllCurrentTreeReversedPaths, so you can create HistogramItem instances with the correct properties right away.


Do you view this ThrowingFunction interface as "interface abuse"?

When does such "heavy use" turn into outright abuse?

What it seems like you're asking is "Am I abusing Default Methods?".

When in doubt about how to use a new piece of functionality I typically turn to the Java tutorials. As is the case with other new pieces of functionality in Java 8, there is documentation about Default Methods here.

One specific snippet that caught my eye is this:

"Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces."

I would ask yourself several questions about the implementation in assessing whether or not the new functionality is being abused:

Am I exposing too much business logic in the interface through the default methods?
Is there sufficient justification to expose the methods through the interface as opposed to having them implemented in an abstract class?
Is the code going to be maintainable?
Am I using the default methods feature in the way which it was created to be used?

To address your question about overdoing it, in my opinion you are. The documentation seems to imply what you should be using default methods for and this does not fit that mold. Especially since you're starting with an empty slate as opposed to adding new functionality to existing libraries for which you have to maintain binary compatibility.

In addition, take a look at the Java 8 List interface. Default methods are provided which accept other functional arguments and utilize those arguments on the implemented instance. The same seems true for the Comparator interface.

From the snippet provided it seems like the default methods do not utilize functional arguments. I also don't see any advantage of doing things this way over using the template pattern (which it seems like you're doing anyway) and having an abstract base class declare  the doApply method and have the abstract class call that from behind the curtain of the interface.

I'm biased in that I favor hiding functionality behind interfaces as opposed to exposing it. I perceive the intention of interfaces to be encapsulating data and hiding business logic and design following those concepts.

Here is some reading pertaining to anti-patterns that I try to keep in mind that may be applicable to your question:

Golden Hammer
Silver Bullet

Also, Oracle almost HAD to add some kind of functionality to the language that would provide backwards compatibility with existing libraries while also injecting new functionality. I consider the usage that the developers of the language chose to be a good starting place for evaluating my own usage.

As an aside, there looks to be some really cool stuff in your project.


You could make it smaller by turning your function into a constructor:

function RowObject(row) {
    for (var i = 0; i < columns.length; i++)
      this[columns[i]] = row[i];
}

You would have to call this function with new then. I would avoid putting the assignment on the same line as the for, it is too Golfic to maintain.

The only way to avoid a loop is to fake it:

function convertRowToObject2(row) {
  //o -> object, v -> value, i -> index
  return row.reduce( function(o, v, i){ o[columns[i]] = v; return o; } , {} );
}


Pandas DataFrame.sort_values() new method to exclude by row name

When using pandas leverage on functions in API almost every function is vectorized.
You can break down your problem into categories.

If fixed is None just sort w.r.t given column_names.
Else sort w.r.t given column_names but filter filter fixed indices.
insert fixed at previous positions.

def sort_values(df, column_names, ascending=False, fixed=None):
    if fixed is None:
        return df.sort_values(column_names, ascending=ascending)
    idx = df.index.get_indexer(fixed).tolist()
    s_df = df.sort_values(column_names, ascending=ascending).T
    keep_cols = s_df.columns.difference(fixed, sort=False)
    out = s_df[keep_cols]
    for (loc, name) in zip(idx, fixed):
        out.insert(loc, name, s_df[name])
    return out.T

Note: fixed should be a list.
Example runs:
fixed = ['rank3']
sort_values(df, ['marks'], ascending=False, fixed=fixed)

#        Name marks
# rank2  Jack    30
# rank1   Tom    10
# rank3  nick    50  # rank3 position fixed.
# rank4  juli     5

fixed = ['rank2', 'rank3']
sort_values(df, ['marks'], ascending=True, fixed=fixed) # ascending order.

# sorted in ascending order
#        Name marks
# rank4  juli     5
# rank2  Jack    30 # rank2 position fixed
# rank3  nick    50 # rank3 position fixed
# rank1   Tom    10

Code Review

PEP-8 Violations

E501 - Lines longer than 79 characters. You have many lines with length greater than 79 characters.

# Examples
original_positions = {name: position for position, name in enumerate(df.index.values) if name in fixed_categories}
# Can be refactored as below
original_positions = {
    name: position
    for position, name in enumerate(df.index.values)
    if name in fixed_categories
}

original_positions = dict(sorted(original_positions.items(), key=operator.itemgetter(1), reverse=True))
# Can be refactored as below
original_positions = dict(
    sorted(
        original_positions.items(), key=operator.itemgetter(1), reverse=True
    )
)

You can use pep8online* to check if your code is in accordance with PEP-8 standard.
You can use black* (code formatting tool)
black --line-length 79 your_file.py

* I'm not affiliated to pep8online and black.


ActiveRecord Query for many to many association

To produce the set of records only in cars, but not in drivers, you perform a left outer join, then exclude the records you don't want from the right side via a where clause.

In Rails 6 you do this in this way:

Car.left_outer_joins(:drivers).where(car_drivers: { id: nil })

Take a look at this article: A Visual Explanation of SQL Joins. It may help you figure out how to do some queries.

Aside from this, a good way to iterate over an array to select some elements according to a condition is to use the select method. Using select your code would be like this:

result = Car.all.select { |car| car.drivers.empty? }

But that is not the way to go here, I'm just showing how to use select.

Also, if you want only the id from the cars, you can add pluck(:id) at the end of the query. This is going to get only the id field from the database. Or you just use the method ids but the pluck method works for any field.


if it really has to be brute force solution, then you have to check all possible combinations of take first/take last item for both players

you know that there are 4 items, so every player takes two of them, combinations are (for each player):

take first (0), take first (0)
take first (0), take last  (1)
take last  (1), take first (0)
take last  (1), take last  (1)

as you can see, numbers are similar to binary numbers equal to 0-3(dec)

second player should do the same in an inner loop for every iteration of first player (outer loop)

pseudo code would be:

ArrayList <Integer> boxes = {5, 3, 7, 10}

boolean shouldTakeFirst(int combination, int iteration) {
    return (combination & (1<<iteration)) > 0; // checks if i-th bit of combination is "1"
}

int player1Score(int combinationP1, int combination P2) {
    int score = 0;
    for (int i=0; i<boxes.size()/2; i++) {
        score += shouldTakeFirst(combinationP1, i) ? boxes.popFirst() : boxes.popLast(); // assuming that .popFirst() and .popLast() remove elements after taking them
        shouldTakeFirst(combinationP2, i) ? boxes.first() : boxes.last();
    }
    return score;
}

for (int i=0; i < Math.pow(2, boxes.size()/2); i++) {
    for (int j=0; j < Math.pow(2, boxes.size()/2); j++) {
        int p1Score = player1Score(i, j);
        int p2Score = sum(boxes) - p1Score;

        // check if scores better than max and remember/print it
    }
}


Test if a number is within 2 of a multiple of 10

You should read about congruent integers and modular arithmic. The distance of a number to a base is the minimum distance of its congruent value and its inverted congruent value.

 public boolean nearBase(int num, int base, int deviation) {

        // ..TODO check guards, normalize input or throw exceptions
        // - base and deviation are expected strict positive integers
        // - deviation is expected smaller than base
        // - num is expected a positive integer

        var congruent = num % base;
        var inverted = base - congruent;
        var distance = Math.min(congruent, inverted);
        return distance <= deviation;
    }

 // your method rewritten ->
 public boolean nearTen(int num) {
        return nearBase(num, 10, 2);
    }


This code of yours is not working, despite your assurances that it is. It replaces just the first occurrence of 'ins', and that should be obvious since you call the replaceFirst method. The example sentence you use in the code is not the same as the sentence in your description. The one in the description will fail your code:

This is a java institute which insures that you are in that institute. ins!

Your code will produce:

This is a java JSStitute which insures that you are in that institute. ins!

and it should produce:

This is a java JSEtitute which insures that you are in that JSEtitute. ins!

There are three problems

the specification says replace the ins in institute with JSE, your code though, replaces just the first ins in institute, not them all
you replace the ins with JSS, and not JSE.
you don't check for the beginning of the word... you will find ins in "dustbins".

These small details are things you have to fix, and show a low attention to detail.

Of course, a more advanced solution would be:

s.replaceAll("\\bins(?=titute\\b)", "JSE");

You can see that in action here in Ideone


$scope.$watch(
    "data.message",
    function (newval,oldval){
        $window.localStorage['stuff'] = newval;
    })

Not entirely sure why this is formatted this way. Looks odd. Also, you use double and single quotes. They don't really matter for JS strings, but for consistency, use one of the two. I usually recommend single quotes because they're cleaner-looking.

$scope.$watch('data.message',function (newval,oldval){
  $window.localStorage['stuff'] = newval;
});

More compact, less weird. :D

I notice you use Github-flavored markdown but that entails sending it over the wire and waiting for a response. That's a slight overhead plus it heavily relies on a service that may go down any time. I suggest you look for an offline library. I suppose there is one for Github-flavored (MarkdownPad supports such) but other libraries could come close.

Naming could also need rework. FirstCtrl and SecondCtrl don't really tell me anything about the controllers without reading their code (which is the first sign of terrible code, having to read everything). The first controller could be Editor because it has your text area binding while the second could be GitHubMarkdownRederer because that's what it does.

I don't see why you need to compile the markup before appending it to the DOM. It doesn't require Angular facilities. You can simply pop it in as HTML in the DOM.

Appending arbitrary markup on the current is dangerous. What editors like jsFiddle do is host the renderer in a totally different domain and render it on the page using an iframe. That way, built-in browser security takes care of the rest, preventing inter-domain, inter-frame communication. There are other options out there, not sure which one is best for the situation.


List class/controller to prevent memory exhaustion

Is the class itself thread safe

Looks fairly safe except TasksController Controller part.

Firstly, I would suggest to use .NET classes for storing concurent data instead of List<T> depending on your needs you can use ConcurrentBag<T>, ConcurrentQueue<T>.
Secondly, create lock for TasksController Controller and use it inside getter. Something like this:

private static TasksController Controller {
    get{
        lock(_controllerLock){
           if(_controller == null){ (_controller = new TasksController();}
           return _controller
        }
    }}

Is deriving from IDisposable necessary

I would say: no. All tasks should be disposed automatically when they finish.

However, there is only one but, you might to cancell your tasks when object is being disposed. That means if they do some heavy calculations which you do not need anymore after main object disposes. See this answer for information how to do that.

For more information about disposing tasks see MSDN blog post


If you need to wrap SomeClass, make your wrapper an abstraction:

public interface ISomeClassWrapper
{
    // expose the methods and properties you want to wrap
}

Then everywhere it's needed in the code, replace static method calls like this:

public void DoSomething()
{
    SomeClass.Xyz();
}

With something like this:

public class MyOtherClass
{
    private readonly ISomeClassWrapper _wrapper;

    public MyOtherClass(ISomeClassWrapper wrapper)
    {
        _wrapper = wrapper;
    }

    public void DoSomething()
    {
        _wrapper.Xyz();
    }
}

Now, if you're worried about how many instances of SomeClassWrapper (which implements ISomeClassWrapper but MyOtherClass doesn't need to know that), don't instantiate it. ever.

How do you ensure there's only 1 instance of it?

When you've replaced SomeClass.Xyz(); with _wrapper.Xyz();, you've done several things:

MyOtherClass is now decoupled from SomeClass, and even from SomeClassWrapper.
The ISomeClassWrapper dependency is now statically declared as such, so just by looking at MyOtherClass's constructor you know it needs an implementation for ISomeClassWrapper to carry out its tasks.
You can now provide a fake/mock implementation of ISomeClassWrapper, and write a test for DoSomething() without worrying about side-effects in code that you have no control over.
The code that's responsible for providing the ISomeClassWrapper instance/implementation, is also responsible for passing everyone that wants an ISomeClassWrapper instance, the same instance. Most IoC containers can do this very, very easily.


is this a correct mutex?

It is not correct. There is a requirement for std::mutex::lock (http://en.cppreference.com/w/cpp/thread/mutex/lock):

  If another thread has already locked the mutex, a call to lock will
  block execution until the lock is acquired.

A simple test below that uses your mutex consumes 100% CPU that means it is busy-waiting. I think you did it by mistake.

On the contrary if I use std::mutex for the same test consumes 0% CPU in waiting on mt.lock().

mutex mt;
int main() {
    auto f = []() {
        mt.lock();
        mt.unlock();
    };
    mt.lock();
    std::thread t (f);
    std::this_thread::sleep_for(std::chrono::seconds(60));
    mt.unlock();
    t.join();
}

Below is a pidstat report for running a test with your mutex:

$ pidstat 1 -p $(pidof custom_mutex)
Linux 3.10.0-229.el7.x86_64 (sk71.net.billing.ru)       05/16/2017      _x86_64_        (2 CPU)

09:44:31 AM   UID       PID    %usr %system  %guest    %CPU   CPU  Command
09:44:32 AM  1000      9806   11.00   88.00    0.00   99.00     0  custom_mutex
09:44:33 AM  1000      9806   14.00   86.00    0.00  100.00     0  custom_mutex
09:44:34 AM  1000      9806   13.00   86.00    0.00   99.00     0  custom_mutex
09:44:35 AM  1000      9806   15.00   84.00    0.00   99.00     0  custom_mutex
09:44:36 AM  1000      9806   15.00   83.00    0.00   98.00     0  custom_mutex
09:44:37 AM  1000      9806   12.00   87.00    0.00   99.00     0  custom_mutex
09:44:38 AM  1000      9806   16.00   83.00    0.00   99.00     0  custom_mutex
09:44:39 AM  1000      9806   15.00   85.00    0.00  100.00     0  custom_mutex

And this is a report for a test that uses std::mutex:

$ pidstat 1 -p $(pidof std_mutex)
Linux 3.10.0-229.el7.x86_64 (sk71.net.billing.ru)       05/16/2017      _x86_64_        (2 CPU)

09:46:45 AM   UID       PID    %usr %system  %guest    %CPU   CPU  Command
09:46:46 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex
09:46:47 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex
09:46:48 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex
09:46:49 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex
09:46:50 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex
09:46:51 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex
09:46:52 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex
09:46:53 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex

update

I believe your mistake is in parameters for syscall. FUTEX_WAKE on my Linux is equal to 1. But take a look at:

inline int futex_wait(void *addr, int block_if_value_is) {
    return syscall(SYS_futex, addr, block_if_value_is, nullptr, nullptr, 0);
}

It passes block_if_value_is to SYS_futex as a parameter for int op. However the value of block_if_value_is in your program is equal to LOCKED and LOCKED is 1 (it means that it is equal to FUTEX_WAKE):

static constexpr int UNLOCKED = 0;
static constexpr int LOCKED = 1;

futex_wait(&m_state, LOCKED);

So you do not wait. You actually ask the kernel to wake up 0 (nullptr) processes. That is why you instead of waiting in kernel on your futex  returns:

return syscall(SYS_futex, addr, block_if_value_is, nullptr, nullptr, 0);


Total beginner Tic Tac Toe game in Python

Here are my notes:

your printBoard function has code repetition, you can see there is a pattern 0 1 2, 3 4 5, 6 7 8, so  you can do a for loop, example:

for i in range(3):
  print (board[i * 3] + '|' + board[i * 3 + 1] + '|' + board[i * 3 + 2])

your legalMoves list is not required, because it's just numbers from 1 to 9, so you can check against that example: if n >= 1 and n <= 9: #accepted

"move = int(input('Pick a number 1-9:'))", you need to check for the input first if it can be converted to int or not to prevent the user from breaking your program if non int string value was typed, and to do that you can store the input in a string then check against it to be an int or not example:

def isInt(strInt):
  for c in strInt:
    if c not in "0123456789": return False
  return True

n = input()
if isInt(n): move = int(n)

and your checks inside the while loop can be shortened to using for loop instead, you can see a pattern in those cells positions, so if you want to check horizontally, yoou need to do, example:

for i in range(3):
  if board[i * 3] == board[i * 3 + 1] == board[i * 3 + 2] and board[i * 3] != "-":
    # do something

and vertically

for i in range(3):
  if board[i] == board[i + 3] == board[i + 6] and board[i] != "-":
    # do something

and diagonally

  if (board[0] == board[4] == board[8] or board[2] == board[4] == board[6]) and board[4] != "-":

without checking for "X" or "O", you just need to check for "-"

you need also to prevent the user from overwriting an already filled cell, example

if board[move - 1] != "-":
  print("Pls choose an empty cell")

you need also to check for tie, because not all time you get a winner example if your main loop I mean the one for each user correct move which are 9 moves, if it reaches the end and there is no winner then it's a tie, and you should let the user know.

That's it, you can improve your code now, I hope you like my feedBack, also I have written a full solution, you can find it in your question in Stack Overflow, and if you have any question, I will be happy to answer.


SPOJ Class Leader using circular linked list

Don't use using namespace std

Prefer '\n' to std::endl

The reason is that std::endl flushes the stream. This can lead to performance issues when called frequently (Not your primary performance issue but still just good practice.) Furthermore many people consider good code to be explicit and would prefer a call to std::flush when you want to flush the stream.

Avoid Globals

OOP provides encapsulation so that variables that should not be accessible from outside a given scope can't be. Not only is it harder for you to make mistakes altering variables on a large scale but it also makes anyone touching your code unable to do it too.

Memory Leaks

You have many calls to new but do not have a single call to delete. Your program leaks every bit of memory it allocates. The two main problem areas are both here:

int func(node* p, int k) {
    if (p->next == p)return p->data;
    int f = k;
    node* q = new node();
    while (f--) {
        q = p;
        p = p->next;
    }
    q->next = p->next;
    func(q, k);
}

first you create a new node pointed to by q and then immediately assign q to p therefor making it impossible to ever delete the memory you just allocated.

Then you assign q->next = p->next; effectively unlinking p from the rest of the list. Once the function goes out of scope p is lost and the memory pointed to by it can never be freed.

Prefer nullptr to NULL

NULL is a C Macro that is may or may not defined as 0 and can cause ambiguity. nullptr on the otherhand is a keyword.

while (r->next != NULL)

And don't compare values to NULL (or nullptr) - pointers convert implicitly to Booleans. Prefer instead to represent the conditional as:

while (r->next)

Prefer initialization over assignment

struct node {
    int data;
    node* next;
};

Your node is not really complete. Imagine I do this:

node myNode;
std::cout << myNode.data;

What will print? We don't know. It's undefined behavior.

Even if you provided a default constructor (which is overkill and unnecessary) and assigned the variables default values there it would be suboptimal because you will essentially giving your variables garbage values only to give them the meaningful ones momentarily later.

struct node {
    int data{ 0 };
    node* next{ nullptr };
}

Here the node is constructed properly and without the potential for UB. If you don't want to assign data the default value of 0 you could create a constructor that takes an int as a parameter and initializes data to the value passed. Something like:

struct node {
    int data;
    node* next{ nullptr };
    node(int data) : data{ data } {};
}

Naming

Use better names. You will thank yourself months from now when rereading old code. Single letter variables are hard to keep track of and require you to memorize your code when more explicit naming makes that unnecessary. The exception to that are the parameters of the problem you are being given to solve. Well named functions also better help understand what is being done as well.

Take for instance your createLL function. This function doesn't create a linked list. It adds a single node to the end of the list. add_node or push_back would be more appropriate names.

And func() is the most generic possible name for a function you can come up with. I don't expect to see that name outside of pseudocode.

Prefer prefix over postfix

Your code is the perfect example of when to use both of these. In your for loop you use postfix which tells me you are incrementing with postfix as a matter of course which is a bad habit to get into. Postfix creates a copy, then increments the original and then returns the copy. This can be useful such as in you while loops. If you used prefix there you would end up with an off-by-one error. The constant copying that is done in your while loops is trivial with integral values like you use but if it was a non-trivial (perhaps a user defined class) value a simple solution would be to decrement your variable with prefix within the loop itself.

Omit return 0

The compiler will return from the end of main() without you needed to tell it to. Not only is it unnecessary but by doing so you signal to readers of your code that you may return error codes elsewhere in the program (which you don't).

int t;
cin >> t;

This is an input that you didn't provide in your description of the problem. You dealt with it correctly programmatically but it is an important requirement and thus should have been in your description. It is important to note that this is considered a reasonable exception to initializing variables. You define your variable and immediately assign it via input from the user.

int n, m, o;

Don't declare more than one variable per line. It can be misleading (with pointer assignment and initialization in particular) and can make it hard to track.

for (int i = 1; i<n; i++) {         //created linked list with values index+1
    createLL(i + 1);
}

If you start i at 2 the you don't need to add 1 when passing it as a parameter. Note the change from < to <= in the comparison.

for (int i = 2; i <= n; ++i) {
    createLL(i);
}

while (r->next != NULL) {           //traverse to the end
    r = r->next;
}
r->next = head;                     //created a circular linked list

This whole loop is unnecessary. You already know where the last element in your list is.

tail->next = head;

Put all of that together and it looks something like this:

#include <iostream>

struct node {
    int data{ 0 };
    node* next{ nullptr };
};

void add_node(node*& tail, int n) {
    node* temp = new node();
    temp->data = n;
    tail->next = temp;
    tail = temp;
}

int josephus(node*& start_node, int index_shift) {
    if (start_node->next == start_node) {
        return start_node->data;
    }

    int shift_count = index_shift;
    node* temp = start_node;

    while (shift_count--) {
        start_node = temp;
        temp = temp->next;
    }

    start_node->next = temp->next;
    delete temp;
    return josephus(start_node, index_shift);
}

int main() {
    int num_tests; // formerly T
    std::cin >> num_tests;

    node* head = new node();

    while (num_tests--) {
        int num_nodes; // formerly n
        int start_index; //formerly m
        int shift_by; //formerly o
        std::cin >> num_nodes >> start_index >> shift_by;

        if (num_nodes == 1) {
            std::cout << num_nodes << '\n';
            continue;
        }

        head->data = 1;
        node* tail = head;

        for (int i = 2; i <= num_nodes; ++i) {
            add_node(tail, i);
        }

        tail->next = head;

        while (head->data != start_index) {
            head = head->next;
        }

        std::cout << josephus(head, shift_by) << '\n';
    }
    delete head; // just noticed I never deleted this. (Sure the program
    // ends here but you always want to clean up your memory.)
}

Note the pointers passed as reference so that I didn't need a global variable. More explicit names like start_node, num_students, josephus, and temp. I'm not implying my names are the best but they are clearer and more explicit like add_node. Note the calls to delete when necessary.

But this isn't really the best solution for several reasons:

Avoid naked new/delete.

You could use smart pointers but they can be a bit unwieldy when being repointed frequently. You should use them anyway when you can but we are going to change our solution.
The data structure is poorly made.

I understand that C++ doesn't have a circular list and that a circular list seemed especially appealing for this problem but a.) implementing a full scale data structure is a much more complicated task than this b.) there are simpler workarounds. Your circular list is just a bunch of exposed nodes that you manually link together at the end. A good data structure design would not expose the nodes directly and would use templates to provide for reusability.
You should prefer standard data structures.

Years of man hours have gone into them. If you want to remake some for a learning exercise: Great! But it doesn't belong with your Josephus solution.
We are still getting TLE.

The way to use a standard std::list as a circular list would be with the use of iterators. I have the following example:

#include <iostream>
#include <iterator>
#include <list>

int main() {
    int num_tests;
    std::cin >> num_tests;

    while (num_tests--)
    {
        int num_students; // formerly n
        int start_index; //formerly m
        int steps; //formerly o
        std::cin >> num_students >> start_index >> steps;

        std::list<int> students;

        for (auto i = 1; i <= num_students; ++i)
        {
            students.push_back(i);
        }

        std::list<int>::iterator it = students.begin();
        for (auto i = 1; i < start_index; ++i)
        {
            ++it;
            if (it == students.end())
            {
                it = students.begin();
            }
        }

        auto countdown = num_students - 1;
        while (countdown--)
        {
            for (auto i = 0; i < steps; ++i)
            {
                ++it;
                if (it == students.end())
                {
                    it = students.begin();
                }
            }

            if (it != students.begin())
            {
                it = students.erase(it);
                --it;
            }
            else
            {
                students.erase(it);
                it = students.end();
                --it;
            }
        }

        std::cout << *it << '\n';
    }
}

In this example you simply use an iterator to traverse the list much like you did with your nodes. However here we have a standard memory-safe container. no leaks. No manual memory management. You have to take some care to ensure you are incrementing and wrapping correctly and that you never dereference your std::list::end() but this is much safer. (And when you break things it will shout at you and you can get to debugging faster.) You may notice that I did not implement this with recursion. Feel free to reimplement it that way as a learning experience.

(Also be aware that both of these solutions really should factor out the entire problem into one higher level function. Encapsulation is important in C++ and a decluttered main() is highly desirable.)

This still isn't the best solution. Mostly because at the end of the day programming challenges like this are not generally going to be successfully completed by brute force. This solution still gets TLE.

as @vnp noted this is the Josephus Problem. As such it can actually be expressed mathematically. The following expression was found on Geeks for Geeks:

#include <iostream>

int josephus(int num_students, int steps)
{
    if (num_students == 1)
    {
        return 1;
    }
    else
    {
        /* The position returned by josephus(n - 1, k) is adjusted because the
        recursive call josephus(n - 1, k) considers the original position
        k % n + 1 as position 1 */
        return (josephus(num_students - 1, steps) + steps - 1) % num_students + 1;
    }
}

int main() {
    int num_tests;
    std::cin >> num_tests;

    while (num_tests--)
    {
        int num_students; // formerly n
        int start_index; //formerly m
        int steps; //formerly o
        std::cin >> num_students >> start_index >> steps;

        auto answer = josephus(num_students, steps);

        answer = (answer + start_index) % num_students;

        if (answer != 0) {
            std::cout << answer << '\n';
        }
        else
        {
            std::cout << num_students << '\n';
        }
    }
}

The solution works as the size decreases recursively and k % n + 1 tracks the position and allows for skipping over otherwise removed candidates. Then the start_index is applied to shift the survivor respectively.

Now is the point I get to disappoint everyone! This still returns TLE. I suspect the excessive calls to % which are expensive to process for the performance issue. I have tried viewing the more complicated mathematical expression of the solution but it is over my head. It is available in the Wikipedia page I linked. I hate to be anti-climactic so if anyone else has the solution I encourage you to post it in an answer so I can upvote it.


Dealing with resource closure when rethrowing an exception

It seems that your code would benefit dramatically from use of RAII. To illustrate, let's assume the existence of an HTTPConnection class that opens an appropriate connection in its constructor and closes it at destruction. The code would look more like the following:

const string HTTPopotamus::GET(void) {
    HTTPConnection conn(/*connection parameters here*/);

    conn.sendRequest(/*request parameters here*/);
    conn.waitForResponse(HTTP_REQUEST_TIMEOUT);

    return this->readData(hRequest);
}

This approach is more elegant and clear and explains itself with no need for comments. Any exception thrown, such as exceptions that represent a failed connection or a timeout event would be propagated to the caller while the HTTPConnection object would still be destroyed properly.


Reverse a sentence quickly without pointers

The shortest code I can produce is:

private static string Reverse(string input)
{
    return String.Join(" ", input.Split(' ').Reverse());
}

But the following alternative should be much faster:

private static string Reverse(string input)
{
    // Create a new StringBuilder and allocate the same space as in the input string:
    StringBuilder builder = new StringBuilder(input.Length);

    // Declare 2 index variables:
    int index;
    int lastIndex = input.Length;

    // Iterate from the end to the start of the string
    // while the ' ' char is found:
    while ((index = input.LastIndexOf(' ', lastIndex - 1)) != -1)
    {
        builder.Append(input, index + 1, lastIndex - index - 1).Append(' ');
        lastIndex = index;
    }
    // Last iteration (for the first token in the input string):
    if (lastIndex != index)
    {
        builder.Append(input, 0, lastIndex);
    }
    return builder.ToString();
}

The main idea is to iterate from the end of the input string to the beginning, looking for the space char.
Also it makes sense to rely on the .NET built-in methods as much as possible.
Therefore I used:

The StringBuilder class for accumulation of a result.
The String.LastIndexOf method for searching for the space char.

The reasons to use the StringBuilder:

It is very effecient.
It contains the Append(string value, int startIndex, int count) method which copies specified substring to the inner buffer directly (without creating an intermediate substring from the input string).

EDIT.
A new approach not using the StringBuilder class and with the same main idea:

private static string Reverse(string inputString)
{
    // Get array of chars from the inputString,
    // and allocate the same space in the output array:
    char[] input = inputString.ToCharArray();
    char[] output = new char[input.Length];

    // Declare 3 index variables:
    int index;
    int lastIndex = input.Length;
    int outputIndex = 0;

    // Iterate from the end to the start of the string
    // while the ' ' char is found:
    while ((index = inputString.LastIndexOf(' ', lastIndex - 1)) != -1)
    {
        Array.Copy(input, index + 1, output, outputIndex, lastIndex - index - 1);
        outputIndex += lastIndex - index;
        output[outputIndex - 1] = ' ';
        lastIndex = index;
    }
    // Last iteration (for the first token in the input string):
    if (lastIndex != index)
    {
        Array.Copy(input, 0, output, outputIndex, lastIndex);
    }
    return new string(output);
}

It is slightly less efficient than previous approach, but it is still very fast.


Assuming that LOG_ENTRY.event can have arbitrary string content, your code is vulnerable to an SQL injection attack.  You must escape strings in queries, and not copy them blindly into the query.

The 256-byte limit for the query buffer seems artificially limiting.  I would expect your library to do whatever it takes to compose and execute the right SQL query without bungling it with an undersized buffer.  One way to do that without malloc() or variable-length arrays is to define the struct to match the table definition.

typedef struct {
    int severity;
    char event[129]; /* 128 characters plus NUL. Latin1 means 1 byte per character */
    char source[33];
    struct tm tm_info;
} LogEntry;

The buffer would need to be large enough to accommodate the fixed text and the substituted strings, keeping in mind that mysql_real_escape_string() can double the number of bytes.  (I would use sizeof(FIXED_QUERY) + 2 * sizeof(LogEntry) + 3 * sizeof(int) + 20 as a generous estimate of the needed buffer size.)  Out of paranoia for unterminated strings, I'd use placeholders like "%.128s" for snprintf().

ltdb is such a cryptic function name.  log_to_database() would be much better.

Requiring the program to be recompiled to change the password is not proper.  The caller should have to make a call to initialize the library with the database connection parameters.  Another approach, which is still sloppy but slightly better, is for your library to read the connection parameters from a configuration file.


Creating a PowerPoint in vba by calling "slide" subroutines

Public ppApp As PowerPoint.Application
Public ppPres As PowerPoint.Presentation
Public ppSlide As PowerPoint.Slide

Assuming we're looking at a standard module, this is a red flag. Anyone, anywhere, can go and do this:

Set ppPres = Nothing

Or this:

Set ppApp = New PowerPoint.Application

...or otherwise shatter other procedures' assumptions. Variables' scope should be as limited as possible. These 3 public object variables are going to bite you, one day or another.

The ppApp application is never exited, which means more memory is consumed by the system after your macro runs, than before it did. And I wouldn't be surprised that the more you run it, the more memory it consumes. Why is that?

sub CreatePres()
Dim ppTextbox As PowerPoint.Shape
Dim slidesCount As Long
Set ppApp = New PowerPoint.Application

The procedure is doing much more than create pres; it creates a whole PowerPoint application instance, a new one every time it runs.

  About object instantiation

  Whoever creates an object, is responsible for that object's lifetime. When the object is no longer needed, the scope that created the object is also the scope that cleans it up.

Surely that Application class has a Quit method, or something similar - that method should be called before the procedure exits, in all exit points (i.e. even if an error occurs at any point).

My procedure would probably look something like this:

Option Explicit

Public Sub CreatePresentation()
    With New PowerPoint.Application
        Dim pres As PowerPoint.Presentation
        Set pres = .Presentations.Add
        CreateSlides pres
        SavePresentation pres
        pres.Close
        .Quit
    End With
End Sub

The procedure creates a presentation. An implementation detail of that, is that in order to create a presentation it first creates a PowerPoint app, but the outside world couldn't care less. Nor does it care about slides, or for a file name for the presentation (I suspect you're leaving PP open so that the user can tweak as needed and save when they see fit?) - these are separate concerns, there's a separate procedure at a lower abstraction level for that.

Kudos for beginning to split your code into separate procedures! At first it's normal not to be sure where or why split, but the more you familiarise yourself with the concept of abstraction, the easier it will become.

If you can look at a chunk of code and say "this chunk does XYZ", then chances are that it actually belongs in some DoXYZ procedure. Extracting the details of how slide2 is generated was a great first step.. but what about slide1? The part that deals with slide1 is mixing abstraction levels within the procedure: why do we need to know all the details about slide1 but slide2 gets its own dedicated procedure? The number of lines of code involved has nothing to do with the decision, only what's going on does.

Keep up the good work!

Rubberduck would have picked up a few issues:

Option Explicit is not specified. That's dangerous, a mere typo and you have a bug, one that can be pretty tricky to locate.
createPres is implicitly Public. Better make that explicit.
slide2 is implicitly Public, but that one has no business being public. Should be Private
Worksheets implicitly refers to the active workbook. May or may not be intended.
Cells implicitly refers to the active worksheet. Here if you qualify the Range call with a worksheet object other than ActiveSheet, you would get a run-time error because of that.
Call statement is obsolete and can safely be omitted (along with the parentheses around the arguments).
Consider renaming parameter i. Naming is hard, but meaningful names are important. slidePosition would be a better name IMO... But does a procedure named slide2 need to know about where to insert the slide?
Consider renaming procedure slide2 so that the name starts with a verb. Procedures do something: describe it.

Beyond that, I'd say use PascalCase for procedure names and keep camelCase for local variables [and parameters], and avoid Select and Activate where possible (use the object model instead).


Simple C++ program that calculates the measures of a sphere

I see a number of things that may help you improve your code.

Prefer portable code

This code could be entirely portable if the #include "stdafx.h" were omitted.  It's Windows specific and doesn't really help here, even on Windows.

Understand header include paths

There is a subtle difference between #include "iostream" and #include <iostream>.  Although it's implementation defined, most compiler implementations is that the quotation mark form searches locally first (e.g. the current directory) and then searches system include directories if that fails.  The angle bracket form usually searches in system include directories.  See https://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename for more.

Fix your formatting

The code is all jammed up on the left margin with no indenting.  I don't know if that's how you wrote it or if it's a cut-and-paste error when posting the question, but it really makes the program hard to read.  It makes no difference to the compiler, but you should strive for a good consistent style that includes visual clues for the human reader of your code.

Fix the bug

The calcSphereMesures routine is returning the address of a variable that's local to that routine.  That's a bug.  If you need to return multiple values, either pass in a pointer to an appropriate structure to be filled in by the routine or allocate one using new and returning that.  I'd prefer the former, because it makes ownership of the structure a little cleaner (that is, the caller must both allocate and free the structure).  Note that although I'm using the word structure, here, that isn't necessarily a struct -- it could just as well be an array or some other data structure.

Consider using an object

The area, circumference, etc., could all be attributes of a Sphere class.  This would have the advantage that one could write sphere.diameter() instead of results[3] for example.

Use name spaces

When you #include <cmath>, it brings those functions into the std:: namespace and may also put the symbols into the global namespace.  You're counting on the latter which is not guaranteed by the standard.  You can fix that by using std::pow instead of just pow.

Use a better value of \$\pi\$

There's little point in asking for the precision of a double if you're going to approximate \$\pi\$ as 3.1416.

Understand the use of function declarations

A function declaration is required before the use of the function.  Your separate declaration and implementation of the calcSphereMesures() function would make sense if the declaration were in its own header file, but that's not the case here.  For that reason, I'd suggest eliminating the declaration -- keeping them synchronized is just another task that you can eliminate.

Check your spelling

The word "measure" is consistently misspelled within the code.  It would be nice to fix that.


Just a couple points (also well done properly qualifying namespaces, a rare thing to see).

#pragma once is non-standard. Meaning it will probably work but is not guaranteed to. Bjarne himself recommends against using it.
Not following your multiple private and public approach. Usually you have a section for each without repeating the keywords.
It makes more sense to order your interface from public to private as people using it don't want to look at the internals of your class, they want to know what methods they can use.
You don't do anything in either your constructor or your destructor. In this case it makes sense to let the compiler take care of them.
Avoid declaring more than one variable per line