Instead of get_insersec_region, I would call this method __and__. This way you can use overlap = r1 & r2, just like for set intersection.

You can add intersect = __and__ if you also want the expressiveness of overlap = r1.intersect(r2).

Instead of returning None, I would consider returning an empty Rectangle. This way you don't need any special code to handle e.g. (r1&r2).area. For this, I would set default values for the coordinates, all 0.

Incidentally, I would add an area method and make it a property:

@property
def area(self):
    return (self.max_x - self.min_x) * (self.max_y - self.min_y)

The reason it should be a property is maintainability. If you decide at some point that you only want to compute the area at creation time because a Rectangle is not allowed to change size anymore, you could remove this function and just store self.area = ... in the constructor. Also it is evidently true that the area of a rectangle is a property of that particular rectangle.

And an __or__ method to get the bounding rectangle. You might need this if you want a GUI and update only the region where things changed but still want to do only one update. Then you need to find a rectangular area which includes all objects, which you can then just get by |ing all rectangles.

Your __str__ method can be simplified using map and str.join:

def __str__(self):
    return '\t'.join(map(str, (self.min_x, self.max_x, self.min_y, self.max_y)))

Alternatively, you can use str.format:

def __str__(self):
    return '{self.min_x}\t{self.max_x}\t{self.min_y}\t{self.max_y}'.format(self=self)

The latter slightly more future proof, because you can replace it with this in Python 3.6, using f-strings:

def __str__(self):
    return f'{self.min_x}\t{self.max_x}\t{self.min_y}\t{self.max_y}'

Final code:

class Rectangle:
    def __init__(self, min_x=0, max_x=0, min_y=0, max_y=0):
        self.min_x = min_x
        self.max_x = max_x
        self.min_y = min_y
        self.max_y = max_y

    def is_intersect(self, other):
        if self.min_x > other.max_x or self.max_x < other.min_x:
            return False
        if self.min_y > other.max_y or self.max_y < other.min_y:
            return False
        return True

    def __and__(self, other):
        if not self.is_intersect(other):
            return Rectangle()
        min_x = max(self.min_x, other.min_x)
        max_x = min(self.max_x, other.max_x)
        min_y = max(self.min_y, other.min_y)
        max_y = min(self.max_y, other.max_y)
        return Rectangle(min_x, max_x, min_y, max_y)

    intersect = __and__

    def __or__(self, other):
        min_x = min(self.min_x, other.min_x)
        max_x = max(self.max_x, other.max_x)
        min_y = min(self.min_y, other.min_y)
        max_y = max(self.max_y, other.max_y)
        return Rectangle(min_x, max_x, min_y, max_y)

    union = __or__

    def __str__(self):
        return 'Rectangle({self.min_x},{self.max_x},{self.min_y},{self.max_y})'.format(self=self)

    @property
    def area(self):
        return (self.max_x - self.min_x) * (self.max_y - self.min_y)


Calculating overlap of segments in chromosome data

I read the data in

