Your solution looks massively overcoded and woefully under-engineered - as if you had fixed on one particular solution facet (striding in the manner of the mod 6 wheel with unrolling of one revolution) of a particular approach (trial division) before analysing the problem.

Also, you didn't specify with regard to which quality you want your code to be compared to others. It is way too convoluted for scoring on elegance and simplicity, and it is way too slow for scoring on speed. Hence it is impossible to guess what you think its merit might be...

You obviously overlooked the bit about only scanning up to the square root of the current number in the pseudo code. This alone makes your code run much more slowly than the simplest, cleanest, most straightforward algorithm without any optimisations whatsoever. In other words, all that nonsense with wheeled striding and unrolling is for nought.

To answer your question: compared to the pseudo code your solution does not fare well at all.

If you are looking for speed in contexts that involve the enumeration of non-trivial numbers of primes then you might want to look at sieves. The Sieve of Eratosthenes is simple but offers an unbeatable bang for buck ratio.

For the piddling small numbers that Project Euler tasks deal in, I'd recommend going for simplicity, cleanness and elegance. At least that will give you are more thorough understanding of the algorithms. Forget all the half-understood supposed optimisations that you may have seen somewhere. They are only optimisations if they are needed, applicable, and applied correctly. In all other cases they are pessimisations, and they also keep you from understanding your own code, obviously.

Start simple. Measure. Add complications one by one and measure the effect.

Also, the work that is done fastest is the work that you don't do at all. Hence it always pays to look at a problem with an eye for opportunities not to do things. This includes donning first the glasses of the mathematician, then those of the algorithmist, and only last the loupe of the performance coder.

Answer to eirikdaude's question in the comment (posted here to give it space):

Wheeled striding can cut the workload by a certain (small) constant factor, by way of skipping a certain part of the numbers to be scanned.

Double striding cuts the load in half by skipping multiples of two; mod 6 striding skips a further third, mod 30 (2*3*5) striding a further fifth, and so on.

Effectiveness decreases as you add more small primes and the effort increases explosively. Double striding has the best bang-for-buck ratio in many cases, and it has other advantages (like regular strides, as opposed to the 2,4,2,4 step of the mod 6 wheel or the 48 step sequence of the mod 210 wheel). Higher wheel orders than 2 require careful coding and engineering to realise at goodish part of the theoretical speedup. Even the highest-order wheel with the most perfect coding can realise only a small constant speedup, typically not more than half an order of magnitude (without even considering the slow-down due to the much more complex code).

The column 'modulus' gives the wheel circumference, 'spokes' gives the number of hops in an increment sequence, 'ratio' gives the ratio of how many numbers need to be scanned compared to scanning all candidates.

The mod 30 wheel has a lot of nice advantages (starting with the fact that it maps nicely to eight-bit bytes) but cannot even double the performance of the mod 2 wheel, despite all the effort required for implementing it. Mod 210 wheels are occasionally found in heavy-duty industrial-grade code, and wheels higher than 13 (starting with 17, i.e. mod 510,510) definitely belong in the pyrrhic oddball category.

Use the 'ratio' column to gauge the limit on possible speedups due to workload reduction, and use the 'spokes' column to gauge the required code complexity (unrollings, sizes of lookup tables etc.).

Have a look at my answer in the topic Printing all the prime numbers between two bounds to see benchmarks for actual speedups gained from wheeled striding in a roughly similar setting. Compare actual speedups to the theoretical limits gleaned from the table, to the increase in code complexity despite the tricks employed, and how little this all accomplishes compared to algorithmic optimisations.

Morale: outside of academic papers, wheels can give you only a small constant boost.

On the other hand, scanning only candidate factors up to the square root of the current number instead of all candidates gives exponential benefits, several orders of magnitude already with the small Euler target (100001st prime).

I found it very rewarding to treat the Euler problems with respect, giving them the full math ponderation and pencil+paper preparation before throwing down the first line of code - and then striving for the simplest-possible, cleanest, most elegant code that I can manage (some might say this comes a couple decades too late, and they might not be entirely wrong about that...).


HackerRank challenge to count ways to climb a staircase, solved using Java Fork Join

The reason your code still runs slow is the huge increase in how often you calculate the smaller steps.

If you want to find the number of ways for N steps. You calculate (N-1) once, (N-2) 2 times, (N-3) 4 times ..., (N-10) 274 times, ... (N-24) over a million times

Fun fact: the number of times you calculate (N-x) = calculateNumberOfWays(x).

oopexpert solved this by storing all the previous steps in a cache, so you calculate each step exactly once. This means it now takes O(N) recursive calls the first time the algorithm is called. And only 1 call afterwards (since it now became a lookup instead of a calculation).

The downside is that you actually store all intermediate results. An alternative solution is to not use recursion at all but work your way from the bottom up and store only the last 3 steps. An implementation could look like this:

public static int calculateNumberOfWays(int stairHeight){
    if(stairHeight < 0){
        return 0;
    }
    if(stairHeight < 2){
        return 1;
    }
    int twoStepsBack = 0;
    int previousStep = 1;
    int currentStep = 1;
    for(int i = 2; i <= stairHeight; i++){
        int nextStep = twoStepsBack + previousStep + currentStep;
        twoStepsBack = previousStep;
        previousStep = currentStep;
        currentStep = nextStep;
    }
    return currentStep;
}

This also has the next big advantage of not using recursion at all. Recursion in java is only good if you have a limited number of recursive steps. Otherwise you'll quickly run into a StackOverFlowError.

For example, running the following tiny program:

public static void main(String[] args) {
    recursionTest(0);
}

public static void recursionTest(int step){
    System.out.println(step);
    recursionTest(step+1);
}

Threw an error after printing 11412. For your problem giving input of over 10000 would be insane so it's probably not really an issue though which brings me to the next problem with your solution.

Both our solutions can only solve up to stairHeight 36. At 37 we get an integer overflow. Changing it from int to long allows up to 72.

If you want to work with really BIG integers, java has a BigInteger class. I'll leave the conversion to BigInteger to you (it's not that hard, as long as you remember to use someBigNumber.add(otherBigNumber) instead of the normal +).

Just for fun I tried to run it with n=10000 but the result is huuuuge (as expected). To give an idea, if I take result.toString().lenth() it's still 2647. But at least the program calculates this almost instantly :)


Naming, naming, naming.

I've never heard of a "glob search", but I like the idea of implementing it in vba. One thing I know, is that I don't expect vba to read like python, so os.SEP would be clearer as os.PathSeparator, or even better, as path.Separator. Now I do have a tendency to go by .net naming standards, but really, anything other than a YELLCASE SEP would be cleaner and clearer.

Even the python community seems to agree that using os.path.sep over os.sep makes for clearer code - I'd use os.path.sep to make it very clear that it's the path separator and I recommend you use os.path.sep for clarity, since it's a path separator, not an OS separator. So I'd go with path.Separator, or path.Sep to maintain Pythonish naming.

  Looking at your linked question, I see @RubberDuck already recommended using better names for your constants; sorry to reiterate the same advice here.

Underscores

I know python loves snake_case, but in vba that kind of casing is potentially confusing (for class methods, more specifically) - I'd recommend sticking to language's PascalCase naming convention, and using a consistent camelCase for locals and parameters, for readability's sake (the actual VB/VBA conventions would go PascalCase all the way, but I find that maddening). I find pat_list would really benefit from simply being called patterns, or more accurately, patternParts - the _list suffix feels Hungarian, and seems to reflect the type, which could just as well be a regular Collection - I like that you're using your own List type though.

Parameters

The documentation I've found actually calls its sole parameter pathname:

  glob.glob(pathname)

  Return a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif), and can contain shell-style wildcards.

You haven't shown us how the client code might use this function, and it's.. pretty hard to guess just by looking at this post, without diving into the os implementation - I'd have to jump to the definition of os.SubItems to figure out why I need to pass a root parameter on top of a pattern.

Looking at your added example call, I think it could be worth combining the two parameters into a single pathName parameter, making the function callable like this:

?Glob("C:\users\ptwales\????-herp\*\*.txt").ToString

The difficulty would be to parse the string and differenciate the root from the pattern - splitting on path separator and using anything to the left of a part that contains any wildcard as the root, and everything else as the pattern, would certainly be possible, and would make it a better API IMO; the root and pattern parts are really two parts of the same string, that you've split in two because it's more convenient to do so since the implementation calls os.SubItems which wants a root parameter - in other words, splitting that string in two is really only leaking implementation details into the API.

Function as a local variable

I don't like this:

Set GlobRecurse = New List
...
GlobRecurse.Extend GlobRecurse(folder, pat_list, index + 1)

While this certainly works, it is rather ugly. Not because of multiple assignments (roughly requivalent to multiple [non-returning] return statements), but because the function's name is being used a local List variable, happily being appended to.

I would much rather see this:

Private Function GlobRecurse(ByVal root As String, ByVal pat_list As List, ByVal index As Integer) As List

    Dim result As List

    If index = pat_list.Count Then
        Set result = os.SubItems(root, pat_list(index))
    Else

        Set result = New List

        Dim folder As Variant
        For Each folder In os.SubFolders(root, pat_list(index))
            result.Extend GlobRecurse(folder, pat_list, index + 1)
        Next folder

    End If

    Set GlobRecurse = result

End Function

Especially with the recursive nature of the function, you'll want to avoid repeating the function's name for no reason. My rule of thumb, is to never read from the function identifier, only to assign it.


Streaming variable length integers from a file

It turns out it was possible to increase the speed about 12 times by using the offset argument of varint.decode to traverse the buffer rather than slicing read bytes off of the buffer for each value.

rs.on('data', function(buffer) {
  var buffer, value, byteLen, offset;

  if (remainder) {
    buffer = Buffer.concat([remainder, buffer]);
    remainder = null;
  }

  offset = 0;

  while(offset < buffer.length){
    // decode the value and check how many bytes it required
    value = vi.decode(buffer, offset);
    offset += vi.decode.bytesRead;

    if (offset <= buffer.length){
      // keep the result and update position in the buffer
      total += value;
    } else {
      // result is incomplete, store remainder to be prepended to the next chunk
      remainder = new Buffer(buffer.length - offset);
      buffer.copy(remainder, 0, offset);
    }
  }
});

Much better.

UPDATED to incorporate suggestions.


There's a few things you can do and different approaches depending on your personal preference. You could:

Extract the cases to pure functions

Extracting the logic to methods could help with readability and ease testing.

const addPicture = (state, action) => [
  {
    id: action.id,
    picture: action.picture,
    votes: 0,
  },
  ...state,
]

