Add numbers in array without adding adjacent number This is first time I code reviewing and would like feedback on coding in industry standards and optimum code.

This program adds number in array in two formats:

Adds adjacent numbers in a serial manner as proof for the actual sum to refer to the required output.
Adds the last and first variables in the array.

import java.util.stream.IntStream;

class  twoadj1
{
    public int a;
    public int b[];
    public int sum=0;
    public int sum1=0;
    public int k=0;
    public int m=0;
    twoadj1(int size)
    {
    b = new int[size];
    k = size-1;
    m = size;
    }
    void valueadd()
    {
        {

        for(int z = 0; z < b.length; z++) {
            b[z] = (int)(Math.random()*9);

        System.out.print(b[z]+ " ");
        int sum = IntStream.of(b).sum();
        System.out.println("real sum"+sum);
        }
        for (int j=0;j<b.length/2;j++)

            {

        sum1 = sum1+b[j]+b[k];
        k--;
        System.out.println("Process: " +sum1);
            }
        if((m%2)==0)
            System.out.println("Sum after required output1: " +sum1);
            else if((m%2)==1)
            {
            sum1 += b[m/2];
            System.out.println("Sum after required output2: "+sum1);
            }

        }
    }
}

public class twoadj {
    public static void main(String[] args)
    {
    twoadj1 a = new twoadj1(5);
    a.valueadd();
    }
}

Your indentation is inconsistent, and it looks like you got confused yourself, since you are computing and printing "real sum" many times.

The code organization could use improvement as well.  The valueadd() function does a lot of stuff:

Populating the array with random members
Printing the array
Summing the array using streams, and printing that sum
Summing the array by working from the ends towards the middle, and printing that sum

There is no way to figure out what it does without reading all of the code.  Ideally, each function should be limited to a single responsibility.

There are a lot of instance variables, all cryptically named, and all public:

public int a;
public int b[];
public int sum=0;
public int sum1=0;
public int k=0;
public int m=0;

Only the array should be an instance variable here; all of the others could be local variables.

The output looks a bit sloppy as well.  For example, I would expect there to be a newline after printing the array contents, and a space after "real sum".

Suggested solution

