Color-coded console output I wrote this Console.Write function to use in my applications where I need to easily color-code output.

Example syntax would be:

Console.WriteLine("<f=red>this is in red");
Console.WriteLine("<b=gray><f=white>This is white on gray. <f=green>This is green on gray. <b=darkmagenta>This is green on dark magenta. <b=d>This is green on default.");

Which results in this...

I'm looking for a general review of the code.

//github.com/BenVlodgi/CommandHelper
public static class Console
{
    private static Regex _writeRegex = new Regex("<[fb]=\\w+>");

    public static void WriteLine(string value, int? cursorPosition = null, bool clearRestOfLine = false)
    {
        Write(value + Environment.NewLine, cursorPosition, clearRestOfLine);
    }

    public static void Write(string value, int? cursorPosition = null, bool clearRestOfLine = false)
    {
        if (cursorPosition.HasValue)
            System.Console.CursorLeft = cursorPosition.Value;

        ConsoleColor defaultForegroundColor = System.Console.ForegroundColor;
        ConsoleColor defaultBackgroundColor = System.Console.BackgroundColor;

        var segments = _writeRegex.Split(value);
        var colors = _writeRegex.Matches(value);

        for (int i = 0; i < segments.Length; i++)
        {
            if (i > 0)
            {
                ConsoleColor consoleColor;
                // Now that we have the color tag, split it int two parts,
                // the target(foreground/background) and the color.
                var splits = colors[i - 1].Value
                    .Trim(new char[] { '<', '>' })
                    .Split('=')
                    .Select(str => str.ToLower().Trim())
                    .ToArray();

                // if the color is set to d (default), then depending on our target,
                // set the color to be the default for that target.
                if (splits[1] == "d")
                    if (splits[0][0] == 'b')
                        consoleColor = defaultBackgroundColor;
                    else
                        consoleColor = defaultForegroundColor;
                else
                    // Grab the console color that matches the name passed.
                    // If none match, then return default (black).
                    consoleColor = Enum.GetValues(typeof(ConsoleColor))
                        .Cast<ConsoleColor>()
                        .FirstOrDefault(en => en.ToString().ToLower() == splits[1]);

                // Set the now chosen color to the specified target.
                if (splits[0][0] == 'b')
                    System.Console.BackgroundColor = consoleColor;
                else
                    System.Console.ForegroundColor = consoleColor;
            }

            // Only bother writing out, if we have something to write.
            if (segments[i].Length > 0)
                System.Console.Write(segments[i]);
        }

        System.Console.ForegroundColor = defaultForegroundColor;
        System.Console.BackgroundColor = defaultBackgroundColor;

        if (clearRestOfLine)
            ClearRestOfLine();
    }

    public static void ClearRestOfLine()
    {
        int winTop = System.Console.WindowTop;
        int left = System.Console.CursorLeft;
        System.Console.Write(new string(' ', System.Console.WindowWidth - left));
        System.Console.CursorLeft = left;
        System.Console.CursorTop--;
        System.Console.WindowTop = winTop;
    }
}

Comments are inline.

public static class Console

Where's your using directives? They're needed for the code to compile; you should post them.
It's a little bit unusual to give your class the same name as one in System but I see why you did it -- so you can just switch to using your new module with a using.

{
    private static Regex _writeRegex = new Regex("<[fb]=\\w+>");

Don't forget to make it readonly. The pattern for that Regex should be specified as a verbatim string literal so you don't have to double the backslashes (only you can prevent Leaning Toothpick Syndrome) -- @"<[FB]\w+>". You don't save length but it's easier to understand.
I had initially thought that it might make sense to construct this Regex using RegexOptions.Compiled, but it turns out that has no benefit since it's only used in a static method, so it will automatically be cached. But if you ever use nonstatic methods, it's worth trying it and see if it gives a speed increase.

    public static void WriteLine(string value, int? cursorPosition = null, bool clearRestOfLine = false)
    {
        Write(value + Environment.NewLine, cursorPosition, clearRestOfLine);
    }

It's inefficient to use + here to append onto the string. Since .NET System.String is immutable, it has to build a whole new string and copy. It would be better to just call Write with the parameters as you got them, followed by System.Console.Write(Environment.NewLine);.

    public static void Write(string value, int? cursorPosition = null, bool clearRestOfLine = false)
    {
        if (cursorPosition.HasValue)
            System.Console.CursorLeft = cursorPosition.Value;

        ConsoleColor defaultForegroundColor = System.Console.ForegroundColor;
        ConsoleColor defaultBackgroundColor = System.Console.BackgroundColor;

        var segments = _writeRegex.Split(value);
        var colors = _writeRegex.Matches(value);

This seems a bit inefficient since you're doing the same matching twice. I strongly suspect that it would be better to skip the .Split call and use a foreach loop on the Matches.

        for (int i = 0; i < segments.Length; i++)
        {
            if (i > 0)

As another reviewer suggested, this is suboptimal. If i==0 is a special case, move it outside the loop so you don't need to test i each time through the loop. (The compiler will probably do this for you, so you won't gain any speed -- it's just for code legibility)

            {
                ConsoleColor consoleColor;
                // Now that we have the color tag, split it int two parts,
                // the target(foreground/background) and the color.
                var splits = colors[i - 1].Value
                    .Trim(new char[] { '<', '>' })
                    .Split('=')
                    .Select(str => str.ToLower().Trim())
                    .ToArray();

This is clever, but it really would be easier and clearer to just use capturing groups in your Regex so you can access the two parts directly from the Match.

                // if the color is set to d (default), then depending on our target,
                // set the color to be the default for that target.
                if (splits[1] == "d")
                    if (splits[0][0] == 'b')

This code would be a lot clearer if you used meaningful variable names instead of splits[1] and splits[0].

                        consoleColor = defaultBackgroundColor;
                    else
                        consoleColor = defaultForegroundColor;

You like terseness -- how about the ternary operator here?

                else
                    // Grab the console color that matches the name passed.
                    // If none match, then return default (black).
                    consoleColor = Enum.GetValues(typeof(ConsoleColor))
                        .Cast<ConsoleColor>()
                        .FirstOrDefault(en => en.ToString().ToLower() == splits[1]);

Again, very clever, but I think it would be more efficient to just build a Dictionary<string,ConsoleColor> one time at the start, rather than searching the whole list each time. LINQ is extremely useful; that doesn't mean it's best used everywhere.

                // Set the now chosen color to the specified target.
                if (splits[0][0] == 'b')
                    System.Console.BackgroundColor = consoleColor;
                else
                    System.Console.ForegroundColor = consoleColor;
            }

            // Only bother writing out, if we have something to write.
            if (segments[i].Length > 0)
                System.Console.Write(segments[i]);
        }

Like the other reviewer said, this if should be at the start so you don't bother unpacking the string at all.

        System.Console.ForegroundColor = defaultForegroundColor;
        System.Console.BackgroundColor = defaultBackgroundColor;

How about System.Console.ResetColor()? It would make these two variables unnecessary.

        if (clearRestOfLine)
            ClearRestOfLine();
    }

    public static void ClearRestOfLine()
    {
        int winTop = System.Console.WindowTop;
        int left = System.Console.CursorLeft;
        System.Console.Write(new string(' ', System.Console.WindowWidth - left));
        System.Console.CursorLeft = left;
        System.Console.CursorTop--;
        System.Console.WindowTop = winTop;
    }
}

Does this do what you want after a WriteLine? It looks to me like it clears the next line not the current one.


Notifications dropdown with TinyScroll I'm relatively new to jQuery and am trying to learn best practices/design patterns with JavaScript. Came across this link and decided to try and put it to something useful.

So far I've made a notifications menu dropdown using TinyScrollBar where the user can remove an individual notification. Once removed, the height of the dropdown updates until there are no more.

Here is a demo of what I have so far.

I would like to know ways on how I can improve my JavaScript.

JS

var TEST = TEST || {};

/* Notifications */
TEST.notif = {};
TEST.notif._notifOpen = false;
TEST.notif._el = null;
TEST.notif._sum = 0;
TEST.notif._defaultVPHeight = 350;

TEST.notif.init = function(){

this._el = $('#notifications');

$('.notif-trigger').on('click',function(e){
    TEST.notif.toggleNotifications();
    return false;
});

// when you click outside the notification menu
// hide the notifications
$('html').on('click',function(e){
    if( TEST.notif._notifOpen ) {
        TEST.notif.hideNotifications();
    }
});

// set initial notifications scrollbar height
this._el.tinyscrollbar( {size: TEST.notif._defaultVPHeight} );
};

TEST.notif.showNotifications = function(){
var $el = this._el,
    $close = $('.notif-close'),
    $li = $('.notif-list li a');

// show notificatoins and update scrollbar position
$el.show().tinyscrollbar_update();

// stop propagation
$li.on('click',function(e){ e.stopPropagation(); });

// remove list-item
$close.on('click', function(e){

    // store
    var liHeight, newH, overviewH;

    // store individual list-item height
    liHeight = $(this).parent().height();

    // remove the list-item you clicked
    $(this).parent().remove();

    // store the new height TEST the viewport
    newH = TEST.notif._defaultVPHeight - liHeight;

    // get height TEST actual contents
    overviewH = $('.overview').height();

    // set new defaultH
    TEST.notif._defaultVPHeight = newH;

    // update scrollbar
    $el.tinyscrollbar_update();

    // once scrollbar is disabled, start changing the viewport height
    if( $('#notifications .scrollbar').hasClass('disable') && $('.notif-list li').length > 1 ){
        $('#notifications .viewport').height( overviewH );
    } else if( $('.notif-list li').length == 1 ) {
        $('.notif-list li.empty').show();
    }

    return false;
});

this._notifOpen = true;
};

TEST.notif.hideNotifications = function(){
this._el.hide();
this._notifOpen = false;
};

TEST.notif.toggleNotifications = function(){
this._notifOpen ? this.hideNotifications() : this.showNotifications();
};

/* init */
$(document).ready(function(){
    TEST.notif.init();
});

From a once over:

Review your comments, some of them just take up space and are not very valuable:

// update scrollbar
$el.tinyscrollbar_update();

Indentation ( this might be because of copy pasting ) is off in your code, making it hard(er) to read
TEST.notif is a mouthful, I would just go for notifications
_el, _sum, _defaultVPHeight should all loose their underscore, they dont make sense. Also I would go either for the Spartan e or the full out element.
TEST.notif._notifOpen -> why notifOpen, it's already part of an object called notif, just call it open
Use lowerCamelCase consistently: tinyscrollbar_update -> tinyScrollbarUpdate

Other than that, your code is well structured and easy to follow.


