Function for calculating Archimedean density functions

Some suggestions:

split code more, line by line, so it is easier to profile and see bottlenecks
use profvis
use %>% less often if that part of code is called frequently, it has some overhead
separate function definitions

This should run a little bit faster: (15s vs 27s on your example)

P_d <- function(x, tau, d){
  alpha <- 1/tau
  l <- sapply(1:d, function(k){
    p1 <- Stirling2(n = d, k = k)
    p1 <- as.numeric(p1)
    p1 * gamma(k - alpha) / gamma(1 - alpha) * x^(k-1)
  })
  sum(l)
}

joe_density <- function(x, tau){
  d <- length(x)
  h <- prod((1 - (1 - x)^tau))

  v1 <- tau^(d-1)
  v2 <- prod((1 - x)^(tau - 1))
  v3 <- (1 - h)^(1 - 1/tau)
  v4 <- P_d( h/(1-h), tau, d)

  p1 <- mpfr(v1, 16) # slow
  p1 * v2 / v3 * v4 # slow
}

The slowest part is mpfr & the last line, because each value is converted to mpfr.
Maybe you can deal with precision loss in some kind of different way?


Constructing an odd-even mergesort sorting network

In general your code is quite hard to comprehend due to the bracing style and the single letter variable names. A bit more spaces and more meaningful names would do quite a bit for readability (I've kept your 2-indent spacing) and also remove the need for most of the comments:

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

int log2ceil(int value)
{
  int i;
  int cmp = 1;
  for (i = 0; cmp < value; i++)
  {
    cmp <<= 1;
  }
  return i;
}

void sort(int length)
{
  int groups = log2ceil(length);
  for (int group = 0; group < groups; group++)
  {
    int blocks = 1 << (groups - group - 1);
    for (int block = 0; block < blocks; block++)
    {
      for (int stage = 0; stage <= group; stage++)
      {
        int distance = 1 << (group - stage);
        int startPoint = (stage == 0) ? 0 : distance;
        for (int j = startPoint; j + distance < (2 << group); j += 2 * distance)
        {
          for (int i = 0; i < distance; i++)            // shift startpoints
          {
            int x = (block * (length / blocks)) + j + i;
            int y = x + distance;
            printf("%2i cmp %2i\n", x, y);
          }
        }
      }
    }
  }
}

int main(char* argv, int args)
{
  const int COUNT = 8;
  sort(COUNT);
}


Get The Base Name of an Elixir Template File

Since you seem to know what the file extension is, you can use Path.basename/2.

"foo.html.eex"
  |> Path.basename(".eex")
  |> IO.puts

If you don’t know the file extension, you can use Path.extname/1 in conjunction.

filename = "foo.html.eex"
filename
  |> Path.basename(Path.extname(filename))
  |> IO.puts


Using goto is not a good practice!!
Instead of using goto, use a do-while or a while loop. You want to do something as long as the answer to "Do you want to continue" is "Yes". This is perfect for a do-while loop.
You should also avoid using goto overagain and instead use a for-loop to iterate through the array. It could also be solved with recursion. Use anything you want except the goto statement!

Make your code self-documenting. Your "explanation" of your code in the beginning of your question confuses me more than helps me.
Self-document your code by using proper variable names. s can be called input instead, and i and b can be called something that explains what they are doing. Right now, I can't exactly understand what they are supposed to do.

Your last block of Console.WriteLine("Do you want to continue?");, including the if-else that comes afterwards should be indented one step further.

If you don't have anything to do in else, just skip that part. if ... { ... } is enough, you don't need else. You'd better remove this, or else...

Use English names for variables, especially when characters outside the range of A-Z, a-z, 0-9, _ are included (such as "ä"). The Swedish word "avgränsare" translates to "delimiter" in English.


Data structure and movement for tilt maze (part 2)

I've a couple of problems with your code.

Creating both a right and top list splits up the data.
Instead you can merge flags into ints to reduce the amount of variables.

The way this can work is if we can 'move up' from that position we add 1.
If we can 'move right' we add 2.
This means if we can't move up or right, we will input 0.
Or if we can do both we'll input 3.

You can then expand on this to add 'move down' and 'move left'.
Where you'd add 4 if it's 'move down', and 8 if it's 'move left'.
This is as we should be able to move up, down, left and right from a single square.
Which would have the value \$1 + 2 + 4 + 8 = 15\$. Or if we couldn't 'move right' we'd have 13.
Your code is WET. As you write pretty much the same thing four times.
Instead I'd use a builder function to remove this duplicate logic.
This is as you can set the special changes in the builder function,
and mutate the data in the returned function.

Take:

def _move(band, x_inc, y_inc):
    def inner(x, y):
        maze = self.maze
        while maze[y][x] & band:
            x += x_inc
            y += y_inc
        return x, y
    return inner

move_right = _move(2, 1, 0)

I'd also like to point out that your variables are wrong.
Your x is actually the index on the y-axis.
This is as your board is in a y-major layout.
But you should fix this as it's outright confusing.
You're relying on a global variable.
This is bad. What if I make a global variable that overwrites yours?
Or if I want to have two boards in memory at the same time?

Instead you should create a class.
Nothing fancy, just an __init__ with top and right, or with my changes maze.
And your four functions.
You don't adhere to PEP8.
Sure, some people use a different style guide, but your code is not consistent.
So you should follow PEP8, like a hobgoblin, to build consistency.
This is as you:

Have both spaces and no spaces around your -=.
Have both a space and no space between your function name an it's parentheses.
Don't have consistent tabbing in your list top.

Sure it's three places of inconsistency, but your code is WET.
And definitely shouldn't have these inconsistencies if you copy and pasted the WET parts.
I'd like to also point out that your variable names start_x and start_y should instead be x and y.
As you're changing them, and so by the end of the function, they are no longer the starting x or y.

Additionally, to simplify the creation of the maze, so you only need to set the flags for if you can move up or right.
You can make a small private helper function.
This just adds if you can move down or left from the cell, without having to check the surroundings.
Just as I said in (1) above.

And so you can end with something like:

class Maze:
    def __init__(self, maze, position=(0, 0)):
        self.maze = self._normalize_maze(maze)
        self.position = position

    @staticmethod
    def _normalize_maze(maze):
        maze = maze[:]
        height = len(maze)
        width = len(maze[0])
        for y in range(height):
            for x in range(width):
                if not (0 <= maze[y][x] <= 3):
                    raise ValueError('Cells in array must be [0,3].')
                if y > 0:
                    maze[y-1][x] |= (maze[y][x] & 1) << 2
                if x > 0:
                    maze[y][x] |= (maze[y][x-1] & 2) << 2
        return maze

    def _move(band, x_inc, y_inc):
        def inner(self):
            maze = self.maze
            x, y = self.position
            while maze[y][x] & band:
                x += x_inc
                y += y_inc
            self.position = x, y
        return inner

    move_right = _move(2, 1, 0)
    move_left  = _move(8, -1, 0)
    move_up    = _move(1, 0, -1)
    move_down  = _move(4, 0, 1)

if __name__ == "__main__":
    maze = Maze([
        [2, 0, 2, 0],
        [0, 1, 2, 1],
        [1, 3, 1, 1],
        [3, 1, 2, 1],
        [1, 1, 3, 0],
    ])
    print(maze.position) # output, (0, 0)
    maze.move_right()
    print(maze.position) # output, (1, 0)
    maze.move_down()
    print(maze.position) # output, (1, 4)
    maze.move_left()
    print(maze.position) # output, (1, 4)
    maze.move_up()
    print(maze.position) # output, (1, 0)


How did you try implementing your regex?

You can take advantage of panda's str methods to vectorize your regex instead of mapping the function over each element of the dataframe.

df = pd.DataFrame(index=np.arange(900000))
df["address"] = "660 1st Ave   New York, NY 10016"

With a dataframe with 900000 addresses,

df.address.str.extract("regex_pattern", expand=True)

will extract your regex from each row of the 'address' column in your dataframe.
Something like,

df[["street", "city", "state", "zip"]] = df.address.str.extract('(.+)[ ]{3}(.+)\,[ ]([a-zA-z]{2})[ ]([0-9]{5})',expand=True)

runs over the entire dataframe in:

  %timeit
  7.2 s ± 81.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Basically, you should look for any opportunity to take advantage of panda's vectorized optimizations (string operations, datetime operations, masks, etc.) as described in the docs: https://pandas.pydata.org/pandas-docs/stable/basics.html#vectorized-string-methods

If at any point you are trying to apply a function to each element in the dataframe/series, stop and check to see if there is already a built-in method that implements what you want.


The way I see it your requirements can be summarized as:

Have a central repository of images.
Load Images from a some data source.
Save Persist Images.
Give a cell its appropriate image based on an identifier.

The main issue I see is that the cells are tightly coupled to the ImageCache object, it might be better to have some sort of ViewModel or controller layer sit between your image cache and cells. This model or controller would contain the information needed to retrieve an image for image cache along with the information needed to display the image to the cell. This would make your code much more testable and decouple your UITableViewCells from the the your singleton cache.

On whether a singleton is necessary-- I am going to take a guess that this is all for one ViewController. Why not just initialize the ImageCache object in that ViewController? If this is truly used across many ViewControllers than I could maybe be convinced to get behind the use of a singleton.

On the WeakReference array... that is valid and actually relatively advanced pattern in Swift, I'm not sure that you really need it here though although its a little hard to tell without more context. It appears LoadableImage is some sort of object that encapsulates a callback that displays the image or an indicator on the UI... in which case yes you would need a weak reference, although I am unsure as to why you even need to store the LoadableImages in an array to begin with. I think that you could abstract away the array if you refactored to a more traditional Callback oriented approach.

In a callback approach the TableViewCells would merely request the appropriate image and show the loading indicator until the callback was called. If you really needed to cache the images, you could do so in an array within the cache.

I wish that your method names were more descriptive in Swift style... for example determineImage(for photoId:String). That's part of the expressiveness and readability of the language. Another example the function received doesn't really express what it's use is I think that its some sort of callback that will display an image once it has been loaded and display that image to a specific LoadableImage, but this needs to be more clear.

I think to give you more advice you need to post more code, along with a description of what the requirements are. For example: How many ViewControllers are using the Cache? Do you need to store images across the lifecycle of multiple ViewControllers? How are you planning on linking the ImageIdentifiers to the TableViewCells.

If you post a few more details, I will follow up with a few code samples, but as it is I don't see how I can give you any tangible direction without knowing a little bit more.


Implementing AES alone is very risky, mainly because it is very easy to make a mistake. I strongly recommend you use phpseclib for this.

Also you should not use ECB mode unless you are encrypting only 1 block.


There's no point in an abstract class with nothing in it. I assume a product has name, description, price, a SKU (product id) at least.

  Line items can be a product or membership type.

implies that a membership is not a product yet I see

public class BookClubMembership : Product

Looks like you'll have every rule iterate the order items. I'd rather see the PurchaseOrderProcessor iterate the items; and only once.

public class PurchaseOrderProcessor {
   public IList<IPurchaseOrderRule> Rules { get; }

The Rules list should not be public. Hide state and expose functionality. If you need to add rules for example, make an Add method.

  Is there a better way for me to program these rules

The Product can have a "type" - with all the types defined in an enum. This eliminates the need for subclasses.

What is a 'line item'? If it means something I'd expect a class. Use your domain language accurately.

  ... I will need to operate on the order and the item as well.

Show me the codez!

_customerActivationService.ActivateBookMembership(order.CustomerId,

Is it a valid assumption that the membership is for the person making the purchase?


Some in-place improvements you could make:

PEP-8 recommends four space indentation, not two;
collections.defaultdict would allow you to scan the list of words only once, without having to explicitly initialise to 0 for each word. Even easier, there's a collections.Counter, too;
Rather than iterate over all of the characters you want to replace, you could use re.sub with a regular expression pattern matching those characters (or re.findall for the characters you do want); and
You should generally use the with "context manager" to handle files; see e.g. the tutorial.

More broadly, though, you have one function with three different purposes:

Handling the file;
Cleaning up the text; and
Counting the words.

Splitting these separate concerns up into separate functions would make those functions easier to test, understand and reuse.

With these ideas applied, you could write something like:

from collections import Counter
import re

def get_text(filename):
    """Read and return the content of a specified file."""
    with open(filename, "rU") as handle:
         return handle.read()

def clean_text(text):
    """Lowercase text and extract words."""
    return re.findall("[a-z]+", text.lower())

def get_word_frequencies(filename):
    text = get_text(filename)
    words = clean_text(text)
    return Counter(words)


Send Response To Browser without DB save confirmation

The big question to ask is: what happens when it doesn’t work? (For whatever reason)

In your case, the user will probably think it worked, only to find out later that it didn’t and will most likely think “stupid app, I just changed this”. You may be okay with it. I wouldn’t. The people paying me probably wouldn’t either.

And what a blessed career you’ve had as a developer if you believe a DB operation failing is such a very rare occurrence. Specially when deployed to production.


Interactive command-line binary to decimal converter

TL;DR:

It's  unlikely to beat Python's own implementation of this which is basically as simple as

decimal = int(binary, base=2)

in terms of convenience, clearity, and performance.
This will throw a ValueErrorin case the number cannot be converted to a binary, e.g. if the user enters something like 101010103.

Welcome to the world of Python, where "batteries included" is a real thing!

If you, for whatever reason, do not want to use the most convenient Python has to offer, it is still possible to write a Pythonic alternative:

decimal = sum(int(digit)* 2**index for index, digit in enumerate(user_input[::-1]))

This little piece of code is called generator expression (relevant PEP, good Stack Overflow post) and is basically the equivalent of:

decimal = 0
for exponent, digit in enumerate(user_input[::-1]):
    decimal += digit * 2**exponent

which is close(r) to what you did in your original implementation. Apart from that you don't have to care about the actual length of the input.

Detailed review

Of course there is more to say about your code than this, especially since you're asking about other aspects as well. So let's look at your code.

Style

Python has an official Style Guide called PEP8 (batteries included, you remember?). The main takeaways that are follow by the better part  of Python programmers are

Use snake_case for variable and function names and CamelCase/PascalCase for class names.
Write function documentation (often just docstrings) """Enclosed in triple quotes""".

I will demonstrate how to apply these principles to your code in a moment.
There are other useful recommendations which help you to keep the appearance of your code clean and readable, so it's definitely worth a read.

Naming

Apart from the stylistic point in the names, there is always the name itself. It's good that you decided to use functions and most of their names are totally fine. The odd one out is clearly checkUI. If you were just left with this name, I highly doubt that you would be able to tell what it does. Since it basically handles most of the interaction with the user, as well as validating and converting the numbers, the obvious (though maybe not ideal) name would be simply main().

The script itself

After we have gone through some high-level aspects of the code, let's dive into the details. I will go through the code function by function.

binaryToDecimal - soon to be binary_to_decimal

As I already said above, the core functionality of the function can basically be replaced by a single line of Python code. And that's likely all the function should do. Apart from the main function, all of them should basically have a single responsibility. At the moment there are three

converting the number
printing the converted number
starting a new round of user input

The 2nd one is easy to fix: simple move the call to print from binary_to_decimal to main. The 3rd one is really, really (and I mean really really) bad design. The conversion function should absolutely not be tasked with starting a new round of user input. To make it worse, this will also lead to recursive calls of your functions, that will eventually end with a RuntimeError when your program exceeds the maximum recursion depth allowed by the Python interpreter. So drop that and never do it again!

getUserInput - soon to be get_user_input

The function is basically fine and a prime example of single responsibility. Maybe it's functionality is even a bit to minimalistic, so you might not actually need it.

checkUI - soon to be main

This is where things get serious. The first and foremost recommendation for this piece of code is similar to the first function we looked at: Get rid of the recursion!. Recursion as such is not a bad thing and valid programming technique in their own right, but not for this purpose!

The idiomatic way to ask for user input repeatedly would be something like

def main():
    """Repeatedly ask for user input and convert its decimal equivalent"""
    while True:
        # read and normalize the user input
        # Note: this might also (better) be done in get_user_input
        user_input = get_user_input().strip().lower()
        if user_input.startswith("q")
            break

        # further validation and conversion
        ...

if __name__ == "__main__":
    main()

The check to stop the program was slightly modified to be a little bit more robust. The way I chose to implement it will also make sure that things like Q, Quit, qsomethingelse, and the like end the program. If that's not what you want, simply replace it with the check you had originally. I also added if __name__ == "__main__": which adds as a kind of safeguard to make sure the "interactive" of your code is only triggered if you use it as script and not try to import it.

Now for the validation and conversion part. With all the other changes in place it will become as simple as

def main():
    """Repeatedly ask for user input and convert its decimal equivalent"""
    while True:
        # read and normalize the user input
        # Note: this might also (better) be done in get_user_input
        user_input = get_user_input().strip().lower()
        if user_input.startswith("q"):
            break

        if len(user_input) > 8:
            print("Binary numbers are a maximum of 8 digits. Please try again")
            continue

        try:
            decimal = binary_to_decimal(user_input)
            print(f"Your binary number converts to {decimal}. ")
        except ValueError:
            print("You did not enter a binary number. (11110000) Please try again.")

Since you chose to limit binary numbers to a maximum length of 8bit (why?), you should likely also include this in the prompt.


What about defining checkDelta?

function checkDelta(dx, dy) {
    if (0 <= x + dx && x + dx < boardSize) {
        if (0 <= y + dy && y + dy < boardSize) {
            // And so on.

This function should make your code really simple.


You could a least separate the variables declarations into constants and variables:

var URL_KEY = 'CurrentURL';

var appName = 'MyApp',
    directoryName = 'MyAppDir';

You could alternatively make a function that returns the constant.

function URL_KEY() { return 'CurrentURL'; }

Replacing a function (like URL_KEY = function() {...}) might be more of a mental barrier for some.


Am I being too redundant in this Django view (or can I reduce the repetition in my code)?

I'd say the best way to be "less redundant" would be to use the already-existing generic views - e.g. DetailView instead of your band_detail.

(I assume you're looking for "the right way to do things" rather than "I'm reinventing the wheel to learn"...)


Optimization for histogram computation algorithm in C

Style

Everything looks quite good to me.

The only thing that I find a bit disturbing is the empty line after comments : it split relevant things apart and it makes the code harder to read.

You could add a bit of documentation explaining what your code does.

Making things more simple

After the for-loop to compute the max value, you perform maxBinValue = maxBinValue == 0 ? 1 : maxBinValue;. As far as I can understand, the point is not to have a division by 0 if max is 0 which corresponds to a situation where histogramBins consist only of 0s which should happen only of totalPixels <= 0 which is quite unlikely.

In any case :

I find the usage of a ternary operator a bit inappropriate here as it might as well be a simple : if (maxBinValue == 0) maxBinValue = 1;. Alternatively, if you were to define functions (or macros) for min and max, this could be : maxBinValue = max(1, maxBinValue).
You could get rid of this is a very very simple way : if you were to assign 1 to maxBinValue in the first place (before the loop), you wouldn't have to worry about it being equal to 0.

Please note that if you were to define a max function/macro, it could be useful inside the loop too as it would become : maxBinValue = max(histogramBins[index],maxBinValue).

Getting rid of magic numbers

This 256 in const int BINS = 256; definitly sounds like a value I've seen in other places. Indeed, it is not just a random setting I can update if I ever want to : it corresponds to the maximum value yuv420sp[index] can take. Its type is unsigned char and the maximum value can be retrieved from limits.h : doing const int BINS = UCHAR_MAX would probably make things easier to understand.


Well, this is technically a way to invalidate your function, but either the built in slicing operator or the reversed function would do this for you in one line:

"flash"[::-1]
>>> "hsalf"

The slice operator takes three parameters, where it starts and ends, but also what step to take as it increments. You could pass in 2 to get every second letter, but you can also pass in a negative value to start at the end and work backwards, hence reversing your string.

The reversed function can take any iterator and return it in reverse as a generator object. This means that it wont strictly print properly, ie. this is what you would get when printing it:

reversed("flash")
>>> <reversed object at 0x0000000002F50898>

But calling join with it will give the result you need:

''.join(reversed("flash"))
>>> "hsalf"

Note that as erip points out this can have trouble with unicode characters in Python 2. In 3 all strings are unicode, but not before then. So reversing non unicode strings actually messes up the byte order, causing erratic behaviour like this:

>>> print("mañana"[::-1])
ana±am

To safely avoid this in 2, make sure to declare it as unicode with a u before the string u"mañana". This will make either method work fine. Alternatively from __future__ import unicode_literals will make all strings unicode like they are in Python 3.

But for your approach I'll still give suggestions. You use a slightly complicated approach. Swapping the values at opposite ends is not entirely obvious so I'd recommend adding comments to elaborate a bit on what the intent is as code is not always readable on its own.

Also you could use Python's multiple assignment to clean up some code. A more simple example is your begin and end could be set at the same time:

    begin, end = 0, len(string) - 1

This doesn't add a lot but can look a little neater. It essentially lets you assign two variables at once. It might be unnecessary, but the same principle can be used to eliminate the need for your temp.

    strlist[end], strlist[begin] = strlist[begin], strlist[end]

This allows you to safely assign both at the same time. The right hand side of the expression is fully evaluated before any assignment, so you wont lose either value.


Empty Constructor

Is a book with no name, author, or title a book? You should not include empty, overloaded constructors unless you know valid defaults. Empty strings are not valid defaults for titles/authors/descriptions.

Data Types

You could use a Time type for opening hours and an Address type for location. This increases code readability, clarity of your api, and type safety...

private Address location;
private Time openingHours;

Method Names

Your library print functions don't print anything, but rather return values! If you have a method printAddress(), I would suspect that the address is printed to the console. Instead, it would make more sense to call this method getAddress().

These are a few quick things I noticed. I'll try to complete this answer later.


After edit original question:

I understand what you are trying to do, and very nice if you can do that.
That's why I'm trying to think together with you for an solution.
The only thing is that I seems not capable enough to reach to an solution.
That's why I'm still posting mine thoughts.

We have some problems(with solutions) that prevents us to check it at creation of the class :

We init with a list, and after constructing the "wrapper" it must be the same list.
The original list may support one or more methods, add may be supported and an addAll or remove maybe not,
Adding/removing a null can be supported or not. So if we want to test add we need a instance of T.
We can make the wrapper abstract and create an abstract T getInstance (); where we give a real instance of T or we disallow a wrapper with an empty List.This solves issue 3 but still not issue 2 when only add is supported we can't remove our T from the list. (reversed is not a problem cause it shall return false if T isn't in the list)
Maybe we could use the Object clone() what gives a shallow copy but that is in this case no problem as the copy is used to test the methods.Still a problem if it throws the CloneNotSupportedException.
We can at construction check if the CloneNotSupportedException is thrown and do the test at runtime => buttons are disabled when user press the button once or buttons are always disabled when cloning isn't possible.

Other bad solution :

Create an enum with all known implementations of List.
Check for instanceOf of the class and get the flags from the enum.

Why possible bad :

ArrayList implements everything.
When I create a subclass of ArrayList and throw at the add an UnsupportedOperationException your check for ArrayList is good and set the flags for an ArrayList.
Still the add operation shall not work.


Finding the 'Minimum' AND of all the possible subsets of a set

There are a few points I'd make about this code.

Choose your language. Right now, you're using a number of C++ headers, so a C compiler can't process your code. Unfortunately, you don't seem to be putting any C++ features to use to make the code more readable, understandable or safe than C code would be.
If you are going to write C++, one starting point is to avoid using built-in array types (as a rule) and printf/scan (nearly always). Unless you have some very specific reason to do otherwise, you're usually better off using std::vector instead of an array, and iostreams instead of printf/scanf.
Some of your variable names would benefit from better names. ha and ans were the two that I found particularly difficult to understand (to the point that I'm still not entirely sure what they mean).
Your code will overflow arithmetic limits on most hardware. In particular:

power[0]=1;
for(int i=1;i<=100000;i++)
{
    power[i]=power[i-1]*2;

...attempts to store 2100000 into a long long. On most typical hardware, long long is limited to 263-1. Although hardware may (probably will) someday expand from its current 64-bit word size to something larger, and long long may expand when it does so, this won't work on most current implementations, and I don't think we can expect to see implementations where it will work any time soon either.

Your only real choices here are to use some type that can store numbers up to 2100000, or else do things some other way so you don't need to store such large numbers. Oh, the final possibility would be to use unsigned long long, and live with the fact that you're storing the value modulo 264-1. For some purposes this works quite nicely (but I'm not sure what you're really using this for, so I'm not sure whether it's adequate for your purposes or not).
The code above also overflows the end of the array. You've defined the array power as:

long long int power[100000];

This means the valid subscripts into this array run from 0 through 99999. Unfortunately, your code loops through 100000, so it tries to write to an element one beyond the end of the array, which gives undefined behavior.

In C and C++, you typically use < for the comparison in a loop like this, so you'd use something like:

static const int size = 100000;

long long int power[size];

// ...

for (int i=0; i<size; i++)
    // write value to power[i]

Indentation. Sometimes indentation gets messed up when you paste here (especially if you have a mixture of tabs and spaces to indent lines), but you definitely want indentation to be more consistent than the code the way I'm seeing it above.


Rethinking it

The obvious change that leaps out at me immediately is to make your list of primes into an object or even class field.  Then you don't need to recreate your primes each time.  You'd create it the first time.  Later you'd just extend it.  An object field would be better programming practice, but a class field would work for this problem.

You might even read in all the input first and then create the primes list once for all of them.  Or just build it to a million before processing the input.  Of course, that would fail if they have some tests where passing means not calculating all million.  Given your current algorithm, it would be easy enough to calculate all the primes from 0 to 1000 beforehand.

Consider holding the primes in a NavigableSet.  Because what you want to know is how many primes are in a range.  So you could replace

            System.out.println(segmentedSieve(l,r)) ;

with

            System.out.println(primes.subSet(l, r).size());

That counts the primes in the set [l, r) if primes is a NavigableSet holding at least all primes less than r.

If you need to count [l, r] or (l, r), you would use the longer version with booleans for inclusiveness.

Specific advice

    static void sieveOfEratosthenes(int l,int r,List<Integer> prime)

You never call this with l as anything but 0.  So you might as well say

    static void sieveOfEratosthenes(int r, List<Integer> prime)

Then you can get rid of the check in the loop:

                if(i>=l)

That's always true if l is zero and i is at least 2.  You don't have to check it.

You don't need the counter variable.  As is, it's equal to prime.size() and you never use it.  Eliminating it saves an operation.  The compiler might do that for you, but you don't need it.

                for(int j=i*2;i*i<=r && j<r+1;j+=i)

This could be

                for (int j = i*i; j <= r; j += i)

You only need to check from i*i.  Anything smaller than that would already be marked.  For example, you already marked everything divisible by 2, so i*2 would be marked for all i greater than or equal to 1.

You only needed to check i*i<=r once.  This still does that check, as the first iteration j equals i*i.

The j<r+1 and j <= r are equivalent if j and r are integers.


Two of the really nice things about regular expressions are:

they can be compiled, which makes them fast, and reusable
they can replace what's between characters, not just the characters themselves.

In your case, you can reduce it to a "simple" lookaround regular expression. What you are looking for, is the gap between two digits...

in a regular expression, the gap can have no width. So, look for a place that follows a digit, and is also followed by a digit. Then, replace that place with a separator.

Then, compile and save that expression away, and reuse it:

private static final Pattern BETWEEN_DIGITS = Pattern.compile("(?<=\\d)(?=\\d)");

public static String formatNumber(String text, char separator) {
    return BETWEEN_DIGITS.matcher(text).replaceAll("" + separator);
}

That pattern is complicated.... but read up on look-behinds, and look-aheads: http://www.regular-expressions.info/lookaround.html


I would suggest handling a nil input explicitly. Then you can:

strip out the and (in s's binding), and just recurse directly
strip out the cons at the bottom, leaving only the append

Here's the code I tested with (in Scheme, since I have neither Emacs nor a CL implementation installed):

;; Requires SRFI 26
(define (combos lst)
  (if (null? lst) '(())
      (let* ((a (car lst))
             (d (cdr lst))
             (s (combos d))
             (v (map (cut cons a <>) s)))
        (append s v))))

And if you really can't bear to see the empty list as one of the combinations (though it really is), just take the cdr of the resulting list. It's always the first element.

Update: I installed Emacs now, so I was able to port my Scheme version to elisp and test it:

(defun combos (list)
  (if (null list) '(nil)
      (let* ((a (car list))
             (d (cdr list))
             (s (combos d))
             (v (mapcar (lambda (x) (cons a x)) s)))
        (append s v))))


There are some things I've seen that may help you improve your code.

Pass references where practical

The dfs() routine doesn't really need to create a duplicate string.  Instead, it could simply reuse a passed string.  We do that by changing the prototype to this:

void dfs(std::string &s)

And then call it like this:

int main() {
    std::string s;
    dfs(s);
    std::cout << "Finished Time : " << clock() / (double) CLOCKS_PER_SEC;
}

On my machine, the original code takes 6.3 seconds, but when modified like this, takes 4.7 instead, making a very easy improvement.

Prefer iterations to recursion

Recursive functions are often a good way to approach a programming task, but there is a tradeoff in terms of memory and time.  Specifically, one can often reduce or eliminate the computational cost of a function call and reduce or eliminate the memory overhead as well by converting from a recursive to an interative function.  In this case, I'd advise altering the code so that the prototype is something like this:

bool brute(const std::string &alphabet, size_t len)

It's then a simple matter of calling the function with increasing sizes until either the password is found or you run out of combinations.  For generating the combinations, I'd suggest using std::next_permutation something like this SO question shows.

Look at similar questions here

Another nice source of advice is other similar questions.  For example, this question is very similar and the answers are generally applicable to your code.


You should not mix PHP logic and HTML. All logic should be placed on top of the document and HTML (+ some minor PHP loops/echos/ifs) below it;
$var = $_GET['q']; is unneeded and you loose memory;
never use the shorttag (<?);
You forgot to set the errormode for PDO, that means it doesn't throw exceptions. To set it, use PDO::setAttribute:

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

I do not recommend to use * in your queries. The query will be faster and easier to use if you specify which columns you want;
You should specify the fetch style of PDOStatement::fetchAll. Otherwise it defaults to PDO::FETCH_BOTH, which means your array get to big and your script slower. You can specify it with a parameter in the function:

$stmt->fetchAll(PDO::FETCH_ASSOC);

Or specify it for the PDOstatement:

$stmt->setFetchMode(PDO::FETCH_ASSOC);

A small tip: Indent your code within each block with a tab or 4 spaces, that makes your code much easier to read. Also, choose a coding standard and use it everywhere. Consistent scripts are a pleasure to write, read and use!

Some none PDO/PHP things:

The <font> element is outdated. You should do this with CSS;
You should not use inline CSS (like style=, align=, width=), put it in a CSS stylesheet instead;
When you are using 2 <br> next to eachother, you almost always know you do something wrong and you should take a look at how to solve it with CSS margins/paddings.


Number of unique substrings of particular length of a binary string

Your code can be more efficient.  For example, both nested for-loops can be replaced with single for-loops.  In the first loop, the next sum can be calculated by left-shifting the previous sum, adding the new bit, and masking off n-bits.  count[sum] is how many times an n-bit pattern == sum has been seen.  So the second loop merely counts how many '1's are in count.  Something like the code below (not tested).

int count_unique(char *arr, int n) {
    int mask = (1 << n) - 1;

    /* the size needs to be 2**n.  This works for n <= 10 */
    int count[1024];
    memset(count, 0, sizeof(count));

    int sum = 0;

    for (int i = 0; arr[i]; i++) {
        sum = ((sum << 1) | (arr[i] - '0')) & mask;

        if (i >= n - 1) {
            count[sum]++;
        }
    }

    int unique = 0;

    for (int i = 0; i < sizeof(count)/sizeof(int); i++) {
        if (count[i] == 1) {
           unique++;
        }
    }

    return unique;
}


Login Script Utilising List Comprehension

I would split off player_count = 0 to a different line. Multiple assignments on one line is perfectly fine for simple assignments (like a, b = 1, 2), but a double list comprehension doesn't qualify for "simple".

Readability Counts

In general, Readability is far more important than conciseness. In fact, the reason concise code is often better is because it's more readable.

Normally, I'd be very careful with double list assignments for that reason. However, in this specific case, I think making it a single line is a good call. It's not overly long nor complex.

Performance

For pure python, I don't think you can really improve your performance even more. You won't get any issues until your password file grows into the MB's, and if that's a problem, you shouldn't be using a file with plaintext passwords anyway, since you'll be running your software in a production environment.

Instead, you'd be hashing and salting your passwords and storing them in a database, which is coincidentally also the best way to improve your performance if you get datasets that large.

However, as long as your username and password are requested from the user by means of the input() function, you won't have an issue.

dict.pop()

This function removes the value from the list. However, you don't seem to be actually doing anything with that value, and you're also discarding the list. So I'd just drop that line.

The only thing I can imagine you fix it would be to stop player2 from using the same credentials as player1. However, you don't save player references anyway. If you want to stop the same credentials from being used twice, I'd recommend to instead save references to the players for later, and then check that a player hasn't already been logged in as another player.


Web Service implementation on the client

Looked briefly into your program, here are few points:

  I would like to know whether or not my web service example method is
  suitable for client-side implementation

Web Client implementation doesn't need the actual implementation, if the service is hit able, it's client can surely be written.

addProduct(String name, String genre, String platform, String developer, String publisher,
int ageRating, double price, int quantity, String description)

Why not create a Product bean and pass it instead of so many params?

  (I have been creating basic web services using the axis2 framework and
  running them on the Apache Tomcat server. However, I am open to any
  suggestions or recommendations in regards to alternative servers and
  frameworks.)

This seems fine but from the learning perspective, give Jersey a try.


Your constructor has

constructor({ play1, play2, rules, messages }) {
  this.play1 = play1;
  this.play2 = play2;
  this.rules = rules;
  this.messages = messages;
}

You may as well Object.assign the parameter to the instance instead:

constructor(config) {
  Object.assign(this, config);
}

pattern is a slightly odd name for what it represents here - the usual English word for one of the clubs, diamonds, etc, is suit. rule is a bit strange as well - a rule usually refers to the process by which a game is played (eg "Hands consist of 6 cards" or "The player with the best hand wins"). To describe the different possible winning combinations and their ranks, I'd use the word handRanks or something similar. play1 and play2 aren't great descriptors either - these represent the cards held in each player's hand, so maybe use player1Cards or player1Hand.

With regards to the play() method, when you want to find an item in an array which fulfills a condition, it would be more appropriate to use .find, rather than a for loop - find more clearly indicates what the intention of the loop is, and is more concise. You also need to set the rank to Infinity if no handRanks pass - why not integrate this Infinity into the handRanks array itself? You're also writing the looping code twice - you can make it more DRY by putting it into a function, and calling that function twice instead.

new Card({ suit: "spade", number: 1 }),  // <-- Suit

new HandRank({  // <-- HandRank
  description: "Six Cards of the same suit",  // <-- Suit
  rank: 1,
  validator: cards => {
    return hasSameSuit(cards, 6);  // <-- hasSameSuit, not hasSamePattern
  }
}),
new HandRank({  // <-- HandRank
  description: "Nothing special",
  rank: Infinity,                 // <-- add this whole new HandRank
  validator: cards => true,
}),

getRank(cards) {
  return this.handRanks.find(({ validator }) => validator(cards)).rank; // <-- this.handRanks
}
play() {
  const rankOfP1 = this.getRank(this.player1Cards); //  <-- player1Cards
  const rankOfP2 = this.getRank(this.player2Cards); //  <-- player2Cards
  return rankOfP1 === rankOfP2
    ? this.messages.tie
    : rankOfP1 < rankOfP2
      ? this.messages.win.player1
      : this.messages.win.player2;
}

One of the benefits of using arrow functions is that if the function contains only a single expression which is immediately returned, you can omit the { } brackets and the return keyword, if you want to make things concise, eg for the hasSameSuit test above:

validator: cards => hasSameSuit(cards, 6),

If you want to find if any item in an array passes a test, but you don't care about which item passes the test, you should use .some, not .find. (.some returns a boolean indicating whether any passed, .find returns the found item) For the hasSamePattern (or hasSameSuit) method, use:

return Object.values(patterns).some(num => num >= threshold);

Your hasConsecutiveNums method has the bug mentioned in the comments previously - a hand of [1, 2, 2, 3] will not pass a 3-consecutive-number test because the sorted array will contain 2 twice, failing if (prevNum + 1 === num) {. De-duplicate the numbers with a Set first.

const nums = [...new Set(cards.map(card => card.number).sort((a, b) => a - b))];

  I wonder if anyone knows how to rewrite the game in functional programming style.

Javascript isn't entirely suited to completely functional programming either, though it can get most of the way there. To start with, make your functions pure, and avoid side-effects and mutations. For example, assigning to a property of the instance with this.play1 = play1; (or this.player1Cards = player1Cards;) is a mutation. None of your code fundamentally requires anything non-functional (except the console.log at the very end, which is unavoidable), so it should be pretty easy to convert - rather than assigning to properties, just keep the variables in a closure, and return a function for the play method, eg:

const makeGame = ({ player1Cards, player2Cards, handRanks, messages }) => () => {
  // getRank is now a standalone function which takes a handRanks parameter
  const rankOfP1 = getRank(player1Cards, handRanks);
  const rankOfP2 = getRank(player2Cards, handRanks);
  return rankOfP1 === rankOfP2
    ? messages.tie
    : rankOfP1 < rankOfP2
      ? messages.win.player1
      : messages.win.player2;
};

const play = makeGame({ ... });
console.log(play());


Interface
Naming
Functions returning a bool should be phrased as a question. empty should be is_empty instead. Yes, the standard library does it wrong too, leading to confusion like "I used vector.empty();, but it didn't empty my vector. Why?"
get should be pop or pop_get. Getters are not supposed to change the object.
Note that it is impossible to write get with the strong exception guarantee, which is the reason why std::vector::pop_back returns void instead of the element.
constexpr
Currently you can mark all your functions constexpr. Sometimes it is possible to evaluate the result of your CircularBuffer at compile time. That probably rarely comes up, but there is no good reason not to do it (yet).
Generality
Type restrictions
There are limits for what Ts I can use your CircularBuffer with. T must be copyable and default constructible. That means I cannot use a struct Foo{ Foo(int); }; or a std::unique_ptr<int>. Arguably those should be allowed.
Move-Only
Supporting move-only types is possible by using std::move in the appropriate spots, mainly buffer[head] = std::move(item); and auto result = std::move(buffer[tail]);. Just try to use a CircularBuffer<std::unique_ptr<int>> and the compiler will tell you about each spot.
Non-Default-Constructible
To be able to use CircularBuffer<Foo> you would need to delay constructing objects until the user uses put. You can achieve that by changing std::array<T, sz> buffer; to alignas(alignof(T)) std::array<char, sz * sizeof(T)> buffer;. That way no Ts are default constructed. When you add an element in put you have to placement new the element: new (&buffer[head * sizeof(T)]) T(std::move(item));. get then has to call std::destroy_at(reinterpret_cast<T*>(&buffer[tail * sizeof(T)])); (or just call the destructor). This makes things more complicated and also reinterpret_cast and new are not constexpr.
Brick Types
Some types like std::mutex cannot be copied or moved, but you could still support them. To do that, offer an emplace function similar to std::vector::emplace_back that constructs the  T in place from a given list of arguments.
get Return Type
Returning a T by value seems reasonable. You are taking out the element. Returning a T & instead seems dangerous, because usage of the buffer will eventually change the value you got. Maybe add 2 peek functions instead that return a reference to the current object without removing it. One of the functions would be T &peek() and the other const T &peek() const.
Bugs
empty When Full
CircularBuffer<int, 3> b;
b.put(1);
b.put(2);
b.put(3);
std::cout << std::boolalpha << b.empty();

That should really not print true.
Over- and Underflow
If I put more items into the buffer than it has space it silently overwrites objects. If I try to get items without putting items in, it simply returns uninitialized objects which is undefined behavior for builtins. This is my fault for using your container incorrectly, but you could be nice and add an assert so that I can find my bug easier.
inline
Your functions are already implicitly marked inline which changes the linkage and has nothing to do with inlining. Whether inlining is the right choice is a complicated case-by-case question that you should leave to your compiler. Only use inline to mean "I want internal linkage", which you can also do for variables since C++17.


Structuring a reusable angular component with multiple communicating directives

It's difficult to tell from these snippets exactly what you're trying to achieve, but I think the questions you have to ask are; how do you anticipate reusing this code? If reusability is the feature, what are the use cases?

If you anticipate needing multiple distinct controllers with a significant and coherent subset of the logic in the get request in the controller, the consider extracting it into a service, to save logic duplication.

Alternatively, if the contents of the controller are only needed for the directive, consider making the controller part of the directive, rather than requiring them to be correctly used in conjunction.

The directive looks good from what I can tell.


Database design for an online learning application

You do have the field languages several times as a string. I'd create a general table languages with all language-related informations and have 1:m or n:m relations to other tables.


Escaping the prison - finding the shortest way

Reviewing Code:

Names

When naming classes in hierarchies, share the naming conventions used in the standard libraries.  Therefore, your top level interface should be Maze, not IMaze.  Likewise, IMazePosition.

Repetition

You are repeating yourself both small and large here.

Small: notice that you repeat yourself for each of the cardinal directions (north, south, east, west).  That code is screaming for a loop:

for(MazePosition nextPosition : crntPosition.getNeighbors()) {
    if (maze.canMove(nextPosition)) candidates.add(nextPosition);
}

Large: notice that solveUsingDepthFirst and solveUsingBreadthFirst are the same except that they order the points differently.  This suggests that you have overlooked an abstraction: a SearchOrder.

public interface SearchOrder {
    boolean isEmpty();
    MazePosition next();
    void add(MazePosition candidate);
}

public class DepthFirstSearchOrder implements SearchOrder {
   Stack<MazePosition> stack = new Stack<MazePosition> ();

   // implement the interface accessing this.stack
}

public class BreadthFirstSearchOrder implements SearchOrder {
   // notice that candidates is a List<>, because the interface
   // really doesn't care about the implementation.
   List<MazePosition> candidates = new LinkedList<MazePosition> ();

   // implement the interface using this.candidates
}

void solveUsingBreadthFirst(Maze maze) {
    solve(maze, new BreadthFirstSearchOrder());
}

void solve(Maze maze, SearchOrder order) {
    // ...
}

Missing Requirements

It looks like you aren't keeping track of the moves you have made; your existing example seems to tell you if a solution exists, but it doesn't actually report what the solution is.  This may or may not be a flaw - depending on the requirements.

Also, it's not fair to assume that your shortest solution in among them.  Imagine a maze that is a big ring, with the exit right next to the start - your depth first search can go the wrong way around the ring, giving you the longest solution instead of the shortest.  (The first result found in a breadth first search will be the shortest).

What you are missing is the ability to measure how far you have traveled when you reach the exit.  So you need something to count the number of moves you have made, so that you can tell if the current path you are taking has improved on your best so far.

If you had such a thing, you could (by generalizing it further) abandon search branches when they are guaranteed to be worse than the solution you have already found....


Fastest method of randomly swapping array indexes / generating random alphabets in C++

This method is biased. Use Fisher-Yates shuffle.
TL;DR: There are \$26^{26}\$ possible outcomes of a. There are \$26!\$ possible permutations of the alphabet. Since \$26!\$ doesn't evenly divide \$26^{26}\$, permutations are not equiprobable.

Regarding speed, I don't think that generating a beforehand is beneficial. It results in 3 memory fetches down the line: alpha[x], tmp = a[x], alpha[tmp]. Generating a random number inside the loop makes only two fetches. It is likely to not be measurable with an alphabet as short as 26 characters, but when shuffling a billion-strong alphabet you'd see the difference.


linearly interpolate NA values in Rcpp::NumericVector

As you suggest, the code does look very "pointery".  I think it might be made clearer with use of some standard algorithms:

std::adjacent_find() (with suitable predicate functions) to find a number followed by NA, or a NA followed by a number.
std::generate() (with suitable generator function) to populate a series of values from one iterator to another.

With those, you won't need any arithmetic on iterators other than a subtraction to find the number of elements you're interpreting.

The form of such a solution is something like this (untested):

#include <Rcpp.h>
#include <algorithm>

constexpr auto is_na = Rcpp::NumericVector::is_na;

//[[Rcpp::export]]
Rcpp::NumericVector naLinInt(Rcpp::NumericVector x) {
    // This function linearly interpolates to fill sequences of NA
    // values surrounded by valid numbers.
    static auto const detect_start_na = [](auto a, auto b){
        return !is_na(a) && is_na(b);
    };
    static auto const detect_end_na = [](auto a, auto b){
        return is_na(a) && !is_na(b);
    };

    auto start = x.begin();

    while (true) {
        // Find transitions to and from NA values.  If we hit end of
        // vector whilst looking, our work is done.
        auto num_to_na = std::adjacent_find(start, x.end(), detect_start_na);
        auto na_to_num = std::adjacent_find(start, x.end(), detect_end_na);
        if (na_to_num == x.end()) {
            break;
        }

        // At this point, num_to_na points to the last number before
        // an interpolation block, and na_to_num points to the last NA
        // of that block.

        ++na_to_num;            // Now, both iterators point to numbers.
        auto const base = *num_to_na;
        auto const target = *na_to_num;

        // To count rails rather than posts, measure difference before
        // incrementing the start position.
        auto const gaps = std::distance(na_to_num, num_to_na);

        ++num_to_na;
        // Now both iterators point immediately *after* transition.

        auto const make_value = [base, target, gaps, i = std::size_t{0}]()
            mutable { return base + (++i * (target - base) / gaps); };
        std::generate(na_to_num, num_to_na, make_value);

        // Advance onwards
        start = na_to_num;
    }

    return x;
}

There are a couple of iterator increments there (because std::adjacent_find returns an iterator to the first of the matching pair), but there's quite a lot less arithmetic than the original.

Although this is longer than the original, much of the difference is the comments that help the reader understand how the state changes through the loop.  That's something that I think is an improvement (though perhaps the terms "rails" and "posts" require a link to a definition of fencepost error for the uninitiated).


Optimised Python Code gives TLE for PRIME1

Finally, I solved the problem. And these suggestions helped. Here is the final solution:

import math
def sieve_basic_list(list_prime):
    max_n=10**9
    m = int(math.sqrt(max_n))
    lim = int(math.sqrt(m))+1
    arr = [True]*(m+1)
    arr[0]=arr[1]=False

    #Calculate primes upto m only so loop runs sqrt(m) times.
    for x in xrange(2,lim):
        if arr[x]==False:
            continue
        for i in xrange(x*x,m+1,x):
            arr[i]=False
    for i,each in enumerate(arr):
        if each:
            list_prime.add(i)

def mnsieve(list_prime):
    #program tc input and mnrange calc
    for _ in xrange(int(raw_input().strip())):
        m,n = map(int,raw_input().split())
        mnrange = [True]*(n-m+1)
        mnrange[0] = False if m==1 else True
        for each in list_prime:
            if each <= int(n**0.5): #important optmisation
                firstfactor = ((m-1)/each)*each #firstfactor nearest to m i.e firstfactor-m gives index
                for x in xrange(firstfactor,n+1,each):
                        if x!=each and x-m >= 0: #x-m can become -ve and that is disastorous in python lists!
                            mnrange[x-m]=False
       for i,each in enumerate(mnrange):
            if each:
                print i+m
       print

list_prime=set([]) #important optimisation
sieve_basic_list(list_prime)
mnsieve(list_prime)

Check it here: on codechef


Finding sum of sub vector satisfying inequality

Since the sum v_l changes with each iteration through your dictionary values of num, I don't know of a way to pre-compute the right-side sums before-hand. This would be a little easier if you could use external modules. That said, you might see a slight speed-up if you use more comprehensions. For example, you can get num via num = {x : vec.count(x) for x in vec}. Also, use == 0 (not is 0) to check zero equality and use is None(not == None) to check None.

Also, you are iterating through all possible combinations. In the case of using votes1 and m1, you know that m = m1 = 10 and n = len(votes1) = 30. So you know that your lower bound is cut-off at 76. Those are 76 permutations that you do not need to use. You can include a break statement at the lower bound since you are incrementing downward (temp[i] -= 1), but I would instead use this lower bound as the starting point and iterate by incrementing upward as you may find some other way to restrict the sums in the upper limit.

Lastly, the use of globals and non-descriptive variable names makes it hard to edit the code. For example, votes instead of vec, ndict instead of n, etc. Also, you can pass R into dfs_backtrack.

I personally prefer iterating over lists instead of dictionaries since you can use zip. I don't have a full solution for your problem, but it may help as a start.

def get_lower_bound(m, n):
    return m*n/4 + 1

def get_upper_bound(m, n, v):
    return v - m*n/4 - 1

def initialize_constants(m, n, votes):
    """ Pre-compute these values as they do not change."""
    size = len(votes)
    total = sum(votes)
    lower_bound = get_lower_bound(m, n=30)
    return size, total, lower_bound

def initialize_vl(votes, m):
    ## I think set look-ups are quickest, these provide unique values just like dictionaries do
    unique_votes = list(set(votes)) #keys for num
    vcounts = [votes.count(x) for x in unique_votes] #vals for num
    vl = sum([a*b for a,b in zip(unique_votes, vcounts)])
    return unique_votes, vcounts, vl

This way, you don't need to use

    temp = dict(vec)
    temp[i] -= 1
    if temp[i] is 0:
        temp.pop(i)
    if temp and temp not in R :

as you are creating temp as a copy of vec; any change to temp changes vec as well. Also, you can iterate through your unique values in list(set(...)) instead of checking if each element is in R.

Sorry I could not be of more help. Let me know if anything is unclear.


I am not sure I understand why you are attempting to extend Writable here.

At the end of the day, it seems as if your pipeline is what you are REALLY wanting to have a promise interface.

Luckily this is really easy to do with recent versions of node using Stream.pipeline and Util.promisify().  There is an even an example in the Stream.pipeline documentation


Angular controller to handle showing or hiding multiple widgets

You could change your ng-show to use a function:

ng-show="isShown('widgetX')" ng-click="toggleWidget('widgetX')"

And then in your controller:

var widgets = {
    widgetA: {
        shown: true
    },
    widgetB: {
        shown: true
    },
    ...
};

$scope.isShown = function(widgetID) {
    return widgets[widgetID].shown;
}

$scope.toggleWidget = function(widgetID) {
    widgets[widgetID].shown = !widgets[widgetID].shown;
}


Which one should I choose to work with, Facebook PHP-SDK or Graph Api with Curl?

I think you'd be better off using the official API wrapper from Facebook. If they ever change their APIs you could download the latest version of their wrapper and continue on.

The best thing you can do for speed is cache the results. PHP can read files on the server a lot faster than downloading the information with CURL.


Building SQL from multiple combinations of query parameters

Instead of dynamic string concatenation, you can do a logic trick. I'm going to use named sql placeholders for clarity. You'll obviously need to implement the code, I'm just giving you the idea.

select a
     , b
     , c
  from someTbl
 where (:PMaxAge  is null or maxAge <= :PMaxAge)
   and (:PMinRent is null or rent   >= :PMinRent)
   and (:PMaxRent is null or rent   <= :PMaxRent)
   -- etc ...

You may need to check for an empty string instead of checking for null to detect when a param was omitted depending on you implementation, but you get the point - let each criteria be satisfied if the param is missing.


Typeahead / Autocomplete using AngularJS directive

There are some points you could improve:

App structure:
I would put the typeahead directive in an own module that you can include as a dependency to your app. angular.module('demoApp', ['pdTypeAhead']).
Click events: I think the best place is in the directive controller because they're there for your typeahead logic.
Keyboard binding: You can add the mousetrap.js keyboard binding in a directive and add it in your typeahead link method. It's a bit tricky because you need to change the typeahead restrict to attribute (otherwise there is a problem with infinite digest loop.).
Your todos:

look & feel: Twitter Bootstrap is a good starting point to do your styling.
Keyboard navigation: You could do it with pure js but I think mousetrap.js is easier to use.
Enter + Escape handling: Also use mousetrap. For event handling you could use $scope.$brodcast('eventName', data) and catch it in your directive's controller with $scope.$on('eventName', function(data) { ... });
Responsiveness: If you'd type the letter a in your code it took pretty long to show the result (> 3000 matches). I think it's OK to limit the result to 100 or lower matches with a limitTo filter and the result is immediately visible.

You can find my code in this fork. (If you like I could do a pull request in your repo.)

There are still the following possible improvements in the updated code:

Controller of the typeahead directive could be in it's own file. Improves readability.
It's probably possible to put code from the typeahead controller into a service for refactoring.
Escape key handling could be improved: After a click on a name you can't undo that click with a press on escape. But if you select with enter you can undo with escape.
Directive template typeahead.tmpl could be moved to the components folder of the directive js/components/typeahead.
Typeahead controller: Use controllerAs instead of $scope (if possible). Best practice, see style guide.
Check if filtering is also possible directly in ng-repeat? Should be possible and better. I've just moved it to js for easier debugging.
Add options to typeahead, e.g. a way to enable or disable autofocus of search input directly in markup e.g. <div type-ahead datalist="dataToPopulate" auto-focus="off">
Add a config provider for options service so you could add the options application wide inside of angular.module(...).config(...). This post is helpful for creating configurable directives.
Add ng-blur to close the typeahead if clicked outside.
Add unit tests for the directive.


Buffer overrun

Your array w should be one larger than it currently is to hold a null terminating character.  Otherwise when you write to w[n] you are writing past the end of the array.

Excess copying

Currently, every time you generate a new permutation, you rewrite all of the w array.  You actually only have to rewrite the parts that changed since the last permutation.  To do this, you should write to w[i] only when c[i] changes.  So for example:

while(c[0] < l){
    c[n - 1] += 1;
    w[n - 1] = s[c[n - 1]];
    for(i = n - 1; i >= 0; i--){
        if(c[i] > l - 1 && i != 0){
            c[i] = 0;
            w[i] = s[0];
            c[i - 1] += 1;
            w[i - 1] = s[c[i - 1]];
        }
    }
}

Alternate implementation

If you are looking to find a faster way to generate permutations, I suggest you look at this codereview question and in particular my answer to it.


Restful CRUD API with Node.js and Express

I know you are generating data for the sake of completion but it does complicate things on what aspect of the code you'd like to focus on. But here are a couple thoughts.

With Express, I often like to treat the routes as controllers in an MVC pattern. So any fetching of data and mutating data, I would create at least a model per resource to encapsulate that part of the code. So the interface may look something like the below:

app.get('/names', async (req, res) => {
  // assuming we are getting data from an async call to a db
  const names = await Name.all();
  res.json(names)
})

app.post('/names', async (req, res) => {
  const newName = await Name.create(req.body);

  res
    .status(201)
    .json({ id: newName.id })
})

app.put('/names', async (req, res) => {
  const { id } = req.body
  const name = await Name.findAndUpdate(id, req.body);
  res
    .status(200)
    .json(name)
})

app.delete('/names', async (req, res) => {
  const { id } = req.body
  const deleted = await Name.deleteById(id)
  res
    .status(200)
    .json({ status: 'success'})
})

Notice that we can implement "Name" class with whatever database(or file or no database) we want. As long as we keep the interface the same, we can swap different "Name" class implementations without having to change our Express routes.

One last point, since there is no "view" suggested here but we can have it if we want. For example, if for some reason, our model doesn't return us exactly what we need, maybe the key is slightly off from our API specifications, we can introduce a view layer that maps whatever the model returns us. This way we can continue to keep our Express routes very thin and handling specific to request/response related responsibilities.


Delete folder if it exists in PowerShell

I assume you're just trying to avoid the error message in case it doesn't exist.

What if you just ignore it:

Remove-Item $folder -Recurse -ErrorAction Ignore

If that's not what you want, I would recommend writing your own function:

function Remove-ItemSafely {
[CmdletBinding(SupportsShouldProcess=$true)]
param(
    [Parameter(
        Mandatory=$true,
        ValueFromPipeline=$true,
        ValueFromPipelineByPropertyName=$true
    )]
    [String[]]
    $Path ,

    [Switch]
    $Recurse
)

    Process {
        foreach($p in $Path) {
            if(Test-Path $p) {
                Remove-Item $p -Recurse:$Recurse -WhatIf:$WhatIfPreference
            }
        }
    }
}


Mutation is generally discouraged in Redux (and React in general) because it breaks tooling/libraries that expect x === y to mean that x and y are the same throughout time.

If you use the React.useEffect or React.useMemo or React.useCallback dependency arguments, or React.memo, you'll run into problems if you mutate objects that you're passing.

We can clean up your code to avoid this mutation in several passes. First, we'll just remove the logs since they don't affect behavior (and they expose certain implementation details we'll want to change):

switch (action.type) {
  case ADD_TASK: {

    let newBoard = state.boards.find(
      board => board.id === action.payload.boardId
    )

    let column = newBoard.columns.find(
      column => column.id === action.payload.columnId
    )
    column.tasks = [...column.tasks, action.payload.task]

    newBoard.columns = [...newBoard.columns, column]

    const addToBoard = state.boards.map(board => {
      if (board.id === action.payload.boardId) {
        board = newBoard
      }
      return board
    })

    const newState = {
      boards: addToBoard
    }
    return newState
  }
  //code omitted
}

Next, let's inline some of these variables. newState and addToBoard are each only used once:

switch (action.type) {
  case ADD_TASK: {

    let newBoard = state.boards.find(
      board => board.id === action.payload.boardId
    )

    let column = newBoard.columns.find(
      column => column.id === action.payload.columnId
    )
    column.tasks = [...column.tasks, action.payload.task]

    newBoard.columns = [...newBoard.columns, column]

    return {
      boards: state.boards.map(board => {
        if (board.id === action.payload.boardId) {
          board = newBoard
        }
        return board
      })
    }
  }
  //code omitted
}

Next, consider this arrow function:

      board => {
        if (board.id === action.payload.boardId) {
          board = newBoard
        }
        return board
      }

You've made your control-flow more complicated by reassigning the parameter, when an early return would do just fine:

      board => {
        if (board.id === action.payload.boardId) {
          return newBoard
        }
        return board
      }

Also, we only actually need newBoard inside this function (it's never used more than once), so we can move it to where it's needed:

switch (action.type) {
  case ADD_TASK: {
    return {
      boards: state.boards.map(board => {
        if (board.id === action.payload.boardId) {
          let newBoard = state.boards.find(
            _board => _board.id === action.payload.boardId
          )

          let column = newBoard.columns.find(
            column => column.id === action.payload.columnId
          )
          column.tasks = [...column.tasks, action.payload.task]

          newBoard.columns = [...newBoard.columns, column]
          return newBoard
        }
        return board
      })
    }
  }
  //code omitted
}

Now we begin to see some redundancy! For example, newBoard is being initialized to "the board with id equal to action.payload.boardId, but we already have a name for it: that's just board! So we can actually get rid of the name newBoard entirely:

switch (action.type) {
  case ADD_TASK: {
    return {
      boards: state.boards.map(board => {
        if (board.id === action.payload.boardId) {
          let column = board.columns.find(
            column => column.id === action.payload.columnId
          )
          column.tasks = [...column.tasks, action.payload.task]

          board.columns = [...board.columns, column]
          return board
        }
        return board
      })
    }
  }
  //code omitted
}

But now we need to deal with the unnecessary mutations. We don't want to modify board (or any of its fields, like columns). Instead, we want to return a copy with changes.

We can do this in parts. For example, instead of

          board.columns = [...board.columns, column]
          return board

we can instead say

          return { ...board, columns: [...board.columns, column] }

which copies board and then replaces the columns field with the new given value.

We now have

          let column = board.columns.find(
            column => column.id === action.payload.columnId
          )
          column.tasks = [...column.tasks, action.payload.task]
          return { ...board, columns: [...board.columns, column] }

and similarly, we can change the last two lines to obtain the non-modifying equivalent:

          let column = board.columns.find(
            column => column.id === action.payload.columnId
          )
          return {
            ...board,
            columns: [
              ...board.columns, { ...column, tasks: [...column.tasks, action.payload.task] }
            ]
          }

However, at this point, it seems likely that you have a bug here. This change duplicates the entire column, in addition to adding the single task to it! It seems that you instead wanted to just add a task to the one column with matching ID, which we can do instead:

switch (action.type) {
  case ADD_TASK: {
    return {
      boards: state.boards.map(board => {
        if (board.id === action.payload.boardId) {
          return {
            ...board,
            columns: board.columns.map(column => {
              if (column.id === action.payload.columnId) {
                return { ...column, tasks: [...column.tasks, action.payload.task] };
              }
              return column;
            })
          }
        }
        return board
      })
    }
  }
  //code omitted
}

This gives us a fully cleaned-up and immutable version of your code. Of course, you might rightfully observe that this is more-heavily nested than your original, which is a common result of switching to non-mutating state. You can use some existing ones or build your own.

For example, in this case, you're frequently using the following pattern:

find a matching object in an array
return the array with all other objects unchanged, and apply a transformation to the one that matches

This is easy to write as a helper function. Here mapIf is used to select the right board and then the right column:

function mapIf(array, condition, transform) {
  return array.map(item => condition(item) ? transform(item) : item);
}

switch (action.type) {
  case ADD_TASK: {
    return {
      boards: mapIf(state.boards, board => board.id === action.payload.boardId, board => ({
        ...board,
        columns: mapIf(board.columns, column => column.columnId === action.payload.columnId, column =>
          ({ ...column, tasks: [...column.tasks, action.payload.task] })
        ),
      })),
    }
  }
  //code omitted
}

Even this is still a bit long, so you can write more helpers, like a hasId higher-order function:

function hasId(id) {
    return item => item.id === id
}

hasId returns a function that checks whether its argument has the original id. So we can instead write:

function mapIf(array, condition, transform) {
  return array.map(item => condition(item) ? transform(item) : item);
}

function hasId(id) {
  return item => item.id === id
}

switch (action.type) {
  case ADD_TASK: {
    return {
      boards: mapIf(state.boards, hasId(action.payload.boardId), board => ({
        ...board,
        columns: mapIf(board.columns, hasId(action.payload.columnId), column =>
          ({ ...column, tasks: [...column.tasks, action.payload.task] })
        ),
      })),
    }
  }
  //code omitted
}

Lastly, you frequently only want to touch one (or a couple) fields in an object. Here's one helper you can write to clean up access to the tasks and columns fields:

function onField(field, func) {
  return item => ({ ...item, [field]: func(item[field]) })
}

this helper allows you to write (for example) onField("x", val => val + 1) to get a function that increases the .x field of its argument by 1, leaving all the others alone. You can use it like so:

function onField(field, func) {
  return item => ({ ...item, [field]: func(item[field]) })
}

function mapIf(array, condition, transform) {
  return array.map(item => condition(item) ? transform(item) : item);
}

function hasId(id) {
  return item => item.id === id
}

switch (action.type) {
  case ADD_TASK: {
    return {
      boards: mapIf(
        state.boards,
        hasId(action.payload.boardId),
        onField('columns', columns => mapIf(
          columns,
          hasId(action.payload.columnId),
          onField('tasks', tasks => [...column.tasks, action.payload.task]),
        )),
      ),
    }
  }
  //code omitted
}

This change suggests a new way to write mapIf, so that it works better with onField, by making it return a transforming function instead of directly taking the array as an argument:

function onField(field, func) {
  return item => ({ ...item, [field]: func(item[field]) })
}

function mapperIf(condition, transform) {
  return array => array.map(item => condition(item) ? transform(item) : item);
}

function hasId(id) {
  return item => item.id === id
}

switch (action.type) {
  case ADD_TASK: {
    return onField(
      'boards',
      mapperIf(
        hasId(action.payload.boardId),
        onField(
          'columns',
          mapperIf(
            hasId(action.payload.columnId),
            onField('tasks', tasks => [...column.tasks, action.payload.task]),
          )
        ),
      ),
    )(state);
  }
  //code omitted
}

The main downside to this approach is that there's lots of nesting that can make it hard to understand what's going on. So if we make one more transformation, and write a chain helper, we can get the (in my opinion, rather beautiful):

function onField(field) {
  return func => item => ({ ...item, [field]: func(item[field]) })
}

function mapperIf(condition) {
  return transform => array => array.map(item => condition(item) ? transform(item) : item);
}

function hasId(id) {
  return item => item.id === id
}

function apply(transform) {
  return func => item => transform(func(item));
}

function chain(func, ...funcs) {
  if (func === undefined && funcs.length === 0) {
    return item => item;
  }
  return func(chain(...funcs));
}

switch (action.type) {
  case ADD_TASK: {
    return chain(
      onField("boards"),
      mapperIf(hasId(action.payload.boardId)),
      onField("columns"),
      mapperIf(hasId(action.payload.columnId)),
      onField("tasks"),
      apply(tasks => [...tasks, action.payload.task]),
    )(state)
  }
  //code omitted
}
```


Determining if someone has read and seen all the questions of a book

What you have written is essentially six independent queries.  Let's drop the pretense that these are correlated subqueries.  Let's also reorder the output columns.  We can also simplify col = A || col = B as col in (A, B).

SELECT (SELECT COUNT(s.id)
          FROM sections s
         WHERE s.chapter_id = ? AND s.module IN (1, ?)
       ),
       (SELECT COUNT(q.id)
          FROM question q
         WHERE q.chapter_id = ? AND q.module IN (1, ?)
       ),
       (SELECT AVG(m.$mkts_col)
          FROM mkts m
         WHERE m.chapter_id = ? AND m.module IN (1, ?)
       ),
       (SELECT COUNT(u.id)
          FROM user_sections u
         WHERE u.chpt_id = ? AND u.user_id = ?
       ),
       (SELECT COUNT(v.id)
          FROM user_questions v
         WHERE v.chpt_id = ? AND u.user_id = ?
       ),
       (SELECT AVG(v.box)
          FROM user_questions v
         WHERE v.chapter_id = ? AND u.user_id = ?
       );

That's about all you can do to rewrite this particular query.  Depending on how your application works, it might make sense to obtain all of these statistics globally, instead of for particular user + chapter + module combinations.  In that case, you would write two queries, each with JOIN and GROUP BY clauses.  One query be joined by chapter and module conditions, and the other would be joined by chapter and user.

After rearranging the columns, it becomes more obvious that you used both user_questions.chpt_id and user_questions.chapter_id.  One of them is probably an error.


You can reduce your code duplication a bit. First, the way you are currently using the ckin function is like this:

name = input("Enter a name").strip()
name = ckin(name)

Wouldn't it be nicer to be able to do:

name = ask_user("Enter a name: ")

For this, just modify your function like this:

def ask_user(message=""):
    user_input = ""
    while not user_input:
        user_input = input(message).strip()
    return user_input

Note that I renamed it (to make it clearer what it does), used the fact that empty strings are falsy and added whitespace around the = operator, as recommended by Python's official style-guide, PEP8.

Going further, you should get into the habit of defining clearly named functions for separate things.

One such concern is getting a pre-populated username list. Currently this list is populated with user input, but this might change in the future. So it would be nice to bundle that part all together in one function:

def get_users():
    # creates a users set, which always includes admin
    users = {'admin'}

    #Ask for 5 names to store as usernames
    print('Please enter 5 unique user names: ')
    while len(users) < 6:
        users.add(ask_user("Enter a valid user name: ").lower())
    return users

Note that I made the datastructure a set here, which gives you \$\mathcal{O}(1)\$ time complexity for in tests. I also made sure that there are actually 5 + 1 users (in other words, user names need to be unique). I also put the str.lower transformation here so we don't need to do it later and only store the canonical user name.

Next is a login function, that asks for a username until a valid one is entered:

def login(users):
    user_name = None
    while user_name not in users:
        user_name = ask_user("Enter login name: ").lower()
    return user_name

And then, the greeting. Instead of iterating over all users until you reached the user that is currently logging in, use the fact that we already know that the user is in users (since we explicitly checked for that in login). So this becomes a simple if..else check:

def print_greeting(user_name):
    if user_name == 'admin':
        print('Hello admin, would you like to see a status report?')
    else:
        print(f'Hello {user_name}, thank you for logging in again')

Here I used an f-string, as introduced in Python 3.6, to make the string formatting a bit easier.

And finally, tying it all together in a main function:

def main():
    users = get_users()
    user_name = login(users)
    print_greeting(user_name)

if __name__ == "__main__":
    main()

Note that I call this main function only under a if __name__ == "__main__": guard. This ensures that the main function does not run if you import from this script in another script.


return means "Eureka! I have found the answer! It is …."  It hands that result back to the caller and stops executing any more code in this function.

Unlike x**y, your function gives incorrect results for negative or non-integer values of y.  You should note that caveat in a docstring.

The standard way to do counting loops in Python is to use range() (or, in Python 2, xrange()).

To reduce the complexity of your code, you should avoid unnecessary special cases.

def pow(x, y):
    """Raise x to the power y, where y must be a nonnegative integer."""
    result = 1
    for _ in range(y):   # using _ to indicate throwaway iteration variable
        result *= x
    return result

This particular looping pattern (starting with some initial value and repeatedly applying an operation to the result) could be reduced to a one-liner:

from functools import reduce  # Optional in Python 2, required in Python 3

def pow(x, y):
    """Raise x to the power y, where y must be a nonnegative integer."""
    return reduce(lambda result, _: result * x, range(y), 1)

This solution is admittedly foreign-looking to a C programmer.  The reduce() function uses 1 as the starting value (equivalent to result = 1 in the first solution).  For each _ in range(y), it does result = result * x.  lambda is just a way to define a simple function on the spot.

A more efficient algorithm would be repeated squaring.


You can be more concise and readable using range and the fact that the default value of the int is 0 :

func WordCount(s string) map[string]int {
    m := make(map[string]int)
    for _, w := range(strings.Fields(s)) {
        m[w]++
    }
    return m
}


Efficient way to efficiently merge arrays of objects in JavaScript

You can use reduce for this purpose. Group the objects into an aggregate object by some key which we can make a parameter to a function mergeByKey. This function takes any number of object arrays which are then flattened (change flat to [].concat(...objArrs) for better browser compatibility) then reduced into a single object. During grouping, object spreading updates the value for each unique key as you did. Finally, extract the array of values from the grouping object using Object.values which is the final result.

Time complexity of the original version was O((n*longest_obj_length)^2), but the updated version is O(n*longest_obj_length).

const mergeByKey = (key, ...objArrs) =>
  Object.values(objArrs.flat().reduce((a, e) => {
    a[e[key]] = {...a[e[key]], ...e};
    return a;
  }, {}))
;

const constList = [
  { name: "jack", id: "1", designation: "hr" },
  { name: "mary", id: "2", designation: "it" },
  { name: "john", id: "3", designation: "fin" }
];

const apiList = [
  { name: "jack", id: "1", height: "10" },
  { name: "mary", id: "2", height: "20" }
];

console.log(mergeByKey("id", constList, apiList));


Your code and both other answers are good. However, I see a gap in the assumption here.

What if the list of available coins changes? This could be culture related (e.g. the Euro uses a €0.20 coin instead of the dollar's $0.25).
A similar issue could be encountered if you start factoring in the availability of change in your register (you can't give three quarters if you only have two)

To be fair, the second bullet point is not part of your current program. But if we solve the first bullet point, we have pretty much solved the second bullet point too (it requires minimal extra effort).

I'm not going to implement the second bullet point, but adding this feature should be relatively easy in my reworked example.

So far, the coin values (and the coin types) have been hard-coded:

Your code:

while(change >= 0.25m)

Danny's code:

decimal quarters = GetNumberOfCoins(ref change, 0.25m);

Denis' code:

private const decimal _quarterValue = 0.25m;

All of them share the same traits: coin values are hardcoded, and so is the list of available coins.

Even though the values themselves are easily changed, changing the available coins (e.g. quarters are decommissioned, or a new coin value is created) creates a bigger workload, because you have to change the calls.

Realistically, the available coins don't change all that often (it would be insanity to try and change this on a federal level).
However, as I mentioned before, if your program needs to be able to handle both Euros and US dollars, then the available coins does change.

So let's improve this.

public class CoinType
{
    public decimal Value { get; set; } //e.g. 0.25
    public string Name { get; set; }   //e.g. "quarter"
}

Note that you can add other properties here:

char CurrencySymbol = '$'
int AmountOfCoinsAvailable = 100

But for the sake of simplicity, we'll only use the value and a name for printing.

Both you and the answerers have already identified that a generalized method should be created to check coin values. I'll not elaborate on the same, because it would just repeat the other answers.

Let's assume the following method exists:

private int CalculateMaxCoins(CoinType coin, decimal remainingAmount);

The return value is the amount of coins that you can use. E.g. 0.80 can fit 3 quarters, so 3 is the return value.

Now, we need to create a list of coins. Note that I'm making it a list instead of a bunch of separate properties, so that the list of available coins can easily be changed.

List<CoinType> availableCoins_USD = new List<CoinType>()
{
    new CoinType() { Value = 0.25m, Name = "quarter" },
    new CoinType() { Value = 0.10m, Name = "dime" },
    new CoinType() { Value = 0.05m, Name = "nickel" },
    new CoinType() { Value = 0.01m, Name = "penny" }
};

This allow us to easily change it to EUR:

List<CoinType> availableCoins_EUR = new List<CoinType>()
{
    new CoinType() { Value = 2, Name = "€2" },
    new CoinType() { Value = 1, Name = "€1" },
    new CoinType() { Value = 0.5m, Name = "50 cent" },
    new CoinType() { Value = 0.2m, Name = "20 cent" },
    new CoinType() { Value = 0.10m, Name = "10 cent" },
    new CoinType() { Value = 0.05m, Name = "5 cent" },
    new CoinType() { Value = 0.02m, Name = "2 cent" },
    new CoinType() { Value = 0.01m, Name = "1 cent" }
};

All the subsequent code will work regardless of the list of coins (so long as the list is comprehensive). So let's assume we've encapsulated this is a method:

private List<CoinType> GetCoinsForLocalCurrency();

We've defined how to get the coins, we've assumed that the calculation (of how many coins of a given type should be used already exists) (cfr the other answers)

All that remains is the logic inbetween these two:

private static void PrintListOfChange(decimal totalChange)
{
    //Get the coins and order them by value (descending)
    var coinTypes = GetCoinsForLocalCurrency()
                    .OrderByDescending(x => x.Value)
                    .ToList();

    //This is where we construct our result
    Dictionary<CoinType, int> neededChange = new Dictionary<CoinType, int>();

    //Placeholder value for calculations
    decimal remainingChange = totalChange;

    foreach(var coinType in coinTypes)
    {
        int coinAmount = CalculateMaxCoins(coinType, remainingChange);

        //Do nothing if the result was 0
        if(coinAmount > 0)
        {
            //Add the results
            neededChange.Add(coinType, coinAmount);

            //See how much money is left to calculate
            remainingChange = remainingChange - (coinAmount * coinType.Value);

            //Minor performance gain:
            //  Stop processing if there is no money left to calculate.
            if (remainingChange == 0) break;
        }
    }

    //All that's left to do is print the values.

    string summaryOfChange = String.Join(
                                    " , ",
                                    neededChange.Select(x => $"{x.Key.Name} x{x.Value}") //e.g. "quarter x3"
                                );

    string fullmessage = $"{totalChange} in change equals: {summaryOfChange}";

    Console.WriteLine(fullmessage);
}

Ignoring the availability of a specific coin type, I think this is the most generalized approach. It requires a method to get the correct list of coins, but it works for any comprehensive list of coins that you provide.

I kept it a brief for the sake of example. There are extra features you could add:

1. What if the full total wasn't calculated in change?

e.g. you were trying to find change for $1.06 but you have no pennies in your list.

After the foreach, you can do:

if(remainingChange > 0)
{
    Console.WriteLine($"{remainingChange} cannot be given in change!");
}

2. There are no currency symbols.

This likely ties into how you define the "local" currency. It's nothing but an extra character to prepend to all values when printing the list.

3. There is no support for plural nouns.

E.g. if you want to be able to print things like 3 quarters (plural) but also 1 quarter (singular).

You would have to define two separate Name properties for a CoinType:

public string Name_Singular { get; set; }
public string Name_Plural { get; set; }

You might be tempted to add an "s" instead, but this falls apart in some cases:

Penny / Pennies
Most foreign currencies do not have a "given name" that is easily pluralized by adding an "s". Note the names I gave to the Euro coins, we lack a real name for the coin and simply list its value instead.


Generic solution to Hibernate's CriteriaQuery

Welcome to Code Review, I have seen your code and I have seen you encapsulated your createQuery method like below:
try { body method } catch (Exception exception) { exception.printStackTrace(); }

You are basically catching all NullPointerException cases and other runtime exceptions you can meet within your method with the Exception class, this is a sign something should be redesigned to avoid these situations.
About the paradigm you are following , you are implementing a personal version of the repository pattern, referring to structures like the jpa repository present for example in the spring framework. You can check while you are creating different queries worrying about the construction of a valid query (and this is the reason why you had to encapsulate your method in the try catch construct), it should be better using an already built class to do the same things with much less effort.


I have used one template engine in c# by name DotLiquid to resolve similar problems.

Readability: You have to extract your message template from the code to separate file. The template itself will lives its own life, usually independently from the code.
Maintainability:

Collect all required parameters and conditions in one place. Having conditions in your message tends to be next step in real message processing. By the way, anonymous classes from DotLiquid work well with your linq.
Then: template processing, message composing, and and putting it to queue to sent it. Sending operation itself could be time consuming and quite tricky

Thus I have handled hundreds of template based messages with rich HTML per day. Obviously, if you're going to write next smtp monster,  you'll write a more perfomance optimal solution. But using such template engine is good place to start.

And here is a code snippet:

// Template itself, assume that is has been loaded from file
var messageTemplate =
@"Deleted Order Item Information
------------------------------------

Delete Date:    {{Date}}
Delete Comment: {{DeletedComment}}
… other text";

// Parses and compiles the template
var template = DotLiquid.Template.Parse(messageTemplate);

// Renders the output
var messageBody = template.Render(DotLiquid.Hash.FromAnonymousObject(
    // Parameters
    new {
        Date = DateTime.Today,
        DeletedComment = "Some Comment"
    }));


Looping

Rather than setting a done flag and looping while not(done): (note: this would usually be written as simply while not done:), you could use a formulation more like:

while True:
    # do things
    if loop_should_end:
        break

This removes the need for the flag and makes the loop easier to follow.

Logic

At present, comp is set outside the loop, so the computer will always guess the same thing. This makes it rather too easy to win - you should move comp = random.randint(1, 4) (note whitespace) inside the loop.

Comparisons

The most obvious tweak is that the canonical replacement for lots of elifs in Python is a dictionary. In this case, you could look up a tuple (comp, guess) and print the result:

RESULTS = {
    (1, 3): "Rock beats scissors, too bad!",
    (2, 1): "Paper beats rock, tough luck!",
    ...
}

then access this inside the loop as easily as:

print(RESULTS.get((comp, guess), "It's a draw!"))

You could also simplify:

stop = input("Do you want to quit? ")
if stop.lower() == "y" or stop.lower() == "yes":

to:

if input("Do you want to quit? ").lower() in {"y", "yes"}:

Validation

You currently have no input validation, so the program could crash with a ValueError if the user types 'scissors' instead of 3. See e.g. "Asking the user for input until they give a valid response" for guidance on this.

Structure

Finally, it is bad practice to have all of your code running at the top level of the script - it makes it much more difficult to re-use later. Instead, I would do something like:

import random

RESULTS = {...}  # possible outcomes

def get_int_input(...):
    """Take valid integer input from user."""
    ...

def game_loop(...):
    """Main game loop."""
    ...

if __name__ == '__main__':
    game_loop()

This will work exactly the same if you run the script directly (see "What does if __name__ == “__main__”: do?") but allows you to use e.g. from wherever import get_input_int elsewhere, simplifying reuse and encouraging modular design.


Using default None values in Python when assigning split() to a tuple

try:
    track, num_tracks = track_info.split('/', 1)
except:
    track, num_tracks = track_info, None

Honestly, this is not a terrible solution. But you should almost never use except:; you should catch a specific exception.

Here is another way:

tracks, _, num_tracks = text.partition('/')
return int(tracks), int(num_tracks) if num_tracks else None