Notice how each method has a one-sentence JavaDoc summary of what it does.  (If you can't write such a summary for a function, then it would be an indication that the function is poorly designed.)

import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ArrayAdder {
    private int[] array;

    /**
     * Randomly populates an array of integers of the specified size.
     */
    public ArrayAdder(int size) {
        this.array = new int[size];
        for (int i = 0; i < size; i++) {
            this.array[i] = (int)(9 * Math.random());
        }
    }

    /**
     * The elements of the array, delimited by spaces.
     */
    public String toString() {
        return IntStream.of(this.array)
                        .mapToObj(String::valueOf)
                        .collect(Collectors.joining(" "));
    }

    /**
     * Sums the array using IntStream.
     */
    public int streamSum() {
        return IntStream.of(this.array).sum();
    }

    /**
     * Sums the array by working from the ends toward the middle.
     */
    public int nestedSum() {
        int i, j, sum = 0;
        for (i = 0, j = this.array.length - 1; i < j; i++, j--) {
            sum += this.array[i] + this.array[j];
        }
        if (i == j) {
            sum += this.array[i];
        }
        return sum;
    }

    /**
     * Demonstrates the equivalence of two addition methods on a 5-element array.
     */
    public static void main(String[] args) {
        ArrayAdder demo = new ArrayAdder(5);
        System.out.println(demo);
        System.out.println("Sum using stream: " + demo.streamSum());
        System.out.println("Nested sum: " + demo.nestedSum());
    }
}


Can calculation of word wrapping be made notably faster? I need to re-wrap a text so that it fits a given width, font and DC. The result needs to be an array of lines. I use the following code:

private struct SplitInfo
{
    public string Word;

    public string SplitChar;

    public override string ToString()
    {
        return Word;
    }
}

private static float GetWidth(Graphics gr, string text, Font font)
{
    SizeF size = gr.MeasureString(text, font, 10000, StringFormat.GenericTypographic);
    return size.Width;
}

public static string[] WrapText(string text, IntPtr hdc, Font font, int textWidthInLoMetric)
{
    // Split words at space (functionality for splitting at multiple different chars omitted for simplicity).
    // This is also why it needs SplitInfo to store the words.
    List<SplitInfo> words = new List<SplitInfo>(text.Split(' ').Select(x => new SplitInfo { SplitChar = " ", Word = x }));

    StringBuilder resultText = new StringBuilder();
    string currentLine = string.Empty;
    SplitInfo lastWord = new SplitInfo { Word = string.Empty, SplitChar = string.Empty };

    using (Graphics gr = Graphics.FromHdc(hdc))
    {
        while (true)
        {
            string newString = (currentLine + lastWord.SplitChar).TrimStart(' ') + words[0].Word;

            if (currentLine != string.Empty && GetWidth(gr, newString, font) > textWidthInLoMetric)
            {
                // Word no longer fits in line.
                resultText.Append(currentLine.TrimEnd() + "\n");
                currentLine = string.Empty;
            }
            else
            {
                lastWord = words[0];
                words.RemoveAt(0);
                currentLine = newString;
            }

            if (words.Count == 0)
            {
                resultText.Append(currentLine.TrimEnd() + "\n");
                break;
            }
        }
    }

    return resultText.ToString().TrimEnd().Split('\n');
}

Performance measurement shows that MeasureString is the main time consumer here (~90%). Is there any clever way to reduce the number of MeasureString calls? Other than that, I don't see opportunities to make word wrapping significantly faster.

One possibility is to cache the measured length for each word. I do this, when the line breaks need to be recalculated (i.e. when document needs to be reflowed) frequently, for example because the user edits words or the user resizes the width of the control.

A second possibility is to use different APIs, for example:

A different StringFormat value passed as a parameter
A different method for example TextRenderer.MeasureText instead of Graphics.MeasureString

My code says ...

        //http://msdn.microsoft.com/en-us/magazine/cc163630.aspx#S7 i.e.
        //"Practical Tips For Boosting The Performance Of Windows Forms Apps" in MSDN says,
        //
        //It's better to use the TextRenderer method overloads that do not get IDeviceContext as an argument.
        //These methods are more efficient because they use a cached screen-compatible memory device context
        //rather than retrieving the native handle for device context from the internal DeviceContext and
        //creating an internal object to wrap it.
        //
        //My profiling shows that the method without the Graphics parameter takes 0.025 msec instead of 0.1 msec.
        //However, the resulting calculation is inaccurate.
        Size size = TextRenderer.MeasureText(
            m_graphics,
            text,
            paintStyle.font,
            proposedSize,
            textFormatFlags);

... and ...

    static TextFormatFlags textFormatFlags =
        TextFormatFlags.NoPrefix |
        TextFormatFlags.NoPadding |
        TextFormatFlags.ExternalLeading |
        TextFormatFlags.Left |
        TextFormatFlags.Bottom;

This code recalculates dozens of pages in a fraction of a second (and because it caches the measured word sizes it only measures all words once, when the document is first loaded).

The corresponding method which I use for drawing the text is:

        TextRenderer.DrawText(
            m_graphics,
            text,
            paintStyle.font,
            drawingPoint,
            color,
            textFormatFlags);


Check if given number can be expressed as sum of 2 prime numbers Similar problem: Sum Of Prime

I've done the given problem in roughly \$\mathcal{O}(n\sqrt{n})\$.

How can I improve this algorithm?

#include <stdio.h>
int isPrime(long long int n)
{
    long long int i;
    for(i=2;i*i<=n;i++)
    {
        if(n%i==0)
            return 0;
    }
    return 1;
}
int main(void) {
    int i, t, prime;
    long long int n, start, end;
    scanf("%d", &t);
    for(i=0;i<t;i++)
    {
        prime = 0;
        scanf("%lld", &n);
        if(n<4)
            printf("No\n");
        else
        {
            if(n%2==0)
                printf("Yes\n");
            else
            {
                start = 2;
                end = n-2;
                while(start<=end)
                {
                    if(isPrime(start) && isPrime(end))
                    {
                        printf("Yes\n");
                        prime = 1;
                        break;
                    }
                    else
                    {
                        start++;
                        end–-;
                    }
                }
                if(prime==0)
                    printf("No\n");
            }
        }
    }
    return 0;
}

Some general remarks:

Use more horizontal space, for(i=0;i<t;i++) is difficult to read.
Use true and false from <stdbool.h> for boolean values, not
the integers 1 and 0.
Declare variables at the nearest scope where they are used, e.g.
in loops:

for (long long i = 2; i * i <= n; i++) { ... }

Always use braces { } in if-statements, even if there is only a
single statement to be executed in the if- or else-case.
Adding the braces easily forgotten if you add more statements later.
long long int is identical to long long. I prefer the latter,
but that is a matter of taste (or your coding style guidelines).

Now to your code:

The isPrime() functions treats n = 1 as a prime number, which
it isn't.
Separate the computation from the I/O. That makes the code more
organized and allows you to add test cases easily.

So the program should look like this:

#include <stdio.h>
#include <stdbool.h>

bool isPrime(long long n) {
    if (n < 2) {
        return false;
    }
    for (long long i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

bool isSumOfTwoPrimes(long long n) {
    // ... check if `n` is the sum of two prime numbers ...
}

int main(void) {
    int t;
    scanf("%d", &t);
    for (int i = 0; i < t; i++) {
        long long n;
        scanf("%lld", &n);
        if (isSumOfTwoPrimes(n)) {
            printf("Yes\n");
        } else {
            printf("No\n");
        }
    }
    return 0;
}

Printing the result can also be done with a single statement:

        puts(isSumOfTwoPrimes(n) ? "Yes" : "No");

You  return true for all even numbers, which is correct because
 Goldbach's conjecture has already been proven for all even numbers in your range 1<=n<=1000000.

For odd numbers, the calculation can be simplified considerably.
If n = p + q is odd then p is even and q is odd, or vice versa.
Since 2 is the only even prime number, this reduces to check
if n - 2 is prime:

bool isSumOfTwoPrimes(long long n) {
    if (n < 4) {
        return false;
    }
    if (n % 2 == 0) {
        return true;
    }
    return isPrime(n - 2);
}

Note another advantage of the separate function: You can "early-return",
and that makes the "state variable" int prime from your code obsolete.

If the program is run with a large number of test cases, then a further improvement would be to pre-compute all prime numbers in the given range,
for example with the Sieve of Eratosthenes.


Winning Pattern Detection This was a question asked to me before setting up an interview.
You are given a game board that contains a four by four (4x4) array of pieces. The pieces can be one of six shapes and can be one of six colors.

If the board contains 4 pieces of the same shape and same color, the board contains a winning pattern.

public enum Color
{
Red,
Blue,
Green,
Yellow,
Black,
Purple
}

public enum Shape
{
Square,
Triangle,
Circle,
Star,
Pentagon,
Octagon
}

public class Piece
{
public Color color;
public Shape shape;

public bool Equals(Piece compareTo) {};
}

public class Board
{
public Piece[,] position = new Piece[4,4];

public void Board(){ /*completely builds the board*/};
public void MakeRandomBoard(){};
public piece GetPiece(int x) {};
public bool IsWinner() {};
}

Write the code to detect when a winning pattern is present in a board.

Answer :

bool isWinner() {
    HashMap <Pair<Color, Enum>, int> pieceCount;
    for(int row = 0; row < 4; row++) {
        for(int col =0; col < 4; col++) {
            Piece p = GetPiece(row, col); // Note: Sig is different than Given.
            Pair <Color, Enum> pair(p.Color, p.Enum);
            if (pieceCount.Contains(pair)) {
                pieceCount[pair]++;
                if (pieceCount[pair] >= 4) return true;
            } else {
                pieceCount[pair] = 1;
            }
        }
    }
    return false;
}

The question was to come up with 3 different ways to solve this and list the pros and cons for each solution. This is one of the solution that I was able to do.
Please give your inputs on the code.

Another method would be to check the board as each piece is added. This has an advantage of real time checking, but requires looping through the whole board.  Also you could use a Dictionary<Piece, int> to keep track of which pieces are added and check that instead of the board array.  Using the ContainsKey eliminates extra looping but requires an extra collection.


Design for a protocol based software in C++ I want a good design to implement a master-slave protocol. The protocol is proprietary and similar to cctalk.
We have:

Master: HEADER [ DATA ] CHECKSUM
Slave: HEADER [ DATA ] CHECKSUM

My choice was to have concrete base classes for request and for response:

class PacketReq {
public:
    typedef std::vector<uint8_t>       container;
    typedef container::const_iterator  const_iterator;

    PacketCommand command() const
    {
        return static_cast< PacketCommand >( mBuffer[ 2 ] );
    };

    const container& data() const
    {
        return mBuffer;
    }

    const_iterator begin() const
    {
        return mBuffer.begin();
    }

    const_iterator end() const
    {
        return mBuffer.end();
    }

protected:
    container mBuffer;
};

class PacketOut1 : public PacketReq {
public:
    PacketOut1()
    {
        mBuffer.reserve( PacketHeaderHelper::HEADER_SIZE );
        mBuffer.push_back( /* something. */ );
        mBuffer.push_back( /* something. */ );
        mBuffer.push_back( /* something. */ );
        mBuffer.push_back( /* something. */ );
    }
};

The response can be a good response or a NACK (an error). My Implentation is:

class PacketRes {
public:
    PacketRes(const std::vector<uint8_t>& buffer)
    {
        if (!checkChecksum( buffer ))
        {
            throw Error("invalid checksum");
        }

        PacketHeaderHelper header( buffer );
        mCommand = header.command();

        if (header.len() > PacketHeaderHelper::HEADER_SIZE)
        {
            const size_t bodySize = header.len() - PacketHeaderHelper::HEADER_SIZE;

            mData.reserve( bodySize );

            mData.insert(
                mData.end(),
                buffer.begin() + PacketHeaderHelper::HEADER_SIZE - 1,
                buffer.end() - 1
                );
        }
    }

    virtual ~PacketReq() {}

    PacketCommand command() const
    {
        return mCommand;
    }

    const std::vector<uint8_t>& body() const
    {
        return mData;
    }

private:
    bool checkChecksum(const std::vector<uint8_t>& buffer) const
    {
        /* calc checksum. */
    }

private:
    std::vector<uint8_t> mData;
    PacketCommand mCommand;
};

class PacketInAck : public PacketReq {
public:
    PacketInAck(const std::vector<uint8_t>& buffer) : PacketReq( buffer )
    {
    }
};

So if I want make a request the sequence is:

lock_guard
send( const PacketOut& p )
std::unique_ptr< PacketRes > read();

But I don't like this design, but it works.

Is there some other way to implement this?

Preliminaries

I would decouple the data transmission + message encoding/decoding from the data connection problem. The linked Uncle Bob article also shows how to distinguish connection management differences for master and slave. You probably want this to work with any reasonable networking implementation. Since you already use boost::noncopyable, I take that as a hint that you are willing to use Boost in general.

My recommendation would be for you to study, and then modify, the simple chat_message/chat_client/chat_server example from the Boost.Asio documentation. That library -or a modified version of it- is likely to become the official networking component in a future version of the Standard Library. So it's a good investment to learn about it.

Message Interface

Compared to the simple chat_message example, your question is a little more involved. I assume that the header information is used to identify which type of message is going to follow. I would recommend to factor all the common message stuff HEADER|BODY|CHECKSUM into an abstract base class IMessage

class IMessage
{
pubic:
    virtual ~IMessage() {} // virtual destructor

    // virtual functions that can be overriden for concrete message types

    static std::string header(std::string const& input)
    {
            return input.substr(0, HeaderLength);
    }

    static std::string body(std::string const& input)
    {
            return input.substr(HeaderLength, HeaderLength + BodyLength);
    }

    enum {
        HeaderLength = /* bla */,
        BodyLength = /* bla */,
        ChecksumLength = /* bla */
    };
};

Message Implementations

You could then define a bunch of different concrete messages that inherit the general message interface IMessage, and add some stuff of their own:

class Request: public IMessage
{
    Request(std::string const& body) { /* decode the buffer */ }

    static std::unique_ptr<IMessage> create(std::string body const&)
    {
        return std::make_unique<Request>(body);
    }

    // Request specific overrides of virtual functions
    // Request unique functions
};

class Acknowledge: public IMessage
{
    Acknowledge(std::string const& body) { /* decode the buffer */ }

    static std::unique_ptr<IMessage> create(std::string const& body)
    {
         return std::make_unique<Acknowledge>(body);
    }

    // Acknowledge specific overrides of virtual functions
    // Acknowledge unique functions
};

You might find it puzzling that I have written both a constructor and a create() function. That is explained in the next section. But for now, note that the declared return type is std::unqiue_ptr<IMessage> but the function body return a unique pointer to the concrete message types. This legal C++ feature is known as covariant return types, and makes it possible to have polymorphic object construction.

Note that std::make_unique is not yet officially availabe but you can get a working version that has been accepted for the upcoming C++14 Standard.

Reading messages

If you look at the Boost.Asio example, the chat_client and chat_server read from a character buffer that is being filled from a socket. So you need to decode the header in order to distinguish which message has to be created.

Especially since you tagged this question with design-patterns, I would recommend to write a small Factory class that keeps a registry of function pointers. At startup, you fill the factory's registry with function pointers to the static member functions create() of all the message types in your application. In this case the registry would be e.g. of type

typedef std::map<std::string, std::function<std::unique_ptr<IMessage>(std::string const&)> Registry;

What this says is that every unique header (encoded in a std::string) stores a pointer to a function taking a std::string and returning a std::unique_ptr<IMessage>. Those type of function pointers are preciesly the create() functions of your messages.

Given a buffer that has been read from the socket, and converted to a std::string, your factory would do something like:

    std::unique_ptr<IMessage> Factory::create(std::string const& input) const
    {
            auto const fun = registry_.find(IMessage::header(input));
            // here you can also do your CHECKSUM validation
            return fun? (fun)(IMessage::body(input)) : nullptr;
    }

What this does is to split the message into a header and body. These functions are static functions of the message interface, so that they can be called before we have a concrete message object. Then the header is looked up in the registry.

If it is found, we simply call the corresponding create() message that was stored, taking the body as argument. This will call the constructor (now you see why we had both a constructor and a creator, because constructors cannot be stored in a factory registry). The constructor will finally create a std::unique_ptr to the concrete message type that was encoded in the header.

If we didn't find a registered message type, we return a nullptr. The caller of the factory creator would then have to check this before being able to safely use the returned pointer.

Final thoughts

The above explained how to decode messages from a stream of tokens that you get from a socket. Writing is of course much easier because then you already know the message type. I think that the data transmission and connection management part, and the semantic part of how to respond to each message type is beyond the scope of this Q&A. The Boost.Asio example does not need too much modification to allow reading your message structures from a socket.

For the above message parsing machinery, I have implemented a heavily templated version of similar protocol called DamExchange (used for letting checkers/draughts engines over a network). You can follow the header trail on a simple use case in my BitBucket repo.


An exercise concering Kotlin Set Task description:
Declare a function twoInThree(a: Set, b: Set, c: Set), which returns the set of all elements, which are contained in exactly two of the three given sets a, b, c.
My solution:
fun main(args: Array<String>) {
    var a = setOf<Int>(1, 2, 5)
    var b = setOf<Int>(2, 7, 0)
    var c = setOf<Int>(3, 5)

    val result = twoInThree(a, b, c)
    println(result) // [2, 5]
}

fun twoInThree(a: Set<Int>, b: Set<Int>, c: Set<Int>): MutableSet<Int> {
    var results = mutableSetOf<Int>()
    var intersectOfAll = a.intersect(b).intersect(c)

    val aIntersectB = a.intersect(b)
    val aIntersectC = a.intersect(c)
    val bIntersectC = b.intersect(c)

    results.addAll(aIntersectB)
    results.addAll(aIntersectC)
    results.addAll(bIntersectC)

    results.removeAll(intersectOfAll)

    return results
}

If got the same result as the instructor and tried it with other sets. It always returned the expected result. So, I guess my solution is formally correct.
But: Could the exercise become solved in a better way?

Before I go into another possible solution I will give you some suggestions on your current code:

Use val instead of var whenever possible. This is possible for all variables in your code.

No need to specify <Int> on setOf, Kotlin can figure out the best applicable type itself.

The function twoInThree is capable of handling any kinds of sets, not just ints. You can use a generic type parameter for this.
Change the method to fun <T> twoInThree(a: Set<T>, b: Set<T>, c: Set<T>): MutableSet<T>
And naturally also val results = mutableSetOf<T>()

Prefer to return immutable types unless you really need to do otherwise, in this case prefer to return a Set over MutableSet (callers don't need to care about the fact that you are using a MutableSet in your implementation)

The approach
Your approach involves checking for multiple intersections and then creating a union of all sets and removing the intersection of all sets.
The assignment is about finding elements which exists in exactly two of the three given sets a, b, c.
Your approach is fine, there's nothing wrong with it, but... Will it scale?
If you would check for elements which exists in all three of the sets, or in exactly one set, that could be done quite easily by returning different intersections and unions and so on. But what if there would be five sets?
The assignment is about exactly two of the three sets.
One, two, three.
We can use counting!
By counting the number of times each element appears, we can iterate over all sets (no matter if it's three, five, or twenty) exactly once.
By counting the number of times each element appears, we can easily change the code to return elements that occur only once, twice, or three times.
So how to do this?

My approach
Start with creating a list of all sets. listOf(a, b, c)
Then go through the list and map each set to all its elements. .flatMap { it } which can also be written as .flatten()
Then create a grouping of the elements .groupingBy { it }
Then create a map with the counts of each element .eachCount()
listOf(a, b, c).flatten().groupingBy { it }.eachCount()

This gives you a map Map<Int, Int> where the keys are the elements and the values are the number of times each element occurs.
Now you can filter this map and return the keys which matches your requirement .filter {  it.value == 2 }.map { it.key }
Full code:
val result = listOf(a, b, c).flatten()
     .groupingBy { it }
     .eachCount()
     .filter { it.value == 2 }
     .map { it.key }


Project Euler #12 in Swift - Highly divisible triangular number I just finished Project Euler #12 in Swift, and since there is not any version yet on Code Review, I would like to have some comments on what I did to try to improve it.

  The sequence of triangle numbers is generated by adding the natural
  numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7
  = 28. The first ten terms would be:

  1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

  Let us list the factors of the first seven triangle numbers:

  1: 1

  3: 1,3

  6: 1,2,3,6

  10: 1,2,5,10

  15: 1,3,5,15

  21: 1,3,7,21

  28: 1,2,4,7,14,28

  We can see that 28 is the first triangle number to have
  over five divisors.

  What is the value of the first triangle number to have over five
  hundred divisors?

import Foundation

let OverNumberOfDivisors = 500

extension Int {
    func isMultipleOf(factor: Int) -> Bool {
        return self % factor == 0
    }
}

func findPrimesFactorFrom(let smallest: Int, let toFactor: Int, inout primesFactor:[Int:Int]) {
    var maxFactor = Int(sqrt(Double(toFactor)))
    maxFactor = maxFactor < smallest ? smallest : maxFactor
    for factor in smallest...maxFactor {
        if toFactor.isMultipleOf(factor) {
            primesFactor[factor] = (primesFactor[factor] ?? 0) + 1
            return findPrimesFactorFrom(factor, toFactor / factor, &primesFactor)
        }
    }

    primesFactor[toFactor] = (primesFactor[toFactor] ?? 0) + 1
}

func highlyDivisibleTriangularNumber() -> Int {

    var currentNumberOfDivisors = 1
    var triangleNumber = 1
    var number = 1

    var primesFactor:[Int:Int] = [:]

    while OverNumberOfDivisors >= currentNumberOfDivisors {

        number++
        triangleNumber += number
        primesFactor = [:]

        findPrimesFactorFrom(2, triangleNumber, &primesFactor)

        currentNumberOfDivisors = 1
        for (index, factor) in primesFactor {
            if index != 1 {
                currentNumberOfDivisors *= (factor + 1)
            }
        }
    }

    return triangleNumber
}

func euler12() {
    let number = highlyDivisibleTriangularNumber()

    println(number)
}

func printTimeElapsedWhenRunningCode(operation:() -> ()) {
    let startTime = CFAbsoluteTimeGetCurrent()
    operation()
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    println("Time elapsed : \(timeElapsed) s")
}

printTimeElapsedWhenRunningCode(euler12)

The code executes in 0.3s

I would make the required number of divisors (500 + 1) a parameter of the
function, and move the computation of the number of divisors into a separate
function:

func highlyDivisibleTriangularNumber(requiredDivisors : Int) -> Int {

    var triangleNumber = 0
    var number = 0
    var currentNumberOfDivisors : Int

    do {
        number++
        triangleNumber += number
        currentNumberOfDivisors = countDivisors(triangleNumber)
    } while currentNumberOfDivisors < requiredDivisors

    return triangleNumber
}

func euler12() {
    let number = highlyDivisibleTriangularNumber(500 + 1)
    println(number)
}

Counting the number of divisors is done via the prime factorization (which is good). Your prime factorization is done recursively and returns a dictionary
of factor/exponent pairs. I would prefer an iterative algorithm:

func primeFactorization(var n : Int) -> [Int : Int] {
    var factors : [Int : Int] = [:]
    var factor = 2

    while factor * factor <= n {
        if n % factor == 0 {
            var exponent = 0
            do {
                exponent++
                n /= factor
            } while n % factor == 0
            factors[factor] = exponent
        }
        factor = factor == 2 ? 3 : factor + 2
    }
    if n > 1 {
        factors[n] = 1
    }

    return factors
}

I prefer the explicit if n % factor == 0 instead of if n.isMultipleOf(factor)
with a custom extension, but that might be a matter of taste.

This gives only a small performance improvement, but the function does
now return the factorization, so you don't have to pass an inout argument.

Also the result cannot contain the factor 1 (as in your method). So counting the number of divisors would simply be

func countDivisors(num : Int) -> Int {

    var numDivisors = 1
    for (prime, exponent) in primeFactorization(num) {
        numDivisors *= (exponent + 1)
    }
    return numDivisors
}

The variable names (prime, exponent) might be more descriptive
than (index, factor) in your code. As the prime number (the dictionary key)
is not needed in the loop you can also write

for (_, exponent) in primeFactorization(num) {
    numDivisors *= (exponent + 1)
}

or just

for exponent in primeFactorization(num).values {
    numDivisors *= (exponent + 1)
}

But actually it is more efficient to combine the prime factorization and
the computation of the number of divisors into a single method, without
storing the factors and exponents in an intermediate dictionary:

func countDivisors(var n : Int) -> Int {

    var numDivisors = 1
    var factor = 2

    while factor * factor <= n {
        if n % factor == 0 {
            var exponent = 0
            do {
                exponent++
                n /= factor
            } while n % factor == 0
            numDivisors *= exponent + 1
        }
        factor = factor == 2 ? 3 : factor + 2
    }
    if n > 1 {
        numDivisors *= 2
    }

    return numDivisors
}

and this is much faster (0.02 instead of 0.14 seconds).

The most performance improvement can be gained by taking advantage of the
special form n * (n+1)/2 of the triangle numbers, and this are the same
arguments as in

Project Euler Problem 12 - triangle number with 500 divisors

In Swift this would be

func highlyDivisibleTriangularNumber(requiredDivisors : Int) -> Int {

    var n = 1
    while (countDivisors((n+1)/2) * countDivisors(n) < requiredDivisors) {
        n++;
        if (countDivisors(n/2) * countDivisors(n+1) >= requiredDivisors) {
            break;
        }
        n++;
    }
    let triangleNumber = n*(n+1)/2
    return triangleNumber
}

which runs in 0.006 seconds on my computer.


Flatten Dictionary Python challenge I have a question about this coding challenge for "Flatten a Dictionary":

  Given a dictionary dict, write a function flattenDictionary that
  returns a flattened version of it .

  If you’re using a compiled language such Java, C++, C#, Swift and Go,
  you may want to use a Map/Dictionary/Hash Table that maps strings
  (keys) to a generic type (e.g. Object in Java, AnyObject in Swift
  etc.) to allow nested dictionaries.

  Example:

  Input:

dict = {
    "Key1" : "1",
    "Key2" : {
        "a" : "2",
        "b" : "3",
        "c" : {
            "d" : "3",
            "e" : "1"
        }
    }
}

  Output:

{
    "Key1" : "1",
    "Key2.a" : "2",
    "Key2.b" : "3",
    "Key2.c.d" : "3",
    "Key2.c.e" : "1"
}

  Important: when you concatenate keys, make sure to add the dot character between them. For instance concatenating Key2, c and d the result key would be Key2.c.d.

def flatten_dictionary(dictionary):

  def items():
  # loop through each item inside the dictionary k, v
      #Appending
      # check if the sub-key and sub-value are
      # inside the flatten_dict(value)
      # join on subkey array
      # add to result
      # clear out prev_keys
    for key, value in dictionary.items():
      if isinstance(value, dict):
        for subkey, subvalue in flatten_dictionary(value).items():
          if key == "":
            yield subkey, subvalue
          yield key + "." + subkey, subvalue

      else:

        yield key, value

  return dict(items())

# test cases 1

dictionary2 = {
            "Key1" : "1",
            "Key2" : {
                "a" : "2",
                "b" : "3",
                "c" : {
                    "d" : "3",
                    "e" : "1"
                }
            }
        }

# output: {
#             "Key1" : "1",
#             "Key2.a" : "2",
#             "Key2.b" : "3",
#             "Key2.c.d" : "3",
#             "Key2.c.e" : "1"
#         }

print(flatten_dictionary(dictionary2))

1. Bugs

The special case for empty keys:

if key == "":
  yield subkey, subvalue
yield key + "." + subkey, subvalue

is missing an else: and so leads to items appearing twice:

>>> flatten_dictionary({"": {"a":1}})
{'a': 1, '.a': 1}

Even if we fix the bug by adding the else:, there's still a problem. Consider this example:

>>> flatten_dictionary({"a": {"": {"b": 1}}, "": {"a": {"b": 2}}})
{'a.b': 2}

What happened to the 1? Ignoring the empty string keys has led two different keys to be collapsed into one. It would be better to remove the special case for empty strings, so that:

>>> flatten_dictionary({"a": {"": {"b": 1}}, "": {"a": {"b": 2}}})
{'a..b': 1, '.a.b': 2}

Python has a limited stack, but dictionaries can be nested arbitrarily deeply:

>>> d = {}
>>> for i in range(1000): d = {'a':d}
...
>>> flatten_dictionary(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr186013.py", line 22, in flatten_dictionary
    return dict(items())
  [... many line omitted ...]
  File "cr186013.py", line 13, in items
    for subkey, subvalue in flatten_dictionary(value).items():
RecursionError: maximum recursion depth exceeded

This problem can be avoided using the stack of iterators pattern.

2. Other review points

The comment does not match the code: there is nothing in the code corresponding to "check if the sub-key and sub-value are inside the flatten_dict(value)" or "join on subkey array" or "clear out prev_keys". Incorrect comments like this are worse than useless: they make it harder to understand and maintain the code.

Did this comment describe an earlier version of the code, and then you changed the code but forgot to edit the comment? It is worth getting into the habit of changing the comment first so that you don't forget.
The construction of the result keys has unnecessary quadratic runtime. For example, in this situation:

>>> flatten_dictionary({'a': {'a': {'a': {'a': {'a': {'a': 1}}}}}})
{'a.a.a.a.a.a': 1}

there is only the need to concatenate one result key ('a.a.a.a.a.a'), but the code concatenates five result keys: not just the one that we need, but 'a.a', 'a.a.a', 'a.a.a.a' and 'a.a.a.a.a' as well. The way to avoid this is to keep a stack of dictionary keys currently being visited, and use str.join on the stack when you need to concatenate the result key.

3. Revised code

def flatten_dictionary(d):
    result = {}
    stack = [iter(d.items())]
    keys = []
    while stack:
        for k, v in stack[-1]:
            keys.append(k)
            if isinstance(v, dict):
                stack.append(iter(v.items()))
                break
            else:
                result['.'.join(keys)] = v
                keys.pop()
        else:
            if keys:
                keys.pop()
            stack.pop()
    return result


Creating a table using given items This simply creates a table using the items passed in. I would like to make this function shorter and/or more efficient. What I have seems pretty redundant.

def apriori_creator(items, k):
    """Function that creates apriori table using supported candidates"""
    table = []
    the_length = len(items)
    new_k = k-2 # first k-2 items as described in algorithm in book for 'apriori gen'
    for x in range(the_length):
        next = x + 1
        for y in range(next, the_length):
            combined = items[x].union(items[y]) # merge
            l_sub_one = list(items[x])
            l_sub_one.sort()
            l_sub_two = list(items[y])
            l_sub_two.sort()
            first = l_sub_one[:new_k] # getting the first k-2 items of the set
            second = l_sub_two[:new_k]
            if first == second:
                table.append(combined)
    return table

For efficiency, you can take take some things out of the inner loop:

The computations that depend only on x should be in the outer loop.
The computation of combined should be under the if where it is used.
Using enumerate and direct iteration instead of range is simpler and a little faster.
l_sub_one = sorted(items[x]) does the same as these two lines:

    l_sub_one = list(items[x])
    l_sub_one.sort()

Revised code:

def apriori_creator(items, k):
    """Function that creates apriori table using supported candidates"""
    table = []
    new_k = k-2 # first k-2 items as described in algorithm in book for 'apriori gen'
    for x, item_x in enumerate(items):
        l_sub_one = sorted(item_x)
        first = l_sub_one[:new_k] # getting the first k-2 items of the set
        for item_y in items[x+1:]:
            l_sub_two = sorted(item_y)
            second = l_sub_two[:new_k]
            if first == second:
                combined = item_x.union(item_y) # merge
                table.append(combined)
    return table

A further improvement is possible.
One way to describe what you are doing is that you are generating all different pairs of items that share the same value of sorted(item)[:new_k]. Your code does this by considering all possible pairs. A more efficient approach would begin by grouping the items by that value. With the help of a dictionary this only requires one pass over the items. Then you only need to generate pairs withing each group.

Here's again revised code. I'm using collections.defaultdict for grouping, and itertools.combinations for pairing.

from collections import defaultdict
from itertools import combinations

def apriori_creator(items, k):
    """Function that creates apriori table using supported candidates"""
    new_k = k-2 # first k-2 items as described in algorithm in book for 'apriori gen'
    groups = defaultdict(list)  # group by the first k-2 items of the set
    for item in items:
        l_sub_one = sorted(item)
        key = tuple(l_sub_one[:new_k])
        groups[key].append(item)

    table = []
    for group in groups.values():
        if len(group) > 1:
            for item_x, item_y in combinations(group, 2): # all pairs
                combined = item_x.union(item_y) # merge
                table.append(combined)
    return table


Stylistic it is mostly nice, and I would possibly change two things. First of I would put all of the code within a function allowing for reuse, and secondly I would change some of the names, i.e. backward_diag and forward_diag.

From an algorithmic point of view there are however some more issues with your code:

Use range(x) when you don't care about the value – Usually it is good to do for column_value in row, but as you dereference using indexes, and don't use the column value at all, I would rather using pure indexing, and let the double loop be:

for y in range(len(grid)):
    for x in range(len(grid[y])):

What's the point with used? – I don't understand why you store the starting value of the largest value. In itself this value is not useful, as any value could be found multiple places, and you don't store which direction the largest value was used.

If storing something I would rather store the indices and direction, something similar to (x, y, "left") where you vary the direction accordingly to current search
Don't repeat the value if a > biggest else biggest – Instead of doubling the if ... else I would rather use a full blown if statement. In other words instead of

left = reduce(operator.mul, grid[y][x - 4:x], 1)
used = grid[y][x - 4:x] if left > biggest else used
biggest = left if left > biggest else biggest

I would rather use:

left = reduce(operator.mul, grid[y][x - 4:x], 1)
if left > biggest:
    used = (x, y, "left")
    biggest = left

Don't repeat calculation – As Zack commented upon I wouldn't calculate both the left and right, and similarily the up and down, as these are redundant.
Strange validation of ranges – The only range you check is the x + 4 < 20, but you don't do any validation on other ranges. This means that you calculate the left even though you don't have 4 values to the left of current value, and so on. This is kind of sloppy, and could easily be avoided.


Javascript FizzBuzz and Behavior-Driven Development Using Mocha and Chai I am currently getting closely acquainted with Behavior-Driven Development. Could someone tell me how I am doing with the Fizzbuzz program below? I am interested in both improving the JavaScript code and the BDD prowess. Any help is appreciated.
fizzbuzz.js
module.exports = function(word, value){
    function sortNumber(a,b) {
        return a - b;
    }

    numbers = function(divisor, max){
        var result = []
        for(i=1;i<=max;i++){
            if ((i % divisor) === 0)
                result.push(i)
        }
        return result
    }

    if (value <= 0)
        return ['error','nonpositive']

    else {
        switch(word) {
            case 'fizz':
                return numbers(3, value)
            case 'buzz':
                return numbers(5,value)
            case 'fizzbuzz':
                return numbers(3,value).concat(numbers(5,value)).filter(function(elem,index,self){
                        return index == self.indexOf(elem)
                    }).sort(sortNumber)
            default:
                return ['error','wrongword']
        }
    }
};

test/fizzbuzz-spec.js:
var chai = require('chai');
    expect = chai.expect,
    fizzbuzz = require('../lib/fizzbuzz');

describe('A fizzbuzz', function(){
    describe('will return an error for invalid words: ', function(){
        it('like fuss', function(){
            expect(fizzbuzz('fuss', 10)).to.be.deep.equal(['error','wrongword']);
        });
        it('like biss', function(){
            expect(fizzbuzz('biss', 10)).to.be.deep.equal(['error','wrongword']);
        });
    });

    describe('will return an error when non-positive integer is passed', function(){
        it('like 0', function(){
            expect(fizzbuzz('buzz', 0)).to.be.deep.equal(['error','nonpositive']);
        })
        it('like -2', function(){
            expect(fizzbuzz('buzz', -2)).to.be.deep.equal(['error','nonpositive']);
        })
    })

    describe('will return valid non-error input when positive integers and valid words are passed', function(){
        it('like fizz and 20', function(){
            expect(fizzbuzz('fizz', 20)).not.to.contain('error');
        })
        it('like buzz and 20', function(){
            expect(fizzbuzz('buzz', 20)).not.to.contain('error');
        })
        it('like fizzbuzz and 20', function(){
            expect(fizzbuzz('fizzbuzz', 20)).not.to.contain('error');
        })
    })

    describe('will return valid results for some basic valid test cases', function(){
        it('like fizz and 10', function(){
            expect(fizzbuzz('fizz', 10)).to.be.deep.equal([3,6,9]);
        })
        it('like fizz and 20', function(){
            expect(fizzbuzz('fizz', 20)).to.be.deep.equal([3,6,9,12,15,18]);
        })
        it('like buzz and 10', function(){
            expect(fizzbuzz('buzz', 10)).to.be.deep.equal([5,10]);
        })
        it('like buzz and 25', function(){
            expect(fizzbuzz('buzz', 25)).to.be.deep.equal([5,10,15,20,25]);
        })
        it('like fizzbuzz and 10', function(){
            expect(fizzbuzz('fizzbuzz', 10)).to.be.deep.equal([3,5,6,9,10]);
        })
        it('like fizzbuzz and 25', function(){
            expect(fizzbuzz('fizzbuzz', 25)).to.be.deep.equal([3,5,6,9,10,12,15,18,20,21,24,25]);
        })
        it('like fizz and 2', function(){
            expect(fizzbuzz('fizz', 2)).to.be.deep.equal([]);
        })
        it('like buzz and 4', function(){
            expect(fizzbuzz('buzz', 4)).to.be.deep.equal([]);
        })

    })
});

Handling invalid input
Instead of returning an array when inputs are invalid, throw exceptions and use throw to detect it in the tests.
Avoid else when previous blocks have return statements
The else can be eliminated since the block evaluated when value <= 0 has a return statement (or would throw an exception). Additionally, the switch statement can be simplified to a few if statements (for an example see this answer to a related question).
Don't forget to set scopes
While the code is in a module, it is best to set the scope of variables and functions - e.g. numbers and i in the loop within numbers should be prefixed by the keywords const and let, respectively, to avoid accidental re-assignment/confusion.
In that same vein, the first few lines of the test are setting variables:

var chai = require('chai');
    expect = chai.expect,
    fizzbuzz = require('../lib/fizzbuzz');

Perhaps you meant to add a comma instead of semi-colon after require('chai')? It would be simpler just to have each variable on its own line:
const chai = require('chai');
const expect = chai.expect;
const fizzbuzz = require('../lib/fizzbuzz');

Actually instead of importing chai just to use expect from it on a separate line, use object-destructuring:
const { expect } = require('chai');
const fizzbuzz = require('../lib/fizzbuzz');


Project Euler #2 - Sum of even Fibonacci numbers to 4,000,000 This particular problem has already been posted here before, but the community is ok with me to post it again, so I can have feedback on my own implementation.

I tried to keep things simple, with each function having its own responsibility so they can be reused in other contexts. Here it is:

(ns marcofiset.euler.problem2)

(defn fib [n]
  (if (< n 0)
    (throw (Exception. "Can't compute fib of n < 0"))
    (loop [i n cur 1 next 1]
      (if (zero? i)
        next
        (recur (dec i) next (+ cur next))))))

(defn fibs []
  (map fib (iterate inc 0)))

(defn fibs-until [max]
  (take-while #(< % max) (fibs)))

(defn solution []
  (apply + (filter even? (fibs-until 4000000))))

(println (solution))

I'm beginning to learn Clojure and this is one of my first exercices. I'd like to have some feedback from more experienced Clojure programmers.

I'm also kind of a Clojure newbie (I've been messing with it off and on for about two years), so take my comments with a grain of salt.

In the loop in fib, I would separate each binding pair with commas, like this:

(loop [i n, cur 1, next 1] ; etc.

Clojure treats commas as whitespace, so you can use them anywhere you can use a space. It can make binding vectors and map literals with everything on one line a lot easier to read.

It looks like your function fibs is just making an infinite lazy sequence of Fibonacci numbers by mapping fib over a range. You can actually write a function to do this directly; see http://clojuredocs.org/clojure_core/clojure.core/lazy-seq (the second example). I don't know how the performance compares, but it's short and a good way to learn about making your own lazy sequences.

I think your solution function is good, but https://stackoverflow.com/questions/3153396/clojure-reduce-vs-apply says there might be a tiny performance advantage to using reduce instead, like this:

(reduce + (filter even? (fibs-until 4000000)))

The hard-coded limit in solution makes me uncomfortable somehow. The rest of your code is very nicely packaged out into separate, reusable functions, so it feels a little odd to see solution not. Maybe pass the limit as an argument, and then write

(println (solution 4000000))

Otherwise your code looks good to me. It's very clean and easy to read.

You might also be interested in type hinting and the memoize function if you're working through Project Euler; they can help improve performance, especially on mathematical code. For example, if you know the argument to fib will always fit in a Java long (64 bits), you can write fib like this:

(defn fib [^long n]  ;etc

This gives the compiler a type hint that lets it avoid reflection, and can improve performance.

You can pass memoize a referentially transparent function (one that always returns the same value given the same arguments), and it will return a new version of the function that caches results. For example, say you'd written a naive Fibonacci like this:

(defn fib [n]
  (if (< n 2)
    1
    (+ (fib (- n 1)) (fib (- n 2)))))

Then you could send that function to memoize, and you'd get a new version that would save its previous results. Since that naive function keeps recalculating the same cases, you'd get a performance boost by turning those repeat calls into map lookups.

I hope some of my comments were helpful, and have fun with Clojure; it rekindled my interest in programming.


jQuery plugin to ajaxify forms This is my first foray into the wild world of jQuery plugin development. The plugin "ajaxifies" forms, which isn't particularly spectacular:

It gets the basics (action, method) from the form itself, serializes the form's fields, and sends the request.
Users can provide (via its options) callback functions for the local ajax events (beforeSend, complete, success and error).
The dataType can also be set from a custom data attribute, which - if present - takes precedence.

Everything seems to be working as expected (repo, with a simple demo). Since this is my first plugin, I'd be particularly interested in critiques of its structure. That said, as always in reviews, any aspect of the code is fair game for criticism.

The plugin code:

(function ($) {

    $.fn.ajaxForm = function (options) {

        var settings = $.extend({}, $.fn.ajaxForm.defaults, options);

        return this.each(function () {
            var $form = $(this);

            dataType = $form.attr("data-dataType");
            if (typeof dataType != "undefined") dataType = settings.dataType;

            $form.on("submit", function (event) {
                event.preventDefault();

                $.ajax({
                    type: $form.attr("method"),
                    url: $form.attr("action"),
                    data: $form.serialize(),
                    cache: false,
                    dataType: dataType,
                    beforeSend: function () {
                        $form.addClass("ajaxForm-loading");

                        if (typeof settings.beforeSend == "function") settings.beforeSend.call($form);
                    },
                    complete: function () {
                        $form.removeClass("ajaxForm-loading");

                        if (typeof settings.complete == "function") settings.complete.call($form);
                    },
                    success: function (response) {
                        if (typeof settings.success == "function") settings.success.call($form, response);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        if (typeof settings.error == "function") settings.error.call($form, XMLHttpRequest, textStatus, errorThrown);
                    }
                });
            });
        });
    };

    $.fn.ajaxForm.defaults = {
        dataType: "json",
        beforeSend: function () {},
        complete: function () {},
        success: function () {},
        error: function () {}
    };

})(jQuery);

Initialization:

$(document).ready(function () {
    $("form").ajaxForm({
        dataType: "html",
        success: function (response) {
            console.log(response);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("Oops: " + errorThrown);
        }
    });
});

Structure and style looks fine, although I have some general notes:

Prefer the strong (in)equality operators (!== and ===) whenever possible
Always use braces, even for one-line "blocks". It's nice to save a few keystrokes, but personally I prefer the consistency of always using braces
You could skip the defaults for the beforeSend, complete, etc. callbacks and leave them undefined. Defining them as empty functions is fine, but not necessary with the checks you're doing.

In terms of features/behavior:

I'd highly suggest simply modifying the user's settings, and then passing them to $.ajax(), rather than declare a new object. That way, users can set whatever extra ajax options they want, and not see them ignored. In other words, let your plugin fill in the blanks in the settings the user passes in, not the other way around.

Besides that:

You may want to skip elements that aren't actually forms
It'd probably be wise to use $form.data("dataType") instead of $form.attr() in case the data type was set using .data() and isn't a real attribute.
Speaking of data type, you should check if it's a string specifically, since that's the only thing jQuery wants anyway.
Lastly about the data type: I don't think your plugin should define a "json" default. Better to let the be defined explicitly by whomever is using the plugin, or leave it at jQuery's default.

Most importantly: Please forward any and all arguments to the callbacks. For instance, the regular beforeSend receives the XHR object and its settings, but if I specify a beforeSend using this plugin, I won't get those. Since the name's the same, I'd expect it to receive the same arguments. I like to use beforeSend to grab the XHR so I can use it as a Deferred/Promise object, but I can't do that here.

By the way, it'd be in the spirit of jQuery to invoke the callbacks in the element's context, not in the context of the jQuery wrapper around the element. But if you follow my suggestion of modifying the settings rather than replacing them, be sure to note in your documentation that this context-switching only applies to those four callbacks. E.g. if I declare a dynamic 201 callback to handle the 201 Created status code, it won't be called in the element's context (and I can think of a clean way to make it happen).

You may also want to get some of the form's attributes using .prop() instead of .attr(). For instance, a method attribute is not required (it'll default to "GET" in that case). Also, the accept attribute is worth checking and carrying over to the ajax options, if present.

Here's what I came up with (untested)

(function ($) {
  $.fn.ajaxForm = function (options) {
    options = $.extend({}, $.fn.ajaxForm.defaults, options);

    // A simple helper function
    function callHandler(name, form, args) {
      if(typeof options[name] === "function") {
        options[name].apply(form, [].slice.call(args, 0));
      }
    }

    return this.each(function () {
      var settings,
          form = this;

      settings = $.extend({}, {
        action:   $form.prop("action"),
        method:   $form.prop("method"),
        accepts:  $form.attr("accept"),
        dataType: $form.data("dataType")
      }, options);

      settings.beforeSend = function () {
        $form.addClass("ajaxForm-loading");
        callHandler("beforeSend", form, arguments);
      };

      settings.complete = function () {
        $form.removeClass("ajaxForm-loading");
        callHandler("complete", form, arguments);
      };

      settings.success = function () {
        callHandler("success", form, arguments);
      };

      settings.error = function () {
        callHandler("error", form, arguments);
      };

      $(this).on("submit", function (event) {
        event.preventDefault();
        $.ajax(settings);
      });
    });
  };

  $.fn.ajaxForm.defaults = {};

})(jQuery);


Function to use projections in legacy algorithms I love the "projections" introduced by the ranges library, and I would like to use them in algorithms that haven't been rangeyfied yet.
I had the idea of using them through a function like this:
#include <utility>
#include <functional>

template<typename TFn, typename TProj = std::identity>
auto
constexpr proj(TFn &&Fn, TProj &&Proj = {})
{
  return [&Fn, &Proj]<typename... TArgs>(TArgs &&...Args)
  {
    return std::invoke(std::forward<TFn>(Fn),
                       std::invoke(std::forward<TProj>(Proj), std::forward<TArgs>(Args))...);
  };
}

This function enables writting, for example:
  std::sort(std::execution::par_unseq, v.begin(), v.end(), proj(std::less{}, &Pair::Key));

instead of:
  std::sort(std::execution::par_unseq, v.begin(), v.end(), [](auto const &lhs, auto const &rhs) { return lhs.Key < rhs.Key; });

Design review
I don’t think you gave a lot of thought to what this library would be actually useful for.
Let me start by just considering the idea of proj() in complete isolation, ignoring any real-use context, and just considering it as a clever trick. From that perspective, I’d have to say that proj() is not a bad idea… but perhaps not the best way to go about it.
Here’s what a ranges call to sort() might look like:
std::ranges::sort(b, e, {}, &Pair::Key);

Here’s what proj() promises, at best:
std::sort(b, e, proj(std::less{}, &Pair::Key));

Here’s what else is possible in C++17, and possibly even before if you’re willing to put in the work of re-implementing std::invoke, etc. (of course it’s also possible in C++20, but… we’ll get to that issue shortly):
myns::sort(b, e, {}, &Pair::Key);

That is, you could implement a wrapper around std::sort() that handles the projection transparently.
For the user, that’s shorter, simpler, and doesn’t require manually specifying the comparator.
Not to mention that when I can advance to C++20 and use the full power of std::ranges, all I need to do (very basically) is a find-replace for myns to std::ranges. If I had these little proj() sub-calls everywhere, the code transform becomes MUCH more complex, and possibly tedious and/or dangerous.
And while you’re at it, why not implement myns::sort() as a neibloid, to get all the sweet, sweet benefits that go along with that?
So if you really want the benefits of projections, why wouldn’t you do that?
Yes, I realize I’m basically saying “re-implement std::ranges”. As a halfway solution proj() only halfway satisfies. What’s the point of that? If you’re going to implement a library tool to make coders’ lives easier, why half-ass it? Who benefits from a mediocre solution? I guess the person writing the library gets to save on some work… but the whole point of library writing is that the library writer is taking on extra work so library users don’t have to. Making things easier for the library writer is silly. You should be concentrating on making things easier for the users.
And by the way, there are a bunch more complications to making something like proj() generally usable that I haven’t mentioned. Like, you’ve created a variant that works with most of the standard algorithms… but it won’t work with std::find() (no predicate, so no Fn). Won’t work with std::merge() (has a predicate, but has two projections). By the time you sort all that out, and test it all rigorously enough to show that it’s trustworthy in production code, you might as well have just used range-v3.
Except… and this is the biggest issue with this whole idea…
This code won’t even compile in C++17. It needs C++20. C++20… where… std::ranges already exists.
So who exactly is this library for?

It can’t be for C++17 (or before) users. (Won’t compile.)
It makes no sense for C++20 (and later) users. (Because if they want a projection in a legacy algorithm, they can just use the std::ranges version. In your example, std::ranges::sort().)

Are you targeting the hypothetical subset of users who are targeting C++20 with their project, but are using a C++20 compiler/library that has lambda templates, std::identity, and constexpr std::invoke… but not the ranges algorithms? That’s a bizarre target group, to say the least. I mean, who targets a C++ version—or uses a specific feature, like projections—without a compiler/library that actually supports it? Not to mention it’s a rather ephemeral group, because presumably if they’re targeting C++20, they could just use std::ranges as soon as the features they need become available in their chose compiler/library, making proj() just a weird stop-gap they would use for a while, then have to weed out of their code base later.
The bottom line is: proj() makes no sense. The only people who could use it… don’t really need it.
(Or, AT BEST, they could maybe use it NOW, for the brief period when their chosen platform supports everything needed to make proj() work, but doesn’t include std::ranges. But, frankly, I’d rather write the lambda than use a mysterious 3rd-party library that’s only going to be useful for a few months then become a legacy maintenance burden.)
From where I’m sitting, this looks like a case of nerd sniping. A neat little theoretical problem became so distracting by its intellectual challenge, that you completely ignored the surrounding real-world problems that are, in point of fact, much more important.
Code review
There’s not much code to review, of course, but….
auto
constexpr proj(//...

It’s pretty bizarre to write the constexpr after the auto. I’ve never seen that done before. I can’t see any sensible reason to adopt this style; it’s only likely to cause confusion.
constexpr proj(TFn &&Fn, TProj &&Proj = {})

Putting the type modifiers next to the variable name, rather than with the type, is a C convention, not a C++ convention. In C++, types matter more, so it makes more sense to say TFn&& Fn.
Also, it is a little peculiar to name variables with UpperCamelCase. UpperCamelCase is usually reserved for template argument names. In other words, TFn&& fn is more conventional.
template<typename TFn, typename TProj = std::identity>
auto
constexpr proj(TFn &&Fn, TProj &&Proj = {})
{
  return [&Fn, &Proj]<typename... TArgs>(TArgs &&...Args)
  {
    return std::invoke(std::forward<TFn>(Fn),
                       std::invoke(std::forward<TProj>(Proj), std::forward<TArgs>(Args))...);
  };
}

The thing that bothers me most about this function is that you:

take the two function arguments as forwarding references
place them into the closures as lvalue references; then
forward them within the closure.

Now, I will admit here that I haven’t sat down and reasoned this through as hard as it really deserves (because it’s late, and because I don’t see the point of the function in any case), but even from a cursory inspection it smells wrong. The smelly part is that you “forget” you’re dealing with forwarding references on that second step.
If the two parameters are lvalues, then no harm, no foul. All the forwarding references will collapse to lvalue references, and the forward()s will degenerate to… well, nothing, effectively; just lvalue references. So you have lvalue references all the way through. All cool.
But if a parameter is an rvalue, then the forward()s will degrade to rvalue references, and may end up moving the argument. So imagine you have a call to, say, sort(), where proj() has been given an rvalue function object (for either parameter, doesn’t matter). On the first execution of the comparator—that is, the first time that lambda proj() returns is called—it will move the function object… leaving it in a moved-from state… so the second time the comparator/lambda is executed, it’s using an “empty” function object. Exactly what damage this will cause depends on what using a “moved-from” function object means, which will depend on the function object type. But in any case, it’s not good.
Okay, put simply:

You have correctly taken the function arguments as forwarding references…
… and you have correctly perfect-forwarded them in the invoke() expressions…
… but you have NOT perfect-forwarded them in the lambda capture.

You need perfectly-forwarded lambda captures. That is NOT trivial… but not too hard (tip: use std::tuple and a mother-ton of decltype(TFn), etc.; don’t forget to mark the lambda mutable).
Summary
As an experiment to explore stuff like projections and perfect-forwarding, this is actually a really neat idea.
As a practical library… I’m not seeing it. Just about the only people who could use it won’t need it. And the tiny demographic who could use it, but who can’t use the superior std::ranges solution, would be unwise to use it (better to wait until their platform supports std::ranges).
The implementation is sound but for that one tricky hiccup: You have perfectly-forwarded everything except the lambda captures. Fix that, and I think it should be a sound implementation. For full practical usability (such as it is), you’d need a couple of overloads for cases not covered by a single predicate and a single projection (for example, an overload without a predicate, for things like std::find(), std::count(), std::remove(), etc.; plus a few other overloads for the more esoteric cases), but once you’ve got the one working, that should be no problem.


Rotate a matrix, using transposition and reflection I want to compare two solutions to the following question from Cracking The Coding Interview by Gayle Laakman McDowell :

  1.7 Rotate Matrix - Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image
  by 90 degrees. Can you do this in place?

We will be assuming we have a square matrix to rotate by 90 degrees clockwise like so:

input:
1 2 3
4 5 6
7 8 9
result:
7 4 1
8 5 2
9 6 3

The book suggests an unusual "layer" method that works its way from the outer edge of the matrix towards the inside

Video explanation by McDowell
McDowell solution code on
Github

A much more intuitive way to solve this seems to be a matrix transpose, followed by a mirror about the vertical axis. This solution is more intuitive because it uses known mathematical matrix operations - the transposition and the reflection. Aside from this being more obvious and easier to read for who have dealt with matrices in the past, it is also more useful because these individual mathematical operations could be saved for other purposes.

Is there any issue with the following code ? More specifically, what are the pros and cons versus the original McDowell solution ?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

typedef vector<vector<int>> matrixT;
class Solution {
    public:
    bool static rotateMatrix(matrixT &mtx){
        if (mtx.size() != mtx[0].size() || mtx.size() == 0) return false;
        int N = mtx.size();

        //transpose matrix
        for (int n = 0 ; n<= N-2; n++)
            for(int m= n+1 ; m<= N-1; m++)
                swap(mtx[n][m], mtx[m][n]);

        //vertical mirror
        for (int n = 0; n < N; n ++)
            for (int m=0; m<N/2 ;m++)
                swap(mtx[n][m], mtx[n][N-1-m]);

        return true;
    }

    void static printMatrix(matrixT mtx){
        for(int m = 0; m < mtx.size(); m++) {
            for(int n = 0; n < mtx.size(); n++)
                cout << mtx[m][n] << " ";
            cout << endl;
        }
    }
};

int main() {
    cout << "input: " << endl;
    matrixT mtx = {{1,2,3},
                   {4,5,6},
                   {7,8,9}};

    Solution::printMatrix (mtx);
    Solution::rotateMatrix (mtx);
    cout << "result: " << endl;
    Solution::printMatrix (mtx);
    return 0;
}

Keep in mind that the primary focus of this web site is to review your working code and provide suggestions on how to improve the code. Questions about which way is better or worse may be based on opinion and that is off-topic for most of the stack exchange websites.
In answer to your question, it could be a possible optimization that reduces the number of steps, but that isn't clear. You may be missing the point of the interview, which is that you should explain as clearly as possible to the interviewer(s) what you are doing at each step so they understand your problem solving techniques. Please note that the video code looked more like C rather than C++, but could have also been other languages.
Avoid Using Namespace std
If you are coding professionally you should get out of the habit of using the using namespace std; statement. In an interview you definitely don't want to use this statement because it is unprofessional. The concept of Name Spaces was invented to specifically solve certain problems such as collision of duplicate function names from core code and library code. This stack overflow question discusses this in more detail.
Use Code Blocks in Flow Control Rather Than Single Statements
Professional coders generally put code blocks or complex statements into if statements, else clauses or loop bodies. The reason for this is to enhance the maintainability of the code. To many bugs have been introduced into code by trying to add one statement to an if statement, else clause or loop. A code maintainer may forget to add the necessary braces so putting them in from the beginning is better. It also makes the code more readable and easier to understand to begin with.
So code like
        int N = mtx.size();
        for (int n = 0 ; n<= N-2; n++)
            for(int m= n+1 ; m<= N-1; m++)
                swap(mtx[n][m], mtx[m][n]);

is better written as
        size_t N = mtx.size();
        for (size_t n = 0 ; n <= N-2; n++)
        {
            for(size_t m= n + 1 ; m <= N-1; m++)
            {
                std::swap(mtx[n][m], mtx[m][n]);
            }
        }

Obviously a maintainer of the code can figure out where to add a statement here.
Horizontal Spacing
It is common to leave spaces between operator and variable. The horizontal spacing in this code is inconsistent.
Prefer std::size_t Over int For Loop Control Variables That Index through C++ Container Classes
While the code in the example from this question will compile and run properly there may be warning messages if the strictest level of compiler switch is used. std::vector.size() returns std::size_t which is unsigned, rather than signed. If the strictest level of switches are used a the following loop might yield the warning message type mismatch.
        for (int n = 0 ; n <= mtx.size() - 2; n++)
        {
            for(int m= n + 1 ; m <= mtx.size() - 1; m++)
            {
                std::swap(mtx[n][m], mtx[m][n]);
            }
        }


Python command line tool for compiling py files to exec files on Mac When I used to use a PC I was familiar with py2exe, the mac equivalent I saw most people talking about was py2app — which compiles python to .app files, not .exec files. I was familiar with compiling C files to execs on mac, and I had heard of cython (but I had never used it before), so I figured I could write something to go from python to cython to an exec. I initially did not write this for anyone else to use — but now I'm thinking about packaging it as a pip module.

This is my first time building a command line tool for executing shell commands and messing with files and directories.

"""(PYCX) PYthon to Cython to eXec, a unix command line util
Usage:
  pycx FILES... [-o DIR --show --delete --run]
  pycx --help

Options:
  FILES              one or more python files to compile
  -o --output=DIR    output directory
  -s --show          show output from exec compiling
  -d --delete        delete the c file after compiling exec
  -r --run           run the exec after compiling
  -h --help          show this screen.
"""
import os, re
from docopt import docopt

args = docopt(__doc__)

# the two pathnames below tell gcc where python is so that cython can be compiled to an exec
INCLUDES = '/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/include/python3.7m'
LIBRARY  = '/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib'
HIDEDATA = '&>/dev/null'  # this is used to hide output while compiling C files

for pyFILE in args['FILES']:
    if pyFILE.endswith('.py'):  # file must be a python file
        path, name = os.path.split(pyFILE)  # split full path to seperate path & filename

        cFILE  = re.sub('\.py$', '.c', pyFILE)  # name of the file with .c extension & path
        FILE   = re.sub('\.py$', '', name)  # name of the file with no extension or path

        PATH   = path + '/' if path is not '' else '.'  # if in current directory, path = '.'
        OUTPUT = args['--output'] + '/' if args['--output'] else ''  # blank if no arg given
        SHOW   = HIDEDATA if not args['--show'] else ''  # will hide gcc output if SHOW is false
        # this command will be used to delete the C file
        DELETE = f'find {PATH} -name "{FILE}.c" -type f|xargs rm -f' if args['--delete'] else ''
        RUN    = f'./{OUTPUT}{FILE}' if args['--run'] else ''  # command to run the exec

        commands = [  # cython to make C file, gcc to compile to exec, and some options
            f"cython --embed -o {cFILE} {pyFILE}",  # convert python to cython C file
            # compile cython C file to exec file
            f"gcc -v -Os -I {INCLUDES} -L {LIBRARY} {cFILE} -o {OUTPUT}{FILE} " + \
            # source python & other options -- hide or show, delete C file, run exec
            f"-lpython3.7 -lpthread -lm -lutil -ldl {SHOW}", f"{DELETE}", f"{RUN}"
        ]
        for command in commands:
            os.system(command)  # execute commands above, excluding blank commands
    else:
        print(__doc__)  # show the help menu if user doesn't put a python file

Besides modifying  INCLUDES and LIBRARY to work with varying path locations, are there any other major problems preventing this from working as a python module? Does this even seem like a tool some people might use?

I recommend that you read PEP 8.

It's advised against doing import os, re. Instead have one line dedicated to each import.
You should have an empty line between importing third party libraries and standard library ones.
In Python it's standard to use snake_case.
You should only have one space either side of the equals sign when performing assignment.
Rather than doing path is not '' you should use the != operator.
'\.py$' is deprecated in Python 3.6, and will become a syntax error in a future version of Python. Instead use r'\.py$'.
Don't mix ' and " string delimiters. Unless it's to do "'".
You don't need to use a \ for line breaking as your within brackets.
You should have the + in front of the next line, rather than the end of the previous line.

Your variable names are crap. path, name FILE, cFILE, PATH. The reason you need your comments is because of this.
If you fix your variable names your comments are useless.
Don't make a list to then call os.system just call it straight away.
Use pathlib, it singlehandedly makes your code ridiculously simple.
Put your code in an if __name__ == '__main__' guard. You don't want to destroy things by accident.

untested:

"""(PYCX) PYthon to Cython to eXec, a unix command line util
Usage:
  pycx FILES... [-o DIR --show --delete --run]
  pycx --help

Options:
  FILES              one or more python files to compile
  -o --output=DIR    output directory
  -s --show          show output from exec compiling
  -d --delete        delete the c file after compiling exec
  -r --run           run the exec after compiling
  -h --help          show this screen.
"""
import os
from pathlib import Path

from docopt import docopt

INCLUDES = '/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/include/python3.7m'
LIBRARY = '/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib'
HIDEDATA = '&>/dev/null'

def main(args):
    for path in args['FILES']:
        path = Path(path)
        if path.suffix != '.py':
            print(__doc__)
            continue

        output = Path(args['--output'] or '') / path.stem
        c_file = path.parent / path.stem + '.c'

        os.system(f'cython --embed -o {c_file} {path}')
        os.system(
            f'gcc -v -Os -I {INCLUDES} -L {LIBRARY} {c_file} '
            f'-o {output} -lpython3.7 -lpthread -lm -lutil -ldl '
            + HIDEDATA if not args['--show'] else ''
        )

        if args['--delete']:
            os.system(
                f'find {path.parent} -name "{path.stem}.c" -type f'
                f'|xargs rm -f'
            )

        if args['--run']:
            os.system(f'{output}')

if __name__ == '__main__':
    main(docopt(__doc__))


Converting from std::wstring to std::string in Linux I was bothered by inability of C++ to mix cout and wcout in the same program - so I've found this question:

Converting between std::wstring and std::string

It didn't help me because it was mostly about MS Windows (I'm on Linux), but thanks to it I've found something similar to the WideCharToMultiByte functions in the C++ standard library.

My goal was just to output wide strings to cout intermittently with regular strings. I've written two variants of conversion function, which take wide string as an argument and return a regular string, containing multi-byte characters, ready to be sent to the cout (provided that the locale is appropriate).

#include <iostream>
#include <string>

using std::cout;
using std::endl;

struct T
{
  std::string a;
  std::wstring b;
};

std::string Convert1(const std::wstring& WS)
// ------ conversion using the wcstombs function
{
  const unsigned wlen = WS.length();
  char buf[wlen * sizeof(std::wstring::value_type) + 1];
  const ssize_t res = std::wcstombs(buf, WS.c_str(), sizeof(buf));
  return (res >= 0) ? buf : "?";
}

std::string Convert2(const std::wstring& WS)
// ------ conversion using the wcsrtombs function
{
  mbstate_t st = {};
  const unsigned wlen = WS.length();
  wchar_t wbuf[wlen + 1];
  const size_t copied = WS.copy(wbuf, wlen);
  wbuf[copied] = L'\0';
  const wchar_t* wptr = wbuf;
  char buf[wlen * sizeof(std::wstring::value_type) + 1];
  const ssize_t res = std::wcsrtombs(buf, &wptr, sizeof(buf), &st);
  return (res >= 0) ? buf : "?";
}

int main()
{
  T t = {"Hello", L"Привет"};
  std::setlocale(LC_ALL, "en_US.utf8");
  cout << t.a << endl;
  cout << Convert2(t.b) << endl;
}

It works for me now... Will it work in other setups?

ssize_t is essentially unsigned; that is, the comparison res >= 0 is always true.

The test should be

res != static_cast<std::size_t>(-1)

<cstdlib> and <cwchar> headers are missing
You don't need to WS.copy(wbuf, wlen).

In fact, you don't need wbuf at all:

const wchar_t * wptr = WS.c_str();
std::wcsrtombs(buf, &wptr, sizeof(buf), &st);

works just fine.
I am not sure that calculating buffer length via sizeof(std::wstring::value_type) is a right way. How can you be sure that multibyte sequence will fit? I'd recommend to obtain required size by passing NULL to wcsrtombs.

PS: И тебе привет


Xml messages processing networkstream I'm currently processing xml messages with C#. It is working But I'm not confident that my code is fast enough. There are 3 possible messages I can receive. When I receive one the message an event is triggered and I can access the object outside of this thread and do the necessary processing. The method start is running in a separate thread.
    public void Start()
    {
        NameTable nt = new NameTable();
        object frameAck = nt.Add("frameack");
        object alarmResponse = nt.Add("alarmresponse");
        object watchdog = nt.Add("watchdog");
        StreamReader sr = new StreamReader(_tcpClient.GetStream());
        XmlReaderSettings settings = new XmlReaderSettings
        {
            NameTable = nt,
            ConformanceLevel = ConformanceLevel.Fragment
        };
        XmlReader xr = XmlReader.Create(sr, settings);
        while (!_requestStop)
        {
            try
            {
                while (xr.Read())
                {
                    if (xr.NodeType == XmlNodeType.Element)
                    {
                        object localName = xr.LocalName; // Cache the local name to prevent multiple calls to the LocalName property.
                        if (watchdog == localName)
                            OnWatchdogComplete(new CustomEventArgs(xr.ToClassFromXmlStream<WatchdogFrame>()));
                        if (alarmResponse == localName)
                            OnAlarmResponseComplete(new CustomEventArgs(xr.ToClassFromXmlStream<AlarmResponse>()));
                        if (frameAck == localName)
                            OnAckComplete(new CustomEventArgs(xr.ToClassFromXmlStream<FrameAck>()));
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        xr.Close();
        sr.Close();
        Console.WriteLine("Stopping TcpXmlReader thread!");
    }

This is my extensionmethod to deserialize to an object.
    public static T ToClassFromXmlStream<T>(this XmlReader xmlStream)
    {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(xmlStream);
    }

When I close the program I always get the errors:

There is an error in XML document (9, 12).
Cannot access a disposed object.
Object name: 'System.Net.Sockets.NetworkStream'.

When I was string processing this it would seem that is was going a lot faster. But it was very complex and this very easy.

I think this question is half-way between Stack Overflow and Code Review anyway...

Start() is running on a standalone thread however it uses _tcpClient. Assuming things are properly done you dispose _tcpClient in container class Dispose() method. When it happens your reader will access (indirectly, through sr of type StreamReader) a disposed object (_tcpClient, from which underlying stream comes from).

You may transfer ownership of _tcpClient to your secondary thread.

void Start() {
    try {
        // All the code you already have in-place
    }
    finally {
        _tcpClient.Dispose();
    }
}

However you already have a flag in-place (_requestStop). Hard to say (without surrounding code) what's wrong but you first should check if you set flag _requestStop and immediately exit (even if reading is in progress). You'd better set that flag and then wait until thread completes its work (for an example see How to wait for thread to finish with .NET?).

Few more considerations more on-topic on Code Review.

1) You're not using using statement:

using (var sr = new StreamReader(_tcpClient.GetStream())) {
    // You don't need to explicitly call sr.Close();
}

Do the same for your XmlReader variable xr.

2) XML deserialization isn't as quick as you may wish. If speed is a measured issue then you may consider to manually parse XML fragment (using XmlReader you have) to build your objects.

3) You should avoid to catch a generic Exception. You should know what may go wrong in your code, catch errors you expect and leave to a more generic error handler to catch the others (for example, no matters how many times you retry because of while() but if _tcpClient has been closed then it won't recover its connection and you'll keep generating exceptions).

4) In your big try/catch you also catch exceptions generated by code called in events. Also some exceptions may leave XmlReader in an inconsistent state and you may want to re-create it.

5) You do not need to cache XmlReader.LocalName property value. It won't perform any parsing for each access and call to property getter may be optimized away (inlined) by JIT compiler. It's such micro-optimization that you won't notice any difference even if you read its value Int32.MaxValue times (do not forget you're also working with network data).

6) XmlReader.LocalName type is string, no reason to loose its type assigning to an object variable. The same is true for NameTable.Add() return type: it's a string, don't assign it to an untyped object variable.

7) You compare strings (localName with watchdog and the others) but you do not explicitly say which type of comparison you want. Is it case-sensitive or case-insensitive? Is current culture aware? Make it explicit according to what you want or you may have surprises when current culture has unexpected text comparison rules (see also this post). Change your code to:

if (String.Equals(xr.LocalName, watchdog, StringComparison.InvariantCulture)) {
}


Nested switch to return configuration for combination of 3 database types and 4 domains I am currently doing a code review for a coworker.

I have encountered something like this:

switch (type)
{
    case DatabaseType.Type1:
        switch (domain)
        {
            case DOMAIN_1:
                return DatabaseConfigType.Type1Domain1;
            case DOMAIN_2:
                return DatabaseConfigType.Type1Domain2;
            case DOMAIN_3:
                return DatabaseConfigType.Type1Domain3;
            case DOMAIN_4:
                return DatabaseConfigType.Type1Domain4;
            default:
                Trace.Error("Undefined Type1 domain :" + domain);
                throw new ArgumentOutOfRangeException("domain", domain, null);
        }
    case DatabaseType.Type2:
        switch (domain)
        {
            case DOMAIN_1:
                return DatabaseConfigType.Type2Domain1;
            case DOMAIN_2:
                return DatabaseConfigType.Type2Domain2;
            case DOMAIN_3:
                return DatabaseConfigType.Type2Domain3;
            case DOMAIN_4:
                return DatabaseConfigType.Type2Domain4;
            default:
                Trace.Error("Undefined Type2 domain :" + domain);
                throw new ArgumentOutOfRangeException("domain", domain, null);
        }
    case DatabaseType.Type3:
        switch (domain)
        {
            case DOMAIN_1:
                return DatabaseConfigType.Type3Domain1;
            case DOMAIN_2:
                return DatabaseConfigType.Type3Domain2;
            case DOMAIN_3:
                return DatabaseConfigType.Type3Domain3;
            case DOMAIN_4:
                return DatabaseConfigType.Type3Domain4;
            default:
                Trace.Error("Undefined Type3 domain :" + domain);
                throw new ArgumentOutOfRangeException("domain", domain, null);
        }
    default:
        Trace.Error("Undefined type :" + type);
        throw new ArgumentOutOfRangeException("type", type, null);
}

Obviously, Types and Domains have actual wordy names, I just changed them for the question because they are irrelevant and probably sensitive information. On the other hand, the actual names for the DatabaseConfigType Enum are literally of the format TypeDomain, with the actual names of the type and domain instead of my numbered version.

I see this code, and it just feels wrong. There is some obvious redundancy by having three times (possibly more in the future) the exact same switch conditions inside each "outer" switch case, but since they return an Enum with different values, I just can't figure out a way to actually make this better.

The enum is in no particular order, and can't be expected to stay the same, so I can't do some math-ish unreadable but fast solution, not that I think it would be better anyway.

The code is probably as fast as it can be while still being readable, I'm mostly looking for a way to reduce the copy-paste aspect, therefore the lines of code, because I can't shake the feeling that there has to be a better way. If there isn't, feel free to tell me that.

Just declare a (static readonly) dictionary:

var values = new Dictionary<(DatabaseType, DomainType), DatabaseConfigType>()
{
    { (DatabaseType.Type1, DomainType.Domain1), DatabaseConfigType.Type1Domain1 }
};

Filled with all possible combinations. Then your function will be reduced to:

DatabaseConfigType GetDatabaseConfiguration(DatabaseType database, DomainType domain)
    => values[(type, domain)];

You may want to use TryGetValue() to customize error message or to throw a different, more informative, exception. I'm using C# 7 named tuples but you can do it without them, it's just little bit more verbose because you need to declare your own Tuple because we need it to be a struct unless you use a custom comparer.

Edit: what if you need custom error messages (saying which part is unknown)? You need to nest dictionaries:

var values = new Dictionary<DatabaseType, Dictionary<DomainType, DatabaseConfigType>>()
{
    {
        DatabaseType.Type1, Dictionary<DomainType, DatabaseConfigType>
        {
            { DomainType.Domain1, DatabaseConfigType.Type1Domain1 }
        }
    }
};

In this case to get a value:

DatabaseConfigType GetDatabaseConfiguration(DatabaseType database, DomainType domain)
{
    if (values.TryGetValue(database, out var configTypes))
    {
        if (configTypes.TryGetValue(domain, out var configType))
            return configType;

        throw new ArgumentException($"Unknown domain {domain} for {database}");
    }

    throw new ArgumentException($"Unknown database {database}");
}

Which exception should be thrown? Assuming you can change this part of the code contract I feel ArgumentOutOfRangeException is not the appropriate one in this case (POLA?). Some combinations aren't allowed, an enum may have an invalid value (GetDatabaseConfiguration((DatabaseType)333, (DomainType)444)) or you may simply forgot to update this function after an update to the enum.
In my opinion a generic ArgumentException may be enough (unless you want to differentiate the invalid combination case). A specific exception exists (InvalidEnumArgumentException) but I seldom saw it in real-world code (probably because it doesn't add much value over ArgumentException).

Assuming you changed names but not style then DOMAIN_1 isn't a good name because it doesn't follow common C# naming conventions: it's all uppercase and it uses underscore as separator, it should be Domain1.


Integer version of c++ standard library midpoint I was extremely annoyed by the lengthy, edge-case-galore explanation of integer version of C++ standard library mindpoint implementation here, so I made my own simple 2's complement version. I present it for your judgement.
The general idea is to carry out a + (b-a)/2 in a wider signed integer that won't ever overflow.
Say a and b are N bit integers. Consider them as imaginary signed (2's complement) N+1 bit integers. The obvious magic of 2's complement is that we can carry out addition/subtraction as usual, so first we obtain the lower N bits of the hypothetical N+1 bit difference,
Unsigned diff = Unsigned(b) - Unsigned(a);

working with unsigned type to avoid signed overflow UB. We don't really have the +1 bit, so just imagine sign extension also happens. We only care about lower N bits anyway since we know the final half difference has to fit there. Problem is - we can't do division in this straightforward way, so we have to branch, based on the sign of the final result.

If N+1 bit difference was negative (highest/sign bit set), we jump through hoops:Negate/abs (2's complement approved as subtraction 0-diff).Unsigned negative_2x = -diff; Divide (it works cause sign bit is now guaranteed 0).negative_2x /= 2;
Now we can fit this halved difference back into our original N bit signed int, so we convert it back and negate to restore the original sign.Integer negative = -Integer(negative_2x);
Converting first is important to avoid signed overflow UB again. If original Integer was unsigned this still works, since the wrapping behavior is consistent with 2's complement.

Otherwise if difference was positive, it fully fit in N bits unsigned, and half of it should fit in signed, no hoops:Integer positive = diff / 2;

The actual branch looks like this to encourage conditional move, not that compilers care...
return a + (b < a ? negative : positive);

The code by itself with a primitive/stand-in function signature, for the purposes of copying into an IDE and compiling:
#include <type_traits>

template<typename Integer, typename Unsigned = std::make_unsigned_t<Integer>>
Integer midpoint(Integer a, Integer b)
{
    Unsigned diff = Unsigned(b) - Unsigned(a);

    Unsigned negative_2x = -diff;
    negative_2x /= 2;
    Integer negative = -Integer(negative_2x);

    Integer positive = diff / 2;

    return a + (b < a ? negative : positive);
}

Also available here, passes all the libstdc++ and libc++ unit tests for integers.

Naming things
The variable names are not very clear. I assume the _2x stands for "2's complement" instead for "times 2", but for someone who doesn't know the context, it will be hard to follow. I'm not sure what the best way to name them is though, but as shown below you can avoid the issue altogether.
Don't use a template parameter for a derived type
If you make Unsigned a template parameter, it means someone can override it to something nonsensical. If you want to have a named type that is a derivative of another type, use using inside the function body:
template<typename Integer>
Integer midpoint(Integer a, Integer b)
{
    using Unsigned = std::make_unsigned_t<Integer>;
    ...
}

Simplifying the code
Most of the temporary variables can be removed. I would keep the variable diff, as it is the most important one where the casts are essential, and since it is used twice:
template<typename Integer>
Integer midpoint(Integer a, Integer b)
{
    using Unsigned = std::make_unsigned_t<Integer>;
    Unsigned diff = Unsigned(b) - Unsigned(a);
    return a + (b < a ? -Integer(Unsigned(-diff) / 2) : Integer(diff / 2));
}

The return expression is still reasonably short, and I don't think any information was lost. Adding some comments explaining why the casts are necessary would be helpful though.