const likeUpPicture = (state, action) =>
  state.map(picture => {
    if (picture.id === action.id) {
      return {
        ...picture,
        votes: picture.votes + 1,
      }
    }

    return picture
  })

const likeDownPicture = (state, action) =>
  state.map(picture => {
    if (picture.id === action.id) {
      return {
        ...picture,
        votes: picture.votes - 1,
      }
    }

    return picture
  })

const pictures = (state = [], action) => {
  switch (action.type) {
    case ADD_PICTURE:
      return addPicture(state, action);
    case LIKE_UP_PICTURE:
      return likeUpPicture(state, action);
    case LIKE_DOWN_PICTURE:
      return likeDownPicture(state, action);
  }
}

Object destructuring/Object shorthand

Destructuring parameters could help signal that from a given action we are only concerned with certain properties. Shorthand notation can help keep the functions concise and reduce duplication.

const addPicture = (state, { id, picture }) => [
  {
    id,
    picture,
    votes: 0,
  },
  ...state,
]

const likeUpPicture = (state, { id }) =>
  state.map(picture => {
    if (picture.id === id) {
      return {
        ...picture,
        votes: picture.votes + 1,
      }
    }

    return picture
  })

const likeDownPicture = (state, { id }) =>
  state.map(picture => {
    if (picture.id === id) {
      return {
        ...picture,
        votes: picture.votes - 1,
      }
    }

    return picture
  })

Extract common logic

Since updating a certain element given an id is a common operation extracting the logic to a method might help reduce duplication and increase readability.

const updatePicture = (pictures, predicate, callback) =>
  pictures.map(picture => predicate(picture) ? callback(picture) : picture)

const likeUpPicture = (state, action) =>
  updatePicture(state, picture => picture.id === action.id, picture => ({
    ...picture,
    votes: picture.votes + 1,
  }))

const likeDownPicture = (state, action) =>
  updatePicture(pictures, picture => picture.id === action.id, picture => ({
    ...picture,
    votes: picture.votes - 1,
  }))

Define your reducer another way

For example, using createReducer can result in a compact reducer definition

const initialState = []

const pictures = createReducer(initialState, {
  [ADD_PICTURE]: addPicture,
  [LIKE_UP_PICTURE]: likeUpPicture,
  [LIKE_DOWN_PICTURE]: likeDownPicture,
})

Normalize State Shape

I've defined the methods inline for brevity but you could extract them as above. The official Redux link above gives a good explanation on why you might want to consider normalizing your state shape.

const byId = createReducer({}, {
  [ADD_PICTURE]: (state, { id, picture }) => ({
    ...state,
    [id]: {
      ...picture,
      id,
      votes: 0,
    }
  }),

  [LIKE_UP_PICTURE]: (state, { id }) => ({
    ...state,
    [id]: {
      ...state[id],
      votes: state[id].votes + 1,
    },
  }),

  [LIKE_DOWN_PICTURE]: (state, { id }) => ({
    ...state,
    [id]: {
      ...state[id],
      votes: state[id].votes - 1,
    }
  })
})

const allIds = createReducer([], {
  [ADD_PICTURE]: (state, { id }) => [
    ...state,
    id,
  ],
})

const pictures = combineReducers({
  allIds,
  byIds,
})


Bitmask, How to abstract those callbacks in this implementation

As implied from the comments under OP, it means that VarA is completly unrelated to VarB, they do completly different things.

If that is true, then it is all entirely obscured way of saying that based on some integer you need to do some arbitrary stuff. Arbitrary except that in all cases it returns a string.

Then all you need is encapsulate each callback in an interface:

interface StringGenerator
{
  public function getTheString(): string;
}

Whether each implementation has the right dependencies that arise from bits that are set in the flags which drive which StringGenerator implementation is used is an implementation detail.

class GeneratorABX implements StringGenerator
{
   private $serviceA;
   private $serviceB;
   private $serviceX;

   public function __construct($serviceA, $serviceB, $serviceX)
   {
     $this->serviceA = $serviceA;
     $this->serviceB = $serviceB;
     $this->serviceX = $serviceX;
   }

   public function getTheString(): string
   {
      return $this->serviceA->doStuff() . $this->serviceB->doOtherStuff() . $this->serviceX->toStuffWithB($this->serviceB);
   }
}

Use a DI container to handle the instantiation of all the implementations of StringGenerator.

function setupContainer(): \Psr\Container\ContainerInterface
{
  $container = new ContainerBuilder();
  $container->addService('serviceA', ServiceA::class);
  $container->addService('serviceB', ServiceB::class);
  $container->addService('serviceX', ServiceX::class);
  //...
  $prefix = 'stringGenerator';
  $container->addService($prefix . '1', GeneratorA::class);
  $container->addService($prefix . '3', GeneratorAB::class);
  $container->addService($prefix . '5', GeneratorAC::class);
  $container->addService($prefix . '35', GeneratorABX::class);

  $container->addService('test', Test::class, ['prefix' => $prefix]);
  return $container->buildContainer();
}

To compute flags from array of bools you can use this:

private static function getFlags(bool ...$values): int
{
  $flags = 0;
  $flag = 1;
  foreach ($values as $value) {
    if ($value) {
      $flags |= $flag; // or $flags += $flag;
    }
    $flag = $flag << 1; // or $flags *= 2;
  }
  return $flags;
}

And to get the right generator:

private function getGenerator($flags): StringGenerator
{
  return $this->container->get($this->prefix . $flags);
}

Final result:

class Test
{
  private $container;
  private $prefix;

  public function __construct(\Psr\Container\CotainerInterface $container, string $prefix)
  {
     $this->container = $container;
     $this->prefix = $prefix;
  }

  public function aMethod($values)
  {
     $flags = self::getFlags(...$values);

     return $this->getGenerator()->getTheString();
  }

  // and the private methods mentioned earlier
}

And call it like this:

$container = setupContainer();
$result = $container->get(Test::class)->aMethod($values);

EDIT: Altogether it is a bit analogous to a router. Router is first setup with a bunch of routes. Upon request, the router choses which controller is to be invoked based on the request and the set of routes. Then the appropriate controller is invoked and response is returned to the caller. The Test class is the router. The setup is done via DI container. The StringGenerators are the controllers. The flags are the request. And the resulting string is the response.

EDIT2: To avoid having a lot of StringGenerator implementations, we can instead have one method per each of the generators. Let me show a way how to do that:

class Test
{
  private $map = [
    1 => ServiceA::class,
    2 => ServiceB::class,
    32 => ServiceX::class,
    // ...
  ];

  private $container;

  public function __construct(\Psr\Container\ContainerInterface $container)
  {
    $this->container = $container;
  }

  public function aMethod(array $values): string
  {
    $services = $this->getServices(...$values);
    return $this->getTheString($services);
  }

  private function getServices(bool ...$values): array
  {
    $services = [];
    $flag = 1;
    foreach ($values as $value) {
      if ($value) {
        $services[$flag] = $this->container->get($this->map[$flag]);
      }
      $flag = $flag << 1; // or $flags *= 2;
    }
    return $services;
  }

  private function getTheString(array $services): string
  {
    $flags = \array_sum(\array_keys($services));
    $method = 'generate' . $flags;
    if (!method_exists($this, $method)) {
      throw new Exception('invalid combination of flags ' . $flags);
    }
    return $this->$method(...array_values($services));
  }

  private function generate1(ServiceA $a): string {}
  private function generate2(ServiceB $b): string {}
  private function generate35(ServiceA $a, ServiceB $b, ServiceX $x): string {}
}

function setupContainer(): \Psr\Container\ContainerInterface
{
  $container = new ContainerBuilder();
  $container->addService(ServiceA::class);
  $container->addService(ServiceB::class);
  $container->addService(ServiceX::class);
  //...
  return $container->buildContainer();
}

$container = setupContainer();
$test = new Test($container);
$result = $test->aMethod($values);

Or the same in a more general, more SOLID, although more verbose version:

interface ServiceProviderInterface
{
  public function getServices(bool ...$values): array;
}

class Services implements ServiceProviderInterface
{
  private $map = [
    1 => ServiceA::class,
    2 => ServiceB::class,
    32 => ServiceX::class,
    // ...
  ];

  private $container;

  public function __construct(\Psr\Container\ContainerInterface $container)
  {
    $this->container = $container;
  }

  public function getServices(bool ...$values): array
  {
    $services = [];
    $flag = 1;
    foreach ($values as $value) {
      if ($value) {
        $services[$flag] = $this->container->get($this->map[$flag]);
      }
      $flag = $flag << 1; // or $flags *= 2;
    }
    return $services;
  }
}

interface StringGeneratorInterface
{
  public function getTheString(array $services): string;
}

class Methods
{
  public function generate1(ServiceA $a): string {}
  public function generate2(ServiceB $b): string {}
  public function generate35(ServiceA $a, ServiceB $b, ServiceX $x): string {}
}

class StringGenerator implements StringGeneratorInterface
{
  private $methods;

  public function __construct(object $methods)
  {
    $this->method = $methods;
  }

  public function getTheString(array $services): string
  {
    $flags = \array_sum(\array_keys($services));
    $method = 'generate' . $flags; // could be a method name inflector responsibility
    if (!method_exists($this->methods, $method)) {
      throw new Exception('invalid combination of flags ' . $flags);
    }
    return $this->methods->$method(...array_values($services));
  }
}

class Test
{
  private $services;
  private $generator;

  public function __construct(ServiceProviderInterface $services, StringGeneratorInterface $generator)
  {
     $this->services = $services;
     $this->generator = $generator;
  }

  public function aMethod(array $values): string
  {
    $services = $this->services->getServices(...$values);
    return $this->generator->getTheString($services);
  }
}

function setupContainer(): \Psr\Container\ContainerInterface
{
  $container = new ContainerBuilder();
  $container->addService(ServiceA::class);
  $container->addService(ServiceB::class);
  $container->addService(ServiceX::class);
  //...
  $container->addService(Services::class);
  $container->addService(Methods::class);
  $container->addService(StringGenerator::class, ['methods' => Methods::class]);
  $container->addService(Test::class);
  return $container->buildContainer();
}