Returning a Fibonacci list def fib_m_through_n(m, n):
    """(number, number) -> list

    A function which returns a list containing the mth through the nth
    fibonacci numbers.

    SHOULD BE MODIFIED IN THE FUTURE so it will remember values already computed,
    so when it is called again it reuses that information
    """
    fib_list = [0, 1, 1]
    a, b, c = 1, 1, 0  #why can I do three variable assignments here...
    count = 0
    while count <= n:
        c = a + b; a = b; b = c #...but not here?
        fib_list.append(c)
        count += 1
    print(fib_list[m : n])

fib_m_through_n(0, 17)

I have a few questions about this:

The first is general: are there any clear pythonic violations here, any obvious improvements to style?

The second is included in some of the comments.  Why can I get away with assigning three variables in one line here: a, b, c = 1, 1, 0

but not here:  c = a + b; a = b; b = c

If I try to do this: c, a, b = a + b, b, c

Then I get an incorrect output.

After analyzing the mistake and trying to imagine how things look from the function's POV, it still seems to me like doing three variable assignments in a row should work, assuming that when the function runs it just reads this line from left to right.

Finally, as noted in the section just after the docstring, I want to turn this into a generator.  I have read about generators and understand them a bit, but I don't know how to implement one here.

Of course not.

If you do c, a, b = a + b, b, c, this is what you get

a, b, c = a0, b0, c0
c, a, b = a + b, b, c
## c become a0 + b0
## a becomes b0
## b becomes c0

I'm pretty sure this is not your intention.

In tuple assignment, the right tuple is evaluated first and then assigned to the left tuple. I'm guessing you thought it's done in order. Sorry, but no.

You can instead eliminate the variable c and do this

a, b = a0, b0
a, b = b, a + b
## a becomes b0
## b becomes a0 + b0

UPDATE

This is what is done by the machine, imagine the left values as an array of variables waiting to be assigned values that are on the left. Like this

[c, a, b] = [a + b, b, c]

Imagine the right values as an array of expression waiting to be evaluated. The right one gets evaluated first, then one by one the left variables takes the right values. No assignment is done until the left expressions are evaluated.