a <- read.delim(textConnection("Chromosome\tStart\tEnd
1\t0\t2420037
1\t2420037\t2522634
1\t2522634\t10794763
1\t10794763\t10925915
1\t10925915\t11280057"))

b <- read.delim(textConnection("chr\tstart\tend\tvariantaccession\tvariantsubtype
1\t10001\t127330\tnsv7879\tGain+Loss
1\t10001\t846808\tdgv2n71\tGain
1\t10377\t177417\tdgv1e1\tComplex
1\t10377\t177417\tnsv428112\tGain
1\t10377\t1018704\tdgv3e1\tComplex
1\t10499\t177368\tesv27265\tGain+Loss"))

and then used the GenomicRanges package to efficiently find overlaps between the query "A" and subject "B".

library(GenomicRanges)
A <- makeGRangesFromDataFrame(a)
B <- makeGRangesFromDataFrame(b, keep.extra.columns=TRUE)
olaps <- findOverlaps(A, B)

olaps is basically a two-column matrix, indicating which element(s) of A overlap the corresponding elements of B. In the invocation above A and B enter symmetrically, but could be re-ordered if there were restrictions on the type of overlap (argument type, e.g., all of B strictly within A). To find the extent of overlap, I looked at the parallel (element wise) intersection of each overlap

> isect <- pintersect(A[queryHits(olaps)], B[subjectHits(olaps)])
> isect
GRanges with 6 ranges and 0 metadata columns:
      seqnames           ranges strand
         <Rle>        <IRanges>  <Rle>
  [1]        1 [10001,  127330]      *
  [2]        1 [10001,  846808]      *
  [3]        1 [10377,  177417]      *
  [4]        1 [10377,  177417]      *
  [5]        1 [10377, 1018704]      *
  [6]        1 [10499,  177368]      *
  ---
  seqlengths:
    1
   NA

I could then create a data.frame with whatever information I want, e.g.,

data.frame(query=queryHits(olaps), subject=subjectHits(olaps),
           olap_width=width(isect),
           query_width=width(A)[queryHits(olaps)],
           variantaccession=B$variantaccession[subjectHits(olaps)])

This will be fast for millions of records in A and B.

makeGRangesFromDataFrame is available in the current release version of the package, installed by default when using R-3.1. It's easy to make a GRanges 'by hand', e.g.,

A <- with(a, GRanges(Chromosome, IRanges(Start, End)))
B <- with(b, GRanges(chr, IRanges(start, end), variantaccession=variantaccession))


Enumerating new articles whose publication start date has passed

As for me, the first form is more readable because it clearly describe the condition. It's easy to read and understand. The second form is a little confusing. The first thought I had was: What is the DateTime.Zero? Is this a default value for PublishEnd? If yes then why not to use the DateTime.MinValue? Maybe it's not a default value and I get it wrong somewhere? Of course these thoughts took only seconds but nevertheless.
In general I think that ?? should be used to return the default value with expected type. The default value of the  PublishEnd should be of DateTime type. But the second form distorts the meaning of ?? and returns bool type instead, and it’s confusing.

Edited:
If you want to read is like you said: "if now is greater than (end date or earliest date)"
then you should write it like:

(DateTime.Now > cn.PublishEnd ?? DateTime.MinValue)

And this, third form is better than first and second.


Clean up function in Javascript Event Listener

Toward restructuring and optimization

The expressions Math.floor(event.clientX / 60) and Math.floor(event.clientY / 60) which represents element position are redundantly duplicated across a half of the entire posted function's content.The Extract function technique is reasonably applied and expressed with a separate function:

function getElPosition(e){
    return {x: Math.floor(e.clientX / 60),
            y: Math.floor(e.clientY / 60)};
}

hasClicked and highlightPos variables are assigned with same values in both exclusive branches of if/else conditional.Thus, the assignment statements are moved out as common ones.Furthermore, both highlightPos and advancePosition are essentially point to the target event element position returned by mentioned getElPosition function. Therefore, they could be just eliminated (see the full approach below).

The condition:

if (pieceMoves.moves[i].x - 2 == highlightPos.x || pieceMoves.moves[i].x + 2 == highlightPos.x) {
    isCastling = true;
} else {
    isCastling = false;
}

is just a verbose version of:

isCastling = (pieceMoves.moves[i].x - 2 == elPos.x || pieceMoves.moves[i].x + 2 == elPos.x);

Noisy condition:

if (
    board[highlightPos.y][highlightPos.x] == whiteKingSideCastle ||
    board[highlightPos.y][highlightPos.x] == whiteQueenSideCastle ||
    board[highlightPos.y][highlightPos.x] == blackKingSideCastle ||
    board[highlightPos.y][highlightPos.x] == blackQueenSideCastle ||
    board[highlightPos.y][highlightPos.x] == blackKing ||
    board[highlightPos.y][highlightPos.x] == whiteKing
)

is replaced with flexible Array.includes feature:

if ([whiteKingSideCastle, whiteQueenSideCastle, blackKingSideCastle,
     blackQueenSideCastle, blackKing, whiteKing].includes(board[elPos.y][elPos.x]))

The can_move flag can be eliminated and replaced with check of pieceMoves.length.

board[highlightPos.y][highlightPos.x] indexing is repeated multiple times and worth to be extracted into a variable:

let boardItem = board[elPos.y][elPos.x];

See the full optimized approach:

function getElPosition(e){
    return {x: Math.floor(event.clientX / 60),
            y: Math.floor(event.clientY / 60)};
}

document.addEventListener('click', function (event) {
    let elPos = getElPosition(event);
    if (!hasClicked) {
        if (event.clientX < 480 && event.clientY < 480 && board[elPos.y][elPos.x] != "vacant") {
            if (humanPlayer.indexOf(board[elPos.y][elPos.x]) != -1) {
                isHighlightPossibleMoves = true;
                pieceMoves = processMoves(Object.assign({}, elPos), board);
            }
            hasClicked = true;
        }
    } else {
        if (pieceMoves && pieceMoves.length) {
            for (let i = 0, len = pieceMoves.moves.length; i < len; i++) {
                let boardItem = board[elPos.y][elPos.x];
                if (elPos.x == pieceMoves.moves[i].x && elPos.y == pieceMoves.moves[i].y) {
                    if (boardItem == blackKing || boardItem == whiteKing) {
                        isCastling = (pieceMoves.moves[i].x - 2 == elPos.x || pieceMoves.moves[i].x + 2 == elPos.x);
                    }
                    if (!isCastling) {
                        if ([whiteKingSideCastle, whiteQueenSideCastle, blackKingSideCastle,
                            blackQueenSideCastle, blackKing, whiteKing].includes(boardItem))
                        {
                            boardItem.hasClicked = true;
                        }
                        board = chess.updateBoard(elPos, elPos);
                        chess = new Chess(board);
                        break;
                    }
                    board = chess.returnCastledBoard({x: elPos.x, y: elPos.y}, pieceMoves.moves[i]);
                    chess = new Chess(board);
                    isCastling = false;
                }
            }
        }
        hasClicked = false;
        pieceMoves = undefined;
    }
});


Instead of hard-coding 1000000000, use a constant:

const int maxPrimes = 1000000000;

Then, use it in the loop like this:

for (int i = 3; i < maxPrimes; i+=2)

This will make it clear what this value is.

Regarding the timing, you could use something from <ctime> or another suitable library to time certain code sections. For instance, you may time the loop in main() or just the one in primeChecker() for testing purposes.  This may be OS-dependent, so I'll let you decide on this if you wish to try it.


CompaniesList.Items.AddRange(authCompXml.SelectNodes("//Code")
    .Cast<XmlNode>()
    .Select(node => new ListItem(node.InnerText))
    .ToArray());


your Table is not declared correctly in the markup.

This:

Should look like this

your self closing tag
 means that the row is now closed, you shouldn't have a  outside of a row, it is bad structure and won't show correctly in browsers.

HTML is not made up of
's alone.  you should include other elements as well, even when you are only figuring out your structure.

Image tags are not <image>  they are  and as long as you have everything you need inside the attributes, they are self closing tags.

from the looks of the Graphic, you may not need a table, you probably want a list instead of a table.  If I were you I would look into an unordered list (you can format how you like with CSS)

Element tags do not have Capital letters in them at all,  they are Lowercase.

More Descriptive ID names. If you have something that is going to be styled the same as something else give them class names and declare the style once.  if you have one thing that is going to be different, create a class that will style it and the surrounding items the the same and add another class to it and declare it after the other class.

In Closing

I would say that you should figure out your CSS and then post a new question as well (with the CSS)

this is not a finished structure, it looks like something you threw together in about a half an hour.  probably took you longer to draw the picture than write the HTML


Noughts and crosses command line game in Python 3.5

The functions get_turn, format_player and play_game have no docstrings. What do they do? What do they return?
In check_for_win, the value of format_player(player) does not change and so you could remember it in a local variable to avoid recomputing it on each time around the loop.
check_for_win could be simplified using the built-in function all, like this:

def check_for_win(board, player):
    """Returns True if player has won, otherwise False"""
    player = format_player(player)
    for winning_line in winning_lines:
        if all(board[pos] == player for pos in winning_line):
            return True
    return False

and then that could be futher simplified using the built-in function any, like this:

def check_for_win(board, player):
    """Returns True if player has won, otherwise False"""
    player = format_player(player)
    return any(all(board[pos] == player for pos in winning_line)
               for winning_line in winning_lines)

If the player's input is incorrect, there is no message explaining what the problem was.
Repeatedly switching between player 1 and player 2 can be done using itertools.cycle, like this:

from itertools import cycle
for player in cycle((1, 2)):
    # etc.

I think that printing the winner should be the responsibility of the play_game function, not of the top-level code.
There is no check to see if the game is tied. If the board is full but there is no winner then the game continues to prompt player 2 for a move.


Calculating sum of smallest prime factors for 2 < n < 10**12

Sorry, too long for a comment (this isn't a real review, but it isn't a CR what you need).

This is Project Euler 521 and providing a full answer here would spoil the fun. If you really want to cheat, google it out.

  Is there any way to shorten the runtime of this program?

There are many ways and you'll need more than one:

Iterating till 10**12 alone is too slow, even if you did just a simple sum (one hour maybe).
Determining if a number is a prime, even with a good sieve takes quite some time as well.

Without much thinking, I agree with you that the runtime will be many days.

Your question is actually not about code optimization, but about finding a smarter algorithm. Smarter by a few orders of magnitude. A wonderful hint can be found in forum for problem 10, page 5.

It's solvable without this wonderful idea, too, but it took my computer half an hour. Instead of factoring numbers, I produced them as products, which is much faster when you really want all of them. The next idea is that you don't really need to produce them, counting is enough.


function Constructor(){
  this._isMyPrivates = function(){}
}

The usual problem with this "function inside this constructor to emulate private" approach is that every instance of the constructor will have copies of the functions. This will eat up your memory fast, especially that your object sounds like a base class for physics objects.

Try using prototypal inheritance instead.The methods are defined once, and shared rather than defined for each instance.

// Constructor
var PhysicsEntity = function(mass, entityWidth, entityHeight, accelerationVector, position, lifeTime){
    this.mass = mass;
    this.entityWidth = entityWidth;
    this.entityHeight = entityHeight;
    this.accelerationVector = accelerationVector;
    this.position = position;
    this.velocity = new PVector(0, 0);
};

// Prototype
PhysicsEntity.prototype._calculateForces = function(){}
PhysicsEntity.prototype._applyForces = function(){}
PhysicsEntity.prototype._renderEntity = function(){}
PhysicsEntity.prototype.updateEntity = function(){}

// This means that
// instance (where props live) -> prototype parent (where methods live)
//                                      A
// another instance (where props live) -' // literally pointing to the same object

And don't worry about "private". One can easily tamper the JS anyways, one way or another. You can prefix privates with underscores, as it's the usual convention.


Binary Search recursive & iterative solution

You haven't indicated the purpose for writing these implementations.  The natural alternative would be to use Arrays.binarySearch unless this is purely for learning purposes.
Testing
Your test suite is far from exhaustive, testing that both methods can find the item at position 2 is very minimal (at the moment both implementations could simply always return 2).  Consider adding additional tests for edge cases (end of array being searched, beginning of array being searched for example).  Consider what behaviour you're expecting if the item isn't in the array being searched and adding test cases for those scenarios.
array isn't a great name for the source data in your tests.  sortedArray or dataToSearch would be a bit better however consider declaring the array in each test method.  In a larger test file, scrolling up and down to see the data in the array, versus the test that's being performed adds extra overhead, which can be undesirable.
Implementations
All of your methods are declared as private.  Some of them are meant to be called from outside the class, some of them (such as the recursive call) probably aren't.  This should be reflected in the access declarations.
Naming is an important aspect of development.  The better your names are and the more consistent you are with them, the easier your code is to follow.  You're consistent with your use of left and right, but mid is called pivot in the alternate implementation.  The item to find is either i or item.  IDE's will often give parameter name prompts even when there is no Java Doc.  If you name your parameters well, it's clear that the parameters are (int[] arrayToSearch, int itemToFind)
Doh...
I should really have noticed this earlier... but both of your methods return boolean, however you're asserting they both return 2, which isn't a boolean...  Think about what you want the method to return...implement that...and write the tests accordingly...


Checking if a line in a file contains user.Handle and '-r'+any single digit number

If I see it correctly, you could already simplify your code by saying

if (line.Contains(user.Handle) && !user.Handle.Contains("-r") &&
    (line.Contains("-r1") || line.Contains("-r2") || ... line.Contains("-r9"))

That should be basically the same thing as the above. Now when you look at the last part, you could simplify it to a regular expression -r\d (not sure if - needs to be escaped here) So the final version could look like this:

if (line.Contains(user.Handle) && !user.Handle.Contains("-r") &&
    Regex.IsMatch(line, "-r\\d"))

did I get your question? Did I miss anything?


Get persons full name from their First and Surname

Naming

Whenever you have a simple method that starts with Get, it's an indication that should should consider making it a property (in this case a read only one).

Unnecessary variable
The fullname variable is unnecessary, you might was well return simply the result of the String.Format.

Alternate for higher .Net versions

Depending on your .Net version, you might also want to use string interpolation instead.  If you combine these three things then your GetFullName becomes:

public string FullName {
                  get { return $"Firstname is: {Firstname}, Surname is {Surname}"; }
              }

As an aside, usually you would simply expect the combined full name, rather than it being explicitly stated which is which, so you would have:

get { return $"{Firstname} {Surname}"; }

or using the expression bodied auto property suggested by @Risky Martin you would end up with simply this:

public string FullName => $"{Firstname} {Surname}";

Parameter Validation

It may seem trivial for such a small class, but depending on the use case you should consider if you need to add validation to your constructor.  Is it really valid to construct a Person with a null or empty string for example?  As has been said by @Rick Davin, do you really want/need the setter for FirstName and Surname to be public, does it make sense for a Person object to change its name?  If it does make sense, then again, you should consider if rather than using the auto property you should be performing validation in your set methods.


String to hash in Ruby without JSON.parse

Chain your calls. Don't update the same variable again and again with very different values.
Just construct a hash straight away with each_with_object or construct an array of pairs, and turn that into a hash.
Any sort of splitting/scanning is prone to errors if the string contains tokens that aren't part of the syntax. I.e. a nested string with a semicolon in it will be split as though it's a delimiter.

Anyway, you can do this, for instance:

result = Hash[ string.scan(/(\w+):\s+([^;]+)/) ]

though that'll give you string keys.

To avoid that, you could do:

pairs = string.scan(/(\w+):\s+([^;]+)/).map { |k,v| [k.to_sym, v.strip] }
result = Hash[pairs]

or

result = string.scan(/(\w+):\s+([^;]+)/).each_with_object({}) do |(k,v), hash|
  hash[k.to_sym] = v.strip
end

Another, much less robust way would be:

pairs = string.split(/[:;]/)
  .map(&:strip)
  .each_slice(2)
  .map { |k,v| [k.strip.to_sym, v.strip] }
result = Hash[pairs]

Edit: And the totally unsafe option would be

result = eval("{#{string.tr(';', ',')}}")

On the plus side, your values have proper types (not all strings). On the minus side, eval is evil, and should always be avoided. So, really, don't do this.


I tend towards the former, and then use a lens or traversal to extract the location.

import Control.Lens

class HasLocation t where
  loc :: Lens' t Location

instance HasLocation RExpr where
  loc f (RLExpr l e)    = f l <&> \l' -> RLExpr l' e
  loc f (RConstant l c) = f l <&> \l' -> RConstant l' c
  loc f (RMathExpr l m) = f l <&> \l' -> RMathExpr l' m
  loc f (FCall l i xs) = f l <&> \l' -> FCall l' i xs

With the class you can overload the use of loc for other data types. Because it is a lens you can use it to get/set/modify the location with a large vocabulary without cluttering your namespace.


I'm pretty sure you implemented the necessary features in a standard hash table. If you want the hash table to populate only unique values then you need to change your insert method by looking up the value before inserting it.

Here are some things you did incorrectly or can do better in my opinion:

table = [None] * 256

table is static right now, which means that any instance of the class will have the same table variable. You need to initiate it in __init__.

def get_value(self, key):

get_value is a method that should not be called by the user of the class. I recommend making is private by changing its name to _get_value.

def insert(self, key):
    val = self.get_value(key)
    if self.table[val] == None:
        self.table[val] = key
    else:
        if type(self.table[val]) == list:
            self.table[val].append(key)
        else:
            self.table[val] = [self.table[val], key]

Why starting with a single value and only after that changing to a list? I recommend starting with a list right from the start. As said by python's module this:

  Special cases aren't special enough to break the rules.

That way, you can start with a table of empty lists right from the start, this will simplify your insert and lookup methods.

def delete(self, key):
    val = self.get_value(key)
    if self.table[val] != None:
        if type(self.table[val]) == list:
            i = self.table[val].index(key)
            self.table[val][i] = None

Making the value None can be dangerous - what if the user inserts lot's of values and then removes all of them? the lookup method will then take much more time than required. Although it takes more time, I still think list.remove is the right thing to do here.

    ...
    else:
        KeyError()

You need to raise the KeyError. Also - it's better to put in the error the right message. something like:
raise KeyError("key {key} can't be found.".format(key=key)


The bad part is that ToEnumerable returns an IEnumerable that blocks for each element until it is produced by the IObservable it is called on. This means that you might as well be doing:

public static IEnumerable<R> SelectAsync<T, R>(this IEnumerable<T> source, Func<T, Task<R>> selector)
{
    foreach (var item in source)
        yield return selector(item).Result;
}

and depending on what kind of app you're writing, this might deadlock, though I think your version of going through Rx might avoid that and be more functionality close to:

public static IEnumerable<R> SelectAsync<T, R>(this IEnumerable<T> source, Func<T, Task<R>> selector)
{
    foreach (var item in source)
        yield return Task.Run(() => selector(item)).Result;
}

Either way, you're blocking a Thread which is seen as a bad thing to do in the age of async/await and the TPL. It would be as bad as using Thread.Sleep with Task.Run. It is not likely to lock up your app, especially if your app is multi-threaded, but it most certainly will block a Thread on the thread pool.

I've certainly seen people get away with using Thread.Sleep with Task.Run with no real consequences, but keep in mind that it can cause issues when you scale.

As for how you might know this without being intimately familiar with Rx and the details of how its operators work? That's easy. Just know that you can never go from having an asynchronous value (Task<T>) to having a synchronous value (T) without awaiting (which requires that you stay in an async context) or blocking. Even Rx doesn't have enough magic to change that :)


Display Tournament League from total Players

You can clean up your code by looking for similarities and getting rid of the duplication by creating separate functions. I'll demonstrate.

Let's take a look at this bit:

    if(A==2)
        if(result.isEmpty()){
            result = "( "+ getPlayerId(index) +" vs " +getPlayerId(index+1) +" )";
            index+=2;
        }
        else{
            result =  result+" vs ( "+getPlayerId(index)+" vs "+ getPlayerId(index+1) +" )";
            index+=2;
        }
    else if(A==1)
        if(result.isEmpty()){
            result = ""+getPlayerId(index);
            index+=1;
        }
        else{
            result = result+" vs "+ getPlayerId(index);
            index+=1;
        }

    if(B==2)
        if(result.isEmpty()){
            result = "( "+ getPlayerId(index) +" vs " +getPlayerId(index+1) +" )";
            index+=2;
        }
        else{
            result =  result+" vs ( "+getPlayerId(index)+" vs "+ getPlayerId(index+1) +" )";
            index+=2;
        }
    else if(B ==1)
        if(result.isEmpty()){
            result = ""+getPlayerId(index);
            index+=1;
        }
        else{
            result = result+" vs "+ getPlayerId(index);
            index+=1;
        }

Step 1 - add braces.

    if(A==2){
        if(result.isEmpty()){
            result = "( "+ getPlayerId(index) +" vs " +getPlayerId(index+1) +" )";
            index+=2;
        }
        else{
            result =  result+" vs ( "+getPlayerId(index)+" vs "+ getPlayerId(index+1) +" )";
            index+=2;
        }
    } else if(A==1) {
        if(result.isEmpty()){
            result = ""+getPlayerId(index);
            index+=1;
        }
        else{
            result = result+" vs "+ getPlayerId(index);
            index+=1;
        }
    }
    if(B==2){
        if(result.isEmpty()){
            result = "( "+ getPlayerId(index) +" vs " +getPlayerId(index+1) +" )";
            index+=2;
        }
        else{
            result =  result+" vs ( "+getPlayerId(index)+" vs "+ getPlayerId(index+1) +" )";
            index+=2;
        }
    } else if(B == 1){
        if(result.isEmpty()){
            result = ""+getPlayerId(index);
            index+=1;
        }
        else{
            result = result+" vs "+ getPlayerId(index);
            index+=1;
        }
    }

Step 2 - identify sections of duplicate code and generalize them.

In your case, this is the index+=2 and index+=1 at the end of each case.

    if(A==2){
        if(result.isEmpty()){
            result = "( "+ getPlayerId(index) +" vs " +getPlayerId(index+1) +" )";
        }
        else{
            result =  result+" vs ( "+getPlayerId(index)+" vs "+ getPlayerId(index+1) +" )";
        }
        index+=2;
    } else if(A==1) {
        if(result.isEmpty()){
            result = ""+getPlayerId(index);
        }
        else{
            result = result+" vs "+ getPlayerId(index);
        }
        index+=1;
    }
    if(B==2){
        if(result.isEmpty()){
            result = "( "+ getPlayerId(index) +" vs " +getPlayerId(index+1) +" )";
        }
        else{
            result =  result+" vs ( "+getPlayerId(index)+" vs "+ getPlayerId(index+1) +" )";
        }
        index+=2;
    } else if(B == 1){
        if(result.isEmpty()){
            result = ""+getPlayerId(index);
        }
        else{
            result = result+" vs "+ getPlayerId(index);
        }
        index+=1;
    }

Next, further reduce the duplicate code. You can see that if B is 2, we'll add 2 to index. If B is 1, we'll add 1 to index. We can just add B to index. (We're reducing duplication of constants here)

    if(A==2){
        if(result.isEmpty()){
            result = "( "+ getPlayerId(index) +" vs " +getPlayerId(index+1) +" )";
        }
        else{
            result =  result+" vs ( "+getPlayerId(index)+" vs "+ getPlayerId(index+1) +" )";
        }
        index+=A;
    } else if(A==1) {
        if(result.isEmpty()){
            result = ""+getPlayerId(index);
        }
        else{
            result = result+" vs "+ getPlayerId(index);
        }
        index+=A;
    }
    if(B==2){
        if(result.isEmpty()){
            result = "( "+ getPlayerId(index) +" vs " +getPlayerId(index+1) +" )";
        }
        else{
            result =  result+" vs ( "+getPlayerId(index)+" vs "+ getPlayerId(index+1) +" )";
        }
        index+=B;
    } else if(B == 1){
        if(result.isEmpty()){
            result = ""+getPlayerId(index);
        }
        else{
            result = result+" vs "+ getPlayerId(index);
        }
        index+=B;
    }

Next, remove duplication by creating a separate function that allows you to create the "( "+ getPlayerId(index) +" vs " +getPlayerId(index+1) +" )" part in one call.

private String printVersus(int startIndex){
    return "( "+ getPlayerId(index) +" vs " +getPlayerId(index+1) +" )";
}

Then, use it.

    if(A==2){
        if(result.isEmpty()){
            result = printVersus(index);
        }
        else{
            result = result+" vs "+printVersus(index);
        }
        index+=A;
    } else if(A==1) {
        if(result.isEmpty()){
            result = ""+getPlayerId(index);
        }
        else{
            result = result+" vs "+ getPlayerId(index);
        }
        index+=A;
    }
    if(B==2){
        if(result.isEmpty()){
            result = printVersus(index);
        }
        else{
            result =  result+" vs "+printVersus(index);
        }
        index+=B;
    } else if(B == 1){
        if(result.isEmpty()){
            result = ""+getPlayerId(index);
        }
        else{
            result = result+" vs "+ getPlayerId(index);
        }
        index+=B;
    }

Next, once again identify that there is duplication in handling of string appending - you handle result.isEmpty() in multiple places. Create a separate function. I gave it a bit of a poor name, since I haven't actually checked your business logic yet - I'm just optimizing this based on patterns!

private String appendVersusString(String original, String toAdd){
    if(original.isEmpty()){
        return toAdd;
    }
    else{
        return original+" vs "+ toAdd;
    }
}

Use the new function.

    if(A==2){
        result = appendVersusString(result, printVersus(index));
        index+=A;
    } else if(A==1) {
        result = appendVersusString(result, ""+getPlayerId(index));
        index+=A;
    }
    if(B==2){
        result = appendVersusString(result, printVersus(index));
        index+=B;
    } else if(B == 1){
        result = appendVersusString(result, ""+getPlayerId(index));
        index+=B;
    }

Once again, spot duplication between A and B - they're doing the exact same at the end of the case. I am assuming that A and B cannot go into the negatives.

Since if(A>2 || B > 2) has an early return, A and B are (individually) either 2, 1, or 0.

Thus we can see that if A is 2, we add A. If A is 1, we add A. If A is 0, we don't add anything. Same goes for B.

So we can just do index+=A in all three cases.

    if(A==2){
        result = appendVersusString(result, printVersus(index));
    } else if(A==1) {
        result = appendVersusString(result, ""+getPlayerId(index));
    }
    index+=A;
    if(B==2){
        result = appendVersusString(result, printVersus(index));
    } else if(B == 1){
        result = appendVersusString(result, ""+getPlayerId(index));
    }
    index+=B;

There is still duplication in the handling of A and B when it comes to appendVersusString. I think they're "groups", so I'll name the function handleGroup:

private String handleGroup(String result, int group, int currentIndex){
    if(group==2){
        result = appendVersusString(result, printVersus(currentIndex));
    } else if(group == 1) {
        result = appendVersusString(result, ""+getPlayerId(currentIndex));
    }
    return result;
}

And use your new function.

    handleGroup(result, A, index);
    index+=A;
    handleGroup(result, B, index);
    index+=B;

Final result:

public class EqualPlayer {
    private int index=0;

    public static void main(String[] args){
        EqualPlayer equalPlayer = new EqualPlayer();
        System.out.println(equalPlayer.getEqualPlayerID(26));
    }

    private String getEqualPlayerID(int numberPlayers){
        int nPDevided = numberPlayers/2;
        int A = numberPlayers-nPDevided;
        int B = nPDevided;
        String result="";

        if(A>2 || B > 2)
            return "( "+getEqualPlayerID(A)+" )"+" vs "+ "( "+getEqualPlayerID(B)+" )";

        handleGroup(result, A, index);
        index+=A;
        handleGroup(result, B, index);
        index+=B;

        return result;
    }

    private String handleGroup(String result, int group, int currentIndex){
        if(group==2){
            result = appendVersusString(result, printVersus(currentIndex));
        } else if(group == 1) {
            result = appendVersusString(result, ""+getPlayerId(currentIndex));
        }
        return result;
    }

    private String appendVersusString(String original, String toAdd){
        if(original.isEmpty()){
            return toAdd;
        }
        else{
            return original+" vs "+ toAdd;
        }
    }

    private String printVersus(int startIndex){
        return "( "+ getPlayerId(index) +" vs " +getPlayerId(index+1) +" )";
    }

    private char getPlayerId(int index){
        char [] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
        return  alphabet[index];
    }

}

Lastly, you could consider using a StringBuilder to prevent needless copying of String contents. I also recommend putting spaces around operators to improve readability (if(A == 2) instead of if(A==2) and index += A instead of index+=A).


Your algorithm is ok, there are only a few minor hints for improvement:

You're using double-typed variables. Although in your case the computations will be exact up to fairly large numbers, it's generally safer to use int or long if you don't need the fractional part.

Two of your variable names begin with an upper-case letter (Binary and TempHold). That's unusual for Java code, as the vast majority of programs follows the naming conventions, so much that I find it irritating to read non-conforming code.

Your variable power has a name that confused me first. I'd call it exponent (in mathematics, "power" is the result of exponentiation). And I'd rename TempHold to digitChar and num to digitVal.

Math.pow() isn't really fast, so I recommend a different approach. With every iteration, the power grows by a factor of two, so I'd use something like power = power * 2; inside the loop.

For production code, you should separate input/output from computation, e.g. by putting the conversion part into a method of its own.

It's good style to close Scanners when they are finished (although that will eventually be done by Java's garbage collector if you don't do it explicitly).

So, my version of your program would be:

import java.util.Scanner;

public class BinaryToDecimal {

    public static void main(String[] args) {
        Scanner scan1 = new Scanner(System.in);
        System.out.println("Enter a binary number: ");
        String binary = scan1.next(); // 11011

        String decimal = toDecimal(binary);

        System.out.println(decimal + "(10)");
        scan1.close();
    }

    public static String toDecimal(String binary) {
        long power = 1;
        long sum = 0;

        for (int i = binary.length() - 1; i >= 0; i--) {
            char digitChar = binary.charAt(i);
            int digitVal = Character.getNumericValue(digitChar);
            sum = sum + digitVal * power;
            power = power * 2;
        }
        return String.valueOf(sum);
    }
}


Wells, for the sake of loop-ifying everything, you may want to consider changing boundary as such:

final char[] boundary = "=*=*=*".toCharArray();
...
sb.append( buildLines( '+', boundary, 3, NONE, 0, Direction.CENTER, 1, 2 ) );

That will create =*=*=*, duplicate it once, and add the + character at both ends.

The ternary operator below looks like a good candidate for adding a helper method into the Direction enum:

int pos = charfrom + line * (chardir == Direction.FORWARD ? 1 : -1)

My version is expanded as such:

private enum Direction {
    CENTER( 0 ), UPWARD( 1 ), DOWNWARD( -1 );

    private final int multiplier;

    Direction( final int multiplier ) {
        this.multiplier = multiplier;
    }

    int getMultiplier() {
        return multiplier;
    }
}

And calculating pos is just charfrom + line * chardir.getMultiplier();

One more minor suggestion: The usage of 5 and 3 seems to be repeated quite often, maybe refer to them as coneSize and blockSize? The main body will look something like:

sb.append( buildLines( ' ', cone, coneSize, '*', 0, Direction.UPWARD, coneSize, 1 ) );
sb.append( buildLines( '+', boundary, blockSize, NONE, 0, Direction.CENTER, 1, 2 ) );
sb.append( buildLines( '|', wider, blockSize, NONE, 0, Direction.UPWARD, blockSize, 2 ) );
sb.append( buildLines( '|', narrower, blockSize, NONE, 2, Direction.DOWNWARD, blockSize, 2 ) );
sb.append( buildLines( '+', boundary, blockSize, NONE, 0, Direction.CENTER, 1, 2 ) );
sb.append( buildLines( '|', narrower, blockSize, NONE, 2, Direction.DOWNWARD, blockSize, 2 ) );
sb.append( buildLines( '|', wider, blockSize, NONE, 0, Direction.UPWARD, blockSize, 2 ) );
sb.append( buildLines( '+', boundary, blockSize, NONE, 0, Direction.CENTER, 1, 2 ) );
sb.append( buildLines( ' ', cone, coneSize, '*', 0, Direction.UPWARD, coneSize, 1 ) );

Due to the fact that our sources are fixed lengths now, I don't see much of an improvement on the method signatures since it's not like the current code can be easily expanded to create rockets of different sizes. Maybe I'll attempt another stab at that when I have some more time...


The code still looks a bit strange to me.

obj.f1(obj);

Why are you passing the object as a parameter when the method already is a member? Skip the parameter and use this instead.

You should also try to minimize the number of method the user needs to call to perform one thing. Requiring obj.data to be set before calling obj.f1 is error prone. It would be better to let the obj constructor call GetData to extract the data from the obj.


Simple Prefix Matching Library in Haskell

Library functions, particularly Maybe's Applicative/Alternative instances, can make your code more consise:

makeMatcher spec str = length spec <$ guard (isPrefixOf spec str)

andThen m1 m2 str = do
  l1 <- m1 str
  l2 <- m2 $ drop l1 str
  Just $ l1 + l2

symOrExn m1 m2 str = case catMaybes [m1 str, m2 str] of
  [] -> Nothing
  [l] -> Just l
  -- if you reach this case, the grammar was
  -- constructed badly
  [_, _] -> error "ambiguous match"

leftOr = liftA2 (<|>)

andThenList = foldr andThen identityMatcher

leftOrList = foldr leftOr identityMatcher

A more potent approach is to return not the length at which to split, but the results of the split. In fact, StateT String Maybe String makes this work out of the box:

type Matcher = StateT String Maybe String

makeMatcher :: String -> Matcher
makeMatcher spec = StateT $ fmap (spec,) . stripPrefix spec

runMatcher :: Matcher -> String -> Maybe (String, String)
runMatcher = runStateT

andThen = liftA2 (++)

symOrExn m1 m2 = m1 <* (m2 *> error "ambiguous match" <|> pure ()) <|> m2
  -- I'll admit, this one looks clunky

leftOr = (<|>)

andThenList = fmap concat . sequenceA

leftOrList = asum


Implementation of callback in database request

If you run multiple async functions in a certain orderi it will look like something like this :

getData(function(a){
    getMoreData(a, function(b){
        getMoreData(b, function(c){
            getMoreData(c, function(d){
                getMoreData(d, function(e){
                    ...
                });
            });
        });
    });
});

but it does not look nice and hard to control. Instead use promises, I recommend bluebirdjs library If you use nodejs, take it easy.


Creating list ViewModels in the correct way

UserWorkspaceViewModel

private UserViewModelFactory _userViewModelFactory; instead of using the actual type use the interface like private IUserViewModelFactory _userViewModelFactory;
magic number 1 (Users.GetByDepartmentId(1);) should be expressed by a meaningful constant.
LoadUsers() method. Here IMHO you have used the var wrong. I don't think it is obvious what the right hand side of var users = _unitOfWork.Users.GetByDepartmentId(1); can be.

List<User> users = _unitOfWork.Users.GetByDepartmentId(1);
foreach (var user in users)
{

}

would be more obvious.

UserViewModel

the constructor won't compile, but I assume this is a copy & paste problem.

public UserViewModel(IUnitOfWork unitOfWork)
{
    _unitOfWork = unitOfWork;
}

Save() method

I guess it won't be possible for the Id property to become <0 so a simple else instead of another if would be better.
If the chances are high that you will need to add more code, consider to extract the adding and updating to separate methods.

General

Comments should explain why something is done. What is done should be explained by the code itself by using meaningful names for classes,methods and parameters. So comments like // Use the factory to create the ViewMode should be removed.


Assuming the logic of your sort code is correct.

You can just have your sort function as:

void sort(char **m, int dim);

Your sort function can be like:

void sort(char **m, int dim) {
    int i, j, flag=1;

    for(i=0; i<dim-1 && flag==1; i++){
        flag=0;
        for(j=0; j<dim-1; j++)
            if(strcmp(m[j],m[j+1])>0){
                swap(&m[j],&m[j+1]);
                flag=1;
            }
    }
}

This improves some readability. There is no need to pass &m - like (sort(&m, N)) - to your sort. Just passing m - like sort(m, N) - is enough for changing/comparing/swapping m[i] and m[j].


You have one serious problem - that supergigantic number you want to use is larger than the precision of both doubles AND longs. In fact, because both doubles and longs use 64 bits in Java, you would be better off using longs because with doubles, only 53 of those 64 bits are available for what you want to do.

What this means is that, in order to get a meaningful calculation AT ALL for 21432154197846387216432 that you would have to implement it with something else because the algorithm, as you have implemented it, will give you answers that are completely meaningless because your initial value is a victim of roundoff error.

Now, for numbers up to the limit of long (9223372036854775807), I have created a different implementation that uses only long operations. It's organized differently because we have to force the algorithm to work correctly without any fractional arithmetic.

public class MainTwo {

    private static final long N = 916548345678631l;

    public static void main(String[] args) {

        long start = System.currentTimeMillis();
        long loopUntil = (long) (Math.sqrt(2 * N));
        long M = 1l;

        int doProcess = doProcess(N, loopUntil, M);
        System.out.println(doProcess);

        long end = System.currentTimeMillis();
        System.out.println("[Main.main] elapsed time: " + (end - start));
    }

    public static int doProcess(long N, long loopUntil, long M) {
        int result = 0;

        while (M <= loopUntil) {

            boolean yesProcess = false;
            long val = 0;
            boolean mEven = (M % 2) == 0;
            if (mEven) {
                yesProcess = (N % M == M/2);
                if (yesProcess) {
                    val = (N + 1) / M + (M / 2);
                }
            }
            else {
                yesProcess = N % M == 0;
                if (yesProcess) {
                    val = (N / M) + (M + 1) / 2;
                }
            }

            if (yesProcess) {
                System.out.println("With : " + M);
                result++;
            }
            M++;
        }

        return result;
    }

}

And just for the sake of completeness, here is an implementation using BigInteger that will be able to work correctly against your giant number. Be warned though - using BigInteger makes it more than 20 times slower than the long implementation. I used this BigSquareRoot class.

public class MainThree {
//    private static final BigInteger N = new BigInteger("916548345678631");
    private static final BigInteger N = new BigInteger("21432154197846387216432");

    private static final BigSquareRoot bsr = new BigSquareRoot();
    private static final BigInteger zero = new BigInteger("0");
    private static final BigInteger one = new BigInteger("1");
    private static final BigInteger two = new BigInteger("2");

    public static void main(String[] args) {

        long start = System.currentTimeMillis();
        BigInteger loopUntil = bsr.get(N.multiply(two)).toBigInteger();
        BigInteger M = one;

        int doProcess = doProcess(N, loopUntil, M);
        System.out.println(doProcess);

        long end = System.currentTimeMillis();
        System.out.println("[Main.main] elapsed time: " + (end - start));
    }

    public static int doProcess(BigInteger N, BigInteger loopUntil, BigInteger M) {
        int result = 0;

        while (M.compareTo(loopUntil) < 0) {

            boolean yesProcess = false;
            BigInteger val = zero;
            boolean mEven = M.mod(two).equals(zero);
            if (mEven) {
                yesProcess = N.mod(M).equals(M.divide(two));
                if (yesProcess) {
                    val = (N.add(one).divide(M)).add(M.divide(two));
                }
            }
            else {
                yesProcess = N.mod(M).equals(zero);
                if (yesProcess) {
                    val = N.divide(M).add(M.add(one).divide(two));
                }
            }

            if (yesProcess) {
                System.out.println("With : " + M);
                result++;
            }
            M = M.add(one);
        }

        return result;
    }
}


In this function, the copy (Write XML) is inside, but I want it to be separated from the function.

Shallow Observations

In no particular order:

You need to indent your code, it makes it much easier to read. Give that Tab button some lovin'!
Exceptions are like urine samples: there's a lot of information in there to analyze if and when you need to, and the last thing you want to do is to swallow them.

Separation of Concerns

I think both procedures do more than they claim. Let's break down what needs to happen:

Prompt the user for confirmation, do nothing without user's consent.
Get the names of all target folders.
Find the destination folders.
Determine the name of the file.
Write the file.

Implementation

Prompt the user for confirmation, do nothing without user's consent

Asking for user confirmation before exporting stuff is probably a good idea. This doesn't mean the actual prompting needs to happen in the method that performs the actual export. Consider this:

Public Function GetUserConfirmation(ByVal prompt As String) As Boolean
    Return (MsgBox(prompt, MsgBoxStyle.YesNo) = MsgBoxResult.Yes)
End If

Yes, it's a one-liner. That doesn't make it less of a useful function. We don't really care about MsgBoxResult, we just want to know if the user answered Yes to a question. This function abstracts away the MsgBox call and the need for knowing about MsgBoxResult, which makes it much more If-friendly - whether you're reading:

If GetUserConfirmation(confirmationMessage) Then

Or

If Not GetUserConfirmation(confirmationMessage) Then

You know exactly what's going on and you don't need to worry about how it's implemented.

Now in your code, this would translate to:

Sub ExportToFolder() 'parameters omitted
    If GetUserConfirmation(confirmationMessage) Then
    ' do all that stuff
    End If
End Sub

I think this is a bad construct, it smells like the code in the If statement is begging you to be surrounding a call to that method, so you can do this:

If GetUserConfirmation(confirmationMessage) Then ExportToFolder 'parameters omitted

And have ExportToFolder look like that:

Sub ExportToFolder() 'parameters omitted
    ' do all that stuff
End Sub

This means the logic that grabs an instance variable to come up with the prompt message is also moved outside of the method. Actually by doing this we have just separated the concerns of coming up with a prompt message and prompting the user with some message.

So we've got user confirmation. One down.

Get the names of all target folders

We have some DataTable that represents a selected item which contains a column called "whouseDesc" which is the name of the "parent" folder we want to use. Your code knows about a lot of things it doesn't need to be bothered with: in fact all this DataTable boilerplate just doesn't belong there. The method doesn't want a DataTable, it needs what's it in.

I would replace SelectedItem As DataTable with TargetSubfolderNames As IEnumerable(Of String), it makes the intent much clearer: we need an enumerable bunch of folder names, and we're going to expect they're the names of subfolders of a target folder.

Reading the DataTable that contains the folder names is out of scope here.

The procedure now looks like this, notice how much more focused it's starting to be:

Sub ExportToFolder(ByVal POSPath As String, _
                   ByVal dt As DataSet, _
                   ByVal FolderCopyto As String, _
                   ByVal TargetSubfolderNames As IEnumerable(Of String))

    Dim subfolderName As String
    For Each subfolderName In TargetSubfolderNames
        ProcessCopy(POSPath, dt, FolderCopyTo, subfolderName)
    Next

End Sub

Find the destination folder

ExportToFolder takes the POSPath parameter only to pass it down to ProcessCopy at each iteration. It's the same folder every time you call ProcessCopy, and yet every time the method runs, you're fetching the subdirectories and looping through all of them every time, verifying if the target folder exists under that subdirectory. I'm exhausted, aren't you?

If each call to ExportToFolder() exports stuff into 1 file in 1 folder, then it's not exactly clear why you're looping directories here, why the method is recursive, and how you're coming up with the filename.

My guess is that you want to be sure you're writing to a directory that exists. That's fine, but if there's only 1 file to write to, you're over-complicating it.

Determine the name of the file

If I understand correctly, you know the full file name from the start, and given InvoiceId which is dt.Tables(0).Rows(0).Item("InvoiceID") this would be your file name:

Path.Combine(Whouse, FolderCopyTo) + InvoiceId + ".xml"

So we can have a GetExportXmlFileName function that does it, and that can return an empty string if the folder doesn't exist:

Function GetExportXmlFileName(ByVal ParentFolder As String, ByVal TargetFolder As String, ByVal InvoiceId As String) As String

    Dim result = String.Format("{0}.xml", _
                   Path.Combine(ParentFolder, TargetFolder), _
                   InvoiceId)

    If Not Directory.Exists(Path.GetDirectoryName(result)) Then result = String.Empty

End Function

Your method is starting to look like this:

Sub ExportToFolder(ByVal TargetSubfolderNames As IEnumerable(Of String), _
                   ByVal TargetFolder As String, _
                   ByVal Content As DataSet)

    Dim SubfolderName As String, FileName As String
    Dim InvoiceId As String = Content.Tables(0).Rows(0).Item("InvoiceID")

    For Each SubfolderName In TargetSubfolderNames
        FileName = GetExportXmlFileName(SubfolderName, TargetFolder, InvoiceId)
        If Not String.IsNullOrEmpty(FileName) Then ProcessCopy FileName, Content
    Next

End Sub

Write the file

At this point I'm questioning the need for ProcessCopy altogether:

Sub ExportToFolder(ByVal TargetSubfolderNames As IEnumerable(Of String), _
                   ByVal TargetFolder As String, _
                   ByVal Content As DataSet)

    Dim SubfolderName As String, FileName As String
    Dim InvoiceId As String = Content.Tables(0).Rows(0).Item("InvoiceID")

    For Each SubfolderName In TargetSubfolderNames
        FileName = GetExportFileName(SubfolderName, TargetFolder, InvoiceId)
        If Not String.IsNullOrEmpty(FileName) Then Content.WriteXml(FileName)
    Next

End Sub

Let's see, if we have 4 files to export, and the 2nd one blows up, we can't try the 3rd and 4th like this - we'll have an exception to deal with (read: not swallow).

Sub ExportToFolder(ByVal TargetSubfolderNames As IEnumerable(Of String), _
                   ByVal TargetFolder As String, _
                   ByVal Content As DataSet)

    Dim SubfolderName As String, FileName As String
    Dim InvoiceId As String = Content.Tables(0).Rows(0).Item("InvoiceID")
    Dim Errors As IList(Of String) = New List(Of String)

    For Each SubfolderName In TargetSubfolderNames
        FileName = GetExportFileName(SubfolderName, TargetFolder, InvoiceId)
        If Not String.IsNullOrEmpty(FileName) Then
            Try

                Content.WriteXml(FileName)

                Catch ex As Exception
                    Errors.Add(ex) 'fine, don't do anything with it.
                                   'at least you can break and inspect it.
            End Try
        End If
    Next

End Sub

This is where we can extract a method to wrap the Try...Catch block and, incidentally, the Content.WriteXml call - I'll pretend you want to log errors with an instance-level NLog logger:

Sub ExportToFile(FileName as String, Content As DataSet)
    Try

        Content.WriteXml(FileName)

    Catch ex As Exception
        _logger.ErrorException(FileName, ex)

    End Try
End Sub

This last refactoring has given its final shape to the ExportToFolder method:

Sub ExportToFolder(ByVal TargetSubfolderNames As IEnumerable(Of String), _
                   ByVal TargetFolder As String, _
                   ByVal Content As DataSet)

    Dim SubfolderName As String, FileName As String
    Dim InvoiceId As String = Content.Tables(0).Rows(0).Item("InvoiceID")

    For Each SubfolderName In TargetSubfolderNames
        FileName = GetExportFileName(SubfolderName, TargetFolder, InvoiceId)
        If Not String.IsNullOrEmpty(FileName) Then ExportToFile(FileName, Content)
    Next

End Sub


Be consistent
If you're going to use jQuery, it would be stylistically appropriate (and terser) to use it instead of the native DOM methods. For example:
if(document.getElementById('FridgeTemperatureCheckBox').checked){

can turn into
if ($('#FridgeTemperatureCheckBox').is(':checked')) {

To translate getElementById to jQuery or querySelector, put a # in front of the ID you want to select.
Or you can use vanilla DOM methods everywhere if you prefer (like I do) - but whatever you choose to do, it would be good to do it consistently, otherwise you'll probably confuse future readers of the code.
HTML too: On a similar note about consistency - with your element IDs, better to choose either camelCase, PascalCase, or kebab-case everywhere, but don't mix and match different styles, else you're more likely to run into typo problems when you don't have a set style and mis-remember which style you used. (You can also consider using classes instead of IDs, since IDs with their automatically global variables are unintuitive and can cause bugs.)
DRY code
Rather than selecting the same element multiple times, eg:
$('#FridgeTemperatureBtn').attr('data-toggle', 'modal');
$('#FridgeTemperatureBtn').attr('data-target', '#confirmModal');

It would be more elegant to select the element once and save it in a variable. Or, even better, since .attr returns the existing jQuery collection, just chain the .attr calls:
$('#FridgeTemperatureBtn')
  .attr('data-toggle', 'modal')
  .attr('data-target', '#confirmModal');

Attach listener once, immediately: It looks like the confirmModal only becomes visible when the user clicks the button and has already completed the check, is that correct? If so, consider attaching the #confirmOk click listener immediately, rather than only after the #FridgeTemperatureBtn is clicked. (Attaching identical listeners multiple times won't cause problems in this case, but it's peculiar logic.)
Semantics: Your FridgeTemperatureBtn is an <a>, not a button, so its ID's name should probably be tweaked. If you have it styled to look like a button with your CSS, it would probably be a bit more semantically appropriate to surround a <button> inside an <a> instead.
Unchangeable checkbox UX: The #FridgeTemperatureCheckBox is disabled. Having it be a checkbox is a bit unintuitive, because users generally expect checkboxes to be clickable. Consider informing the user that the check has already been done some other way, such as by adding a checkmark (not a checkbox), or by changing the background color, or something like that.


Rails 5 controller to get information about Steam users

You don't need all those @s. Everything in the action methods can be handled with local variables, and the initlization can be made more Rails-like. For instance:

class SteamController < ApplicationController
  BASE_URL = "http://api.steampowered.com".freeze

  before_action :load_user

  def get_steam_summary_per_user #/steam/:id
    endpoint = url_for_path_and_id("/ISteamUser/GetPlayerSummaries/v0002/", @user.steamId)
    render json: HTTParty.get(endpoint).to_json
  end

  def get_steam_recently_played_per_user #/game/:id
    endpoint = url_for_path_and_id("/IPlayerService/GetRecentlyPlayedGames/v0001/", @user.steamId)
    render json: HTTParty.get(endpoint).to_json
  end

  def get_steam_owned_games_per_user #/allGames/:id
    endpoint = url_for_path_and_id("/IPlayerService/GetOwnedGames/v0001/", @user.steamId)
    render json: HTTParty.get(endpoint).to_json
  end

  private

  def url_for_path_and_id(path, id)
    "#{BASE_URL}#{path}?key=#{ENV["steam_api_key"]}&steamid=#{id}"
  end

  def load_user
    @user = User.find(params[:id])
  end
end

Here I'm using Rails's before_action setup to load the user, since that's common for all actions. The constants have been moved to, well, constants, or their values to where they're used. A method has been added to construct the URLs. I'm using the more Ruby-like approach of string interpolation to build the URLs rather than string concatenation.

Yes, I've hard-coded a few strings into the methods, although they do have some parts in common, but I've based it on the sections of a URL: Base (constant), path (varies from method to method, even if parts of it repeat), and query string (appended at the end).

One thing that stands out is that the User model has a steamId attribute: That should be steam_id - in Ruby you should use snake_case for attribute and method names.

However, a different (and, I think, better) approach would be to make a service object to wrap the Steam API. Basically a plain old Ruby class (you can place it in app/services, for instance).

Your controller actions would simply construct a service object, passing in the user, and then call the relevant method to get what they want. E.g. your controller would be just:

class SteamController < ApplicationController
  before_action :create_client

  def get_steam_summary_per_user
    render json: @steam_client.summary
  end

  def get_steam_recently_played_per_user
    render json: @steam_client.recently_played
  end

  def get_steam_owned_games_per_user
    render json: @steam_client.owned
  end

  private

  def create_client
    user = User.find(params[:id])
    @steam_client = SteamAPIClient.new(user)
  end
end

where SteamAPIClient is your service object. Keep the controller skinny, and put the logic elsewhere.

Another thing that stood out is the way you set up your routes. The Rails Way™ would be to make the API part of the User controller. From your application's standpoint, you're trying to get information about a user - the fact that it comes from Steam's API is an implementation detail.

In other words, I'd rather see URLs like:

/users/:id/summary
/users/:id/owned
/users/:id/recent

than URLs like /steam/:id, or /games/:id. If you follow common RESTful API patterns, those URLs indicate that you have a collection of "steams" and a collection of "games", and the :id is used to pick out a particular one. But that's not your model; you don't have multiple "steams". What you have a users, identified by an id, which in turn have some associated data you can fetch.

Or in route-speak:

resources :users do
  member :summary, via: :get
  member :owned, via: :get
  member :recent, via: :get
end

Doing things this way is another reason to extract the actual Steam API-fethcing code into a service object, so you can just call it from the Users controller.

The give-away in your current code is that all your actions are called ..._per_user. Well, if it's per user, then make it per user by making it member actions on the Users controller.

Basic idea is that you treat the Steam API as you would treat the database: It's a data source. You don't put all the database connection and querying logic in a controller, you just put User.find(x), and the rest happens elsewhere. Same here, in a sense.


Improving design for a CustomerDAO with DatabaseManager object

Single responsibility principle

In terms of SRP, the current code is good, each class is has one clear purpose:

Customer: only the customer details, nothing else
CustomerDAO: only data accessor methods related to customers
DatabaseManager: manage database connection, DatabaseConnectionManager might be a better name

But they can be improved.

Customer

If you can make its fields final, make them final.

No need to call super() in a class whose parent is Object. You can just delete that line.

CustomerDAO

The throws SQLException declarations make this class database specific. In theory, a CustomerDAO could work over a web service or a CSV file. Actually CustomerDAO should be an interface, to model a backend-agnostic concept, with throws declarations that are backend-agnostic. Then an implementation using a database backend should wrap the SQLExceptions and throw the backend-agnostic exceptions instead. In such design you will have the flexibility to replace the DAO with a different backend.

Also, the public empty constructor is pointless.

DatabaseManager

The modern pattern of implementing singletons is this:

public enum DatabaseManager {

    INSTANCE;

    // ...
}

This is truly thread-safe. Use this instead of a private static field, which is not truly thread-safe.

Use a framework

Instead of managing database connections yourself, I strongly recommend using a framework that can greatly simply it for you. For example Spring Framework.


Well, this is difficult, especially without being a linguist. However, the code is horrid, and I can fix that.

s/ /_/g should be tr/ /_/, as single-character transliterations are more efficient than full-fledged regex matches.

/^(.*?)\t(.*?)\t(.*?)(\t|$)/ || next;
$form = $1; $cats = $2; $lemma = $3;

should be

my ($form, $cats, $lemma) = split /\t/, $_, 4 or next;

The .*? in the regex is a big no-no. It wants to split the line into three parts at tabs – so let's use split.

Certain stuff could be written more readable:

  if ($it_mapping) {
    next if $form =~ /.'$/  # optimized from /^.+'$/
         or $form eq "dato"  && $lemma eq "datare"
         or $form eq "stato" && $lemma eq "stare"
         or $form eq "stata" && $lemma eq "stare"
         or $form eq "parti" && $lemma eq "parto"
         or $cats eq "ART" && $form =~ /^(?:una|la|le|gli|agli|ai|al|alla|alle|col|dagli|dai|dal|dalla|dalle|degli|dei|del|della|delle|dello|nei|nel|nella|nelle|nello|sul|sulla)$/;

    # removing capture groups, using eq where appropriate, using postfix if:
    $cats = "PUNCT"     if $cats =~ /^(?:parentf|parento|poncts|ponctw)$/;
    $cats = "PRON"      if $cats eq 'PRO';
    $cats = "PREDET"    if $cats eq 'ARTPRE';
    $cats = "VERB"      if $cats =~ /^(?:VER|ASP|AUX|CAU)$/;
    $cats = "CONJ"      if $cats eq 'CON';
    $cats = "PREP"      if $cats eq 'PRE';
    $cats = "ADJ"       if $cats eq 'DET';
    $cats = "PRON|CONJ" if $cats eq 'WH';

    # cheaper test (equality) as early as possible
    next if $cats eq "PREP" && $form eq 'ad'
         or $cats eq "ADJ"  && $form =~ /^quest[aei]$/
         or $cats eq "PRON" && $form =~ /^quest[aei]$/
         or $cats eq "ADJ"  && $form =~ /^quell[aei]$/
         or $cats eq "PRON" && $form =~ /^quell[aei]$/
         or $cats eq "CONJ" && $form =~ /^[oe]d$/;
  }

Note that I did not optimize the gargantuan regex – the trie optimization will transform that into a state machine, which is far more efficient. This regex match was also moved before the $cats normalization in order to bail out as early as possible.

$qmlemma = quotemeta ($lemma);

should be

my $qmlemma = quotemeta ($lemma);

because lexical variables can be more efficient, and it makes it easier to reason about the code.

The next part (looping through the $cats) is very hackish, and could be done more efficient with a different data structure.

(I removed my no autovivification recommendation because that behaviour is needed in the else clause again, and it does not effectively save much).

The regex should be changed to /(?:^|[|])$qmlemma(?:[|]|$)/ to avoid unneccessary capturing (and to make it more readable).

The else-branch should be changed to

$cat_form2lemma{$cat}{$form} = $lemma; # avoid unneccessary stringification
my $form_lemma_suffs = '@' . $form . '###@' . $lemma;  # lexical variables!!!
while ($form_lemma_suffs =~ s/^(.)(.+)###\1(.+)/\2###\3/) {
  if (length($2) <= 8) {
    $cat_formsuff_lemmasuff2count{$cat}{$2}{$3}++;
    $cat_formsuff_lemmasuff2count{$cat}{$2}{__ALL__}++ if $multple_lemmas;
  }
}

Most of the changes are meant to improve readability (postfix if, spacing). If I grok that code correctly, then it might be able to change this to

$cat_form2lemma{$cat}{$form} = $lemma; # avoid unneccessary stringification

my ($form_suff, $lemma_suff) = ($form, $lemma);
while (length($form_suff) and substr($form_suff, 0, 1, '') eq substr($lemma_suff, 0, 1, '')) {
  if (length($form_suff) <= 8) {
    $cat_formsuff_lemmasuff2count{$cat}{$form_suff}{$lemma_suff}++;
    $cat_formsuff_lemmasuff2count{$cat}{$form_suff}{__ALL__}++ if $multiple_lemmas;
  }
}

C-style string manipulation with substr is far more efficient than regexes with captures and backrefs.


Method that checks whether to disable or enable the buttons depending on whether data is null or not

In looking at your method, you have a lot of repetition in building your two dictionaries before composing your final result. If you were to simply regroup your code to separate the building of your first and second dictionaries, and the data that supports the construction, you would produce the following method:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult CheckButtons()
{
    int planId = (int)UserSession.GetValue(StateNameEnum.ID, "PlanID");

    planning resultSetA = db.planning.Where(t => t.PlanId == planId).Join(db.matching_image, p => p.MatchingImageId, i => i.Id,
        (p, i) => new
        {
            planning = p,
            i.View
        }).Where(j => j.View == "A").Select(j => j.planning).FirstOrDefault();

    structure sA = db.structure.FirstOrDefault(s => s.PlanId == planId && s.Type == "A");

    Dictionary<string, string> buttonADictionary = new Dictionary<string, string>();
    buttonADictionary.Add("C", resultSetA.CorrespondingId != null ? "disabled" : "enabled");
    buttonADictionary.Add("R", resultSetA.ResponseId != null ? "disabled" : "enabled");
    buttonADictionary.Add("S", (sA != null && sA.Point_x != null) ? "disabled" : "enabled");
    buttonADictionary.Add("D", resultSetA.DistalId != null ? "disabled" : "enabled");
    buttonADictionary.Add("P", resultSetA.ProximalId != null ? "disabled" : "enabled");
    bool aHasData = buttonADictionary.ContainsValue("disabled");

    planning resultSetB = db.planning.Where(t => t.PlanId == planId).Join(db.matching_image, p => p.MatchingImageId, i => i.Id,
        (p, i) => new
        {
            planning = p,
            i.View
        }).Where(j => j.View == "B").Select(j => j.planning).FirstOrDefault();

    structure sB = db.structure.FirstOrDefault(s => s.PlanId == planId && s.Type == "B");

    Dictionary<string, string> buttonBDictionary = new Dictionary<string, string>();
    buttonBDictionary.Add("C", resultSetB.CorrespondingId != null ? "disabled" : "enabled");
    buttonBDictionary.Add("R", resultSetB.ResponseId != null ? "disabled" : "enabled");
    buttonBDictionary.Add("S", (sB != null && sB.Point_x != null) ? "disabled" : "enabled");
    buttonBDictionary.Add("D", resultSetB.DistalId != null ? "disabled" : "enabled");
    buttonBDictionary.Add("P", resultSetB.ProximalId != null ? "disabled" : "enabled");
    bool bHasData = buttonBDictionary.ContainsValue("disabled");

    return Json(new { buttonADictionary, buttonBDictionary, aHasData, bHasData }, JsonRequestBehavior.AllowGet);
}

It's evident at this point that your code at the top and at the bottom is effectively identical, only differing on a value passed into two queries and then on variable names. Inside this single method, you are violating the DRY principle: don't repeat yourself. So let's make the first extraction and create the method here:

private Dictionary<string, string> GetButtonDictionary(int planId, string value)
{
    planning resultSet = db.planning.Where(t => t.PlanId == planId).Join(db.matching_image, p => p.MatchingImageId, i => i.Id,
        (p, i) => new
        {
            planning = p,
            i.View
        }).Where(j => j.View == value).Select(j => j.planning).FirstOrDefault();

    structure st = db.structure.FirstOrDefault(s => s.PlanId == planId && s.Type == value);

    Dictionary<string, string> buttonDictionary = new Dictionary<string, string>();
    buttonDictionary.Add("C", resultSet.CorrespondingId != null ? "disabled" : "enabled");
    buttonDictionary.Add("R", resultSet.ResponseId != null ? "disabled" : "enabled");
    buttonDictionary.Add("S", (st != null && st.Point_x != null) ? "disabled" : "enabled");
    buttonDictionary.Add("D", resultSet.DistalId != null ? "disabled" : "enabled");
    buttonDictionary.Add("P", resultSet.ProximalId != null ? "disabled" : "enabled");
    return buttonDictionary;
}

The method above takes two parameters: a planId that you have obtained, as well as a value. This second variable probably isn't a great name, but you have overloaded the meaning of your string in your original method (it's used to compare against a View property and a Type property) such that I couldn't immediately think of a better name. If you can think of one, just sub it in.

With this extraction, it cleans up your original method nicely, because it can be cleaned up to the following:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult CheckButtons()
{
    int planId = (int)UserSession.GetValue(StateNameEnum.ID, "PlanID");
    Dictionary<string, string> buttonADictionary = GetButtonDictionary(planId, "A");
    Dictionary<string, string> buttonBDictionary = GetButtonDictionary(planId, "B");

    bool aHasData = buttonADictionary.ContainsValue("disabled");
    bool bHasData = buttonBDictionary.ContainsValue("disabled");

    return Json(new { buttonADictionary, buttonBDictionary, aHasData, bHasData }, JsonRequestBehavior.AllowGet);
}

Could we clean this up a little more? Possibly, but it's simplified enough for now so let's go back to the method we extracted. It has a couple of database queries that should probably individually be their own methods (SRP - Single Responsibility Principle), so let's go ahead and do that.

private Dictionary<string, string> GetButtonDictionary(int planId, string value)
{
    planning resultSet = GetPlanningResultSet(planId, value);
    structure st = GetStructure(planId, value);

    Dictionary<string, string> buttonDictionary = new Dictionary<string, string>();
    buttonDictionary.Add("C", resultSet.CorrespondingId != null ? "disabled" : "enabled");
    buttonDictionary.Add("R", resultSet.ResponseId != null ? "disabled" : "enabled");
    buttonDictionary.Add("S", (st != null && st.Point_x != null) ? "disabled" : "enabled");
    buttonDictionary.Add("D", resultSet.DistalId != null ? "disabled" : "enabled");
    buttonDictionary.Add("P", resultSet.ProximalId != null ? "disabled" : "enabled");
    return buttonDictionary;
}

private planning GetPlanningResultSet(int planId, string value)
{
    planning resultSet = db.planning.Where(t => t.PlanId == planId).Join(db.matching_image, p => p.MatchingImageId, i => i.Id,
        (p, i) => new
        {
            planning = p,
            i.View
        }).Where(j => j.View == value).Select(j => j.planning).FirstOrDefault();
    return resultSet;
}

private structure GetStructure(int planId, string value)
{
   return db.structure.FirstOrDefault(s => s.PlanId == planId && s.Type == value);
}

After doing this, you have the obvious bit of repetition left where you get your enabled settings where you repeat your null checks. So let's extract a method to deal with that.

private Dictionary<string, string> GetButtonDictionary(int planId, string value)
{
    planning resultSet = GetPlanningResultSet(planId, value);
    structure st = GetStructure(planId, value);

    Dictionary<string, string> buttonDictionary = new Dictionary<string, string>();
    buttonDictionary.Add("C", GetEnabledSetting(resultSet.CorrespondingId));
    buttonDictionary.Add("R", GetEnabledSetting(resultSet.ResponseId));
    buttonDictionary.Add("S", GetEnabledSetting(st != null ? st.Point_x : null));
    buttonDictionary.Add("D", GetEnabledSetting(resultSet.DistalId));
    buttonDictionary.Add("P", GetEnabledSetting(resultSet.ProximalId));
    return buttonDictionary;
}

private string GetEnabledSetting(object value)
{
    return value != null ? "disabled" : "enabled";
}

After we have completed this extraction, the full code now looks like the following:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult CheckButtons()
{
    int planId = (int)UserSession.GetValue(StateNameEnum.ID, "PlanID");
    Dictionary<string, string> buttonADictionary = GetButtonDictionary(planId, "A");
    Dictionary<string, string> buttonBDictionary = GetButtonDictionary(planId, "B");

    bool aHasData = buttonADictionary.ContainsValue("disabled");
    bool bHasData = buttonBDictionary.ContainsValue("disabled");

    return Json(new { buttonADictionary, buttonBDictionary, aHasData, bHasData }, JsonRequestBehavior.AllowGet);
}

private Dictionary<string, string> GetButtonDictionary(int planId, string value)
{
    planning resultSet = GetPlanningResultSet(planId, value);
    structure st = GetStructure(planId, value);

    Dictionary<string, string> buttonDictionary = new Dictionary<string, string>();
    buttonDictionary.Add("C", GetEnabledSetting(resultSet.CorrespondingId));
    buttonDictionary.Add("R", GetEnabledSetting(resultSet.ResponseId));
    buttonDictionary.Add("S", GetEnabledSetting(st != null ? st.Point_x : null));
    buttonDictionary.Add("D", GetEnabledSetting(resultSet.DistalId));
    buttonDictionary.Add("P", GetEnabledSetting(resultSet.ProximalId));
    return buttonDictionary;
}

private planning GetPlanningResultSet(int planId, string value)
{
    planning resultSet = db.planning.Where(t => t.PlanId == planId).Join(db.matching_image, p => p.MatchingImageId, i => i.Id,
        (p, i) => new
        {
            planning = p,
            i.View
        }).Where(j => j.View == value).Select(j => j.planning).FirstOrDefault();
    return resultSet;
}

private structure GetStructure(int planId, string value)
{
   return db.structure.FirstOrDefault(s => s.PlanId == planId && s.Type == value);
}

private string GetEnabledSetting(object value)
{
    return value != null ? "disabled" : "enabled";
}

This is enough contribution for me. I'll leave it up to you to possibly create better variable names and get the code into a bit better compliance with C# standards. For example, you seem to have classes starting in lowercase (planning, structure) and those should start with capital letters. You seem to have DbSets that should be plural (and capitalized). Finally, this seems to be a lot of work to be in a controller, perhaps it could be be further extracted to a pure business layer. Those modifications would, of course, be up to you.


Extracting relevant form data to an array

You're failing to use the power of jQuery selectors, making the problem much harder than it needs to be.

Furthermore, elmClass = input.attr('class') is buggy.  The elmClass variable is not localized.  If the element (and all previously match elements!) has no class attribute, then the .indexOf() tests will crash.

Since input could be either an <input> or a <textarea>, I'd prefer a more generic variable name.

var tableName = 'some-table';

var objOutgoingData = jQuery(
       'input.form-control[name]:visible,' +
       'textarea.form-control[name],' +
       'textarea.question_textarea_input[name]')
  .not('.element_reference_input')
  .map(function() {
    var $element = jQuery(this);
    return {
        name:  $element.attr('name').split('.').pop(),
        value: $element.val(),
        table: tableName,
    };
}).get();

jQuery('#output').focus(function() {
    $(this).val(
        JSON.stringify(objOutgoingData)
            .replace(/[{\]]/g, '\n$&')
    );
});
input, textarea { font-family: monospace; background-color: #f99; }
.incl { background-color: #9f9; }
#output { background-color: inherit; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <textarea id="output" rows="6" cols="80">Click me to generate objOutgoingData.
Green elements are to be included; red ones and invisible ones excluded.
</textarea>

  <input type="text"   name="input.noclass"                           value="untyped input (no class)">
  <input               name="input.untyped" class="incl form-control" value="untyped input (form-control)">
  <input type="text"   name="input.text"    class="incl form-control" value="text input (form-control)">
  <input type="hidden" name="input.hidden"  class="excl form-control" value="hidden input (form-control)">

  <textarea               name="textarea"         class="incl question_textarea_input">textarea (question_textarea_input)</textarea>
  <textarea type="hidden" name="textarea.hidden"  class="excl">textarea (wrong class)</textarea>
</form>


Indentation
Java's indentation convention is 4 spaces, and not 2 as in your code. You may choose the align = signs between grouped lines, but if you do - be consistent - in your assignment block there are 3 different indentations...

Variables, constants and literals
Variables, which are dynamic and may change as the method progresses, should be named in camelCase, and should be declared as close to their use as possible (no need to declare them at the beginning of the method).
Constants, which do not change when the code is run, should be declared as constants outside the method, and be named in ALL_CAPS.
Personally I think that you should consider dropping the constants altogether, and use literals, since they are less ambiguous then using constants in this case:

sBuild.append("
");
sBuild.append(sbLoop);
sBuild.append("
");

reads better than:

sBuild.append(HEADER);
sBuild.append(sbLoop);
sBuild.append(FOOTER);

which reads better than:

sBuild.append(header);
sBuild.append(sbLoop);
sBuild.append(footer);

Make operations close to where they are used
Same as variable declaration, it is better to calculate a variable value close to where it is used:

Object oName = row.getAttribute("oName");
if(oName != null)
{
    sbLoop.append(columnStart + oName + columnEnd);
}
else
{
    sbLoop.append(columnStart + columnEnd);
}

Naming
You should give variable names which convey information about their purpose and usage. oName and cName are borderline, if they are part of the domain's nomenclature, but sBuild and sbLoop can definitely be improved.

Proper usage of StringBuilder
So, you've decided to use StringBuilder to optimize string concatenations. That's good, but then you use + to concatenate strings before you append them to your StringBuilder! #append method returns this exactly so you can avoid this:

sbLoop.append(columnStart).append(oName).append(columnEnd);

You use sBuild only to wrap your sbLoop with a header and a footer, I suggest you consider simply prepend sbLoop with the prefix, and append it the suffix without using a temp object:

if(prevId != null && !currId.equals(prevId))
{
    if(sbLoop.length() > 0)
    {
        sbLoop.insert(0, header);
        sbLoop.append(footer);
    }
    _oCMap.put(prevId, sbLoop); //HashMap declared at class level

    sbLoop = new StringBuilder();
}

I also think that you should consider not save the StringBuilder in your map, but rather a toString() of it.

Less boilerplate
Your code has a repeating pattern which is something like this:

if(something != null)
{
    sbLoop.append(columnStart + something + columnEnd);
}
else
{
    sbLoop.append(columnStart + columnEnd);
}

I think a better pattern might be:

sbLoop.append(columnStart);
if(something != null)
{
    sbLoop.append(something);
}
sbLoop.append(columnEnd);


Pairwise distance and residual calculation

Let's start by setting
col2 = data[:,2]

to avoid some repetition. (If I knew what was in the data array then maybe I could pick a better name, but all I have to go on is what was in the post.)
Now here are two possible approaches to computing pwresidual:

pwresidual[i,j] is the result of an operation on col2[i] and col2[j]. You might recognize this as being similar to an outer product in mathematics — except that the operation is subtraction rather than multiplication.
But in NumPy every universal function has an "outer" counterpart, and np.subtract is a universal function, so all we need is:
 pwresidual = np.subtract.outer(col2, col2) ** 2

Alternatively, we can use NumPy's broadcasting mechanism, combined with np.newaxis to ensure every pair of items gets operated on:
 pwresidual = (col2[:,np.newaxis] - col2[np.newaxis,:]) ** 2


Read uncommited rows and lock row on update

Some problems here

OR IsLocked <> 1 will be process last
SELECT TOP 1 ID is non-deterministic
I hope HROSAPUID has a unique constraint

_

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Souvik Ghosh
-- Create date: 12-Nov-2016
-- Description: Lock a user ID and return it
-- =============================================
ALTER PROCEDURE LockHROSAPID
@UserIDs varchar(max)
AS
BEGIN
    SET NOCOUNT ON;
    BEGIN TRY
        BEGIN TRANSACTION
            UPDATE [wm_uc1].[UK_HR_HROSAPUserIDs]
            SET IsLocked = 1
            OUTPUT Inserted.HROSAPUID
            WHERE ID = ( SELECT TOP 1 ID
                           FROM [wm_uc1].[UK_HR_HROSAPUserIDs]
                          WHERE HROSAPUID IN (@UserIDs)
                            AND IsLocked IS NULL
                             OR IsLocked <> 1 )
        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        ROLLBACK
    END CATCH
    RETURN
END
GO

maybe something more like this
a single statement is a transaction

  update top (1) [Table_1]
  set bbb = 'no'
  output inserted.pk
  from [Table_1]
  where ( bbb <> 'no' or bbb is null )
  and pk in (13,14,15)


Trying to improve my javascript code in this simple challenge from coderbyte

Your version is actually not that bad but could be simplified slightly and wrapped in a function. You could use charAt to get the character from a string instead of splitting the string. You don't need the initial check on the first and last characters; you can just do these as part of the main loop. (This works because str.charAt(-1) and str.charAt(str.length) both just return empty strings. Similarly if you were using an array, arr[-1] returns undefined.)

Wrapping this in a function and returning false when a non-matching character is found makes the code more efficient, as it does not have to run through the remaining loops when it already knows the answer (this would be the same as inserting break into your code.)

The below code also checks that the characters are either +, =, or a letter, which your original code does not do (so it would accept "===+!+==+3+", for example).

var str = "++d+===+c++=a";
console.log(checkString(str));

function checkString(str) {
    for (var i = 0; i < str.length; i++) {
        if (str.charAt(i) != '+' && str.charAt(i) != '=' &&
            !(str.charAt(i) >= 'a' && str.charAt(i) <= 'z' &&
              str.charAt(i - 1) == '+' && str.charAt(i + 1) == '+')) {
            return false;
        }
    }
    return true;
}

To use regular expressions you need to write pattern.test(str), e.g. /[a-z]/gi.test('a') returns true. However the point of using regex is that you can test a whole string in one go, rather than character-by-character. I think the following will work:

/^((\+[a-z])*\+|=)+$/gi.test('++d+===+c++=a')


Finding the smartest set from an array of numbers

Review

Don't print() but return variables, so other functions can reuse the outcome.
Split up your code into functions, for re usability and to easier test parts of your code.
Write test cases using the unittest module rather then doing it from the CLI every time
There are some code improvements as well,

You could benefit from the collections.defaultdict module
An easier way to count the "1" in the binaray format is: str(bin(ele)[2:]).count("1")
You can benefit from list or dict comprehension, see PEP202

Alternative

import unittest
from collections import defaultdict

def smartest_set(array):
    smart_sets = defaultdict(list)

    for element in array:
        num_of_ones = str(bin(element)[2:]).count("1")
        smart_sets[num_of_ones].append(element)

    # If you'd really want the output be printed, you can add a print statement in the function
    result = [min(e) for e in smart_sets.values()]
    print(result)
    return result

class Test(unittest.TestCase):
    def test_smartest_set(self):
        array = [6, 2, 11, 1, 9, 14, 13, 4, 18]
        expected = [1, 6, 11]
        self.assertEqual(expected, smartest_set(array))

        # More tests here...

if __name__ == "__main__":
    unittest.main()

Or a slightly faster approach storing the minimum value of the counts only

def smartest_set_2(array):
    smarts = {}
    for ele in array:
        num_of_ones = str(bin(ele)[2:]).count("1")
        smarts[num_of_ones] = min(ele, smarts.get(num_of_ones, float('inf'))
    return smarts.values()


Welcome to Code Review.

Your code returns false for the message "hello&9", because the method doesn't check the last character. Change the condition in the for-loop to message.length() - 1.

An alternative is to use a regular expression:
public static boolean isMessageColoured(String message) {
    return message.matches(".*&[a-f0-9].*");
}

This regular expression matches at least one occurrence of &[a-f0-9] in the message.


Temperature converter using "switch" statement

public static float temp;
public static char tempUnit;

There's no reason to make these into global variables. It's better to use local variables:

static void Main(string[] args)
{
    float temp;
    char tempUnit;
}

If you want a first step into OOP, try wrapping the temp and tempUnit into a class (or struct) of their own.

While Console.ReadLine().Split() is essentially the same as Console.ReadLine().Split(' '), I would suggest putting the character in there.

It's a matter of readability. Initially, I assumed it would split on newlines, not spaces, until I remembered. Or, alternatively, add a comments that mentions you're splitting on spaces.

You're not handling garbage values. What happens if the user enters 123f or batman or k 123? Try to handle invalid data and show the user an error message that describes the problem.

if(!float.TryParse(tempInput[0], out temp)
{
     Console.WriteLine($"Cannot parse the value \"{tempInput[0]}\"");

     //Wait until user presses enter and close the application
     Console.ReadLine();
     return;
}

The subsequent code is the same, as TryParse will still put a usable value in the temp variable.

Console.WriteLine(temp + 273.15 + "°K");

While this currently works, I highly suggest not doing this.

It's very hard to spot that you're first doing a mathematical operation (number + number), and then a string concatenation (number + string, which is handled as string + string).

Suppose you're in a culture where the unit comes before the value (e.g. °K 123). You can't just simply invert the code ("°K" + temp + 273.15); because if temp equals 123, your result will be °K123273.15 because it is now concatenating three string values.
While you could work around this issue with parentheses, it's still not a good fix.

There's no reason to inline all statement. Especially when you're a beginner, but this applies to experts as well. Handling the same operations on multiple lines does not affect application performance, but it does dramatically lower readability.

var convertedValue = temp + 273.15;
var convertedValueString = convertedValue + "°K";

Notice that I didn't use Console.WriteLine() yet. You've had to copy paste that in every method, which is not a reusable pattern.

It would be better to have the method return a string:

static string convertCelsiusToKelvin()
{
    var convertedValue = temp + 273.15;
    var convertedValueString = convertedValue + "°K";
    return convertedValueString;
}

And wrap the method call in the Main() method:

switch (tempUnit)
{
    //Converting temp to F and K if tempUnit == c
    case 'c':
        Console.WriteLine("Celsius To Farhenheit and Kelvin");
        Console.WriteLine(convertCelsiusToFarhenheit());
        Console.WriteLine(convertCelsiusToKelvin());

Note: This can be optimized further, but this is already a good first step. It teaches you to separate the calculation from the presentation of the calculated value.

Try to separate the logic into methods more. Your Main() method currently is doing many things that don't really have anything to do with each other:

Read the values
Decide which conversion calculations to do
(As per my suggestion) Printing the converted values.

A minor redesign to show you what I mean. First, let's define a struct for our values:

public struct Temperature
{
    float Value;
    char Unit;
}

You could redesign your main method to be much more abstracted:

static void Main(string[] args)
{
     Temperature input = GetInputFromUser();

     Temperature valueKelvin = CalculateKelvin(input);
     Print(valueKelvin);

     Temperature valueFahrenheit = CalculateFahrenheit(input);
     Print(valueFahrenheit);

     Temperature valueCelsius = CalculateCelsius(input);
     Print(valueCelsius);

    Console.ReadLine();
}

Some explanatory examples:

public static Temperature CalculateKelvin(Temperature inputValue)
{
     switch(inputValue.Unit)
     {
         case 'K':
             //Same unit, so no conversion needed
             return value;
         case 'F':
             // F => K
             return convertFahrenheitToKelvin(inputValue);
         case 'C':
             // C => K
             return convertCelsiusToKelvin(inputValue);

     }
}

public static void Print(Temperature value)
{
    Console.WriteLine($"{value.Value} °{value.Unit}");
}


using 2D array to read datatable ok? or repeatedly call function that reads record by record?

I have discovered, with thanks to you each, that it is better to call the display method within the DataAccess.ReadMethod() than to pass strings, Here's what I think i should do:

public class DataAccess
{
    public bool CreateMan(TestDatabaseEntities dbEntities, Man M)
    {
        return TryDataBase(dbEntities, "Man created successfully",
            () =>
            {
                dbEntities.Men.Add(new Man { ManID = M.ManID, Name = M.Name });
            });
    }

    public bool UpdateMan(TestDatabaseEntities dbEntities, IQueryable<Man> query, Man man)
    {
        return TryDataBase(dbEntities, "Man updated Successfully",
            () =>
            {
                foreach (Man M in query)
                {
                    M.Name = man.Name;
                }
            });
    }

    public bool DeleteMan(TestDatabaseEntities dbEntities, IQueryable myQuery)
    {
        return TryDataBase(dbEntities, "Man deleted Successfully",
            () =>
            {
                foreach (Man M in myQuery)
                {
                    dbEntities.Men.Remove(M);
                }
            });
    }

    public bool ReadMan(TestDatabaseEntities dbEntities, IQueryable myQuery)
    {
        UserInterface MyUI = new UserInterface();
        bool bSuccessful;

        bSuccessful = TryDataBase(dbEntities, "Records read successfully",
            () =>
            {
                MyUI.DisplayDivider();
                foreach (Man m in myQuery)
                {
                    MyUI.DisplayMessage(new string[] { m.ManID.ToString(), m.Name });
                }
                MyUI.DisplayDivider();
            });

        return bSuccessful;
    }

    public bool TryDataBase(TestDatabaseEntities MyDBEntities, string SuccessMessage,  Action MyDBAction)
    {
        UserInterface MyUI = new UserInterface();
        try
        {
            MyDBAction();
            MyUI.DisplayMessage(SuccessMessage);
            return true;
        }
        catch (Exception e)
        {
            MyUI.DisplayMessage(e.ToString());
            return false;
        }
    }
}


def __init__(self, perm, label=""):
        """
        :param perm: List of tuples of type (A, B), which shows that in given sequence of symbols
                        symbol A will be replaced by symbol B
        :param label: Label for better (or worse) representation.
        """
        top_symbols = [p[0] for p in perm]
        bottom_symbols = [p[1] for p in perm]

        top_symbols = set(top_symbols)
        bottom_symbols = set(bottom_symbols)

        if top_symbols != bottom_symbols:
            raise Exception("Incorrect Permutation")

That's an important check, but not a sufficient one. If I pass [(1, 1), (2, 1), (2, 2)] then top_symbols and bottom_symbols will be the same set, but it's not a valid permutation.

    @property
    def inverse(self):
        p = [(p[1], p[0]) for p in self._perm]
        p.sort(key=lambda x: x[0])
        return Permutation(p, "Inverse({0})".format(self._label))

Why sort p? The constructor does that anyway.

    @property
    def symbols(self):
        return sorted([i for i, j in self._perm])

Why sorted? The constructor does that already.

Also, why do some methods use [something involving p[i] for p in self._perm] and others [something involving i and/or j for i, j in self._perm])?

    @property
    def _inversions(self):
        res = 0
        top = [i for i, j in self._perm]
        bottom = [j for i, j in self._perm]
        for i in range(len(top)):
            for j in range(i, len(top)):
                if bottom[i] > bottom[j]:
                    res += 1
        return res

This takes \$O(n^2)\$ time. There are \$O(n \lg n)\$ algorithms to do it, so since you say that performance is a concern you probably want to revisit this method.

    def print_carrier(self):
        [print("{0} -> {1}".format(mutation[0], mutation[1])) for mutation in self._perm if mutation[0] != mutation[1]]

The name is somewhat opaque: carrier?!

The implementation is also somewhat hacky. As far as I can tell without executing to double-check, this is using a list comprehension purely to iterate and produce side effects. Ugh.

    def _find_symbol(self, symbol):
        for i in range(len(self._perm)):
            if self._perm[i][0] == symbol:
                return i

Whoa! If this method is used much at all, it's going to be a major performance hit. IMO you need to revisit the way the data is stored: to do this efficiently you want a dict.

Also: why return i? Under what circumstances would you call this method wanting anything other than self._perm[i][1]?

    def __eq__(self, permutation):
        if type(permutation) != Permutation:
            return False
        condition1 = self.symbols == permutation.symbols
        condition2 = self.__call__(self.symbols) == permutation(self.symbols)
        return condition1 and condition2

Why not just do an equality check on _perm and permutation._perm?

    def __mul__(self, permutation):
        first = [mutation[0] for mutation in self._perm]
        second = self.__call__(permutation(first))
        return Permutation(tuple(zip(first, second)), str(self) + " * " + str(permutation))

Firstly, DRY: first is self.symbols. Secondly, IMO a comprehension for second would be more clearly checkable against the definition of permutation composition. Thirdly, why tuple(...) in the call to the constructor? If zip works in get_letter_id it should work here too.