$container = setupContainer();
$result = $container->get(Test::class)->aMethod($values);
```


Iterating through a linked-list in a cleaner manner

Here's a bit of "light" refactoring. I've basically moved the element constructing into its own function to keep the while-block less crowded.

I'm also using some closure magic for the contextmenu, so it doesn't have to re-get the clicked item.

Lastly, I'm going more by the current ID rather than the current object when looping. This was to avoid the "get the id to get the object to get its id again" code that I see a few places in your version.

function buildListItem(item) {
  var listItem = $('<li/>', {
    contextmenu: function (event) {
      contextMenu.initialize(item); // available via closure
      contextMenu.show(e.pageY, e.pageX + 1);
      return false;
    }
  });

  listItem.append($('<img>', {
    'class': 'playlistItemVideoImage',
    'src':   'http://img.youtube.com/vi/' + item.get('video').get('id') + '/default.jpg'
  }));

  listItem.append($('<a/>', {
    text: item.get('title')
  }));

  return listItem;
}

var firstItemId   = activePlaylist.get('firstItemId'),
    allItems      = activePlaylist.get('items'),
    currentItemId = firstItemId,
    currentItem;

do {
  currentItem = allItems.get(currentItemId);             // get the obj
  if(!currentItem) {
    break;                                               // stop if it ain't there
  }
  playlistItemList.append(buildListItem(currentItem));   // build the list item element
  currentItemId = currentItem.get('nextItemId');         // get the next ID
} while(currentItemId && currentItemId !== firstItemId); // I'm assuming that valid IDs are thruth'y

Another thing to consider would be to use rawer HTML because it can be faster.


Calculating chromosome coverage of a set of regions

Try using the functions from then ByteString package instead of System.IO and String as they are much more efficient. Also, consider using lazy IO (using heGetContents from the link I sent) to read the huge input file as it will not load it all at once in memory while you parse it making it more efficient.


Here is a simple translation of the Wikipedia RC4 key-scheduling algorithm (KSA) and pseudo-random generation algorithm (PRGA) into Go.

package main

import "fmt"

// Key-scheduling algorithm (KSA)
func ksa(key []byte) []byte {
    s := make([]byte, 256)
    for i := range s {
        s[i] = byte(i)
    }
    j := byte(0)
    for i := range s {
        j += s[i] + key[i%len(key)]
        s[i], s[j] = s[j], s[i]
    }
    return s
}

// Pseudo-random generation algorithm (PRGA)
func prga(message, s []byte) []byte {
    text := make([]byte, len(message))
    i, j := byte(0), byte(0)
    for m := range message {
        i++
        j += s[i]
        s[i], s[j] = s[j], s[i]
        k := s[s[i]+s[j]]
        text[m] = message[m] ^ k
    }
    return text
}

// RC4 stream cipher
// http://en.wikipedia.org/wiki/RC4
func rc4(message, key []byte) []byte {
    return prga(message, ksa(key))
}

func main() {
    testRC4 := []struct {
        key, plain []byte
    }{
        {[]byte("Key"), []byte("Plaintext")},
        {[]byte("Wiki"), []byte("pedia")},
        {[]byte("Secret"), []byte("Attack at dawn")},
    }
    for _, test := range testRC4 {
        cipher := rc4(test.plain, test.key)
        fmt.Printf("%s\n", string(test.key))
        fmt.Printf("%s\n", string(test.plain))
        fmt.Printf("%X\n", cipher)
        fmt.Println(string(rc4(cipher, test.key)) == string(test.plain))
    }
}

Output:

Key
Plaintext
BBF316E8D940AF0AD3
true
Wiki
pedia
1021BF0420
true
Secret
Attack at dawn
45A01F645FC35B383552544B9BF5
true

References:

The Go Programming Language Specification

Integer overflow

Conversions

Mod 256 error:

  Constants

  There are boolean constants, rune constants, integer constants,
  floating-point constants, complex constants, and string constants.
  Character, integer, floating-point, and complex constants are
  collectively called numeric constants.

  A constant value is represented by a rune, integer, floating-point,
  imaginary, or string literal, an identifier denoting a constant, a
  constant expression, a conversion with a result that is a constant, or
  the result value of some built-in functions such as unsafe. The
  boolean truth values are represented by the predeclared constants true
  and false. The predeclared identifier iota denotes an integer
  constant.

  Numeric constants represent values of arbitrary precision and do not
  overflow.

  Constants may be typed or untyped. Literal constants, true, false,
  iota, and certain constant expressions containing only untyped
  constant operands are untyped.

  A constant may be given a type explicitly by a constant declaration or
  conversion, or implicitly when used in a variable declaration or an
  assignment or as an operand in an expression. It is an error if the
  constant value cannot be represented as a value of the respective
  type.

  Operators

  Operators combine operands into expressions.

Expression = UnaryExpr | Expression binary_op UnaryExpr .
UnaryExpr  = PrimaryExpr | unary_op UnaryExpr .

binary_op  = "||" | "&&" | rel_op | add_op | mul_op .
rel_op     = "==" | "!=" | "<" | "<=" | ">" | ">=" .
add_op     = "+" | "-" | "|" | "^" .
mul_op     = "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" .

unary_op   = "+" | "-" | "!" | "^" | "*" | "&" | "<-" .

  Comparisons are discussed elsewhere. For other binary operators, the
  operand types must be identical unless the operation involves shifts
  or untyped constants. For operations involving constants only, see the
  section on constant expressions.

  Except for shift operations, if one operand is an untyped constant and
  the other operand is not, the constant is converted to the type of the
  other operand.

For example, the compile error "constant 256 overflows byte" can occur as follows:

b := byte(42)
// constant 256 overflows byte
m := b % 256

The integer literal 256 is an untyped numeric constant. In the expression b % 256, it takes the type (byte) of the other operand b. A byte is an eight-bit unsigned integer that can represent the integers 0 to 255. Therefore, it's an error that the constant value 256 cannot be represented as a value of type byte: "constant 256 overflows byte."


The nextLine method is included in your print, so when you include it at the start then the first line ("Hello World") is stored in input and it is not touched again. Then, when the nextLine in the println method runs, it checks for the next line's content ("I am a file"), and prints "1 I am a file" because it is the first iteration of the loop. It then works successfully in getting and printing the rest of the lines of input.

The next method gets the next word in this context, so using it would cause "Hello" to be stored in input and, as input is never used again, forgotten. nextLine then gets the rest of the line's content and continues successfully for other input lines.

Neither methods are required to start with because the call to nextLine within println runs successfully for each iteration.


Clone array elements when multiplying by a scalar

I might do this:

grid = 9.times.map { "... " * 3 }

Or, better yet, as Naklion proposes in the comments:

grid = Array.new(9) { "... " * 3 }

to get the rows (as separate string instances), and this

grid.each_slice(3) { |rows| puts rows, "\n"  }

to print it similar to yours. But I wouldn't call either approach "idiomatic", just variations on a theme. I don't know if anything really idiomatic can be said to exist for this

However, it might be easier to approach this from a higher level, rather than rely on a string representation. I.e. parse the input grid into Cell, Row etc. objects (I'm obviously assuming this is sudoku we're talking about).
Of course, if you have a clever idea that relies on string manipulation, then go for it!

My point is more that I know you can get far with, say, bitwise representations of sudoku, but implementing that in Ruby (while totally possible) seems "crude". Ruby's not geared toward twiddling bits, but toward more high-level OOP abstractions. It'd be right at home in C/C++, though.

*) I'd go with "rubyesque" or just "ruby" as in "the ruby way of doing things" :)


You should aim to declare variables at initialization when possible. Pre-initialized variables are suspicious and make me wonder whether they are being optionally assigned or edited elsewhere.
       // string userAnswer;

       Console.WriteLine("Calculater or Square Root Calculater?");
       Console.WriteLine("-Please respond with Calculater or Square");
       string userAnswer = Console.ReadLine().ToUpper();
       Console.Clear();


This is going to be a brain dump -type review. Feel free to jump straight to TL;DR if my thinking out loud gets annoying :)

Let's start with the function's signature:

Public Function FPDA(ByVal EffDate As Date, ByVal DOB As Date, ByVal Mode As Integer, ByVal Age As Integer) As Date

You're taking all parameters ByVal, which is good - it means the function cannot alter these values if it tried, it's receiving a copy of what the caller gave it.

I can live with EffDate, DOB and Age identifiers. But as I've mentioned in the comments, Mode is a no-no, especially if it's a magic Integer variable.

Looking at the body of the function I think what Mode is really about is something more like this:

Public Enum TimeSpanType
    Year
    HalfYear
    Quarter
    Month
End Enum

So we can have a body like this:

Select Case Mode
    Case TimeSpanType.Year
        Do Until EffDate > DateAdd("yyyy", Age, [DOB])
            EffDate = DateAdd("yyyy", 1, EffDate)
        Loop

    Case TimeSpanType.HalfYear
        Do Until EffDate > DateAdd("yyyy", Age, [DOB])
            EffDate = DateAdd("m", 6, EffDate)
        Loop

    Case TimeSpanType.Quarter
        Do Until EffDate > DateAdd("yyyy", Age, [DOB])
            EffDate = DateAdd("q", 1, EffDate)
        Loop

    Case TimeSpanType.Month
        Do Until EffDate > DateAdd("yyyy", Age, [DOB])
            EffDate = DateAdd("m", 1, EffDate)
        Loop

End Select

Return EffDate

It's more readable and less error-prone, but it's doing the exact same thing. It gives another meaning to the received parameter EffDate, which might work now, but it's error-prone, and this is where ByVal is saving you.

I would make a copy of EffDate:

Dim result As Date
result = EffDate

And change the last line to:

Return result

Now every branch looks like a Copy+Paste party. How about this:

Dim interval As String

Select Case Mode
    Case TimeSpanType.Year
        interval = "yyyy"

    Case TimeSpanType.HalfYear
        interval = "m"

    Case TimeSpanType.Quarter
        interval = "q"

    Case TimeSpanType.Month
        interval = "m"

End Select

And then you can just do:

Do Until result > DateAdd(interval, Age, [DOB])
    result = DateAdd(interval, 1, result)
Loop

But this is rather ugly. DateAdd lives in the Microsoft.VisualBasic namespace, which only exists to make VB6 developers happy with transition to the Wonderful World of .NET... but by using that namespace, you're missing out on everything the Wonderful World of .NET has to offer!

Date is just a language alias for System.DateTime, which exposes the .NET way of life - exposing methods like AddMonths, which is really all you need here:

Dim monthsToAdd As Integer

Select Case Mode
    Case TimeSpanType.Year
        monthsToAdd = 12

    Case TimeSpanType.HalfYear
        monthsToAdd = 6

    Case TimeSpanType.Quarter
        monthsToAdd = 3

    Case TimeSpanType.Month
        monthsToAdd = 1

End Select

Or better yet - get rid of the Select...Case altogether, because Enums are Integers under the hood:

Public Enum TimeSpanType
    Year = 12
    HalfYear = 6
    Quarter = 3
    Month = 1
End Enum

TL;DR

And then you can just do this:

Dim interval As Integer
interval = CType(Mode, Integer)

Do Until result > DOB.AddMonths(interval*Age)
    result = result.AddMonths(1)
Loop

And now that you've got code that's easy to read, follow and maintain, you can start thinking about how the loop could be simplified.

Strive to get rid of Imports Microsoft.VisualBasic anywhere you see it. VB.NET is .NET, not VB6. Your code will only get better.


Well, the code works. It's definitely not as efficient as it could be, though; you're using floating-point math to accomplish something that could be done entirely in integer operations.

You forgot to #include all the headers you need. By my count, that's

#include <fenv.h>  // feclearexcept
#include <limits.h>  // INT_MIN
#include <math.h>  // floor, log10
#include <stdlib.h>  // abs
#include <errno.h>  // errno
#include <string.h>  // memset

Plus wherever print_error_msg comes from; that's an undefined symbol in the code you posted. I'm guessing it does something similar to perror(NULL)?

If I were writing itoa, I'd start by assuming that I already had the memory allocation taken care of. Then filling the buffer is as easy as what you wrote:

size_t result_length = <some magic>;
char *result = malloc(result_length + 1);
result[result_length] = '\0';
if (number < 0) {
    result[0] = '-';
    number = -number;
}
for (int i = result_length, n = number; n != 0; n /= 10) {
    result[--i] = '0' + (n % 10);
}

(I'd special-case 0 and INT_MIN at the top of the function so that we don't have to worry about them down here.)

Then the only missing piece is the <some magic>. But that's easy — we just need to write some code to count the digits of number. And we already have some code to print the digits of number! So I'd just repeat that code again.

int result_length = (number < 0);
for (int n = number; n != 0; n /= 10) {
    result_length += 1;
}

There — the only headers we needed were <stdlib.h> (for malloc) and possibly <limits.h> (for INT_MIN).

Notice that I wrote '0' + x where you'd written (char)((int)'0' + x). C isn't Pascal or Python; there's no need to jump through hoops like chr(ord('0') + x) here. Characters in C are small integers, and you can do math on them just as you can on any other integer type.

Moreover, you should do math on character types, if it eliminates the need for a cast operation. Type-casting in C and C++ is a code smell; if you really need a cast, something is horribly wrong with your code. In this case, fortunately, you don't need one.

Another place your code uses casts is

void *ret;
...
((char*)ret)[--index] = '\0';

Kudos for using '\0' instead of 0; that's a nice way to indicate to the reader what this particular zero semantically represents. But kill the cast! In this case, you think you need the cast because ret is a void*. However, the only places you refer to ret, you cast it to char*. This is a huge honking sign that ret really wants to be char*.

char *ret;
...
ret[--index] = '\0';

Problem solved. ret had no business being a void* in the first place.

No comment on the theoretical correctness of the floating-point stuff; because, as I said, I wouldn't have used floating-point to print integers in the first place. I have tested your code on all 4 billion 32-bit integers, though, and can report that it works fine in practice.


Properly disposing of a WCF connection using IDisposable

The adviced way to call a service endpoint when the connection is not an open stream, is to have the lifecycle of you client in line with the operation you are calling.

So rather than storing an instance of the client..

private WebService()
    {
        client = new MyWebServiceContractClient();
    }

You should create a client on demand. To work around the known issue on Dispose, a solid solution is available.

public double GetAnswer()
    {
        try
        {
            using (new MyWebServiceContractClient()) {

                //do some work
                return answer;
            } // <- there is a known issue here: https://stackoverflow.com/questions/573872/what-is-the-best-workaround-for-the-wcf-client-using-block-issue
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return -1;
        }
    }


Since the question gives a couple of guarantees about the input, take advantage of them. If you want to communicate these preconditions, assert them. Something like

string timeConversion(string s) {
    // Assume input is in the format hh:mm:ssAM or hh:mm:ssPM
    assert(s.length() == 10);
    int size = s.length();
    ...

...
if(s[size-2]=='A'){
    string hh = s.substr(0,2);
    int h = stoi(hh);
    ...
else{
    string hh = s.substr(0,2);
    int h = stoi(hh);
    ...

You do the same thing no matter which branch is taken. You can hoist this in front of the if statement

string hh = s.substr(0, 2);
int h = stoi(hh);
if (s[8] == 'A') {
    ...
} else {
    ...
}

After the previous step, the logic left is fairly straight-forward.

If it is AM and the hours read 12, set hh = "00". Otherwise do nothing.
If it is PM add the hours read 12, do nothing. Otherwise add 12 to the hours.

This is good. One thing to note is that two paths lead to the same conclusion of do nothing or don't change the time. I would keep the exact same logic and restructure a little to avoid redoing work.

...
if (s[8] == 'A') {
    if (h == 12) {
        // 12:mm:ssAM -> 00:mm:ss
        hh = "00";
    }
} else if (h != 12) {
    // 12:mm:ssPM -> 12:mm:ss, otherwise add 12 hours.
    hh = to_string(h + 12);
}

return hh + s.substr(2, 6);


Vanilla JS/CSS -- set of buttons to trigger sliders by transitioning height value

Redundant CSS The rules in .dyn-slide:not(.active) already exist in the .dyn-slide block, so they're not needed - feel free to remove them entirely. (The .dyn-slide.active { height: auto; isn't being used either, since the height is being set directly via JS)
Semicolons or not? To be stylistically consistent and to reduce bugs, either use semicolons everywhere they're appropriate, or (if you consider yourself skilled enough not to run into problems with ASI) don't use semicolons. Choose a style you want, then enforce it.
Use const, avoid var - you're using modern syntax, which is great, but you're using var in a few places. In ES2015+, best to always use const (or, if you need to reassign, let), but var isn't a great idea - it has weird rules like function scope instead of block scope, and automatically assigns its variables to the global object when used on the top level, among other weirdness. (ESLint rule: no-var, I highly recommend using a linter to automatically prompt you to fix code quality smells)
Unused variable You do
} else {
  var height = slide.clientHeight + 'px';

but never use the height variable - remove it. (ESLint rule: no-unused-vars)
Whole else block is redundant Or, remove the whole block there: the element's height has been set to 0 at the beginning of the function, so setting it to 0 again won't change anything.
You can save the last active slide in a variable instead of looping over all slides at the beginning of the click handler.
Trigger reflow instead of using setTimeout Rather than setTimeout, you can trigger a DOM reflow by reading a style property from the DOM, for example, access the offsetHeight of an element. This allows you to code synchronously:
Indentation Some of your indented blocks are not properly aligned. Consider using an IDE to automatically indent correctly - this'll make it easier for you and others to understand the code at a glance.
Refactored:

const slides = document.querySelectorAll('.dyn-slide');
const buttons = document.querySelectorAll('.dyn-gallery-btn');
let lastSlide;

buttons.forEach((button, i) => {
  button.addEventListener('click', () => {
    const slide = slides[i];
    const wasActive = slide.classList.contains('active');
    if (lastSlide) {
      lastSlide.classList.remove('active');
      lastSlide.style.height = 0;
    }
    lastSlide = slide;
    if (wasActive) {
      return;
    }
    slide.classList.add('active');
    slide.style.height = 'auto';
    const newHeight = slide.clientHeight + 'px';
    slide.style.height = '0px';
    slide.offsetHeight; // Force a reflow
    slide.style.height = newHeight;
  })
})
.dyn-slide {
   background: red;
   transition: height .5s ease-in-out;
   height: 0;
   overflow: hidden;
}

.dyn-slide.active {
  /* Height will be set to either auto or 0 by JS */
  overflow: hidden;
}
<button  class="dyn-gallery-btn" type="button"> one </button>
<button  class="dyn-gallery-btn" type="button"> two </button>

 one text

 two text

<button  class="dyn-gallery-btn" type="button"> three </button>
<button  class="dyn-gallery-btn" type="button"> four </button>

 three text

 four text


"Longest Collatz sequence" in C slower than in Python 3

Assuming int is 32 bit long on your system, an integer overflow occurs on c with upper = 1000000. The multiplication in c = 3 * c + 1 can cause c to grow quite large, eventually exceeding the \$2^{31}-1\$ upper limit of a 32-bit signed integer, and thus rolling over into negative values. Obviously, the algorithm does not work correctly for negative values of c, and gets stuck.

In Python on the other hand, none of this occurs, since it extends integers to arbitrary length automatically, and thus avoids overflows.

You can "postpone" this problem (i.e. make your program work for larger values of upper) by using larger (and unsigned) integer types, such as uint64_t from stdint.h for c up to \$2^{64}-1\$.

However, if you want your C code to work for arbitrarily large upper values, you'll have to use an external library for arbitrary-precision integers, such as GNU GMP (or roll your own, which is really not advisable except as an exercise). The disadvantage is slightly worse performance, which would likely be comparable to the Python version for such a simple and arithmetics-heavy program.


Optimized pulling items out of arrays in nested objects

Although at the time of writing, flatMap is not in every browser (according to MDN not in Edge and Samsung Internet);

data.flatMap(obj => obj.items).filter((e, i, ary) => ary.indexOf(e) == i)

Although, you could check the uniqueness from the result array in your code, and push only if not in there, to save one loop over the array.

Another option would be a reducer like

uniqItems = (acc, {items}) => acc.concat(items.filter(item => acc.indexOf(item) < 0))

to data.reduce(uniqItems, []).


Locating contact information from a CSV spreadsheet

You would do well to use generator functions to break this down into parts that might be re-usable for other steps in your pipeline.

For example, the first thing you do in your loop is read a row from the CSV file and process some of the fields. That's a good candidate, right there:

def normalized_csv_rows(reader):
    """Filter CSV data, cleaning up email & web fields.        """
    for row in reader:
        email, web, phone, locn = row
        email = email.lower().strip("[]'")
        web = web.strip("[]'")
        yield email, web, phone, locn

The next obvious thing I see is that you require three of your fields to be unique. That's another good candidate for a filtering generator:

def require_unique_field(num, reader):
    seen = set()
    for row in reader:
        field = row[num]
        if field not in seen:
            seen.add(field)
            yield row

You can stack these up to require several unique fields. Finally, you require the location field to be "truthy", which generally means non-empty. So let's go with that:

def require_nonempty_field(num, reader):
    for row in reader:
        if row[num]:
            yield row

With these tools in hand, let's look at your for loop:

for row in readCSV:
    website = row[1].strip('[]\'')
    email = row[0].lower().strip('[]\'')
    phonenumber = row[2]
    location = row[3]
    if location:
        if website not in websites:
            if phonenumber not in phonenumbers:
                if email not in emails:
                    for x in data:
                        if x in website:
                            for r in remo:
                                if all(r not in website for r in remo):
                                    if phonenumber not in phonenumbers:
                                        if email not in emails:
                                            websites.add(website)
                                            phonenumbers.add(phonenumber)
                                            emails.add(email)
                                            locations.append(location)
                                            mylist = zip(emails, websites, phonenumbers, locations)

The first few lines are taken care of by our normalization function:

reader = readCSV
reader = normalized_csv_rows(reader)

The if location: is our require_nonempty_field function, with a field number of 3:

reader = require_nonempty_field(3, reader)

The lines like if email not in emails: (which occurs twice - I hope somebody was drunk for St. Patty's day) can be replaced with our require_unique_field function:

reader = require_unique_field(0, reader)
reader = require_unique_field(1, reader)
reader = require_unique_field(2, reader)

So we can rewrite the top part like this:

EMAIL, WEBSITE, PHONE, LOCATION = 0,1,2,3

data = ["electric", "electricians"]
# remove urls that have these strings,  only works with the first string
# but not second one.
remo = ["listings", "nationwide", "/mip", "car", "/locations", "/YB", "?utm_source", "/locallocksmithnearby",
        "key.me", "find-locksmiths-near-me", "premium-locksmiths", "locksmithnearyou24hrs"]
fil = 'newfiles/output8.csv'

with open(fil) as csvfile:
    reader = csv.reader(csvfile, delimiter=",")
    reader = normalized_csv_rows(reader)
    reader = require_nonempty_field(LOCATION, reader)
    reader = require_unique_field(EMAIL, reader)
    reader = require_unique_field(WEBSITE, reader)
    reader = require_unique_field(PHONE, reader)

Now, however, we come to the tricky part. You have a list of "must contain" items, data. But that list includes one word that is a prefix of another word.

If electricians is part of website, then electric is also part of website, since electric is a substring of electricians. The result is that this will tend to cause those rows containing electricians to be emitted twice. I suspect this is why you have two copies of the if email in emails: conditionals included in the stack.

A better idea would be to pre-process the filter words, to eliminate the longer word:

data.sort(key=len)
data2 = []
for word in data:
    for prefix = data2:
        if word.startswith(prefix):
            break
    else:
        data2.append(word)
data = data2
del data2

Once we have a "clean" list, you can write another generator function. Better still, we can make the cleanup part of the generator function, to
make sure the user doesn't give us bad data:

def field_contains(num, strings, reader):
    """Read rows from reader and pass those which have any member of
    strings as a substring of field num.

    """
    strings_by_len = sorted(strings, key=len)
    substrings = []
    for word in strings_by_len:
        for prefix in substrings:
            if word.startswith(prefix):
                break
        else:
            substrings.append(word)

    for row in reader:
        field = row[num]
        if any(s in field for s in substrings):
            yield row

And you can add that to the constraints on the reader:

reader = field_contains(WEBSITE, data, reader)

Similarly, you have a "blocking" list, where some substrings must not be in the website field. This is a similar function to the last, except you want to yield the row when the condition fails:

if not any(s in field for s in substrings):
    yield row

Then add that to the constraints:

reader = field_does_not_contain(WEBSITE, remo, reader)

At this point, reader is a stack of generators that will only yield the rows you want. However, not a single one of them has been read! So you can just pass this in to your output code:

writer.writerows(reader)

Please note, however, that it's important to keep this nested below the with open(fil) statement, since none of the data has been read in! The structure should look like:

with open(fil) ...:
    reader = ...
    with open(whatever) as outputcsv:
        writer = ...
        writer.writerows(reader)


Mixing chrome.i18n (internationalization method) into templates

I doubt performance will take much of a hit by passing chrome.i18n into your templates, but I still don't think you should do it.

Templates should be solely for visualising data where possible, sometimes this requires a small amount of logic, but you should keep it out whenever possible. I would much rather see this:

var i18n = chrome.i18n;

...

templateHelpers: function () {
    return {
        hdMessage: i18n.getMessage('hd'),
        instant: this.instant
    };
}

-

<% if( video.get('highDefinition') ) { %>
    <%= hdMessage %> ·
<% } %>

In the long run this prevents your templates from being cluttered with internationalisation specific code, which will also be useful if you ever need to change the library.


Automatic Databinding of controls to Model

IMHO Anything that relies on controls' Tag property is fishy. In 15 years of VB4-5-6/VBA and then WinForms development, every single time I saw the Tag property assigned, there was a better way to solve the problem. I think using that property more often than not violates the principle of least surprise (POLS), because it's not typical to put anything in there - if anything it means a control is begging to be derived from that control's class, and featured with the relevant properties - which is obviously too much trouble to be worth the while.
That's my rant against using the Tag property. That said it looks rather clean, much cleaner than this similar question, but it suffers from the same issue:

WinForms applications are better off with the Model-View-Presenter pattern.
[...] if you want to simulate WPF behavior in WinForms, the real thing will be much less trouble, and leave you with much cleaner code.
Sorry if that's not what you wanted to hear...

For a big project I'd seriously consider either MVP or MVVM with WPF.


Taking objects from literal with many objects

you can use the map function provided for all arrays. You would need to make sure that response.data always returns an array, even in the case where nothing was returned from the api otherwise you can get an error.

var newArray = response.data.map(function(data) {
  return {amount: data.amount}
});

would get you what you are looking for.


If you like new features, and even experimental features, you can make your code a lot cleaner.

Concepts

A lot of those arcane SFINAE techniques will be obsolete once concepts are out, and concepts are already available in an experimental state with the last versions of gcc (enable them with the -fconcepts option):

template <typename Container, typename Value>
concept bool HasFindFunction = requires(Container c, Value v) {
    c.find(v);
};

... and that's it for your trait.

if constexpr

To specialize the contains function, you can rely on C++17 if constexpr. It's a compile-time if, in which only the chosen branch has to be well-formed. So, here's what you could write:

template <typename Container, typename Value>
auto find(Container&& cont, Value&& val) {
    if constexpr (HasFindFunction<Container, Value>) {
        std::cout << "member find\n";
        return cont.find(val);
        }
    else {
        std::cout << "algorithm find\n";
        return std::find(std::begin(cont), std::end(cont), val);
    }
}

I replace contains by find, because I find it a pity to make a hard won information (the item position) go to waste. You can then write contains on top of it.

Complete working example (g++ prog.cc -Wall -Wextra -std=gnu++2a -fconcepts)

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

template <typename Container, typename Value>
concept bool HasFindFunction = requires(Container c, Value v) {
    c.find(v);
};

template <typename Container, typename Value>
auto find(Container&& cont, Value&& val) {
    if constexpr (HasFindFunction<Container, Value>) {
        std::cout << "member find\n";
        return cont.find(val);
        }
    else {
        std::cout << "algorithm find\n";
        return std::find(std::begin(cont), std::end(cont), val);
    }
}

template <typename Container, typename Value>
auto contains(Container&& c, Value&& v) {
    return std::end(c) != find(c, std::forward<Value>(v));
}

int main() {
    std::map<int, int> map;
    std::vector<int> vector;

    find(map, 5);
    contains(vector, 5);
}


You could let your class implement OnClickListener

public class MainActivity extends Activity implements OnClickListener{
    ...
}

and then use the onClickfunction like this:

public void onClick(View v)
{
    switch (v.getId())
    {
        case R.id.button1:
            mp.start();
            break;
        case R.id.button2:
            mp.pause();
            break;
        case R.id.button3:
            mp.stop();
            break;
        default:
            break;
    }
}

That way you have all actions that happen on a press of a button in the same place in your program.

You should also change the ID to something more meaningful, eg. play, pause, stop.
This makes your code far more maintainable and easier to understand which Button does what just by skimming the code of the MainActivity(which you also might want to rename to something like MediaPlayerActivity incase you decide to add additional Activity classes, for example to select a new song.

Additionally I would advise you to change the visibility of the Buttons to private, rather than default.


Need help with my code using a base class?

I think it would be better if Session.Begin() returned an IDisposable, which would call Session.Close() in its Dispose(). That way, you can enclose the whole method inside using and you don't have to worry about calling it properly. (For example, it's not called in your code if the code is invalid.)
You can extract the creation of I or O into a generic method. It will also have a delegate parameter that represents the type-specific fill method.
It's better if you throw a specific exception (maybe something like InvalidCodeException), not Exception.

With these changes, the code would look like this:

private P CreateP<T>(PDetail pDetail, Action<T> fillT) where T : P, new()
{
    var p = new T { PDetail = pDetail };
    FillBaseP(p);
    fillT(p);
    return p;
}

public P GetP()
{
    using (this.Session.Begin())
    {
        var pDetail = GetPDetail();

        if (pDetail == null)
            return null;

        switch (pDetail.Code)
        {
        case "1":
            return CreateP<I>(pDetail, FillI);
        case "3":
            return CreateP<O>(pDetail, FillO);
        default:
            throw new InvalidCodeException("Code is invalid");
        }
    }
}

  If I'm constantly checking type like If(var is O) or If(var is I) I feel as though I'm doing something wrong. Is this the case?

Yeah, probably. But it's hard to tell (and advise a better approach) without seeing the code.


Hiding and showing spreadsheet rows based on cell value

You have indented the blocks, but not the scopes.

Private Sub DoSomething()
    '<~ here
End Sub

Might not be the case here, but in a module with multiple procedures, it's much easier to glance at the code and see where scopes begin & end when their contents are indented.

Application.ScreenUpdating = False

That's great: Excel isn't going to be wasting cycles repainting itself everytime you make a change. There's a problem though:

Application.ScreenUpdating = True

If there's a runtime error anywhere between these two instructions, execution jumps out of the procedure scope and ScreenUpdating never gets set back to True, and because the error is never handled, well, you have a potentially unhandled runtime error waiting to be thrown without warning in your user's face.

Right here:

If Range("R" & i) = "Show" Then

If Range("R" & i) contains an error value, VBA can't compare it to a String literal, and boom, runtime error 13, type mismatch. You should always assume that a worksheet cell can contain an error (#VALUE!, #NA, #REF!, etc.), and shield your code against that classic mistake using the IsError function:

If Not IsError(Range("R" & i)) Then

In any case, whenever you toggle Application state, the procedure should have an On Error statement that ensures state is cleanly toggled back in case of an error.

Private Sub DoSomething()
    On Error GoTo CleanFail
    Application.ScreenUpdating = False

    '...do stuff...

CleanExit:
    Application.ScreenUpdating = True
    Exit Sub
CleanFail:
    '...handle error...
    Resume CleanExit
End Sub

Dim iLastRow As Variant

This means to be a row number, and given the Systems Hungarian prefix (drop it!), it has all looks of an Integer. It should be a Long, because a 16-bit signed integer couldn't work with more than 32,767 rows - and a worksheet can have many, many more rows than that. Internally, the VBA7 runtime allocates a 32-bit integer for it anyway, so you might as well use a Long.

Except you can't.

iLastRow = Range("R1:R" & Cells(Rows.Count, "R").End(xlUp).Row).Value

Because it's actually an array, that contains every single value in column R!

That's actually not a bad idea in itself, except the only thing you're using it for, is to determine how many "cells" it contains - here:

For i = 1 To UBound(iLastRow, 1)

Write code that says what it means, and means what it says. If you name a variable "last row", make it hold the last row number - not a variant array that contains every single value in a column. Or, name it visibilityToggleColumn or something similar.

i being an Integer is also problematic. Use a Long, so you don't need to worry about how many rows there might be - there's no reason to use an Integer for this.

This Boolean assignment is a common pattern:

If Range("R" & i) = "Show" Then
    Rows(i).EntireRow.Hidden = False
Else
    Rows(i).EntireRow.Hidden = True
End If

So common, the latest 2.1 pre-release of Rubberduck includes an inspection (and a quick-fix) for it:

  Boolean literal assignment in conditional

  A member is assigned True/False in different branches of an If statement with no other statements in the conditional. Use the condition directly to assign the member instead.

Applying the quickfix turns this:

    If Range("R" & i) = "Show" Then
        Rows(i).EntireRow.Hidden = False
    Else
        Rows(i).EntireRow.Hidden = True
    End If

Into this:

    Rows(i).EntireRow.Hidden = Not (Range("R" & i) = "Show")

Which can then be simplified to this:

    Rows(i).EntireRow.Hidden = Range("R" & i) <> "Show"

Rubberduck also complains about implicit references to ActiveSheet - these are the root cause behind roughly 40%1 of all VBA questions asked on Stack Overflow, every day.

Unqualified Range, Rows, Columns, Names, and Cells calls, all implicitly refer to the ActiveSheet... when you're in a standard module. When you're in a worksheet module's code-behind, they implicitly refer to that sheet. The simple fact that the same identical code does different things depending on where it's written, should be enough to be explicit about it.

Since this is all happening behind Sheet1, IMO the ideal qualifier would be Me. So instead of this:

Sheet1.Cells.EntireRow.AutoFit

I would have that:

Me.Cells.EntireRow.AutoFit

And then here:

iLastRow = Range("R1:R" & Cells(Rows.Count, "R").End(xlUp).Row).Value

I'd have this:

iLastRow = Me.Range("R1:R" & Me.Cells(Me.Rows.Count, "R").End(xlUp).Row).Value

Note that if you're in the code-behind for Sheet1, you can interchangeably use Sheet1 and Me, ...but you shouldn't. Consistency is king. Seeing Me as a qualifier immediately reminds the reader that they're looking at code that's in a class module (a Worksheet is a class, Sheet1 is a Worksheet instance; ditto for Workbook and ThisWorkbook). On the other hand, qualifying with a specific worksheet's codename makes that code usable from anywhere, i.e. if you want to move that code from Sheet1.Worksheet_Change to the ThisWorkbook.SheetChange handler, nothing would have to change and it would work identically.

Okay got it. Now what about performance?

Worksheet manipulations are inherently slow. Reading & writing cell values is slow, and resizing and formatting cells is even slower.

Surely you know of the "hold Ctrl down" trick? Hold down the Ctrl key, click on the row headings you want to hide, right-click once, pick "hide" once, and poof all the selected rows get hidden at once!

You can do exactly the same thing in VBA, using a little Union helper function - something like this:

Private Function CombineRanges(ByVal source As Range, ByVal toCombine As Range) As Range
    If source Is Nothing Then
        Set CombineRanges = toCombine
    Else
        Set CombineRanges = Union(source, toCombine)
    End If
End Function

Now all you'll be doing with Range objects, is dereferencing them - as opposed to accessing their members and mutating their state.

Before I share the resulting code, I'd like to add that there are probably certain things you want to abstract away into other members. I'd declare module-level Const values, to avoid magic literals, and I'd probably expose a Property Get members or two, to abstract as many concepts and expose them to other code if they need to - otherwise make them Private, doesn't hurt.

So anyway, here's my version:

Option Explicit
Private Const VisibilityToggleColumn As Long = 18 'column "R"
Private Const VisibilityToggleValue As String = "Show"

Public Property Get LastRow() As Long
    LastRow = Me.Cells(Me.Rows.Count, VisibilityToggleColumn).End(xlUp).Row
End Property

Public Property Get VisibilityToggleColumnValues() As Variant
    VisibilityToggleColumnValues = Me.Range(Me.Cells(1, VisibilityToggleColumn), Me.Cells(LastRow, VisibilityToggleColumn)).Value
End Property

Private Sub Worksheet_Change(ByVal Target As Range)

    On Error GoTo CleanFail
    ToggleApplicationState False

    Me.Cells.EntireRow.AutoFit

    Dim rowsToHide As Range
    Dim rowsToShow As Range

    Dim visibilityToggleValues As Variant
    visibilityToggleValues = VisibilityToggleColumnValues

    Dim i As Long
    For i = LBound(visibilityToggleValues) To UBound(visibilityToggleValues)

        Dim currentCell As Range
        Set currentCell = Me.Cells(i, VisibilityToggleColumn)

        Dim currentToggle As Variant
        currentToggle = visibilityToggleValues(i, 1)

        If IsError(currentToggle) Then
            'if a cell contains an error, we don't want to hide it
            Set rowsToShow = CombineRanges(rowsToShow, currentCell)
        Else
            If StrComp(currentToggle, VisibilityToggleValue, vbTextCompare) = 0 Then
                Set rowsToShow = CombineRanges(rowsToShow, currentCell)
            Else
                Set rowsToHide = CombineRanges(rowsToHide, currentCell)
            End If
        End If

    Next

    If Not rowsToShow Is Nothing Then rowsToShow.EntireRow.Hidden = False
    If Not rowsToHide Is Nothing Then rowsToHide.EntireRow.Hidden = True

CleanExit:
    ToggleApplicationState True
    Exit Sub
CleanFail:
    MsgBox "Unhandled error in 'Worksheet_Change' handler: " & Err.Description, vbExclamation
    Resume CleanExit
    Resume
End Sub

Private Sub ToggleApplicationState(ByVal enabled As Boolean)
    Application.ScreenUpdating = enabled
    Application.EnableEvents = enabled
    Application.Calculation = IIf(enabled, xlCalculationAutomatic, xlCalculationManual)
End Sub

Private Function CombineRanges(ByVal source As Range, ByVal toCombine As Range) As Range
    If source Is Nothing Then
        Set CombineRanges = toCombine
    Else
        Set CombineRanges = Union(source, toCombine)
    End If
End Function

Notice I'm using the StrComp function to compare the strings with vbTextCompare - this ensures a case-insensitive comparison without the extra processing overhead of LCase/LCase$ or UCase/UCase$ conversions.

That code runs in just over 200ms2, with over 13,000 rows in column R - and there's probably still more room for improvements, but I'll leave it at that for now.

1By no scientific measurement whatsoever. It's just an extremely common mistake.

2Lazily measured with a very basic Timer diff.


A concurrent queue that supports exactly two threads and not more. One thread is allowed to push, the other to pop

Naming

I don't understand what CircularSpsc is supposed to mean, and how to even pronounce it (circular space?). I suggest you use a full name without omitting the vowels.

Include guards

You were right to add an include guard to the header file (.hpp). It is supposed to prevent the header file to be included more than once in a single translation unit, which could cause "multiple definition" errors.

However, in the implementation file (.cpp) an include guard is not needed, because this file is not supposed to be included at all.

The implementation file is in fact included at the end of the header file, but this is not the right way to get it compiled. Instead, you should pass its name directly to the compiler in addition to the "main" .cpp file.

You can read more about how compilation works in C++ here, for example.


How to create associative hashs in Ruby (on Rails) dynamicly

You should save projects in array or something like it, not hash. For example

  Mite::Customer.all.each do |customer|
    @customers[customer.id] = {:name => customer.name, :projects => []} # !!!
  end

  Mite::Project.all.each do |project|
    @customers[project.customer_id][:projects] << project # !!!
  end


The immediate thing that jumps out to me is your use of an ArrayList for this. By continuously removing the first element, you force the array list to shift everything left one space each time (an O(n) operation assuming no underlying optimizations!)

Instead of removing from the array list (incurring an expensive shift), I would recommend that you keep an index.

    while(cardsLeft.size() >= 1)
    {
        //if we can't pick up the next card, we're at a dead end - no solutions
        if(cardsLeft.get(0) > numPicked)
            return 0;

        // ...
        for(int i: cardsLeft)
        {
             // ...
        }

        // ...

        cardsLeft.remove(0);
        // ...
    }

becomes

    int cardIndex = 0;
    while(cardIndex < cardsLeft.length())
    {
        //if we can't pick up the next card, we're at a dead end - no solutions
        if(cardsLeft.get(cardIndex) > numPicked)
            return 0;
        // ...
        for(int i = cardIndex; i < cardsLeft.length(); ++i)
        {
             // ...
        }
        // ...

        //cardsLeft.remove(0);
        ++cardIndex
        // ...
    }


You hate h̶a̶t̶s̶ reputation? Click here to get rid of it

It would be better to do this with a user style, e.g. using the Stylus extension, like this:

.rep, .reputation, .reputation-score {
    visibility: hidden;
}

One advantage of user styles over scripts is that they're applied as soon as the page starts to load, so you won't see the rep counts flicker briefly while the page is loading.  Also, user styles will automatically apply also to new dynamic content loaded e.g. via Ajax (such as new answers posted while you're viewing the page).

If you insist on using a user script, it's possibly to emulate user styles by using @run-at document-start and injecting a custom style element into the page early, like this:

// ==UserScript==
// @name        Hide Stack Exchange reputation (demo)
// @namespace   http://vyznev.net/
// @description A demonstration of using style injection to emulate user styles
// @author      Ilmari Karonen
// @version     1.0
// @license     Public domain
// @match       *://*.stackexchange.com/*
// @match       *://*.stackoverflow.com/*
// @match       *://*.superuser.com/*
// @match       *://*.serverfault.com/*
// @match       *://*.stackapps.com/*
// @match       *://*.mathoverflow.net/*
// @match       *://*.askubuntu.com/*
// @homepageURL http://codereview.stackexchange.com/a/120100
// @grant       none
// @run-at      document-start
// ==/UserScript==

var css =
    ".rep, .reputation, .reputation-score {\n" +
    "    visibility: hidden;\n" +
    "}\n";

var style = document.createElement('style');
style.textContent = css;
(document.head || document.documentElement).appendChild(style);

I use this method in my Stack Overflow Unofficial Patch (SOUP) user script (which combines a bunch of more or less minor interface bugfixes and improvements together) to let me efficiently apply both CSS-only and JS-based tweaks from a single user script.

One detail worth noting is that styles injected this way will generally end up being included before any actual site style sheets on the page, which means that they will be overridden by site CSS selectors of equal specificity.  In some cases, you may need to use !important and/or various specificity hacks to make sure that your custom styles will take precedence.


Sign-up wizard structure seems too repetitive

You can make this DRYer if you can assume that :

You keep naming each step stepx
No other variables in $scope start with step

In that case you could use a function that sets in a first step the right scope active and then the other steps inactive:

function updateScopeSteps( $scope , step )
{
   //Default to step1
   step = step || 'step1';
   //Set step
   $scope.step = step;
   //Activate step
   $scope[ step ] = {active: true, done:false, todo: false};
   //De-activate all other steps
   for( var name in $scope ){
     if( name.substring(0,4) == 'step' && name != step ){
       $scope[name].active = false;
       $scope[name].todo = true;
     }
   }
}


Verify application configuration from JSON file with matching type using TypeScript in an Angular project

If you're worried that someone may replace your schema during build, you should also be worried that someone might replace any other file as well. That's pure paranoia...
I would say the typescript way is to write the config in typescript as well. If that's not an option, then sure go for schema validation.
Anyway for your current implementation, there is a quite a lot that can be simplified in those conditions.
This:
candidate && typeof candidate === 'object'

can be replaced with just
typeof candidate === 'object'

As there is no falsy value of type object.
Further those hasOwnProperty checks are not necesary. Deserialized json will have all those properties belong to their own. And if somebody passes an object that was not created by parsing json, but let's say instantiating a class, do you really care if those properties belong to the instance, the class or its parent?
export const isConfiguration = (candidate: any): candidate is Configuration => {
  return (
    typeof candidate === 'object' &&
    typeof candidate.endpoints === 'object' &&
    isEndpoint(candidate.endpoints.api) &&
    isEndpoint(candidate.endpoints.smsGateway) &&
    typeof candidate.auth === 'object' &&
    (candidate.auth.company === null || typeof candidate.auth.company === 'string')
  )
}


LINQ queries improvement - repetition of query

The first thing (and this is very minor) is that the expression a == true and simply a are identical. Thus you don't need all those == true's.

The simplest, most obvious way is to simply extract a private method for your filter:

private boolean isActive(AnswerSelectLabel answer)
{
  return answer.Active
      && answer.Variable.Active
      && answer.Variable.Question.Active
}

public IEnumerable<AnswerSelectLabel> GetAll()
{
  return db.AnswerSelectLabel
      .Where(isActive) //you'll pardon me if this is syntax error, I've been in java land too long now, where this would be this::isActive
      .OrderBy(x => x.DisplayOrder)
      .ThenBy(x => x.Value);
}

public IEnumerable<AnswerSelectLabel> GetByVariable(IEnumerable<Respondent> respondents, string idVariable)
{
  return respondents.SelectMany(x => x.AnswerSelect)
      .Select(x => x.AnswerSelectLabel)
      .Where(isActive)
      .Where(x => x.idVariable == idVariable);
}

and so on.

Slightly more sophisticated (and almost certainly overkill), is to extract some kind of interface on your answer, variable, and Question, classes. Something like

interface IActivatable
{
  public Active { get; }
}

If you make this change, you can start to play games with exactly what you're asking to be active:

public IEnumerable<AnswerSelectLabel> GetByVariable(IEnumerable<Respondent> respondents, string idVariable)
{
  return respondents.SelectMany(x => x.AnswerSelect)
    .Select(x => x.AnswerSelectLabel)
    .Where(x => new IActivatable[]{x, x.Answer, x.Answer.Question}.all(x => x.Active))
    .Where(x => x.idVariable == idVariable);
}

which, again, we can extract a method for. But this time we're parameterized on the actual things we want to check, which is nice because it means we can pick-and-choose what we want to be active. In your case it looks like this is always answer, question, and variable, but if that's not the case this is likely helpful:

public IEnumerable<AnswerSelectLabel> GetByVariable(IEnumerable<Respondent> respondents, string idVariable)
{
  return respondents.SelectMany(x => x.AnswerSelect)
    .Select(x => x.AnswerSelectLabel)
    .Where(x => isActive(x, x.Answer, x.Answer.Question))
    .Where(x => x.idVariable == idVariable);
}

private boolean isActive(params IActivateable activatables){
  return activatables.all(x => x.Active);
}

Of course, if this isn't the case, this is just useless speculative code, so don't do it.

If I could make a couple more notes:

using strings as a catch-all for ID's has gotten me in trouble, so now I push to create specialized ID classes (where a simple GUID wont do). Don't let this burn you too!
GetByQuestion(IEnumerable<Respondent> respondents, string idQuestion) and GetByVariable(IEnumerable<Respondent> respondents, string idVariable) are suffering from a sort of linq-feature-envy. They don't use your db field at all, so why are they on this class? Do these methods exist so that I can do something like this:

var respondents = dal.GetAllRespondents();
respondents = respondents.Where(callerSpecificFilter);
var asnwers = GetByVariable(respondents, "1234");

If this is the case, and you can afford the potential performance hit, you can remove the respondents parameter and take a Func<Respondent, Boolean> filter instead. Then simply apply the filter yourself.


That does not look very DRY ( Dont repeat yourself ), not to mention that it does not look good that every function must be aware of the connection string.

For updates, you could do something like this:

exports.setPassword = function (id, password, callback) {
  genericUpdate('UPDATE users SET password=$1 WHERE id=$2', [password, id], callback );
};

exports.setStatus = function (id, status, callback) {
  genericUpdate('UPDATE users SET status=$1 WHERE id=$2', [status, id], callback );
};

function genericUpdate( queryString, parameters, callback )
{
  callback = callback || function(){};
  pg.connect(conString, function (err, client, done) {
    if (err){
      callback(err);
    } else {
      client.query(queryString, parameters, function (err) {
        done();
        callback(err || null);
      });
    }
  });
}

I added curly braces and newlines to your if statements, other than that your code seems fine.

EDIT: some thoughts on selects, you probably want a few generic selection functions, if you create one that is meant for selecting on an id, then you can get away with always returning the first data record if any.

exports.getStayInTouch = function (userId, callback) {
  selectById( 'SELECT * FROM stay_in_touch_contacts WHERE user_id=$1' , userId , callback );
};

function selectById( queryString, id, callback )
{
  callback = callback || function(){};
  pg.connect(conString, function (err, client, done) {
    if (err){
      callback(err);
    } else {
      client.query(queryString, id, function (err,results) {
        done();
        if(err)
          callback(err)
        else
          callback(null, results.rows[0] );
      });
    }
  });
}


Creating lstlistings for Java files in multiple Java folders

to me it stroke odd that you use old java.io classes to list files, while using the newer (not-so-new-anymore) java 7 java.nio classes to determine file type.
I say you should use Files.isDirectory(Path p) and Files.newDirectoryStream(Path p) to check and list files in directory.

Furthermore, if you want to traverse a directory tree, you have the wonderful Files.walkFileTree() that does all the traversing for you.  You need to implement a FileVisitor that has interception points for start and end of directory and of course for visiting a file.  I believe this can help you in detecting src directories.


C++ Coding Exercise - Maximum unit to load into a truck given it size

Names are better then indices. Consider
  struct box_type {
      int amount;
      int capacity;
  };

box.amount seems cleaner that box[0].

Along the same line, declaring such a structure would let you define
  friend bool box_type::operator <(const box_type& l, const box_type& r) {
      return l.capacity < r.capacity;
  }

and eliminate a lambda, as well as sort_boxtypes function.

I don't like max_units (it sounds like there are min_units somewhere). Similarly, truck_size is a truck size, a constant; consider a remaining_size or something like that.

It feels that a truck_size >= 0 comparison shall be done beforehand. Consider
  std::sort(boxes.begin(), boxes.end());
  for (auto box = boxes.rbegin(); box != boxes.rend(); ++box) {
      auto the_load = std::min(box.amount, remaining_size());
      units += box.capacity * box.amount;
      remaining_size -= the_load;
      if (remaining_size == 0) {
          break;
      }
  }
  return units;


Choice of tables for a project to handle attendance

Please use sensible names for your column names. Even though I read you explanation I can only vaguely guess what slno and jntunno might mean. I assume jntunno is some sort of student id (that's what I'm guessing from the student table - each student seems to have a unique one) - so what about studentid? I assume slno is simple primary id - so why no name it id?
Your dailyatt table has a column for each student (based on my assumptions above). I assume it is supposed to show which student has attended a specific class at a specific date. Now what happens if you add a new student - you will have to add a new column to your db schema, and another one, and another one ....

Furthermore the new students might not have been enrolled for older classes yet when you add a new column you have to choose a value for old attendances. So you start making special values for that case.

Also try creating a query like How many students have attended a specific class. It will end up looking like this select 11341A0501+11341A0502+... from dailyatt where ... - not very nice.

In other words: Yes, it's a bad idea for more than one reason.

When designing a schema and you try to think in terms of objects or concepts then a table should describe that object or concept - meaning the columns should be the properties of it and the rows should be the various instances of it. So I'd make three tables:

courses - describes courses (id, name, subject/description)

classes - describes classes (id, date and time, courseid) (so this table holds all the classes held for a specific course)

classattendance - student attendance for a specific class (id, classid, studentid)

Then you could do a select count(*) as numStudentsAttended from classattendance where classid = 1234 to find how many student attended a specific class for example.


Short Java FizzBuzz using recursion and parameters

Recursion is usually not a favoured strategy in Java due to concerns about stack overflow and function call efficiency.  However, we can still review FizzBuzz as an exercise in recursive programming.

The first observation I have is that recursive solutions usually start by checking for the base case first.  I recommend that you stick to that pattern.  As a bonus, checking for count > max will prevent infinite recursion if the function is accidentally called with the count and max parameters reversed.

Another typical feature of recursive solutions is that they avoid mutation and reassignment.  When you recurse, previous values of your variables will already be kept on the stack for you, and that is generally sufficient to solve most problems.  In your case, you've used +=, whereas you should be able to use just +.

You've used three ternary conditionals.  If you reorder them, you can avoid concatenating += "fizz" followed by += "buzz".

Since this is a pure function, it should probably be declared static, so that you don't have to instantiate an object just to call the code.

Finally, note that the resulting string is already terminated by \n, so perhaps you should call System.out.print() rather than .println().

public void fizzbuzz(int count, int max, String accumulator) {
    // Check for the base case
    if (count > max) {
        System.out.print(accumulator);
        return;
    }

    // ... then proceed to the recursive cases.
    //
    // The first case below would be better written as (count % 15 == 0),
    // but I've kept it as (count % 3 == 0 && count % 5 == 0) for easier
    // comparison with your original code.
    String fizzer = (count % 3 == 0 && count % 5 == 0) ? "fizzbuzz\n" :
                    (count % 3 == 0) ? "fizz\n" :
                    (count % 5 == 0) ? "buzz\n" : count + "\n";
    fizzbuzz(count + 1, max, accumulator + fizzer);
}

You asked about reducing the number of parameters.  The first parameter I would eliminate is not count or max, but the accumulator.  You could change it into a return value instead, and it would be more natural.  The caller would have to be responsible for printing the result — and I would also consider that an improvement, since it keeps the calculation and the output routines separate.

public static String fizzbuzz(int count, int max) {
    if (count > max) {
        return "";
    }
    String fizzer = (count % 15 == 0) ? "fizzbuzz\n" :
                    (count %  3 == 0) ? "fizz\n" :
                    (count %  5 == 0) ? "buzz\n" :
                                        count + "\n";
    return fizzer + fizzbuzz(count + 1, max);
}

public static void main(String[] args) {
    System.out.print(fizzbuzz(1, 30));
}

Once you've done that, you can eliminate one more parameter by making it left-recursive instead of right-recursive.

public static String fizzbuzz(int n) {
    if (n <= 0) {
        return "";
    }
    String fizzer = (n % 15 == 0) ? "fizzbuzz\n" :
                    (n %  3 == 0) ? "fizz\n" :
                    (n %  5 == 0) ? "buzz\n" :
                                    n + "\n";
    return fizzbuzz(n - 1) + fizzer;
}

public static void main(String[] args) {
    System.out.print(fizzbuzz(30));
}


Find the kth largest element of an array

Here is the median of medians algorithm which also takes \$O(n)\$ in the worst cases:

Divide the array into \$\frac{n}{5}\$ lists of 5 elements each.
Find the median in each sub array of 5 elements.
Recursively ﬁnd the median of all the medians, let's call it \$M\$.
Partition the array into two sub array 1st sub-array contains the elements larger than \$M\$. Let's say this sub-array is \$a1\$, while other sub-array contains the elements smaller than \$M\$. Let's call this sub-array \$a2\$.
If \$k \le |a1|\$, return selection(a1,k).
If \$k− 1 = |a1|\$, return \$M\$.
If \$k \gt |a1| + 1\$, return selection(a2,k −a1 − 1).

Let's see an interesting example of this where we have to find out the median of unsorted array in linear time. This may sounds NO at first look because median of array is middle element in sorted array if array is of odd length and middle of two middle elements if array is even length.

We can do it using quick/heap sort which takes \$O(nlogn)\$ time, but can we improve? Yes, have you heard about counting sort, which takes \$O(n)\$ time but extra \$O(Max−Min+1)\$ space, where Max and Min are the element of the array?

What if the array is ar[]={10000000,200000000}. Waste of space, right? But if you think about the median, which is nothing but the middle element of the array, where \$k = \frac{n}{2}\$ if array is odd length, can you see anything now? The median is nothing but \$\frac{n}{2}\$th smallest element in the array.

Great, so we got it. We can call median of medians algorithm up to \$k = \frac{n}{2}\$ and we can return ar[n/2] as the median.

Here's the pseudocode for the same:

//selects the median of medians in an array

static int selection(int a[], int s, int e, int k)

{

   // if the partition length is less than or equal to 5

   // we can sort and find the kth element of it

   // this way we can find the median of n/5 partitions

   if(e-s+1 <= 5)

   {

       Arrays.sort(a,s, e);

       return s+k-1;

   }

   /* if array is bigger we partition the array in sub-arrays of size 5
   no. of partitions = n/5 = (e+1)/5 iterate through each partition and
   recursively
   calculate the median of all of them and keep putting the medians in the
   starting of the array
   */

   for(int i=0; i<(e+1)/5; i++)

   {

      int left = 5*i;

      int right = left + 4;

      if(right > e) right = e;

      //left+(right-left)/2 median will be 3rd element e.g.ar[2] in zero index based array

      int median = selection(a,left, right, 2);

      swap(a[median], a[i]);

   }

  /*now we have array  a[0] = median of 1st 5 sized partition a[1] = median of
  2nd 5 sized partition and so on till n/5 to find out the median of these n/5
  medians we need to select the n/10th element of this set (i.e. middle of it)
 */

   return selection(a, 0, (e+1)/5, ((e+1)/10));

}

Call this function as:

selection(ar,0,ar.length-1,k) //k=n/2 which is median

Analysis of algorithm:

Dividing the array by 5 assures a worst-case split of 70-30 and at-least half of the medians are greater than the median-of-medians, hence at-least half of the \$\frac{n}{5}\$ blocks have at-least 3 elements and this gives a \$\frac{3n}{10}\$ split, which means the other partition is \$\frac{7n}{10}\$ in the worst case. That gives a time complexity of \$T(n) = T(\frac{n}{5}) + T(\frac{7n}{10}) + O(n)\$.

More reading:

Page on indstate.edu
The Median-of-Medians Algorithm | Hacker News


Refactoring my problem-solution to reduce complexity

I plan to think up a better algorithm later and post an answer on that, but for now, I'd like to offer a critique of your existing code.

Typically using namespace std; should be avoided in favor of either using the std:: qualifier or just importing the identifiers you plan to use at a function level. (E.g. inside of main, doing something like using std::cout;.)

You should verify that your input reading succeeds:

if (!(cin >> n)) { return EXIT_FAILURE; }

(And something similar in your loop.)

On the off chance that something goes wrong, you'd rather bail out with an exit code than do nothing. If you really wanted, you could even put out an error message (though for contest-style problems like these that would be more for your use than the end purpose).

It's a good habit in C++ to use ++i whenever you can as opposed to i++. For an int or any other built in, it doesn't particularly matter, but for complex types, ++i can avoid an expensive copy.

The most common manifestation of this is iterators. ++i increments an iterator in place. i++ creates a copy of the iterator, increments the original one and then returns the copy. If you're not actually capturing the copy, there's no reason to create one.

Try to give variables more useful names. Imagine coming back to this 6 months from now, or imagine if I hadn't read the problem statement. I would be left wondering what in the world all these 1 character variable names are. Descriptive variables assist the reader in more quickly comprehending what code is doing.

Rather than pushing back pairs over and over again, I would take advantage of vector's values constructor and std::pair's default constructor:

std::vector<std::pair<int, int> > attendees(numAttendees);
for (int i = 0; i < numAttendees; ++i) {
    if (!(cin >> attendees[i].first >> attendees[i].second)) {
        return 1;
    }
}

Not only with this have a bit better performance (since it doesn't have to keep resizing the vector), it is a bit cleaner. (If the pair default ctor actually turns out to be expensive, you could use reserve() to avoid the vector resizing but still allow you to use make_pair to avoid the default construction of each pair.)

Is your input guaranteed to be sorted? If not, you need to either sort or scan over the entire data set rather than starting at i + 1.

This comes down to opinion, but I find space around operators (e.g. i+1 as i + 1) much easier to read. For example for (int i = 0; i < n; ++i) vs for(int i=0; i<n; ++i).

You need to include utility for pair, I believe.

Whenever you have a deep nesting of loops, it's typically a sign that something should be pulled into a function. For example, I would pull the for(int j = i+1; ...) part of the loop into a function called countInvolvedAttendees (or something hopefully better named -- I'm drawing a blank).

std::pair is a double edged sword. It's very, very convenient for holding any pair, but it's generality is also it's downfall. In particular, it basically murders decent naming. When I see a std::pair<int, int>, I have no idea what in the world the two ints are at all. Compare that to a Attendee that has a seatPosition and voiceDistance, and suddenly the meanings are very clear. Unfortunately though, creating a custom struct or class for this seems a bit overkill.

What I'm trying to get across is please be mindful of the problem of std::pair's vagueness. In all but the simplest of circumstances, it's typically better to create something with proper names. Otherwise, it's too easy to get caught up in first and second and flip them, forgot what one means, and so on.

std::endl is a common case of I don't think that does what you think it does.

In particular, std::endl is equivalent to os << '\n' << std::flush;.

For lots of outputting, this constant flushing can be shockingly slow. In cases like this, where you're outputting a giant batch and not responding to human input as it comes, I would use '\n' instead.

Since this is a lot to take in, I might write out a revised version in a bit when I get some more time :).


As the documentation for shutil.copyfile(src, dst) says,

  If dst already exists, it will be replaced.

You have attempted to work around that by checking if not os.path.exists(dst) first.  However, that logic is vulnerable to a race condition if the destination file springs into existence just after the check.

A way to ensure that you do not overwrite an existing file is to use os.open() with the os.O_EXCL flag.  You would need to write the read-write loop yourself to transfer the file contents, but that is not difficult.


If I'm not misunderstanding the intent of your script you don't need the if elses at all.

For starters not having a space to trim when calling trim(Right or Left) is not a problem. No errors are thrown. So you could just do this:

function addWords() {
    var value = $('#input').val();

    if ((/^[a-zA-Z\s]*$/.test(value)) && (value !== '')) {
        value = value.trimLeft().trimRight();
        $('#output').append($('').text(value + ' '));
    } else {
        alert('Please use characters only.');
    }
}

For simplicities sake instead of value.trimLeft().trimRight() you can just use value.trim().

Edit: Also as Dagg pointed out(see comments below) String.prototype.trimLeft() and String.prototype.trimRight() are non-standard but String.prototype.trim() is in the spec's for ES5.


It's been a while since I coded in C but here are couple observations.

Input validation. You should check if the scanned character is really an upper case letter or exit with an error otherwise.
Choice of functions. Since you're scanning and printing out a character at a time, you could have used putchar instead of printf, and getchar instead of scanf.
Variable naming. let is not the best variable name since it is often used as a keyword in other languages. You also could have used the same variable in place of let and back.
Code formatting. There are a lot of different opinions about how to format source code, but most agree that it is better to put parenthesis around loop and condition bodies.

Here is how I would have formatted your code.

#include <stdio.h>

int main(void) {
    char ch;
    char row;
    char spaces;
    char letter;

    printf("Please, insert an uppercase letter: ");
    scanf("%c", &ch);

    for (row = 'A'; row <= ch; row++) {
        for (spaces = ch; spaces > row; spaces--) {
            printf(" ");
        }
        for (letter = 'A'; letter < row; letter++) {
            printf("%c", letter);
        }
        for (; letter >= 'A'; letter--) {
            printf("%c", letter);
        }
        printf("\n");
    }
    return 0;
}