Gets AWS VPC subnet info I was hoping to get a quick review of a script I wrote for retrieving AWS VPC Subnet information.  Any and all ideas welcome. I am looking specifically for logic enhancements, and optimizations to make the code more pythonic. Also, I was initially constructing a dictionary, however I had to adjust since many of the aws values have "-" hyphens. :-(

One note - I am using two spaces vs. four due to internal standards.

#!/usr/bin/env python
# encoding: utf-8

import argparse
import logging
import string
import sys

from boto import vpc, exception

from lib.aws_location import LocationData
from lib.aws_util import check_config

def get_subnets(connection, vpc_id):
  """Function that returns all subnets within a given AWS VPC.
  :connection: AWS Connection.
  :vpc_id: VPC Identifier.

  """
  return connection.get_all_subnets(filters={'vpc_id': vpc_id})

def format_data(region, vpc_id, vpc_subnet, subnets):
  """Function that outputs region data based on template.

  :region: EC2 Region.
  :vpc_id: VPC Identifier.
  :vpc_subnet: Subnet allocated to VPC.
  :subnets: Subnets defined within VPC.

  todo:: Serialization. (yaml/json)
  """
  with open('vpc_subnets.tmpl') as f:
    templ = string.Template(f.read())

  region_dict = {}
  region_dict['region'] = region
  region_dict['vpc_id'] = vpc_id
  region_dict['vpc_subnet'] = vpc_subnet
  region_dict['subnets'] = ', '.join(subnets)

  print templ.safe_substitute(region_dict)

def parse_args():
  parser = argparse.ArgumentParser(
      description='Script for obtaining VPC Subnet information.')

  group = parser.add_mutually_exclusive_group()

  group.add_argument("-d", "--debug",
      help="Enable debug messages",
      action="store_true")

  group.add_argument("-v", "--verbose",
      help="Enable verbose messages",
      action="store_true")

  args = parser.parse_args()

  if args.debug:
    logging.basicConfig(level=logging.DEBUG)
  elif args.verbose:
    logging.basicConfig(level=logging.INFO)
  else:
    logging.basicConfig(level=logging.CRITICAL)

def main():
  parse_args()

  try:
    check_config()
  except EnvironmentError as e:
    print("Error: Could not open config file: {}".format(e))
    sys.exit(1)

  loc = LocationData()

  for region in loc.get_regions():
    try:
      connection = vpc.connect_to_region(region)
      for vpc_raw in loc.get_vpcs_raw(connection):
        vpc_id = str(vpc_raw).split(':')[1]
        subnets = []
        for subnet_id in get_subnets(connection, vpc_id):
          subnets.append(subnet_id.cidr_block)
      format_data(region, vpc_id, vpc_raw.cidr_block, subnets)
    except exception.EC2ResponseError as e:
      logging.error("EC2Error: {}".format(e))
      continue

if __name__ == '__main__':
  main()

I haven't used much boto, so I can just focus on some style comments:

Use four spaces per indentation level
Remove unused imports (boto.exception)
Try to order imports in alphabetical order
Move argument parsing and logging configuration code to separate functions
Be careful of the usage of next. What you were probably looking for is continue, but you can just remove that line to move on to the next region in the loop
--dedug and --verbose don't seem to make sense together. Have a look at ArgumentParser.add_mutually_exclusive_group.
Use a template or, at least, a multiline string to avoid writing so many print statements.


Function that adds commas between groups of 3 digits in a string My program contains some very large integers and uses the GMP library. The output contains integers (probably small enough to fit into int). I would like to make the output easy to read by adding commas between every three digits with any left overs on the left side.

Examples:

1234 => 1,234
12345 => 12,345
123456 => 123,456
123 => 123

The input of the function would be a string representing an integer, because the value of the mpz_class would be converted to a string. I know there's been a lot of discussion of adding commas to int but not string. The mpz_class can't be converted to an int because it may be too big.

Here is what I have and it isn't pretty.

using namespace std;

/*add commas between groups of 3 digits with remainder on left side*/
string addCommas(string in)
{
    const int length = in.length();
    if(length < 4)
    {
        return in;
    }
    int inserted = 0;
    int i = length % 3;
    if(i == 0)
    {
        i = 3;
    }
    for(; i < length + inserted; i = i + 4)
    {
        in.insert(i, ",");
        inserted++;
    }
    return in;
}

Given its use in the program, it is guaranteed the input will not be a negative number. Though I still wonder if it's good to include a check? The program focuses on quick results. How can this code be more readable?

Avoid using namespace std

The standard namespace isn't designed to be imported wholesale, and name collisions could later appear that silently change the meaning of your program (such as when you add an extra include, or move to a newer C++ standard).

std::string::insert moves content multiple times

We're not very efficient, because the later characters will be shuffled as many times as there are preceding commas inserted.  Worse, we don't even reserve() enough space to add the commas, so there could (theoretically at least) be multiple memory allocations.

Don't reinvent the wheel

It would be simpler and more flexible to use std::numpunct to perform the formatting.


Python fir tree maker I've made a code that does exactly what https://sapin.herokuapp.com/?n=5 would do.
Here's my code ;
import sys

def firtree(tree_size):
    fir = []
    width = 1
    minus = 2
    foot_width = 1
    for i in range(1,tree_size+1):
        for j in range(1,i+4):
            fir.append("*"*width)
            width = width + 2
        if i % 2 == 0:
            minus += 1
        width -= minus
        if i % 2 == 0:
            foot_width += 2
    fir = [" "*(int((len(fir[-1]))/2)-int(len(i)/2))+i for i in fir]
    for i in fir:
        print(i)
    for i in range(1,tree_size+1):
        print(" "*int((len(fir[-1]))/2-int(foot_width/2))+"|"*foot_width)

size = int(sys.argv[1])
firtree(size)

How can I improve it ?

Use comments to guide the reader through the major phases of the algorithm.
Imagine returning to this code to fix a bug or add a feature. Simple comments
can help you zero in on the needed location to do that work.
Centralize the creation of literal parameters (see space, wood, branch).
This makes it easy to quickly change stylistic details.
Let you code breath: add space around operators. This can help a lot with
readability and thus maintainability.
As a general rule (there are exceptions), don't reuse variable names for
different concepts. The first part of the function uses fir for uncentered
rows. Then you replace that fir with one having centered rows. Prioritize
code clarity by using different variable names. The same point can be made when
you create the trunk: do it in another variable.
Create convenience variables to eliminate repeated calculations, as shown in
max_width.
Invest more in laying out the code for readability, as shown in the list
comprehenion to create centered.
Take advantage of floor-division if you want an integer result (//).
When iterating i and j are conventional variable names when dealing with
indexes. Your code follows that convention. But it also uses i when iterating
over other things (like the rows). Less ambiguous is a short name that has
a conceptual connection to the thing you are iterating over: for example, if
iterating over rows, use r as the loop variable.
Separate computation from reporting. This is better for debugging and
automated testing. The firtree() function is where computation happens.
Do the printing at a higher level in the call stack.
Put orchestration code inside a function, as shown in main(). Also
better for testing and debugging.
Here's your code with those suggestions applied. Note this this edit does not
fix the bug in your code related to the width of the next top section (width
of next section is supposed to be width of previous section minus 2).
import sys

def main(args):
    size = int(args[0])
    fir = firtree(size)
    for row in fir:
        print(row)

def firtree(tree_size):
    # Setup.
    width = 1
    minus = 2
    foot_width = 1
    space = ' '
    wood = '|'
    branch = '*'

    # Create the top of the tree, first as uncentered rows.
    rows = []
    for i in range(1, tree_size + 1):
        for j in range(1, i + 4):
            rows.append(branch * width)
            width = width + 2
        if i % 2 == 0:
            minus += 1
        width -= minus
        if i % 2 == 0:
            foot_width += 2

    # Convert the rows to centered rows.
    max_width = len(rows[-1])
    centered = [
        space * (max_width // 2 - len(r) // 2) + r
        for r in rows
    ]

    # Build the trunk.
    trunk = [
        space * int(max_width / 2 - foot_width // 2) + wood * foot_width
        for i in range(1, tree_size + 1)
    ]

    # Profit.
    return centered + trunk

if __name__ == '__main__':
    main(sys.argv[1:])

But those types of suggestions only help so much. At the end of the day, this
kind of code is annoying because its so tediously algorithmic: too much math,
too much fine-grained list-indexing, etc. An easier way to solve the problem
can be found taking fuller advantage of an insight in your current code: focus
first on making uncentered rows, like this:
*
***
*****
*******
*******
*********
***********
*************
***************
|||
|||

Then let Python format-strings do all of the grubby work of centering the rows.
We can also improve code readability a bit more by delegating sub-calculations
to helper functions, each doing a very small thing. That approach keeps
the primary function fairly readable.
def firtree(tree_size):
    # Setup.
    wood = '|'
    branch = '*'

    # Rows for the tree branches, which are organized in sections.
    top = []
    row_len = 1
    for n_rows in range(4, 4 + tree_size):
        sect, row_len = section(n_rows, row_len, branch)
        top.extend(sect)

    # Rows for the tree trunk.
    is_even = not tree_size % 2
    width = tree_size + is_even
    height = tree_size
    trunk = [wood * width for _ in range(height)]

    # Return those rows, but centered.
    return centered(top + trunk)

def section(n_rows, init_len, marker):
    # Returns a (ROWS, NEXT_LEN) tuple for a tree section.
    # Handling the next-length calculation here, where it happens to be
    # easy to do, helps keep the primary function simpler.
    end_len = init_len + n_rows * 2
    next_len = end_len - 4
    rows = [marker * n for n in range(init_len, end_len, 2)]
    return (rows, next_len)

def centered(rows):
    # Takes rows. Returns centered rows.
    fmt = '{:^{}}'
    width = max(len(r) for r in rows)
    return [fmt.format(r, width) for r in rows]


Proper use of type_info in relation to mapping components to a type I'm trying to map a components type to the component value itself in a map. The following code all works properly. My main question is this. Is storing the map key as std::type_info* the best way to accomplish what I'm doing? I'm also not digging the ugly static_cast<T*> I'm doing during the usage part.

Entity.h

#pragma once
#include "IComponent.h"
#include <map>
#include <typeinfo>

class Entity
{
public:
    Entity(void);
    ~Entity(void);
    void AddComponent(IComponent* component);
    IComponent* GetComponent(const std::type_info* typeInfo);
private:
    std::map<const std::type_info*, IComponent*> components;
};

Entity.cpp

#include "Entity.h"

Entity::Entity(void)
{
}

Entity::~Entity(void)
{
    for (auto &mapValue : components)
    {
        delete mapValue.second;
    }
}

void Entity::AddComponent(IComponent* component)
{
    const type_info* info = &typeid(*component);
    components.insert (std::pair<const std::type_info*,IComponent*>(info, component));
}

IComponent* Entity::GetComponent(const std::type_info* typeInfo)
{
    return components.at(typeInfo);
}

Example Usage

IComponent* baseComponent = entity->GetComponent(&typeid(PerkList));
PerkList* perkList = static_cast<PerkList*>(baseComponent);

type_info:

Using the type_info reference is a viable approach, but it can be made better with  type_index in conjunction with an unordered_map.

static_cast:

I don't think there is a way around the cast here. You can make it slightly less verbose by defining a template helper method that wraps the type cast:

template<class T>
T * Entity::GetComponent()
{
    return static_cast<T *>(components.at(&typeid(T)));
}

// Usage:
PerkList * perkList = entity->GetComponent<PerkList>();

One nice extra of this approach is that you can replace the static_cast inside with a dynamic_cast during debug/dev builds and check that the types are self-consistent. Then add a preprocessor to use the faster static_cast for a "release" build if you need to squeeze every cycle.

Pointers:

Returning a raw pointer to IComponent is questionable to say the least. A raw pointer conveys no ownership, so it is very easy to leak or delete the objects multiple times when you have raw pointers flying around like this. You should take a look at shared_ptr and weak_ptr before further expanding your implementation. Or perhaps return just a reference (IComponent &) if the caller of GetComponent() should not own the object.

Minor details:

Don't add void to the parameter list of functions/methods that take no parameters. This is a C-ish style. C++ does not require that; () is just as good. So avoid the unnecessary verbosity.
Empty destructors/constructors should be omitted or made defaults.


Bit-based universe simulation I am working with this problem (https://open.kattis.com/problems/whowantstoliveforever). As the problem states, my program has to determine if the universe lives or dies based on the input 0s and 1s.

  To determine the next value of the i-th bit, look at the current
  value of the bits at positions i−1 and i+1 (if they exist; otherwise
  assume them to be 0). If you see exactly one 1, then the next value of
  the i-th bit is 1, otherwise it is 0. All the bits change at once, so
  the new values in the next state depend only on the values in the
  previous state. We consider the universe dead if it contains only
  zeros.

My code works but when submitting it to Kattis.com it says ""Time Limit Exceeded" > 3.00 s". Below is my code.

import sys

def get_bit(bits, i):
    if 0 <= i < len(bits):
        return int(bits[i])
    else:
        return 0

def get_new_state(old_state):
    new_state = []
    for index in range(len(old_state)):
        if (get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 0) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 1):
            new_state.append(0)
        elif(get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 1) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 0):
            new_state.append(1)
    return new_state

def is_dead(state):
    if set(state).pop() == "1":
        return False
    elif set(state).pop() == 1:
        return False
    elif len(set(state)) == 1:
        return True
    else:
        return False

def foresee_fate(state):
    seen = []
    while True:
        if is_dead(state):
            return False
        if state in seen:
            return True
        seen.append(state)
        state = get_new_state(state)

num_cases = int(sys.stdin.readline().strip())
for i in range(num_cases):
    cur_state = []
    case = sys.stdin.readline().strip()
    for char in case:
        cur_state.append(char)
    print("LIVES" if foresee_fate(cur_state) else "DIES")

What are some ways to improve the performance of my code?

You are representing each state of the universe as a list of bits. However, CPUs are experts at handling sequences of bits — that's what an integer is!

Given two bits, the way to find out whether exactly one of them is 1 is to use the ^ operator (XOR).

You should be able to solve this challenge using bit-shifting (<< and >> operators) and ^.


Applying DocumentListener on multiple JTextField Say I have 5 JTextField: jTextField1, jTextField2...

Now I want them to behave the same on DocumentListener, so I decided to make only one DocumentListener and set it to the 5 components.

Meanwhile I'm doing this:

jTextField1.getDocument().putProperty("owner", jTextField1);
jTextField2.getDocument().putProperty("owner", jTextField2);
..
..

And I have this listener:

DocumentListener documentListener = new DocumentListener() {
    public void changedUpdate(DocumentEvent arg0)
    {
        Object owner = arg0.getDocument().getProperty("owner");
        enableDetachButton(getContentPane());
        changeColor((JTextField) owner);
    }

    public void insertUpdate(DocumentEvent arg0)
    {
        Object owner = arg0.getDocument().getProperty("owner");
        enableDetachButton(getContentPane());
        changeColor((JTextField) owner);
    }

    public void removeUpdate(DocumentEvent arg0)
    {
        Object owner = arg0.getDocument().getProperty("owner");
        enableDetachButton(getContentPane());
        changeColor((JTextField) owner);
    }
};

Finally, I do:

jTextField1.getDocument().addDocumentListener(documentListener);
..
..

Is this approach OK? What improvements can I do?

Almost fine. You are doing the same stuff in all 3 update methods of the DocumentListener, so I suggest creating a new private method in it and just calling it from all 3 update methods. That way you avoid code duplication and only have one location to change in the future instead of having to maintain the same code 3 times.

DocumentListener listener = new DocumentListener() {

    @Override
    public void removeUpdate(DocumentEvent e) {
        doStuff(e);
    }

    @Override
    public void insertUpdate(DocumentEvent e) {
        doStuff(e);
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        doStuff(e);
    }

    private void doStuff(DocumentEvent e) {
        Object owner = e.getDocument().getProperty("owner");
        enableDetachButton(getContentPane());
        changeColor((JTextField) owner);
    }
});


C++ code to launch a Windows 8 app This is my first C++ in many years. It's based on some stuff I found on the internet, including a Microsoft article on a similar topic. But I'm sure there are C++ idioms that might make this better or leaner (my main goal).

#include <ShObjIdl.h>
#include <atlbase.h>
#include <wchar.h>

int wmain(int argc, wchar_t* argv[])
{
    HRESULT hr = S_OK;

    if (argc < 2)
    {
        hr = E_INVALIDARG;
        wprintf(L"Supply an app ID (AppUserModelId) for the application to launch.");
        return hr;
    }

    const wchar_t* appId = argv[1];

    hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
    if (FAILED(hr))
    {
        wprintf(L"Error initializing COM");
        return hr;
    }

    CComPtr<IApplicationActivationManager> aam = nullptr;
    hr = CoCreateInstance(CLSID_ApplicationActivationManager, nullptr, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&aam));
    if (FAILED(hr))
    {
        wprintf(L"Error creating ApplicationActivationManager");
        CoUninitialize();
        return hr;
    }

    hr = CoAllowSetForegroundWindow(aam, nullptr);
    if (FAILED(hr))
    {
        wprintf(L"Error calling CoAllowSetForegroundWindow");
        CoUninitialize();
        return hr;
    }

    unsigned long pid = 0;
    hr = aam->ActivateApplication(appId, nullptr, AO_NONE, &pid);
    if (FAILED(hr))
    {
        wprintf(L"Error calling ActivateApplication");
        CoUninitialize();
        return hr;
    }

    CoUninitialize();

    return 0;
}

Pretty small and simple, but I want to open-source this. And I definitely know the feeling of looking at JavaScript newbies' code and going "ugh! why didn't they just do <x>!" So I want to come across as a suave sophisticated C++ programmer instead ;)

One piece of feedback is that your error handling code is very repetitive.  You are calling CoUninitialize in every failure block.  That might seem OK for one cleanup task (though I'd tend to disagree), but once you have N things to clean up on failure (or even successful return), it gets to be a lot of effort and maintenance.

There are a few ways around this that I've seen.

Have a single block that cleans up (frees any buffers, unintializes COM, whatever).  That goes at the end if your function.  Make all failure and success paths reach this block.

As an example of how you might do that in COM code, here's the "wrong" way:

hr = Foo();
if (FAILED(hr))
{
   Cleanup();
}

hr = Bar();
if (FAILED(hr))
{
   Cleanup();
}

Cleanup();

There are several choices for the "right" way.  One of them would be:

if (SUCCEEDED(hr))
   hr = Foo();
if (SUCCEEDED(hr))
   hr = Bar();

Cleanup();

If you are not religiously opposed to goto (this probably makes more sense in C than C++), this approach is also common:

   hr = Foo();
   if (FAILED(hr))
      goto cleanup;
   hr = Bar();
   if (FAILED(hr))
      goto cleanup;

cleanup:
   Cleanup();

There are of course more C++ like (rather than C style) ways to prevent cleanup from becoming too much of a hassle.  In particular it would probably be a better idea to wrap initialization and de-initialization in the RAII idiom.  In this example (COM initialization), you might have a class that (1) initializes COM, (2) tracks that it's been initialized, and (3) in its destructor, deinitializes COM if it has been initialized.  Something like this: [nb: I am typing in a web form, it may not be perfect :-)]

Example:

class ComInitialization
{
   bool init;
public:

   ComInitialization() : init(false) {}

   HRESULT Initialize()
   {
      HRESULT hr = S_OK;

      if (!init)
      {
         hr = CoInitializeEx(/* ... */);
         if (SUCCEEDED(hr))
         {
            init = true;
         }
      }

      return hr;
   }

   ~ComInitialization()
   {
      if (init)
      {
         CoUninitialize();
      }
   }
}

With this approach you can have simply:

ComInitialization comInit;

hr = comInit.Initialize();

Then after this block, you can return in any place you like, success or failure, even throw exceptions, and COM will still get uninitialized.

(Notice I didn't initialize COM in a constructor.  This allows us to inspect the HRESULT on failure without wrapping it in an exception.  I'm sure many would suggest wrapping HRESULTs in exceptions.  This is not personally my taste.  YMMV.)


Read and output CSV content OO PHP Okay, I am wanting to expand my armoury within PHP, so I've been researching OO PHP. With my researched knowledge I went on to create a quick script that reads a CSV file and outputs the results.

CSV Class:

class CSV {

    private $file;

    public function __construct($filename, $mode) {
        $this->file = fopen($filename, $mode);
        return $this->file;
    }

    public function endFile() {
        return feof($this->file);
    }

    public function getCSV($mode) {
        return fgetcsv($this->file, $mode);
    }

    public function close() {
        fclose($this->file);
    }
}

The test file:

require('class.csv.php');

$csv = new CSV('postcodes.csv', 'r');

while(!$csv->endFile()) {

    $postcode = $csv->getCSV(1024);
    echo $postcode[0] . "<br />";

}

$csv->close();

I am just wondering if there are... or what are the improvements I could make in regards to the OO approach. This is purely a script for me to put the knowledge i've learnt together. I'm not another 'following the crowd person' who creates every script in an OO approach because they 'can'.

I understand it is a short script but I am wanting to make sure I have the correct approach before moving forward.

While I think this is a very solid foundation, I think you could expand this to make it easier to use.

The first thing which caught my eye was the possibility to make a file handle open longer than necessary. You have already implemented the functionality, but to have the handle closed before the script is terminated is a responsibility of the developer. I would add a __destruct() magic method which checks if the file handle has been closed when the object is out of scope.

public function __destruct() {
    if(is_resource($this->handle)) { // Property name changed, see next.
        $this->close();
    }
}

The next thing is to provide a default $mode. As this class would mainly be used to read the file you could easily set a default value. As of now your code does not utilize any other functionality provided by the different file handle modes, so this should not change anything, other than making your class easier to use.

public function __construct($filename, $mode = 'r') {...

While we are at the constructor I would also rename your property $this->file into $this->handle and save the opened file name in a separate property. This is to write better error messages.

private $file;
private $handle;

public function __construct($file, $mode = 'r') {

    if(!is_string($file)) {
        throw new InvalidArgumentException('Parameter $file must be a string. Provided type: ' . gettype($file));
    }

    if(!is_file($file) || !is_readable($file)) {
        throw new RuntimeException('The provided file could not be opened for reading. File: ' . $file);
    }

    $this->file   = $file;
    $this->handle = fopen($file, $mode);
}

I would also write some error checking. The most obvious place something bad could happen is when opening the file handle. If you first make sure the file actually exists and throw a well written exception if not, you will save yourself some time when errors occur.

The next place I think could use some error checking is when you are reading a line using fgetcsv() in method getCSV(). If an error occurs it returns false, but the current state of the code is completely unaware this may have happened. A simple check to see if it returned false and then throw an exception would suffice.

public function getCSV($mode)
{
    $value = fgetcsv($this->handle, $mode);

    if($value === false) {
        throw new RuntimeException('Encountered an error while reading CSV file: ' . $this->file);
    }

    return $value;
}

Misc (naming)

I feel like the name of the class is somewhat misleading. If I only look at the like name I might also get the impression I can save values into the specified file. Consider changing the name to reflect its exact behavior. I would consider something like ReadCSV sufficient. I also think this is true for the method getCSV(). Do I read the entire file or just one line? It can be hard to determine just by looking at the name. I would rename it to readLine(). This name also skips the CSV part, as the class name states its associated with a csv file, so it should not come as a surprise.

I also have a little trouble understanding your argument $mode in the method getCSV(). If you look at the documentation for fgetcsv() it has more than one optional parameters, but none named $mode. Consider changing this to the same names, as this would make it easier to understand for other developers (or yourself in six months) who knows the method signature or looks at the documentation.

You should also consider writing documentation using the DocBlock feature. This can help reduce confusion when argument names are ambiguous and provide a short description of the behavior of the method as well as which exceptions it can throw.

Additional

You could also write methods for reading the entire file. A method that looks something like the following could be useful.

public function readAll()
{
    $array = [];

    while(($columns = fgetcsv($this->handle)) !== false) {

        $rows = count($columns);

        for($i = 0; $i <= $rows; $i++) {
            $array[] = $columns[$i];
        }

    }

    return $array;
}

Hope this helps. Please keep in mind none of this code has been tested.

Happy coding!


Tic Tac Toe in Swift Any feedback encouraged.  My checkForWinner function feels cumbersome to me.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var buttonOne: UIButton!
    @IBOutlet weak var buttonTwo: UIButton!
    @IBOutlet weak var buttonThree: UIButton!
    @IBOutlet weak var buttonFour: UIButton!
    @IBOutlet weak var buttonFive: UIButton!
    @IBOutlet weak var buttonSix: UIButton!
    @IBOutlet weak var buttonSeven: UIButton!
    @IBOutlet weak var buttonEight: UIButton!
    @IBOutlet weak var buttonNine: UIButton!

    @IBOutlet weak var gameResult: UILabel!

    var gameState = ["","","",
                     "","","",
                     "","",""
                     ]

    let winningCombos = [[0, 1, 2], [3, 4, 5], [6, 7, 8], //horizontal
                         [0, 3, 6], [1, 4, 7], [2, 5, 8], //vertical
                         [0, 4, 8], [2, 4, 6]] //diagonals

    var gameOver = false
    var turnCount = 0
    var currentPlayer: String!

    func pickFirstPlayer() -> String {
        if arc4random_uniform(2) == 0 {
            currentPlayer = "o"
        } else {
            currentPlayer = "x"
        }
        return currentPlayer
    }

    func toggleNextPlayer() {
        if currentPlayer == "o" {
            currentPlayer = "x"
        } else {
            currentPlayer = "o"
        }
    }

    @IBAction func makeMove(sender: AnyObject) {
        let space = sender.tag
        if (gameState[space] == "" && gameOver == false) {
            let turnImage = UIImage(named: "\(self.currentPlayer).png")
            sender.setImage(turnImage!, forState: .Normal)
            gameState[space] = self.currentPlayer
            self.toggleNextPlayer()
            self.turnCount++
            self.checkForWinner()
        }
    }

    func checkForWinner() {
        var winner = ""
        for combo in winningCombos {
            var row: [String] = []
            for space in combo {
                row.append(gameState[space])
            }
            if (row[0] == row[1] && row[1] == row[2] && row[0] != "") {
                gameOver = true
                winner = row[0].uppercaseString
                gameResult.text = "\(winner) is the winner!"

            }
        }
        if (turnCount == 9 && winner == "") {
            gameResult.text = "It's a tie!"
            gameOver = true
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        pickFirstPlayer()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Using strings (in your case: "o" and "x") to identify the two
players is inflexible and error-prone:

If you mistype "o" as "O" or "0" then the program will not work
properly or crash, and the compiler cannot warn you about that.
If you decide to use different player names or different names for the image resources then you have to change it at many places.
The actual display of a player's name as uppercase letter is "hidden"
at

winner = row[0].uppercaseString

in checkForWinner().

Defining string constants

let playerO = "o"
let playerX = "x"

would be one possible solution, but the better way is to use an
enumeration which can take exactly two values:

enum Player : String {
    case X = "x"
    case O = "o"
}

Methods to get the "other" player, the display image, and to select
a random player can be added directly to the enum definition:

enum Player : String {
    case X = "x"
    case O = "o"

    func other() -> Player {
        switch (self) {
        case .O: return .X
        case .X: return .O
        }
    }

    func image() -> UIImage {
        return UIImage(named: self.rawValue + ".png")!
    }

    static func random() -> Player {
        return arc4random_uniform(2) == 0 ? .O : .X
    }
}

This makes the pickFirstPlayer and toggleNextPlayer() methods
in the view controller obsolete, and viewDidLoad() becomes

override func viewDidLoad() {
    super.viewDidLoad()
    currentPlayer = Player.random()
}

where currentPlayer is defined as

var currentPlayer: Player!

To print a player's name, implement the CustomStringConvertible
protocol:

extension Player : CustomStringConvertible {
    var description: String {
        return self.rawValue.uppercaseString
    }
}

If winner is value of type Player then

gameResult.text = "\(winner) is the winner!"

prints the winner's name using the description method, and you
can adopt that to your needs without affecting the rest of the code or the image resource names.

Your gameState variable describes the contents of the game board,
so I would call it board instead. Each field can be empty, or be
occupied by one of the players. This can be modeled by

var board : [Player?] = [nil, nil, nil,
    nil, nil, nil,
    nil, nil, nil,
]

i.e. an array of optional players.

I would separate the determination of a possible winner from the
display of the outcome, e.g. by defining the method as

func checkForWinner() -> Player? { ... }

which either returns the winner or nil. In that method,

       var row: [String] = []
        for space in combo {
            row.append(gameState[space])
        }

can be simplified using map(). Using the new Player type and return type it  would look this:

func checkForWinner() -> Player? {
    for combo in winningCombos {
        let row = combo.map { board[$0] }
        if (row[0] != nil && row[0] == row[1] && row[1] == row[2]) {
            return row[0]
        }
    }
    return nil
}

It would suffice to check only the rows which are changed by the
last move. On the other hand, with 8 winning combinations, that
does not make a big performance difference.

Assuming that the makeMove() action is connected to buttons
only, you should declare it as

@IBAction func makeMove(sender: UIButton) { ... }

this allows better error checking than sender : AnyObject.
(When you create the action in interface builder, there is an option
for that.)

Using all the above stuff, the makeMove() method becomes

@IBAction func makeMove(sender: UIButton) {
    let space = sender.tag
    if (board[space] == nil && !gameOver) {

        sender.setImage(currentPlayer.image(), forState: .Normal)
        board[space] = currentPlayer
        turnCount++

        if let winner = checkForWinner() {
            gameOver = true
            gameResult.text = "\(winner) is the winner!"
        } else if (turnCount == 9) {
            gameOver = true
            gameResult.text = "It's a tie!"
        } else {
            currentPlayer = currentPlayer.other()
        }
    }
}

You use the UIView's tag property to identify from which button
the action method is called. This is OK, but note that 0 (zero)
is the default tag for all views. It is therefore better to tag the
buttons with 1 ... 9 instead of 0 ... 8, and adjust that in

    let space = sender.tag - 1

A final note about using self: You can access properties and
methods of the current class without using self (unless there
is an ambiguity, e.g. due to a local variable or function parameter with the name name, or if self is captured implicitly in a block.)

Whether you use self or not to access properties is
a matter of taste and programming style,
but in any case it should be consistent in your code, which it
currently isn't:

self.turnCount++
// ...
gameOver = true

(Remark: There was a language proposal to require self for accessing instance members, which
was rejected recently.
Also ++ and -- will be deprecated soon and removed in Swift 3.)


Saving a contact and dealing with exceptions try{save.Username = usernamedetails.Rows[0].ItemArray[0].ToString(); }
catch{ save.Username = ""; }
try { save.Firstname = dtdetails.Rows[0].ItemArray[1].ToString(); }
catch { save.Firstname = ""; }
try { save.LastName = dtdetails.Rows[0].ItemArray[2].ToString(); }
catch { save.LastName = ""; }
try { save.Address1 = dtdetails.Rows[0].ItemArray[3].ToString(); }
catch { save.Address1 = ""; }
try { save.Address2 = dtdetails.Rows[0].ItemArray[4].ToString(); }
catch { save.Address2 = ""; }
try { save.Postoffice = dtdetails.Rows[0].ItemArray[5].ToString(); }
catch { save.Postoffice = ""; }
try { save.District = dtdetails.Rows[0].ItemArray[6].ToString(); }
catch { save.District = ""; }
try{ save.State = dtdetails.Rows[0].ItemArray[7].ToString(); }
catch{ save.State = ""; }
try { save.Country = dtdetails.Rows[0].ItemArray[8].ToString(); }
catch { save.Country = ""; }
try { save.MobileNumber = dtdetails.Rows[0].ItemArray[9].ToString(); }
catch { save.MobileNumber = ""; }
try { save.LandLine = dtdetails.Rows[0].ItemArray[10].ToString(); }
catch { save.LandLine = ""; }
try { save.Pin = dtdetails.Rows[0].ItemArray[11].ToString(); }
catch { save.Pin = ""; }
try { save.Cmpnyname = dtdetails.Rows[0].ItemArray[12].ToString(); }
catch { save.Cmpnyname = ""; }
try { save.Design = dtdetails.Rows[0].ItemArray[13].ToString(); }
catch { save.Design = ""; }
try { save.Loc = dtdetails.Rows[0].ItemArray[14].ToString(); }
catch { save.Loc = ""; }
try { save.CmpnyPincode = dtdetails.Rows[0].ItemArray[15].ToString(); }
catch { save.CmpnyPincode = ""; }
try { save.EmailID = dtdetails.Rows[0].ItemArray[16].ToString(); }
catch { save.EmailID = ""; }
try { save.OffNumber = dtdetails.Rows[0].ItemArray[17].ToString(); }
catch { save.OffNumber = ""; }

Is this type of strategy suitable for coding?

You shouldn't use general catch, you should always catch only the exceptions that you actually want to catch.
Avoidable exceptions like index out of range or null reference should indicate an error in your code. Instead of handling them, you should make sure they never happen.

For your specific case, you could write an extension method that checks that the index isn't out of range and that the value isn't null (and returns empty string if it is).

Something like:

public static string GetAsStringOrEmpty(this object[] array, int index)
{
    if (array == null)
        throw new ArgumentNullException("array");

    if (index >= 0 && index < array.Length)
    {
        string value = array[index] as string;

        if (value != null)
            return value;
    }

    return string.Empty;
}

You would then use it like this:

var array = dtdetails.Rows[0].ItemArray;
save.Firstname = array.GetAsStringOrEmpty(1);
save.LastName = array.GetAsStringOrEmpty(2);
…


Repeatedly incrementing array elements using OpenCL I am learning how to program in opencl and I made a simple program that simply takes an array and adds 1 to every element. I want to run it many times (this is just so that i can benchmark how it does against my cpu, I understand it is a dumb application).

I feel like the way I am doing it right now is inefficient because i seem to be instructing the gpu to do each iteration one by one instead of telling it from the start that it has to do it many times.

Here is my code (Please look for the comment "RELEVANT PART STARTS HERE":

#include <iostream>
#include <CL/cl.hpp>

int main(){
    //get all platforms (drivers)
    std::vector<cl::Platform> all_platforms;
    cl::Platform::get(&all_platforms);
    if(all_platforms.size()==0){
        std::cout<<" No platforms found. Check OpenCL installation!\n";
        exit(1);
    }
    cl::Platform default_platform=all_platforms[0];
    std::cout << "Using platform: "<<default_platform.getInfo<CL_PLATFORM_NAME>()<<"\n";

    //get default device of the default platform
    std::vector<cl::Device> all_devices;
    default_platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices);
    if(all_devices.size()==0){
        std::cout<<" No devices found. Check OpenCL installation!\n";
        exit(1);
    }
    cl::Device default_device=all_devices[0];
    std::cout<< "Using device: "<<default_device.getInfo<CL_DEVICE_NAME>()<<"\n";

    cl::Context context({default_device});

    cl::Program::Sources sources;

    // kernel calculates for each element C=A+B
    std::string kernel_code=
        "   void kernel simple_add(global  int* A){       "
        "       A[get_global_id(0)]=A[get_global_id(0)]+1;                 "
        "   }                                                                               ";
    sources.push_back({kernel_code.c_str(),kernel_code.length()});

    cl::Program program(context,sources);
    if(program.build({default_device})!=CL_SUCCESS){
        std::cout<<" Error building: "<<program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(default_device)<<"\n";
        exit(1);
    }

    const int N = 1e5   ;

    // create buffers on the device
    cl::Buffer buffer_A(context,CL_MEM_READ_WRITE,sizeof(int)*N);

    int A[N] ;

    for(int i = 0;i<N;i++){
        A[i] = i;
    }

    //create queue to which we will push commands for the device.
    cl::CommandQueue queue(context,default_device);

    queue.enqueueWriteBuffer(buffer_A,CL_TRUE,0,sizeof(int)*N,A);

    int C = 1e5;

    // RELEVANT PART STARTS HERE !!!

    for(int i = 0;i<C;i++){
        cl::Kernel kernel_add=cl::Kernel(program,"simple_add");
        kernel_add.setArg(0,buffer_A);
        queue.enqueueNDRangeKernel(kernel_add,cl::NullRange,cl::NDRange(N),cl::NullRange);
        queue.finish();
    }

    // RELEVANT PART ENDS HERE !!!

    queue.enqueueReadBuffer(buffer_A,CL_TRUE,0,sizeof(int)*N,A);

    printf("%d\n",A[N-4]);

    return 0;
}

Sorry, but this is a general review and will not answer your specific question. While this is a simple test program, it is good to develop some habits in writing C or C++ programs.

Complexity
One of the good habits to keep in mind is the Single Responsibility Principle which states

  "every module, class, or function should have responsibility over a
  single part of the functionality provided by the software, ...".

The Single Responsibility Principle is the first pillar in SOLID programming. SOLID programming is a set of principles that generally improve object oriented programming.

The code is too complex to be in one function, main() could be divided into may functions that would make it easier to read and debug. Generally main() should do the following when necessary:
 - call a function to process command line arguments.
 - call functions to set up for any processing
 - call one function to do the processing, this function may call
   many other functions
 - call functions to clean up after processing

In this program there doesn't seem to be any command line arguments so that function isn't necessary. Some possible functions called by main():
 - Set Up Platforms
 - Set Up Devices
 - Set Up Program
 - Set Up Queues
 - Execute Program
Any or all of these functions can return bool or int to indicate success or failure

Use System Defined Constants to Make Code More Readable
Rather than using return(1); or return(0) in main there are constants defined in cstdlib or stdlib.h that indicate success or failure of a program, these are EXIT_SUCCESS and EXIT_FAILURE. Since they are system defined they are more portable than zero or one. They also make the code self documenting:

    return(EXIT_SUCCESS);

    return(EXIT_FAILURE);

Avoid the Use of the Exit Function in C++ and C
The code is good in that it only calls std::exit() from main(), however, it is generally a bad idea to call std::exit() especially from functions that are not main(). When calling exit from a function other than main no cleanup code will be called and if the program is a program that shouldn't terminate such as an operating system there can be dire side effects. Even calling exit from main may not clean up after processing as explained in this stackoverflow.com question. The accepted practice is to call return from main.


setup.py with data_files and __author__ parsing All my projects have a fairly similar package layout:

package_name/
package_name/setup.py
package_name/package_name/__init__.py
package_name/package_name/data/foo.txt

package_name/package_name/__init__.py contains:

__version__ = '0.0.1'
__author__ = 'Alec Taylor <alec.taylor6@gmail.com>'

With a setup.py like:

from setuptools import setup, find_packages
from os import path, listdir
from functools import partial
from itertools import imap, ifilter
from ast import parse
from pip import __file__ as pip_loc

if __name__ == '__main__':
    package_name = 'foooooo'

    f_for = partial(path.join, path.dirname(__file__), package_name)
    d_for = partial(path.join,path.dirname(path.dirname(pip_loc)), package_name)
    to_funcs = lambda name: (partial(path.join, f_for(name)),
                             partial(path.join, d_for(name)))

    _data_join, _data_install_dir = to_funcs('data')

    get_vals = lambda var0, var1: imap(
                   lambda buf: next(imap(lambda e: e.value.s, parse(buf).body)),
                       ifilter(lambda line: line.startswith(var0) or
                                            line.startswith(var1), f))

    with open(path.join(package_name, '__init__.py')) as f:
        __author__, __version__ = get_vals('__version__', '__author__')

    setup(name=package_name,
        author=__author__,
        version=__version__,
        test_suite=package_name + '.tests',
        packages=find_packages(),
        package_dir={package_name: package_name},
        data_files=[
            (_data_install_dir(), map(_data_join, listdir(_data_join())))
        ]
    )

This setup.py has been tested on Windows and Linux with Python 2.7.

PS: I'm planning to upgrade all my packages to work with 2.7 and 3+.

Your use of lambdas and partials makes no sense, and is really hard to understand. If you need them to be functions then just make them functions. Or even better, just write the code out. Some of them are just one-off functions and don't add any value, and should be inlined. The others are just ridiculously hard to read, and should be defined as normal functions.

First let's look at how you get the values from the file. I'm pretty sure I know what the general idea of your algorithm is.

for line in source file
    if the line has one of the values we want
        parse the line, and save the value

This is much easier to implement like this

def extract_values(source_file, desired_vars):
    with open(source_file) as f:
        for line in f:
            if any(line.startswith(var) for var in desired_vars):
                parsed = ast.parse(line).body[0]
                yield parsed.targets[0].id, parsed.value.s

filename = path.join(package_name, '__init__.py')
metadata_names = '__author__', '__version__'
values = dict(extract_values(filename, metadata_names))

Using all of your lambdas and iterables doesn't seem to give much value - I assume you were doing them because this is potentially a big file and you don't want it all in memory? If so don't worry about it - doing the for line in f automatically does buffered-IO and memory management.  Then we can use a generator and construct a dict from it.  This is much more readable, and is unlikely to make much of a difference in performance. More importantly, however, is that unless you're doing something ridiculous in setup.py it shouldn't really matter.

Next let's look at how you get the data files.  I cannot figure out why you did it this way. This line:

data_files=[
    (_data_install_dir(), map(_data_join, listdir(_data_join())))
]

is basically nonsensical.  You map _data_join onto each file inside of calling _data_join()?  What we really have here are two constants - some data install directory, and some data file directory. We want to list all of the files in the data file directory, and pair them with the data install directory.  We can just do something like this

data_files = data_install_folder, [path.join(data_file_source, filename) for filename in listdir(data_file_source)]

Putting this all together, we have something like this

from setuptools import setup, find_packages
import os
import ast

from compatibility import filter, map
from pip import __file__ as pip_loc

def extract_values(source_file, desired_vars):
    with open(source_file) as f:
        for line in f:
            if any(line.startswith(var) for var in desired_vars):
                parsed = ast.parse(line).body[0]
                yield parsed.targets[0].id, parsed.value.s

if __name__ == '__main__':
    package_name = 'foooooo'

    filename = os.path.join(package_name, '__init__.py')
    metadata_names = '__author__', '__version__'
    values = dict(extract_values(filename, metadata_names))

    data_file_source = os.path.join(os.path.dirname(__file__), package_name)
    data_install_folder = os.path.join(os.path.dirname(path.dirname(pip_loc)), package_name)

    all_data_files = os.path.join(data_file_source, filename) for filename in listdir(data_file_source)
    data_files = [(data_install_folder, all_data_files)]

    setup(name=package_name,
        author=values['__author__'],
        version=values['__version__'],
        test_suite=package_name + '.tests',
        packages=find_packages(),
        package_dir={package_name: package_name},
        data_files=data_files
    )

As a quick note, if you want to get things working for both Python 2 and Python 3, imap and ifilter don't exist in Python 3. I usually like to make a file like compatibility.py that I put things like that into, then just import from that.

try:
    from itertools import imap as map, ifilter as filter
except ImportError:
    pass


Prompting the user to enter Name value pairs and then printing it out using a Name_value class I am learning from Bjarne Stroustrup's book for beginners and I on Chapter 6 Exercise 4 as seen below. I am studying it alone and I need some reviews.

Are my comments any good?

Can you recommend me some improvements regarding comments or overusing functions?

The writer of the book has some solutions for his exercise and he doesn't use the put_in function for example.

Are global variables that bad? I used it when declaring vector<Name_value>pairs.

/*
4. Define a class Name_value that holds a string and a value. Rework exercise 19 in Chapter 4 to use a
vector<Name_value> instead of two vectors.

Chapter 4 : 19. Write a program where you first enter a set of name-and-value pairs, such as Joe 17 and Barbara 22. For each pair, add
the name to a vector called names and the number to a vector called scores (in corresponding positions, so that if
names[7]=="Joe" then scores[7]==17). Terminate input with NoName 0. Check that each name is unique and
terminate with an error message if a name is entered twice. Write out all the (name,score) pairs, one per line.
*/

#include "../../std_lib_facilities.h"

const string print_names = "NoName";
const int print_val = 0;

//class of the name and corresponding value
class Name_value {
public:
    string Name;        //the name of the person
    int value;          //their respective score
    Name_value(string Na, int val)
        :Name(Na), value(val) { }
};
vector<Name_value>pairs;        //the list of names and their corresponding values

//put the pairs in the vector
vector<Name_value> put_in(string x, int y) {
    pairs.push_back(Name_value(x,y));
    return pairs;
}

int main()
try
{
    string names;
    int scores;
    cout << "Enter 'NoName' and score '0' when you want to print out the results!\n";
    cout << "Please enter some names and their scores (Ex.: Joe 22 Anne 53): ";
    while (cin) {
        cin >> names >> scores;
        if (!cin) error("You have not entered a string and then a value!\n");
        if (names == print_names && scores == print_val) {
            cout << "The list of pairs entered: \n";
            for (int i = 0; i < pairs.size(); i++) {
                 cout << pairs[i].Name << '\t' << pairs[i].value << '\n';
            }
            break;
        }
        for (int i = 0; i < pairs.size(); i++)
        {
            if (names == pairs[i].Name) error("Duplicates found!\n");
        }
        pairs = put_in(names, scores); //put the values into the vector list
    }
}
catch (exception&e)
{
    cerr << "error: " << e.what() << '\n';
    return 1;
}

Yes, global variables really are that bad. Do try to avoid them.
Personally I find it easier to read if you add some vertical space to your member initializer list like so:

Foo(int a, int b)
    : a{a}
    , b{b}
{}

Don't omit braces as that can lead to hard to find bugs (For example Apple's goto fail bug would have been much easier to spot if braces had been used.
Prefer prefix over postfix
It's okay to use whitespace more leniently

// This might be debatable
pairs.push_back(Name_value(x,y));

// But this just looks strange
catch (exception&e)

Considering that you add a space everywhere else in the code you might as well add one in those cases.
Your naming could be improved. Namely put_in, x and y are not the greatest variable names. Also why is Name capitalized? Why names and scores when they only hold one name/score? Remember that variable names should always reflect intent as your goal is to write self-documenting code.
This code is confusing

pairs = put_in(names, scores); //put the values into the vector list

First get rid of that comment. Second, why are you returning the vector after you already added the values to it? Why even use a function for this in the first place? Simply doing:

pairs.push_back(Name_value(names, scores));

Has the same effect.
While you didn't write it, you still use using namespace std included via the header file provided by Bjarne(?).
Just a reminder that this is considered bad
but hopefully it will be explained further into the book as well.
I'm no expert on exceptions but the way you use them seems wonky, maybe someone else can chime in here.


Using jQuery UI .position() in a backwards compatible way Trying to implement this API in a way that works pre and post jQuery UI 1.9:

I have a subtle feeling that there should be a more elegant way.

/** Prefix number with '+'/'-' or return empty string for 0. */
function offsetString(n){
    return n === 0 ? "" :(( n > 0 ) ? ("+" + n) : ("" + n));
}

var posOpts = {
    at: "left top",
    of: $target
};

if( isVersionAtLeast($.ui.version, 1, 9) ){
    posOpts.my = "left" + offsetString(markerOffsetX) +
       " top" + offsetString(markerOffsetY);
} else {
    posOpts.my = "left top";
    posOpts.offset = "" + markerOffsetX + " " + markerOffsetY;
}
$dropMarker.position(posOpts);

Interesting question,

have you tried passing +0 as an offset, that should work and make your code a little easier to read.

/** Prefix number with '+'/'-' or return empty string for 0. */
function offsetString(n){
    return '' + ( n < 0 ? n : '+' + n );
}

As for the isVersionAtLeast($.ui.version, 1, 9) I would only check this once.

function generateCompatibleOffsetFunction(){

  if( isVersionAtLeast($.ui.version, 1, 9) ){
    return function setOffset( options , offsetX , offsetY ){
      options.my = "left" + offsetString(offsetX ) + " top" + offsetString(offsetY );
    }
  } else {
    return function setOffset( options , offsetX , offsetY ){
      options.my = "left top";
      options.offset = "" + offsetX + " " + offsetY;
    }
  }
}

var setOffset = generateCompatibleOffsetFunction();

/** Prefix number with '+'/'-' or return empty string for 0. */
function offsetString(n){
    return '' + ( n < 0 ? n : '+' + n );
}

var posOpts = {
    at: "left top",
    of: $target
};

setOffset( posOpts, markerOffsetX, markerOffsetY );

$dropMarker.position(posOpts);


breadcrumbs in spring Breadcrumbs should look like this:
Home > Mobiles & Tablets > Mobile Phones > Phone Super Duper

every product belongs only to one category. e.g Phone Super Duper can be found only under Mobile Phones.
This is just a sketch but i want to know your opinion if the direction is ok or i should change the strategy.

ANY critique or suggestions are welcome
 JSP

    <c:forEach items="${breadcrumbs}" var="breadcrumb" varStatus="status">

&gt;

<c:choose>
                <c:when test="${breadcrumb.url eq '#'}">
                    <a href="#" onclick="return false;"
                        <c:if test="${status.last}">class="last"</c:if>>${breadcrumb.name}
                </c:when>

                <c:otherwise>
                    <a href="${baseURL2}${breadcrumb.url}"
                        <c:if test="${status.last}">class="last"</c:if>>${breadcrumb.name}
                </c:otherwise>

            </c:choose>

    </c:forEach>

HomePageController

@RequestMapping("/")
    public String showHomePage(HttpServletRequest request, Model model) {
        model.addAttribute("breadcrumbs", contentPageBreadcrumbBuilder.getBreadcrumbs(request.getServletPath()));
        return "welcome";
    }

ProductPageController

@RequestMapping(value = "/product")
    public String getProductById(@RequestParam("id") int productId, Model model) {
        Product product = new Product();
        Category  category = new Category();
        category.setCategoryName("someCategory");
        product.setProductId(1);
        product.setProductName("someProductName");
        product.setCategory(category);
        model.addAttribute("breadcrumbs",  productBreadcrumbBuilder.getBreadcrumbs(product));
        return "product";
    }

ProductBreadcrumbsBuilder

@Component
public class ProductBreadcrumbBuilder {
    public List<Breadcrumb> getBreadcrumbs(final Product productModel) throws IllegalArgumentException {
            final List<Breadcrumb> breadcrumbs = new ArrayList<>();
            breadcrumbs.add(getProductBreadcrumb(productModel));
            Breadcrumb category = getCategoryBreadcrumb(productModel.getCategory());
            breadcrumbs.add(category);
            Collections.reverse(breadcrumbs);
            return breadcrumbs;
        }

        protected Breadcrumb getProductBreadcrumb(final Product product) {
            final String productUrl = "/products/" + product.getProductId();
            return new Breadcrumb(productUrl, product.getProductName());
        }

        protected Breadcrumb getCategoryBreadcrumb(final Category category) {
            final String categoryUrl = "/categories/" + category.getId();
            return new Breadcrumb(categoryUrl, category.getCategoryName());
        }

Breadcrumb

public class Breadcrumb {

    private String url;
    private String name;

    public Breadcrumb(final String url, final String name)
    {
        this.url = url;
        this.name = name;
    }

REST apis usually have

GET /products - retrieves all products
GET /products/10 - retrieves product with id 10.

And thus I'd suggest that instead of requesting GET /product?id=10, you do GET /product/10.

Take a look at the URL in your webbrowser - this is GET /questions/119636/.


Direction enum class As request of Simon's comment:

Direction.java

package net.woopa.dungeon.datatypes;

import java.util.Random;

public enum Direction {
    NORTH, EAST, SOUTH, WEST;
    private static Random rnd = new Random();

    static public Direction randomDirection() {
        return Direction.values()[rnd.nextInt(4)];
    }

    // Rotate 90 degrees clockwise
    public Direction rotate90() {
        return values()[(ordinal() + 1) % 4];
    }

    // Rotate 180 degrees
    public Direction rotate180() {
        return values()[(ordinal() + 2) % 4];
    }

    // Rotate 270 degrees clockwise (90 counterclockwise)
    public Direction rotate270() {
        return values()[(ordinal() + 3) % 4];
    }

    public Boolean isHorizontal() {
        return this == EAST || this == WEST;
    }

    public Boolean isVertical() {
        return this == NORTH || this == SOUTH;
    }

    public int dx(int steps) {
        if (this == EAST) {
            return steps;
        }
        if (this == WEST) {
            return -steps;
        }
        return 0;
    }

    public int dy(int steps) {
        if (this == NORTH) {
            return steps;
        }
        if (this == SOUTH) {
            return -steps;
        }
        return 0;
    }

    public int forwards_x(int n) {
        if (this == EAST) {
            return n + 1;
        }
        if (this == WEST) {
            return n - 1;
        }
        return n;
    }

    public int forwards_y(int n) {
        if (this == NORTH) {
            return n + 1;
        }
        if (this == SOUTH) {
            return n - 1;
        }
        return n;
    }

    public int backwards_x(int n) {
        if (this == EAST) {
            return n - 1;
        }
        if (this == WEST) {
            return n + 1;
        }
        return n;
    }

    public int backwards_y(int n) {
        if (this == NORTH) {
            return n - 1;
        }
        if (this == SOUTH) {
            return n + 1;
        }
        return n;
    }

    public int left_x(int n) {
        if (this == NORTH) {
            return n - 1;
        }
        if (this == SOUTH) {
            return n + 1;
        }
        return n;
    }

    public int left_y(int n) {
        if (this == EAST) {
            return n + 1;
        }
        if (this == WEST) {
            return n - 1;
        }
        return n;
    }

    public int right_x(int n) {
        if (this == NORTH) {
            return n + 1;
        }
        if (this == SOUTH) {
            return n - 1;
        }
        return n;
    }

    public int right_y(int n) {
        if (this == EAST) {
            return n - 1;
        }
        if (this == WEST) {
            return n + 1;
        }
        return n;
    }
}

What are your thoughts about this class?  The main grip I have personally is the left_y, right_x, etc methods. The code works, and here is some example of its usage below. But I feel there may be a better way?

Example usage:

Direction dir = Direction.randomDirection();
if (grid.get(dir.left_x(x), dir.left_y(y)).equals(CoreMaterial.WALL) && grid.get(dir.right_x(x), dir.right_y(y)).equals(CoreMaterial.WALL) && grid.get(dir.backwards_x(x), dir.backwards_y(y)).equals(CoreMaterial.FLOOR) && grid.get(dir.forwards_x(x), dir.forwards_y(y)).equals(CoreMaterial.FLOOR)) {
    StandardMethods.build_door(dir, new Vector2D(x, y), CoreMaterial.CAKE, grid);
}

The above example has a location (x,y) for a door on a grid and then checks around it to ensure that there are doors either side and floors the other two either sides?

Symbols:

. = floor

# = wall

+ = door

Example:

.#.
.+.
.#.

This would be okay for the placing of the door.

There are two things I think worth mentioning here:

use of random
magic numbers in enums

Random

Even though the java.util.Random class is thread-safe, it is not a great idea to use them in a multi-threaded context. As your class is an enum, it is likely that at some point it may be used in a threaded context (if it is not already). You should consider changing your code:

private static Random rnd = new Random();

to instead be (note also that this is 'final', and this is a java.util.concurrent.ThreadLocalRandom):

private static final ThreadLocalRandom rnd = ThreadLocalRandom.current();

This will give you better scalability in the future (or the present if you are already multi-threaded.

Enum Magic Numbers

Enums are a great concept in Java, and, it is one of those places where I believe magic numbers (special values with little apparent context or meaning) are really useful, and are OK.

You can embed 'magic' in with the enums and not worry too much about the readability... enums are supposed to be magic things.... So, I would consider code like the following:

import java.util.concurrent.ThreadLocalRandom;

public enum Direction {

    // use magic numbers to set the ordinal (used for rotation),
    // and the dx and dy of each direction.
    NORTH(0, 0, 1),
    EAST(1, 1, 0),
    SOUTH(2, 0, -1),
    WEST(3, -1, 0);

    private static final ThreadLocalRandom rnd = ThreadLocalRandom.current();

    static public Direction randomDirection() {
        return Direction.values()[rnd.nextInt(4)];
    }

    private final int r90index, r180index, r270index;
    private final boolean horizontal, vertical;
    private final int dx, dy;

    private Direction(int ordinal, int dx, int dy) {
        // from the ordinal, dx, and dy, we can calculate all the other constants.
        this.dx = dx;
        this.dy = dy;
        this.horizontal = dx != 0;
        this.vertical = !horizontal;
        this.r90index  = (ordinal + 1) % 4;
        this.r180index = (ordinal + 2) % 4;
        this.r270index = (ordinal + 3) % 4;
    }

    // Rotate 90 degrees clockwise
    public Direction rotate90() {
        return values()[r90index];
    }

    // Rotate 180 degrees
    public Direction rotate180() {
        return values()[r180index];
    }

    // Rotate 270 degrees clockwise (90 counterclockwise)
    public Direction rotate270() {
        return values()[r270index];
    }

    public Boolean isHorizontal() {
        return horizontal;
    }

    public Boolean isVertical() {
        return vertical;
    }

    public int dx(int steps) {
        return dx * steps;
    }

    public int dy(int steps) {
        return dy * steps;
    }

    public int forwards_x(int n) {
        return n + dx;
    }

    public int forwards_y(int n) {
        return n + dy;
    }

    public int backwards_x(int n) {
        return n - dx;
    }

    public int backwards_y(int n) {
        return n - dy;
    }

    public int left_x(int n) {
        // if we are E/W facing, our left/right 'x' co-ords are still 'x'
        // if we are N/S facing, our left/right 'x' is `-dy`
        return n - dy;
    }

    public int left_y(int n) {
        // see left_x comments for the idea
        return n + dx;
    }

    public int right_x(int n) {
        // see left_x comments for the idea
        return n + dy;
    }

    public int right_y(int n) {
        // see left_x comments for the idea
        return n - dx;
    }
}

The code above is very efficient. There are no conditionals in the methods, they will likely all be inlined in to the calling code. The 'smarts' are all contained within the enum, it 'just works'.


Invoking only the last registered event handler We are building a game and we have a dialog system. Dialogs may open and stack on top of one another.

When every dialog opens, it registers itself to handle the BackButtonPressed event:

AppHelper.OnBackPressed += HandleBackPressed;

When the dialog closed, it unhooks from the event:

AppHelper.OnBackPressed -= HandleBackPressed;

The problem is, we'd like the event to raise the event handler of the active dialog only (the active dialog is the last one registered to the event.

A proposed solution was to:

Manually create the add and remove methods for the event
Keeping registered handlers in a list.
When raising the event, call the last handler in the list

Here's an example in code, is this the proper way of doing this?

private static List<BackPressed> backPressed = new List<BackPressed>();

public static event BackPressed OnBackPressed
{
    add
    {
        backPressed.Add(value);
    }
    remove
    {
        if(backPressed.Contains(value))
        {
            backPressed.Remove(value);
        }
    }
}

Raising the event:

backPressed[backPressed.Count - 1].Invoke();

Yes, this is a reasonable way to implement the event. Another would be use the normal even implementation (without explicit add and remove) and get the last subscriber using GetInvocationList().

But I think the fundamental problem here is that what you want doesn't really behave like an event, so it probably shouldn't be an event.

What I would probably do is to make the abstraction something like “a collection of open Dialogs”, not “a collection of delegates that are going to be invoked when the back button is pressed”.

That way, you can easily access the top-most open Dialog and invoke its HandleBackPressed() method. But you could also use it for other purposes. So this would make your code more flexible, without adding much complexity.


Rendering different view classes based on the value of a string Here I'm instantiating different classes based on the value of a type property. This type property will determine what view is rendered and displayed on screen to the user.

As you can see there's a lot of repetition here. The main problem I'd like to eliminate is all those else ifs.

onShow: function() {
    var type = this.model.get('type').toLowerCase();

    if (type === 'face') {
        this.regionItems.show(new FaceDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    } else if (type === 'voice') {
        this.regionItems.show(new VoiceDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    } else if (type === 'text-prompted') {
        this.regionItems.show(new VoiceDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));

    } else if (type === 'face-password (text)') {
        this.regionItems.show(new PinDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));

    } else if (type === 'pin') {
        this.regionItems.show(new PinDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    }  else if (type === 'live voice') {
        this.regionItems.show(new VoiceLiveness({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    } else if (type === 'voice-face (image)') {
        this.regionItems.show(new FaceDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    } else if (type === 'voice-face (audio)') {
        this.regionItems.show(new VoiceDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    } else if (type === 'gps') {
        this.regionItems.show(new GPSDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));

    } else if (type === 'face-password (image)') {
        this.regionItems.show(new FaceDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    } else if (type === 'voice-face (challenge audio)') {
        this.regionItems.show(new VoiceLiveness({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    } else if (type === 'fingerprint') {
        this.regionItems.show(new FingerDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    }
}

I intend to extract

{
    model               : this.model,
    authRequestModel    : this.authRequestModel,
    collection          : this.model.attemptItemsDataCollection
}

to the top of the method as an options variable and then pass it to the constructor when I instantiate each view (FaceDetail, VoiceDetail, etc.)

After this I'm still left with all those else ifs.

The obvious answer is to introduce a map:

var typeToConstructor = {
    'face' : FaceDetail,
    'voice' : VoiceDetail,
    // ...
}

Then you can simply look up your constructor function:

onShow: function() {
    var type = this.model.get('type').toLowerCase();
    var constructor = typeToConstructor[type];
    if (typeof constructor !== 'function') {
        // Unknown type... do something
    }

    // execute the constructor.
    this.regionItems.show(new constructor({
        model               : this.model,
        authRequestModel    : this.authRequestModel,
        collection          : this.model.attemptItemsDataCollection
    });
}


VBA Error Handling Sub, Working for all subs The idea is to make an error handling procedure, which prints messages in DEV mode and shows MsgBox in PROD mode. Looking for any wise idea to improve it:
Public Const SET_IN_PRODUCTION = False

Sub TestMe()

    On Error GoTo TestMe_Error
    Debug.Print 0 / 0
    Exit Sub

TestMe_Error:
    StandardError Err, "TestMe"

End Sub

Public Sub StandardError(myError As Object, Optional moduleName As String = "")

    If SET_IN_PRODUCTION Then
        MsgBox "Error in " & moduleName & vbCrLf & myError.Description, vbCritical, title:=myError.Number
    Else
        Debug.Print "Error in "; moduleName & vbCrLf & myError.Description
    End If

End Sub

The lines StandardErr Err are to be used for almost any procedure and function in the code, for "advanced" error handling.

Passing around the Error object like this feels intuitively like a good way of freezing error state and providing it to logging/error reporting functions, so I see why you've come up with this.
Reading the comments, @HackSlash does make a good point - that myError could hold anything if it's declared As Object, and that could lead to errors when you try to get its Description or Number. I'd probably change the signature from this:

Public Sub StandardError(myError As Object, Optional moduleName As String = "")

... to this
Public Sub StandardError(ByVal myError As VBA.ErrObject, Optional ByVal moduleName As String = "")
    If myError Is Nothing Then Err.Raise 5, Description:="Must pass valid Err Object"

ByVal because we don't need to change what the caller's copy of the variable points to
By declaring myError with the type (interface) we want, it means rather than receiving the generic and somewhat obscure error message:

Run-Time Error 438
Object doesn't support this property or method

... or even harder to diagnose if Nothing is passed;

Run-Time Error 91
Object variable or With block variable not set

... we get a clearer Type Mismatch error that takes us right to the source

The calling site is pretty simple though, so it's unlikely you'd type it in wrong, but still, doesn't harm to add some Error checking. But come to think of it, what does happen if an Error is raised inside the error handling routine? Or If I call Err.Clear? Doing this:
Public Sub StandardError(ByVal myError As ErrObject, Optional moduleName As String = "")

    Err.Clear    'do something to modify GLOBAL error state

    If SET_IN_PRODUCTION Then
        MsgBox "Error in " & moduleName & vbCrLf & myError.Description, vbCritical, Title:=myError.Number
    Else
        Debug.Print "Error in "; moduleName & vbCrLf & myError.Description
    End If

End Sub

... results in no Error being printed - myError.Description has been cleared even though I never touched myError explicitly, something funny is going on here...

It turns out Err is not some locally scoped variable that gets supplied as a hidden argument to every Sub or Function, and which you can just pass around. If we look in the object browser it is in fact a function in the VBA.Information module that returns an object of type VBA.ErrObject, but crucially, this is the same object every time. Or in other words (taken from an answer on SO):

When you encapsulate an ErrObject like you did, you're essentially
just giving yourself another way (besides the Err function) to
access the ErrObject instance - but it's still the exact same object
holding the properties of the current run-time error state.

What this means is that you never need to pass the "Err Object" to the logging routine at all, since the Err function will provide access already. What this also means is that you need to be very careful about the possibility of errors creeping into your logging function, since even if these are ignored, they will reset the global error state and your logger could now misreport the errors.
Admittedly, your logger is very simple, so this doesn't present any immediate problem, but what if in the future you want to log to a file:
Private Function GetFile(ByVal path As String) As File

   Dim result As File

   'Try open log file, catch error if it doesn't exist
   On Error Resume Next
   Set result = File.Open(path)
   On Error Goto 0

   'If log file didn't exist, make a new one
   If result = Nothing Then Set result = File.NewFile(path)

   Set GetFile = result
End Function

Public Sub StandardError(Optional moduleName As String = "")

    Set myFile = GetFile("C:/Users/blah/log.txt") 'Ooops, just nuked global error state

    If SET_IN_PRODUCTION Then
        MsgBox "Error in " & moduleName & vbCrLf & Err.Description, vbCritical, title:=myError.Number
    Else
        myFile.Print "Error in "; moduleName & vbCrLf & Err.Description
    End If

End Sub

o.k that's just pseudocode, I know myFile.Print is invalid syntax, but you get the idea
As Mathieu points out in that post I linked, you can roll your own class that saves runtime error state if you want to be safe, but even that has drawbacks. I find the best way to tackle this is to pass the relevant bits to a generic logger like I did here:

logError "WinAPI.SetTimer", Err.Number, Err.Description

and freeze the Err state precisely when you want to.

#Conditional Compilation

Public Const SET_IN_PRODUCTION = False

I'd probably use conditional compilation here
#If SET_IN_PRODUCTION Then
    MsgBox "Error in " & moduleName & vbCrLf & myError.Description, vbCritical, Title:=myError.Number
#Else
    Debug.Print "Error in "; moduleName & vbCrLf & myError.Description
#End If

and define SET_IN_PRODUCTION either in the project's settings or with code
#Const SET_IN_PRODUCTION = False

simply because conditional compilation is quite a standard method for Debug vs Ship mode, and it replaces a runtime If statement called many times with a compile time one called only once


Implementing a very simple memory block for quick allocation and memory alignment. C++ This is programmed in Visual Studio 2019 with the C++17 feature set.
The intent with this code is to be able to create memory blocks of the specified alignment and size, so as to have contiguous cache-friendly memory and to only do one malloc and free for the whole block. Is there something wrong or missing from this implementation so that it would effectively fulfill its purpose?
MemoryBlock.h
#pragma once
class MemoryBlock
{
private:
    void* p_rawMem;
    void* p_currentMemLocation;
    size_t p_currentMemLocationOffset;
    size_t p_totalMemSize;
    size_t p_remainingMemSize;
    size_t p_alignment;
    void *p_lastMemByteLocation;
    void p_addCurrentMemLocation(size_t delta);
public:
    MemoryBlock(size_t size, size_t alignment);
    void* getMemoryWith(size_t size, size_t alignemnt);
    ~MemoryBlock();
};

MemoryBlock.cpp
#include <memory>
#include <stdexcept>
#include <cmath>
#include <assert.h>
#include "MemoryBlock.h"

void MemoryBlock::p_addCurrentMemLocation(size_t delta)
{
    if (delta == 0) {
        return;
    }
    p_currentMemLocationOffset += delta;
    assert((p_currentMemLocationOffset) <= p_totalMemSize);
    p_remainingMemSize -= delta;
    if (p_remainingMemSize == 0) {
        p_currentMemLocation = p_lastMemByteLocation;
    }
    else {
        p_currentMemLocation = static_cast<void*>(static_cast<char*>(p_currentMemLocation) + delta);
    }

}

MemoryBlock::MemoryBlock(size_t size, size_t alignment):
    p_rawMem(_aligned_malloc(size, alignment)),
    p_currentMemLocation(p_rawMem),
    p_currentMemLocationOffset(0),
    p_totalMemSize(size),
    p_remainingMemSize(size),
    p_alignment(alignment),
    p_lastMemByteLocation(static_cast<void*>(static_cast<char*>(p_rawMem) + (size - 1)))
{
}

void* MemoryBlock::getMemoryWith(size_t size, size_t alignment)
{
    if (size > p_totalMemSize) {
        throw std::bad_alloc();
    }
    if (size == 0) {
        throw std::invalid_argument("size must be greater than 0");
    }
    if (alignment == 0 || (alignment &(alignment-1))!= 0) {//checks it alignment is power of 2
        throw std::invalid_argument("alignment should be a power of 2.");
    }
    if (alignment > p_alignment) {
        throw std::invalid_argument("alignment requirement is greater than the memory block alignment.");
    }
    if (size > p_remainingMemSize) {
        return nullptr;
    }
    if (p_totalMemSize == p_remainingMemSize) {
        p_addCurrentMemLocation(size);
        return p_rawMem;
    }
    p_addCurrentMemLocation((std::ceil(p_currentMemLocationOffset/(double)alignment)*alignment)-p_currentMemLocationOffset);
    void* retVal = p_currentMemLocation;
    p_addCurrentMemLocation(size);
    return retVal;
}

MemoryBlock::~MemoryBlock()
{
    _aligned_free(p_rawMem);
}

main.cpp
int main()
{
    MemoryBlock memBlock(1024,1024);
    int *memBlockIntPtr = new(memBlock.getMemoryWith(sizeof(int),alignof(int))) int(1);
    std::cout << *memBlockIntPtr << std::endl;
    constexpr size_t intArrSize = 4;
    int *memBlockIntArrPtr = static_cast<int*>(memBlock.getMemoryWith(sizeof(int)*intArrSize, alignof(int)));
    for (size_t i = 0; i < intArrSize; i++)
    {
        new (&memBlockIntArrPtr[i]) int(i);
    }
    for (size_t i = 0; i < intArrSize; i++)
    {
        std::cout << memBlockIntArrPtr[i] << std::endl;
    }
    return 0;
}

I also ask you if the usage of the code is correct in the main function, and if I'm handling the void pointers adequately in both single-variable and array cases. If not, of course, please correct me with an explanation. Say if I'm doing main, specifically, correctly or the whole thing- and if not, make it clear why. Also suggest if I should be using an underlying memory buffer of char* instead of void* (perhaps combined with static arrays).

Use C++17 aligned new or aligned_malloc()
_aligned_malloc() is a Windows-specific, non-portable function. Luckily, C++17 added the portable aligned_malloc() without an underscore. It also introduces a variant of new that allows aligned allocation. The latter would look like so:
#include <new>
...
MemoryBlock::MemoryBlock(size_t size, size_t alignment):
    p_rawMem((void *)new(std::align_val_t(alignemnt)) char[size]),
    ...
{
}

Unnecessary special case for p_remainingMemSize == 0
Why is this a special case in p_addCurrentMemLocation? Just adding delta to the current pointer is perfectly fine. A pointer that points just beyond the end of an array or an allocated memory region is still a valid pointer.
Consider avoiding the check for delta == 0
An if-statement is not free, especially not if the branch predictor cannot correctly predict the result of the condition. If delta is zero, then the rest of the code still works correctly, and it's just two additions and a subtraction.
Don't use floating point math
You should not need to use floating point math to calculate how much to advance p_currentMemLocationOffset inside getMemoryWith(). Depending on which processor your code is running on, converting to double and back to size_t can be an expensive operation. Furthermore, double has less precision than size_t on 64-bits machines, so the result might be wrong if very large memory blocks are used.
Instead of ceil(p_CurrentMemLocationOffset / (double)alignment), use the fact that integer division rounds down, and compensate for this by adding alignment - 1 first:
p_addCurrentMemLocation((((p_currentMemLocationOffset + alignment - 1) / alignment) * alignment) - p_currentMemLocationOffset);

Alternatively, use the modulo operation to determine how much to add:
p_addCurrentMemLocation((alignment - p_currentMemLocationOffset % alignment) % alignment);

The latter will be especially fast if the compiler can deduce that alignment is always a power of two.
char * vs. void *
It's probably easier to use char * internally for the pointers, since you are doing arithmetic on them. And if you do that, the only time you need to cast is when returning from getMemoryWith().