You should create full text search indexes for these fields and use MATCH ... AGAINST

This way you can change this line to:

$query = "SELECT * FROM coils MATCH ( name, resistance, wraps, wire_1, wire_2, wire_3, wire_4, wire_5, wire_6) AGAINST ('$term') LIMIT 25";

Updated: If you want stick to string substitution when mounting your $query (like you did), make sure you have sanitized your $term variable in order to prevent SQL injection attacks. But it's highly recommended using bind solution nicely expanded below by @greg-burghardt.

More information about MATCH AGAINST can be found here: https://dev.mysql.com/doc/refman/5.7/en/fulltext-natural-language.html


Return a 404 when a resource is not found in Spring Boot

Your URL path isn't very RESTlike. You have built the URL to describe an operation when a more common approach is to build the URL to describe a resource.

So instead of https://example.com/api/mappings/get-by-id/42 one would build a URL like https://example.com/api/mappings/42.

The name get-by-id is fully redundant in REST world as the "get" operation is already defined in the HTTP GET-method (the @GetMapping annotation in Spring Boot) and identifying resources by their identifier is always the default operation :).


Overall it's pretty good, but there might be something iffy going on with the rules you use.

I had honestly never heard of one-handed solitaire, but if I understand it correctly, there are no special rules for the last cards. You either have exactly 4 cards left, and win if you can discard them all, or you lose.

But you have a last2 rule, where you change the rules to look at the 1st and 2nd card if there are less than four cards left. I imagine this skews the results.

Anyway, in terms of code:

Don't mix plain console.log and a custom logging function.
Put the code for playing 1 round into a function. Right now it's all inside a loop that runs 10000 times. It'd be a lot simpler to just call play() and get a won/lost boolean back. You can always loop that.
It'd be simpler to unshift cards onto the hand. Then you'd always be comparing hand[0] to hand[3] instead of having to subtract stuff from hand.length. Splicing also becomes just splice(0, 4) or splice(1, 2)
You can use concat instead of Array.prototype.push.apply (or the slightly shorter alternative [].push.apply). The difference, however, is that concat returns a new array instead of modifying the receiver like push does.
You can simplify Card and Deck a little by using a list of values for rank as well as suit:

function Card(suit, rank) {
  this.suit = suit;
  this.rank = rank;
}

Card.prototype = {
  toString: function () {
    return this.rank + this.suit;
  }
};

Card.suits = ["♠", "♥", "♣", "♦"];
Card.ranks = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"];

function Deck() {
  var cards, shuffled, i;

  cards = Card.suits.reduce(function (cards, suit) {
    return cards.concat(Card.ranks.map(function (rank) {
      return new Card(suit, rank);
    }));
  }, []);

  shuffled = [];
  while(cards.length) {
    i = Math.random() * cards.length | 0;
    shuffled.push(cards.splice(i, 1)[0]);
  }

  return shuffled;
}

I've named Deck with PascalCase as though it's a constructor, which it isn't quite. But you can call it as new Deck or just Deck() and either thing'll work, as it explicitly returns something.

You could also take a different tack altogether. You don't really need a hand array: You can just examine the shuffled deck directly. For instance:

function play() {
  var deck = new Deck,
      i = deck.length,
      a, b;

  while(true) {
    // decrement if we're too close to the end of the deck
    i = Math.min(i, deck.length-4);

    // if we had to decrement past zero, game's over
    if(i < 0) {
      return deck.length === 0;
    }

    // the cards to examine
    a = deck[i],
    b = deck[i+3];

    // match cards or decrement
    if(a.rank === b.rank) {
      deck.splice(i, 4);
    } else if(a.suit === b.suit) {
      deck.splice(i + 1, 2);
    } else {
      i--;
    }
  }
}

(Edit: I updated the code based on @Jonah's comment below to examine the deck from the end, rather than the beginning.)

Running 300,000 games, I get a 0.730% chance of winning, which is pretty close to 1 in 140.

Edit: It makes for a nice animation - see snippet below

var frameTime = 100;
var button = document.getElementsByTagName("button")[0];
var span = document.getElementsByTagName("span")[0];

function Card(suit, rank) {
  this.suit = suit;
  this.rank = rank;
}

Card.suits = ["♠", "♥", "♣", "♦"];
Card.ranks = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"];

function Deck() {
  var cards, shuffled, i;

  cards = Card.suits.reduce(function (cards, suit) {
    return cards.concat(Card.ranks.map(function (rank) {
      return new Card(suit, rank);
    }));
  }, []);

  shuffled = [];
  while(cards.length) {
    i = Math.random() * cards.length | 0;
    shuffled.push(cards.splice(i, 1)[0]);
  }

  return shuffled;
}

function play() {
  var deck = new Deck,
      i = deck.length - 4;

  button.disabled = true;
  span.innerHTML = "";

  function step() {
    var a, b;

    i = Math.min(i, deck.length - 4);
    drawState(deck, i);

    if(i < 0) {
      if(deck.length) {
        span.innerHTML = "Lost (" + deck.length + " cards remain)";
      } else {
        span.innerHTML = "Won!";
      }
      button.disabled = false;
      return;
    }

    a = deck[i];
    b = deck[i+3];

    if(a.rank === b.rank) {
      deck.splice(i, 4);
    } else if(a.suit === b.suit) {
      deck.splice(i+1, 2);
    } else {
      i--;
    }

    setTimeout(step, frameTime);
  }

  step();
}

function drawState(deck, offset) {
  var canvas = document.getElementsByTagName("canvas")[0],
      ctx = canvas.getContext("2d");

  canvas.width = 520;
  canvas.height = 35;

  function drawTriangle(x, y) {
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x + 3, y + 5);
    ctx.lineTo(x - 3, y + 5);
    ctx.closePath()
    ctx.fill();
  }

  if(offset >= 0) {
    drawTriangle(offset * 10 + 5, 25);
    drawTriangle((offset + 3) * 10 + 5, 25);
    ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
    ctx.fillRect(offset * 10, 0, 40, 22);
  }

  ctx.fillStyle = "#000";
  ctx.font = "10px serif";
  ctx.textAlign = "center";

  deck.forEach(function (card, x) {
    x = x * 10 + 5;
    ctx.fillText(card.rank, x, 10);
    ctx.fillText(card.suit, x, 20);
  });
}

button.addEventListener("click", play, false);
play();
<canvas></canvas>

<button>Play again</button>


Generate a series of random integers between 1 and 10

Your code could potentially run forever - in theory, it could randomly pick the same number again and again and again. Probably won't, but the point is that the code may take a long time to run.

A simpler approach is to generate the numbers 1-10, and then shuffle them, Fisher-Yates style. Something like:

var numbers = new Array(10),
    shuffled = [];

// fill one array with the numbers 1-10
numbers = numbers.fill(1).map((_, i) => i + 1);

// shuffle by taking a random element from one array
// and pushing it to the other array
while (numbers.length) {
  let idx = numbers.length * Math.random() | 0; // floor trick
  shuffled.push(numbers[idx]);
  numbers.splice(idx, 1);
}

console.log(shuffled);

(The "floor trick" works by using bitwise OR. Now, bitwise OR zero does actually do anything, but all JavaScript bitwise operations interpret their operands to 32-bit integers, so it's like casting to an int, discarding decimals - i.e. it floors the number.)


Finding two consecutive triangular numbers with a given target sum

A few suggestions:

Explicitly return False if the condition fails, i.e., if there aren’t two triangular numbers that sum to n.

As it stands, your function with either return True or None.
Don’t store the first n triangular numbers in a list; check them as you go through.

For large n, you’ll be creating a very large list, which will slow down Python. And the vast majority of the numbers in that list will be greater than n, so cannot possibly sum with a consecutive triangular number squared to give n.

This is much more efficient:

for i in range(1, n + 1):
    # If T_1 = i (i+1) / 2 and T_2 = (i+1) (i+2) / 2 then
    # we have
    # T_1^2 + T_2^2 = (i+1)^2 [i^2 + (i+2)^2] / 4
    result = (i+1)**2 * (i**2 + (i+2)**2) / 4
    if result == n:
        return True
    elif result > n:
        return False

We’re not storing lots of numbers in a list, and we’re only going until it’s impossible to find a working combination.

On my fairly weedy old laptop, this can take O(10^7) input and finish in under a second.
Use a better function name, and write a docstring.

Per PEP 8, function names in Python should be lowercase_with_underscores; your CamelCase function gives the impression of being a class.

And Triangular isn’t a very helpful name – if I saw that being called, I’d probably assume it was returning the nth triangular number. Something like

def is_consecutive_triangular_square_sum(n):

doesn’t roll off the tongue as nicely, but it’s never going to be confused for getting triangular numbers, and the is_ prefix suggests that it probably returns a boolean.

You should also write a docstring, which explains what the function is supposed to do. Useful for interactive help and/or people reading your code.


Pointless loops

You have a couple of loops that do nothing but waste time:

     while (val != iterator)
       iterator--;

That loop does the same thing as:

    iterator = val;

Similarly, this loop:

         while (counter < value)
         counter++;

is the same as:

         counter = value;

Way too complicated

Your code that fills the buckets is confused and complicated:

 for (int j = 0; j < vectSize; j++)
   {
     int val = 0;
     int count = 0;
     int element = 0;
     int iterator = M;
     val = V[j];
     while (val != iterator)
       iterator--;
     element = iterator + M;
     count = U[element];
     count++;
     U[element] = count;
   }

It should really be a one line loop:

for (int j = 0; j < vectSize; j++) {
    U[V[j]]++
}

Note that this uses buckets in the range 0..M, whereas yours uses buckets in the range M..2M for no good reason.

Similarly, your bucket unpacking loop could be simplified to:

int index = 0;
for (int i = 0; i <= M; i++) {
    for (int j = 0; j < U[i]; j++) {
        V[index++] = i;
    }
}

This assumes that you allocated U to hold M+1 elements, to allow for values in the range 0..M.


Program that guesses your number using bitwise operations

Here are some things that may help you improve your code.

Understand type implications

The code includes a bitFlag array that is declared as const int8_t but then contains a value that is 0x80.  The problem with that is that when the compiler encounters the constant 0x80, it converts it into an int by default, and so that would be the value 128.  However, 128 is not representable in an int8_t.  That bit pattern is actually -128 as an int8_t, so I'd recommend either using a different type (such as uint8_t) for the variable or writing -0x80 for the constant which is correct, but a little strange looking.

Know the standard types

This function is in the current code:

int getOneOrZero()
{
    return (rand() >> 14);   // >> the bitwise operator
}

There are two problems with this.  The first is that it apparently assumes that an int is 16 bits.  However, on my machine, an int is 64 bits.  In general, you can't assume that the size of an int is a fixed size.  The standard only says (implicitly from the required range) that it must be 16 bits, but it may be larger.  The second problem is addressed in the next point.

Consider using a better random number generator

Because you are using a compiler that supports at least C++11, consider using a better random number generator.  In particular, instead of rand, you might want to look at std::bernoulli_distribution and friends in the <random> header.

Here's one way to rewrite it:

int getOneOrZero()
{
    static std::mt19937 gen{std::random_device{}()};
    static std::bernoulli_distribution bd;
    return bd(gen);
}

Ensure every control path returns a proper value

The swapZeroOrOne routine returns 1 or 0 under some set of conditions but then doesn't return anything at all otherwise (although it prints an error essage).  This is an error because all control paths should return a value.  Since it's only used once, and because it can be trivially rewritten, I'd probably replace this:

case 'n' :
    { int newNum = swapZeroOrOne(num);
      return newNum*flag;
    }

with this:

    return (1-num)*flag;

Avoid using goto

Having a goto statement in modern C++ is usually a sign of bad design.  Better would be to eliminate them entirely -- it makes the code easier to follow and less error-prone.  In this code, it's probable that you could use a loop instead:

for (bool playing=true; playing;  )
    // code to play the game
    // ask user if they want to play again
    playing = answer == 'r';
}

Don't use system("cls")

There are two reasons not to use system("cls") or system("pause").  The first is that it is not portable to other operating systems which you may or may not care about now.  The second is that it's a security hole, which you absolutely must care about.  Specifically, if some program is defined and named cls or pause, your program will execute that program instead of what you intend, and that other program could be anything.  First, isolate these into a seperate functions cls() and pause() and then modify your code to call those functions instead of system.  Then rewrite the contents of those functions to do what you want using C++.  For example, if your terminal supports ANSI Escape sequences, you could use this:

void cls()
{
    std::cout << "\x1b[2J";
}

Think of the user

If the user were to get an error message that said:

  ERROR ! In getUpdateForGuessNum

What use is that unless they also happen to be the author of the code?  Instead, for errors that are an indication of a program flaw, I'd use assert or for things that are unusual but still should be accomodated by the program, use an exception.

Use objects

You have a guessNum and counter to support the game and then separate functions printNums and getAnswer, etc. that operate on guessNum. With only a slight syntax change, you would have a real object instead of C-style code written in C++.  You could declare a GuessNum object and then printNums, getAnswer, etc. could all be member functions.

Don't use std::endl unless you really need to flush the stream

The difference between std::endl and '\n' is that std::endl actually flushes the stream. This can be a costly operation in terms of processing time, so it's best to get in the habit of only using it when flushing the stream is actually required. It's not for this code.

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


Dealing with KB, MB, GB and TB and bytes

Here's a slightly less repetitive way to write it since we know each unit is 1024 as large as the last:

function kmgtbytes (num) {
    var unit, units = ["TB", "GB", "MB", "KB", "Bytes"];
    for (unit = units.pop(); units.length && num >= 1024; unit = units.pop()) {
        num /= 1024;
    }
    return [num, unit];
}


Determine if subset in int array adds up to a given input integer

This solution is very dependant on m for the space complexity.

I worry that, with the inputs:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2000000000]

and the target sum 2000000002 that your program will run out of memory (it will do: boolean[][] m = new boolean[sum + 1][a.length + 1]; which will create an array of about 20GB or more.... actually, it will be worse... about 80GB.

Additionally, you have labelled this as a 'dynamic programming' problem, but there is no recursion here, and no memoization/re-use....

In a review, I would challenge this solution's scalability, and assumptions.


A few sorting algorithms implemented in C

This is a pretty good straightforward implementation of these algorithms. It's really nice that they're all implemented in-place so no extra memory is needed. It looks pretty good, but I have a few suggestions.

Better Naming

Your function names are pretty good. (I might add "sort" to the various sorting routine names, but it's not a big deal.) However, the variable names are a bit too terse. Normally, I'd object to using arr as the name for an array and name it after what's stored in the array. (Something like grades or names or whatever was being sorted.) In this example case, it's acceptable, but keep that in mind for the future.

It's tradition for i and j to be used for loop control variables, and I don't mind those. But I would change n to numElements. (Or if you have a better name for the array, name it num<whatever's in the array> such as numGrades, numNames, etc.)

The function parameters a and l should be named with more readable names, like arr and length. ord is reasonable, but I'd prefer order.

Use enum when appropriate

ch is presumably supposed to hold a character, which would be a reasonable name, except that it holds an int. Likewise, ord is supposed to hold the order.

Both of those should be an enumerated type. I'd make one for the sort type and one for the sort order. Something like this:

typedef enum {
    SO_Ascending = 1,
    SO_Descending
} SortOrder;

typedef enum {
    ST_Insertion = 1,
    ST_Selection,
    ST_Bubble
} SortType;

You can then create variables of those types and read the values into them.

Error handling

You may have noticed that the user can enter invalid values, too. You should verify that the values they entered are reasonable and prompt them again if not. To do that, it would probably make sense to break out some of the functionality in main() into separate functions. I suggest something like this:

void promptForArray(int arr [ MAXSIZE ], int* numElements)
{
    do {
        printf("\nEnter number of elements for array = ");
        scanf("%d", numElements);
        if ((*numElements <= 0) || (*numElements > MAXSIZE))
        {
            printf("\nYou entered an invalid value for the number of elements. Please choose a value between 1 and %d\n", MAXSIZE);
        }
    } while ((*numElements <= 0) || (*numElements > MAXSIZE));

    printf("\n\nEnter the array elements one by one : \n\n");
    for(int i = 0; i < *numElements; i++){
        scanf("%d",&arr [ i ]);
    }
}

You could then do a similar thing for getting the sort function and sort order. Something like this:

void promptForSortType(SortType* sortType)
{
    do {
        printf("\n\nWhat sorting you want to use ?\n\n Insertion (1) , Selection (2) or Bubble (3)\n\nEnter choice = ");
        scanf("%d", sortType);
        if ((*sortType < ST_Insertion) || (*sortType > ST_Bubble))
        {
            printf("\nYou entered an invalid sort type. Please enter a value between 1 and 3.\n");
        }
    } while ((*sortType < ST_Insertion) || (*sortType > ST_Bubble));
}

Readability

Do the above things should improve the readability of your code, but you can do more. I recommend leaving spaces around operators (+, -, =, etc.).

This method of introducing function prototypes within main() is very odd:

void insertion(int*,int,int),selection(int*,int,int),bubble(int*,int,int);

Instead, you should put them above main and put them all on separate lines, and you should name the parameters so someone reading them knows what the parameters mean. Something like this:

void insertion(int *arr, const int length, const SortOrder ord);
void selection(int *arr, const int length, const SortOrder ord);
void bubble(int *arr, const int length, const SortOrder ord);

Use const where appropriate

You may have noticed that I made length and ord const in the above examples. They don't change, so it's best to mark them as unchanging. Then the reader and the compiler know more about the intent of the function. You could also make arr const in the print() function.


Given two words, transform the first one into the second

The algorithm is wrong and can't be fixed.
It's not dynamic programming, it's greedy: it iterates over the strings once and decides immediately which operation to perform. Consider some test cases:
                 case 1            case 2            partial read

string 1:        abcde             abcde             abc..
string 2:        abxde             abxcd             abx..

optimal          replace c         insert x          ?
strategy         by x              delete e

Both cases are identical in the first three characters, yet the operations to perform are different. They depend on characters not yet read.
Any algorithm that does not take into consideration the full picture before making a single descision must fail at least one of those test cases. Yours fails the second.
Brute force
The naive way to overcome this problem is a brute force algorithm. Evaluate all possible sequences of operations (insertions, deletions, replacements). When all input was read, output the best sequence.
Dynamic programming
Dynamic programming starts out similar to brute force and evaluates all possible operations, but whenever it finds that two sequences of operations yield the same intermediate result, it keeps (and evaluates further) only one of them.


Loops through each row in a binary image and gets the width of each group of black or white pixels

You don't need a number of pixels, you need to detect narrow bars and wide bars. Use first black and white bar width as a pattern with 15% margin for next bars. The wide bar has 2.0 to 3.0 times the width of a narrow bar. Try to detect start or stop code at the begin of selected line, if it is correct, then read the rest of the line...
After every 5 black+white bars (in the right direction) you can decode two digits, black bars define 1st and white 2nd ...
Bars have weights: 1st: 1, 2nd: 2, 3th: 4, 4th: 7: 5th 0. Add weights of every wide bars, and you get the digit (11 = 0).
If 3 lines give you the same result, this is probably your code...

EDIT:

You can see the algorithm on your code:


Thread Safe Bank Transaction: Deposit, Withdrawal, Check Balance and Transfer in Java

Let's break this down.

You have two locks for single object that guarding same fields.

It's generally bad practice, and it doesn't make sense as second lock(transferLock) is used only in single operation. It won't guard for other operations.
It could possibly work if you have a static read-only lock for transfer with the following semantics: add/sub/get are global read lock and transfer is global write lock, then yu should acquire read lock on transfer on regular operations and write-lock on transfer op, but that would allow on;y single transfer at a time, and that's definitely not what you are trying to achieve.

Your locks leak outside of your main class (reed aren't private/protected).

This could lead to uncontrolled use from outside, say future versions of code could misuse locks. I can see that they have package level visibility, that's semi ok, but Account#add,Accound#sub, Account#getBallance are public and not guarded by locks, so that destroys the purpose of haveing locks package-private.
I'd suggest put all usage of locks inside instance methods mentioned above, and add another method:
class Account{
public void transfer(Account other, int amount) { ... }
}

Then all logic related to locking would be in a single, controlled place.

Lock ordering. If you are using granular locks, so no single lock for all accounts and you need to lock several objects you should have STRICT lock order.

You are trying to achieve this with tryLock and while loop, this COULD actually work if you have used your rw lock, but it would be possible to deadlock as you are acquiring other locks then. And it's not really performant to wait in spin-loop here, you can wait forever.
I'd suggest to user your rw-lock but first, sort two accounts by accountId, then take write locks in order of account ids from lower to higher.
//pseudocode
if (acc1.id<acc2.id) {
  acc1.lock.writeLock().lock()
  acc2.lock.writeLock().lock()
}else{
  acc2.lock.writeLock().lock()
  acc1.lock.writeLock().lock()
}

It could be actually combined with tryLock, but it could take a while to acquire such locks.

Minor thing, it's preferable to call unlock() inside finally block, so no objects would stick in a locked state.


This check

if ((DateTime.Now - _lastUpdate).TotalMilliseconds <= _timerInterval )
{
    return;
}

is superflous, because the timer fires at a defined interval.

Does the ServerName change over the time the application is running ? I guess not so it would be better to request the name once and store it for later usage.

The same applies to ServerStarted.

Personally I would create an extension method for the TimeSpan which would do the whole work with the day(s), hour(s) and minute(s). Something along these lines

public static string ToWords(this TimeSpan timeSpan)
{
    return  timeSpan.Days + (timeSpan.Days != 1 ? " days" : " day") + ", "
          + timeSpan.Hours  + (timeSpan.Hours != 1 ? " hours" : " hour") + ", and "
          + timeSpan.Minutes  + (timeSpan.Minutes != 1 ? " minutes" : " minute");
}

and calling like so

var uptimeString = serverUptime.ToWords();

Disclaimer: I don't like the name of the method.


Spiral Scanning for matrix using recursion

It is very important you indent your code properly as it will make your code easier to read and less prone to errors.  This statement in particular is problematic:

if(counter>=n*m)
return;

You should use returns around your if blocks and loops even when they are single-statement bodies, you should indent your code so it is clear the return is part of the if block, and you should use spaces around your operators to make it easier to read:

if(counter >= n * m) {
    return;
}

Right here, you should remove the if, braces, and indentation:

    //scan bottom
 //   if(m-call>0)
    {   printf("\nbottom\n");
        for(j=m-2-call;j>=call;j--)
        {printf(" %d ",a[n-1-call][j]);
        counter++;
        }
    }

It doesn't make sense to have messy, hard-to-read code like this lying around.  Also, the final code shouldn't show fixed bugs and commented (dead) code - it should just be the working code and comments stating what it does as needed (I am not an advocate of a comment per line).

You should name your variables better:

void spiralscan(int a[][20],int n,int m,int call,int counter)

What are n and m anyway?  Also, you should put spaces after your commas.

It will probably be easier to read your code if you use PascalCase, snake_case, or camelCase to name your variables and functions becausevariableandfunctionnameswithnowordseparatorsarehardtoreadwhenverylong.  It seems snake_case is common among C programmers.


Circular Queue in C for an embedded project

Functionality unclear

Post discusses "... circular queue. (in order to store characters ...".

After digging deeply into code I now realize the goal is not to enqueue a character and then a character and so on.  Instead the goal is to enqueue a group of characters, then another group and so on.

This is not clear from the the post and importantly, it is not clear from the .h file.

Documentation

The .h file, as a public interface deserves  as least a little documentation/comment per function.

Nonuniform name-space

__QUEUEH, queue, queue_init, enqueue, dequeue, printQueue would benefit with a more  common naming convention to clearly show that they belong together.

Consider QUEUE_H, queue, queue_init, queue_set, queue_get, queue_print

queue_t

Information hiding: The members of queue_t do not need to be in the .h file.  The below is sufficient.  If external code needs to read any of these members, I recommend a function to do so.

typedef struct queue queue_t;

Put the full struct queue definition in the .c file.

.initialized is a good candidate for bool.

// unsigned char initialized;
bool initialized;

Unnecessary item in .h

As a static function, printQueue does not belong in the .h file.  Remove it.

Avoid standard library collisions

The below conflicts with bool from stdbool.h.  Do not re-invent the standard boolean type.

// #if !defined bool
// typedef unsigned char bool;
// #endif
#include <stdbool.h>

queue_init()

Why set .head, an unsigned type, to a negative value?  Set to a unsigned value.

// q->head = -1;
q->head = -1u;

moveTail()

The role of magic number 2 is unclear here and in many of the functions.  Explain the 2.

Unexpected strMaxSize

How does reading the data in the queue relate to the length of anything?

int len = q->buf[q->tail];

The role of strMaxSize in dequeue() is unclear.

Hmmmmm

After more review it looks like the first character in a group of characters is the group's length.

enoughSpaceAvailable()

Avoid overflow: size+2 can overflow - this code has no control over the value of size.  Consider a more robust test.

// if(q->freeSpace < size+2) return 0;
//return 1;

return q->freeSpace > size && q->freeSpace - size >= 2;

const

Many functions would benefit with a const queue_t *

// enoughSpaceAvailable(queue_t* q, unsigned int size)
enoughSpaceAvailable(const queue_t* q, unsigned int size)

3 to do the job of 2

Unclear why code uses .bufSize, .freeSpace, .occuSpace when only 2 are needed.  I'd expect .bufSize, .occuSpace are sufficient here.

Overall

Code lacks documentation to indicate the overall coding goals.  Without that, there is too much to discover.

I still do not know how to use best these calls.  Will enqueue(q, "", 0); cause havoc?   How to test is the queue is empty? What are all the error codes?  Why are errors negative?  What does a positive response mean?

To me, it is  the un-posted testfile contains too much information there and not enough here.

This code deserves an update and then a following review.

Sample alternate aqueue.h.
I avoided "queue" as too generic and used "aqueue".

/*
 * aqueue: queue of groups of binary data
 */

#ifndef AQUEUE_H
#define AQUEUE_H

typedef struct aqueue aqueue_t;

// All functions that return `int` return 0 on success.

/*
 * Initialize the queue with the buffer to use and its size.
 * Size [4..UINT_MAX]
 * Return TBD with invalid parameter values.
 */
int aqueue_init(aqueue_t* q, unsigned char* buf, unsigned bufSize);

/*
 * Insert a copy of what `data` points to.
 * Return TBD with insufficient space
 */
int queue_set(aqueue_t* q, const unsigned char* data, unsigned dataSize);

/*
 * Extract entry from the queue.
 * Return TBD when attempted with empty queue.
 * Return TBD when dataSize is too small.
 */
int aqueue_get(aqueue_t* q, unsigned char *data, unsigned dataSize);

/*
 * Queue empty?
 */
_Bool aqueue_empty(const aqueue_t* q);

/*
 * Get data without removing from the queue  (Peek)
 * Return TBD when attempted with empty queue.
 * Return TBD when dataSize is too small.
 */
int aqueue_top(const aqueue_t* q, unsigned char* data, unsigned dataSize);

#endif


In your example you're adding events inside events, this is not good idea because it creates unnecessary closures and can lead to memory leaks.

First I would cache the elements so you only query the DOM once, improving performance. Then you can create a function to hide all images, and a function to go to the next image, and reuse that function for both events:

// IIFE (Immediately invoked function expression)
// to not leak variables to global scope
(function(){
    // Cache elements
    var list = document.getElementById('list');
    var btn = document.getElementById('btn');

    var current = 0;

    // Hide all images
    function hide() {
        for (var i=0; i<list.children.length; i++) {
            list.children[i].style.display = 'none';
        }
    }

    // Go to next image
    function next() {
        hide();
        list.children[current++].style.display = 'block';
        // Did we reach the end?
        if (current >= list.children.length) {
            current = 0;
        }
    }

    // Reuse function
    window.onload = btn.onclick = next;
}());

Demo: http://jsfiddle.net/F5Hg7/2/


I can't see any obvious glaring bugs, but I can make a few suggestions to improve your initial baby steps, namely

Varying length arrays

Take your learning a step further and make the functions take arrays of varying lengths and see if your implementation still works. From the looks of it, it should still work without being heavily modified.

Generic array

I am not too familiar with Rust, but if it supports generics, then why don't you make the function generic so that it can take any two arrays of the same data type and merge them.

Conclusion

That is all. The code didn't really have a lot of ways things can go wrong because of the fixed size of the arrays. But you did a good job with the merge function which is what I think you were going for in the first place. See if you can implement the two suggestions above, then create another post


It's an Apache config file. It isn't going to look pretty. :)

That being said, I don't understand why you have RewriteCond specified for any of these rules. What is that condition preventing? The rewritten URL's are not causing redirect, so it is not clear to me when you would ever run into the condition of having "code" as a query string parameter.

These conditions really don't make sense for case when you are adding trailing slashes, and if you truly are getting query strings in these trailing slash use cases, you are effectively stripping the query string out of the redirect as you are not using QSA flag.

You should consider using R=301 flag instead of just R for these trailing slash redirect use cases in order to signal to the client that this is permanent location for the resource that is to be used.

I personally find it easier to read through rewrite logic and have that logic to be less error prone if all redirects are handled first in the file, followed by more complex rewrite logic.

Finally, if your app keeps growing in complexity to where you have more of these redirect rules being added, you might consider simply moving to more of a front controller model where you evaluate the URI in PHP and route within your application accordingly.


Password generator + storage console app

There is no particular need for this to be a class. While the reading of the file and the writing of the file are coupled, IMO this is not yet enough to make it into a class.

What is especially confusing is that you use members even for local variables which are not needed in the other methods.

Now, first, your reading of the file can be greatly simplified:

def read_password_file(file_name="passwords.txt"):
    with open(file_name) as f:
        return {key: password for key, password in map(str.split, f)}

This also allows using a different file than the default. It uses a dictionary comprehension and the fact that files are iterable.

The generation of the random passwords should be separate from the CLI interface (in case you want to change one without the other). The generation itself can also be simplified by using the string module:

import random
from string import ascii_lowercase, ascii_uppercase, digits, punctuation

ALLOWED_CHARS = ascii_lowercase + ascii_uppercase + digits + punctuation

def generate_random_pass_word(length=14, allowed_chars=ALLOWED_CHARS):
    return "".join(random.choices(allowed_chars, k=length))

This uses the random.choices function introduced in Python 3.6.

Your saving and retrieving from the passwords dictionary can become this:

import hashlib

def get_key(name):
    return hashlib.md5(name.encode('utf-8')).hexdigest()

def save_password(passwords, password, file_name="passwords.txt"):
    if password is None:
        print('First generate a password')
        return
    print('to save the generated pass word give it a name')
    name = get_key(input())
    if name in passwords:
        print('your key password already exists!')
    else:
        with open(file_name, 'a') as f:
            f.write(f"{name} {password}\n")
        passwords[name] = password
        print('password stored')

def read_password(passwords):
    print('to read the generated pass word type its name')
    name = get_key(input())
    if names in passwords:
        print(passwords[name])
    else:
        print('we are sorry your password is non existent')

Note that I call your self.myPass what it is, a simple name. It is not really a password (you could look it up in the file and use a rainbow table to get the cleartext) and even the context of having to think of a good password to store your good password seems ridiculous (do you use this password generation function to generate this password? What password do you use to store that password?).

I also used the new f-string (Python 3.6+) to simplify the writing to the file.

And finally, your main function, which has the user interface:

def main():
    pass, action = None, None
    passwords = read_password_file()

    print('perform one of the actions')
    while action != 'break':
        action = input('new action please\n')
        if action == 'generate':
            print('determine your generated password length, We recommend above 14 characters')
            length = int(input())
            pass = generate_random_pass_word(length)
            print('generated:', pass)
        elif action == 'read':
            read_password(passwords)
        elif action == 'save':
            save_password(passwords, pass)
        else:
            print(action + 'is not a valid action')

if __name__ == "__main__":
    main()
    print('fin')

Note that I put the calling of main under a if __name__ == "__main__": guard to allow importing from this script from another script.


How many ways we can make the change of the amount using the coins given

Got it working faster! Here's my updated code. I was able to use DP and memoize.

static int calculatePossibleCombinations(int pos, int amount)
{
    if(amount == 0)
    {
        return 1;
    }

    if(pos < coins.length)
    {
        int ways = 0;
        int remainingAmount= 0;
        String key = pos + "-" + amount;

        if(memoizeMap.containsKey(key)) {
            return memoizeMap.get(key);
        }

        while(remainingAmount <= amount)
        {
            ways = ways + calculatePossibleCombinations(pos+1, amount- remainingAmount);
            remainingAmount = remainingAmount + coins[pos];
        }
        memoizeMap.put(key, ways);
        return ways;
    }
    return 0;
}


Iteratively generating permutations with repetitions

I think a first problem is that m should be changed to m-1. Or maybe better you should change it so that the lines "i=0;" are changed to "i=1;" instead, and also initializing the vector with 1 instead of 0.

By what I understand a permutation does not necessarily contain each number at least once. So we just need to generate all possible vectors of length \$n\$ with elements in the set \$ \{1,2,\dots, m\}\$.

Your method is the same thing I would do, except I would not use pop_back and instead I would just modify the elements in place (although this is really a small change):

vector <vector <int> > genperms(int n,int m) {
    vector <vector<int>> perms;
    vector <int> curr(n,1);
    perms.push_back(curr);
    while(true){
        int change = 0;
        for(int i=n-1;i>=0;i--){
            if(curr[i] < m){
                curr[i]++;
                for(int j=i+1;j<n;j++){
                    curr[j] = 1;
                }
                change = 1;
                perms.push_back(curr);
                break; //try to change again
            }
        }
        if(change == 0) break; //if we couldnt make a change we are done
    }
    return perms;
}

This modification seems to give like an 8% boost in speed in my computer (using the n=8,m=8 case) . Although probably one can get better improvements if a vector is changed for something else.

If you want to speed this up you can also reserve the outer "perms" vector to a large enough size.


Are fetchAll() and for() good choices for my code?

Using fetchAll usually is not a problem. There are some things to optimize here in my opinion:

Use a foreach loop instead of for loop. Your result is already limited. No need to duplicate this here. This removes the iterator counter and assignment:

foreach ($products as $product) {
    $text1 = $product[0];
    $time1 = $product[1];
?>

Using the Object fetch mode (returns objects instead of indexed arrays) makes this even more readable and saves you the name assignments:

foreach ($products as $product) {
     // $product->text1; $product->time1;
?>

Though I'd recommend to remove these. Introducing numbers in variable names usually suggests there is a second one. E.g. time2.
As @mat's mug pointed out, indentation is very important. Same goes for empty lines. There are great to structure your code in logical blocks. For this example here, I'd have an empty line after setting up the cache and one after loading the products.


Allow UITextView to resize as the user is typing

It can actually be a lot simpler!

UITextView is a UIScrollView where by default the contentSize updates to fit whatever text is in the current view.

Assuming that you have constraints set up (e.g. pinning left, top, and right anchors so that the height is free to grow) then it's as simple as overriding the default value of isScrollEnabled and setting it to false.

You could do that either in your storyboard, or in your text view subclass.

I would suggest moving any logic you have around animating size of the text view out of the view controller and bundle it into your text view subclass.

Assuming that your constraints are set up in the storyboard, your view controller (at this point) doesn't need to have anything:

import UIKit

class ViewController: UIViewController {

}

Your text view subclass should have everything it needs to do to animate it's height change, and keeping the code there will make your view controllers more lightweight, and your TextViewAutoHeight more reusable in different scenarios.

Your current code doesn't actually animate the height so it's off-topic for /CodeReview, so I suggest searching stack overflow for questions around "UIView animate with duration", and perhaps reposting here when you have working code ready for review.

import UIKit

class TextViewAutoHeight: UITextView {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        isScrollEnabled = false
        NotificationCenter.default.addObserver(self, selector: #selector(updateHeight), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
    }

    func updateHeight() {
        // trigger your animation here

        /*
        var newFrame = frame

        let fixedWidth = frame.size.width
        let newSize = sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))

        newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
        self.frame = newFrame
        */

        // suggest searching stackoverflow for "uiview animatewithduration" for frame-based animation
        // or "animate change in intrinisic size" to learn about a more elgant solution :)
    }
}


Extending Exception: avoiding code duplication

Naming:

ResponseParser doesn't actually parse a response. Parsing a response would mean taking some response object and extracting data from it. This class does the opposite - given some data, it generates HTTP response.

Separation of concerns:

Exception classes are aware of how to output themselves as HTTP response. Would be better to structure things the other way around: passing the exception object to ResponseParser that generates the HTTP response.

Side-effects:

parseResponse() outputs HTTP headers and returns JSON. It's confusing when function has a return value and it also generates some output. I would it to expect to also output the JSON as the response, or returning both headers data and JSON without causing any side-effects.


First off, Jean-François is absolutely right: you cannot assume any particular bit widths for the built-in types, short, int, long, etc. Use the types defined in stdint.h that have explicit bit widths to ensure that the code is correct and portable.
Otherwise, your code looks pretty good, and this is a reasonable implementation. But…

Is this a good way to implement the macros or is there a better way?

There is indeed a better way: to use inline functions rather than macros. :-)
After an optimizing compiler finishes, the resulting code will be equivalent, but the advantages of functions are numerous: type safety, the ability to use expressions as arguments, no insidious parenthesization bugs, etc.
You will still need some preprocessor magic to avoid generating code when it is not necessary, but this is still much cleaner than implementing the whole header as a mess of macros.

Define a couple of inline helper functions that do the conversion, like so:
inline uint16_t Reverse16(uint16_t value)
{
    return (((value & 0x00FF) << 8) |
            ((value & 0xFF00) >> 8));
}

inline uint32_t Reverse32(uint32_t value)
{
    return (((value & 0x000000FF) << 24) |
            ((value & 0x0000FF00) <<  8) |
            ((value & 0x00FF0000) >>  8) |
            ((value & 0xFF000000) >> 24));
}

Although it is not strictly necessary, I have kept your explicit masking because I think it increases the clarity of the code, both for human readers and for the compiler. Others may feel that simpler is better. For example, Reverse16 could simply be implemented as return ((value << 8) | (value >> 8));.

However, I've chosen to format your code slightly differently for nice vertical alignment. I think this makes it easier to read, and easier to audit for correctness at a glance.

On most compilers, there are byte-swapping intrinsics that you could have used to implement the body of these functions. For example, GNU compilers (including GCC and Clang) have __bswap_32 and __bswap_16 macros in the <byteswap.h> header, and Microsoft's compiler offers the _byteswap_ushort and _byteswap_ulong intrinsics in the <intrin.h> header.
While intrinsics can often result in better code than writing out the C code long-form, all compilers I tested here are exceptionally smart: GCC, Clang, and ICC all recognize the bit-twiddling code used above and compile it to identical object code as if we had used the intrinsic—a single BSWAP instruction on the x86 architecture! Microsoft's compiler makes this optimization for the 32-bit version, but not for the 16-bit version. However, its output either way is still perfectly reasonable, and if you're seeking portable code, there is no compelling interest in using the intrinsics. For once, you don't need them to get optimal code!

Now that we have those helper functions, we need to define some more inline functions that work like your macros, except that the conditional logic will be encapsulated within the body of the functions, rather than surrounding the macro definitions.
Naturally, since these are functions, not macros, we'll use a different (title-case) naming convention. We don't need SCREAMING_CASE because they're not scary anymore:
inline uint16_t LittleEndian16(uint16_t value)
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
    return value;
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
    return Reverse16(value);
#else
#    error unsupported endianness
#endif
}

inline uint16_t BigEndian16(uint16_t value)
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
    return Reverse16(value);
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
    return value;
#else
#    error unsupported endianness
#endif
}

inline uint32_t LittleEndian32(uint32_t value)
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
    return value;
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
    return Reverse32(value);
#else
#    error unsupported endianness
#endif
}

inline uint32_t BigEndian32(uint32_t value)
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
    return Reverse32(value);
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
    return value;
#else
#    error unsupported endianness
#endif
}

The complete code is slightly longer than the macro-based version, but the safety and other benefits of functions more than justify this expanded length. The compiler doesn't care, and it only takes a few minutes longer to write. You will more than make up for it later in the time you don't have to spend debugging macros used in expressions.
You'll use them in basically the same way as the macros. Instead of LITTLE_ENDIAN_SHORT(value), you'd call LittleEndian16(value). Note that I've also used the explicit bit-width in the function's names, instead of the ambiguous short and long type names.


Generating DNA sequences and looking for correlations

One word: numpy.

A few more words:

numpy is a library that includes highly-tuned algorithms (often in Fortran, C, and C++) specifically for the purposes of accelerating numerical computations over matrices and other arrays. If it's at all applicable to what you're trying to do, it's almost certainly the best answer. Even when numpy itself isn't appropriate, look at the other components of scipy (the larger project it's part of).

At the moment, the numpy site seems to be down, and the scipy site seems to be responding but broken. The docs wiki is working, at least. (Please don't take this as an indication that numpy is some fly-by-night project; almost everyone who does numerical or scientific computing in Python relies on it. I'm sure it'll be fixed shortly.)

However, there are other possibilities for other use cases:

Analyze your algorithms and make sure the problem isn't what you're doing, rather than how you're doing it. There's no point making everything 30% faster, or even 95%, when the real problem is that you're doing 1000000 loops instead of 1000.
Profile your code, and don't worry about the parts that aren't slow or aren't called often.
Whenever it's possible to use a built-in function, even if it's a bit more awkward, it's often faster. (For example, sticking an iterator in a collections.deque of size 0 is at least 30% faster than any pure-Python way of walking and disposing the iterator.)
Cython gives you a way to write almost-Python code that gets compiled into C (and then into binary code).
You can port (bits of) your code to C explicitly.
Sometimes just running in PyPy (or maybe Jython or IronPython) instead of the normal CPython makes a big difference.
Replace explicit lists with generators, and explicit list-building loops that can't be replaced by generators with list comprehensions.
If you need that last 2%, there are all kinds of tricks, like rebinding members of objects to local variables, that aren't always more trouble than they're worth.

A couple more words on Cython:

The first step to accelerating some slow critical code with Cython is just to move it as-is into Cython. If that doesn't help enough, try adding explicit types to variables and turning function definitions from def into cdef. If that's still not enough, then you have to actually learn how to use Cython effectively—but you may get enough win that you don't even have to understand why it's helping. (Although obviously you should learn anyway.)


Filter shell script to find lines that contain all specified patterns

join is the name of a common Unix command, so using that name for your function could create confusion.

I don't recommend munging the patterns to dynamically write an awk program.  As you pointed out, your technique is vulnerable to injection, resulting in execution of arbitrary awk code.  Instead, I'd write a fixed awk script that does the job.

#!/usr/bin/env awk -f

BEGIN {
    # Treat command-line arguments as patterns rather than input filenames.
    for (i = 1; i < ARGC; i++) {
        patterns[i - 1] = ARGV[i];
    }
    # Truncate argument list, so that awk always read from standard input.
    ARGC = 1;
}

{
    for (i in patterns) {
        if (!match($0, patterns[i])) {
            next;
        }
    }
    print;
}

To search for literal strings instead of regular expressions, use the index(haystack, needle) function instead of match(haystack, needle).


Selecting names with two consecutive, same letters

The outer for loop can be replaced with a foreach loop: foreach (var name in names). It removes the need for two counter variables, and simplifies indexing of the array, making the code easier to read.
This method would be more flexible if it accepted a single string and returned a boolean: bool HasRepeatingLetters(string str). That allows you to use it for single names as well as for multiple names.
For multiple names, the above method can easily be combined with Linq: var matchingNames = names.Where(name => HasRepeatingLetters(name)).ToArray() (you can remove the ToArray (or ToList) call if you want lazy evaluation). In this case, you don't even need an anonymous function, because the signature of HasRepeatingLetters already matches what Where requires: names.Where(HasRepeatingLetters).
Keep in mind that ToLower is culture-dependent (not all languages use the same upper/lowercase conversion rules). You may want to give your function an extra (optional) CultureInfo argument to control its behavior.
Performance of your function should be O(n), not O(n^2). Passing in twice as many strings, or strings that are twice as long, requires twice as much work, not four times as much. It would only be O(n^2) if, for example, you compared each string against every other string.
Calling ToLower on the given string would simplify your code, and it should be a bit faster too for names without repeating characters. You could also keep your for loop, but store the previous lower-cased character as you go, so you don't need to convert it to lower-case twice. That would make the code a little more complicated, so it's probably not worth the hassle. Of course, if performance is important, you should actually measure it.


Average interval between dates with random blanks

One thing that stands right out is formatting cells in each iteration of a loop. Less to do within each iteration should speed things up just a bit so why not just format the entire column after the loop has done all the calculations?

I am not sure sure if you are working with more than one workbook or if that's part of an automated process but

Set CurrentSheet = ActiveWorkbook.ActiveSheet
LastRow = CurrentSheet.Range("A" & Rows.Count).End(xlUp).Row - 1
LastCol = CurrentSheet.Cells(4, Columns.Count).End(xlToLeft).Column

seems like a bit of an overkill. You are not using the CurrentSheet (pascal case vs camel case you know) anywhere in the code but you don't quality the Cells. Why not just:

lastRow = Range("A" & Rows.Count).End(xlUp).Row - 1
lastCol = Cells(4, Columns.Count).End(xlToLeft).Column

Have you heard of offsets? Experience taught me that it's easier to maintain offsets rather than +1s +2s etc.

Cells(CurrentRow, LastCol + 1).Value = DateTtl / DateCount

=

Cells(currentRow, lastCol).Offset(0,1) = DateTtl / DateCount


How Does This Naive Stack Implementation Look?

The mechanical usage of the struct seems correct, but I'm having some conceptual issues with the original code.

First, the Stack structure models a single element instead of the entire structure. I find this weird, and it makes it impossible to implement custom protocols for the stack abstraction. Your module seems to partially abstract stack elements, and partially the entire stack structure.

Second, what is the purpose of key/value? Stack should work on arbitrary elements. What is in those elements should be left to the client of the structure, and not hardcoded as a requirement of theStack module.

Then, function push/3 accepts the abstraction as the last argument. This is contrary to the recommended conventions (subject as the first argument), and makes it impossible to use the abstraction with pipe operator |>.

Even if the last issue was fixed, pipes still won't work since push returns the result in format of {:ok, ...}. This is not needed, especially since there is no possible error outcome.

Notice that this doesn't hold for pop, which must return two values: last element pushed, and the modified structure (a stack containing remaining elements).

Disregarding the fact that stack really doesn't require an abstraction (Elixir list is already a stack), here's my take on it:

defmodule Stack do
  defstruct elements: []

  def new, do: %Stack{}

  def push(stack, element) do
    %Stack{stack | elements: [element | stack.elements]}
  end

  def pop(%Stack{elements: []}), do: raise("Stack is empty!")
  def pop(%Stack{elements: [top | rest]}) do
    {top, %Stack{elements: rest}}
  end

  def depth(%Stack{elements: elements}), do: length(elements)
end

This can then be used as:

iex(1)> Stack.new |> Stack.push(1) |> Stack.push(2) |> Stack.pop
{2, %Stack{elements: [1]}}


Optimize code for sending collected data to a database

Functional approach

For simplicity you can create few helper functions to get rid of code duplication:

getValuesFromPost(array $list): gets list of parameters names and
returns according POST values.
composeFieldListSql(array $list): gets list of fields and returns SQL expression of fields list like 'ComputerName', 'usage_0', 'usage_10'
composeValuesListSql(array $list): gets list of values and returns SQL expression of escaped values list like 'PC', 'value1', 'value2'
composeInsertSql(array $fields, array $values): composes full insert SQL expression from fields and values lists.

Functions composeFieldListSql() and composeValuesListSql() could be declared inside function composeInsertSql() since you don't need to use them elsewhere.

Your code will look like this:

$fields = ['ComputerName', 'usage_0', 'usage_10', 'usage_20', 'usage_30', 'usage_40', 'usage_50', 'usage_60', 'usage_70', 'usage_80', 'usage_90', 'users', 'OrderDate'];
$sql = composeInsertSql($fields, getValuesFromPost($fields));
mysqli_query($cxn, $sql);

Object oriented approach

Basically you could write wrapper class for mysqli extension functions to encapsulate low level interactions with extension and to make interaction with database more abstract. Also, it will be easy to change inner working of wrapper, if for example you will decide to change database type.

Or you can use one of many existent wrappers, which are already covered by tests and have rich functionality.


Bad variable names. dollars and cents would be more appropriate that firsthalf and secondhalf... I mean, c'mon, these variables don't represent "halfs" of anything. float isn't very descriptive either. Perhaps rawvalue would be better, and maybe result_buffer would be better than answer.
The entire code for whole numbers is unnecessary. When you run toFixed() on a whole number it becomes a float (string) anyway.
Rather than creating a new variable and arbitrarily swapping between let and const, why not just reassign float (or in my version, raw_value). You won't need it anymore after that anyway.
You might wanna consider casting it to a float in case a string is passed to the function, in which case your toFixed would fail.
It doesn't make a hue difference whether you declare your variables at the top or as needed when you're working on a small function, but be consistent. And if you do declare them all at the top, I would suggest doing it in a single statement for a small performance boost. In this case, I would personally just declare them as you go to keep the function concise.
When you're doing a backwards loop like that you don't need all three statements in the for loop. You could just do for (let i = firstHalf.length; i--;). That said, looping backwards and then reversing (or looping at all for that matter) makes for smelly code. You can just use a little regular expression to chunk the chars up: /.{1,3}/g
Don't reassign a variable just to return it, just return it. It's less work for the computer that way.

const moneyFormat = (raw_value) => {
  raw_value = parseFloat(raw_value).toFixed(2).split('.');
  let dollars = raw_value[0],
    cents = '.' + raw_value[1],
    format_buffer = dollars
      .split('').reverse().join('') // reverse it
      .match(/.{1,3}/g) // chunk it
      .map(c=>c.split('').reverse().join(''))
      .reverse(); // reverse it again
  return format_buffer.join(' ') + cents;
}

console.log(moneyFormat(2310000.159897)); // '2 310 000.16'
console.log(moneyFormat(1600)); // '1 600.00'
console.log(moneyFormat("1600"));
console.log(moneyFormat("234123.2134123"));


Avoiding "warning: Use of uninitialized value" when fetching an integer CGI parameter

Standard practice is to scope variables using my.

Since Perl 5.10, the preferred way to write this is to use the logical defined-or operator to provide a default value when undef is encountered.

my $param_page = int(param('page') // 1);


Create release package from git tag with Powershell

You should put [CmdletBinding()] before the param block. This gives you some nice features.

I changed $checkForNewTagsOnly to be of type switch rather than string. You can call the script like this MyScript -checkForNewTagsOnly or MyScript -checkForNewTagsOnly:$false. I think that is better because otherwise how are people supposed to know to supply a "Y" as a parameter?

I made the tag parameter mandatory (Mandatory=$true) so that you won't need to check for it later.

By the way, I think you should start these parameters start with a capital letter. That is the convention.

[CmdletBinding()]
param(
    [Parameter(Mandatory=$true, HelpMessage="Enter the tag.")]
    [string] $tag,
    [string] $gitURI = "https://github.com/jquery/jquery.git",
    [switch] $checkForNewTagsOnly = $true #if yes then it will exit if the folder already exists
)

We use $checkForNewTagsOnly like this now that it is a boolean:

if ($checkForNewTagsOnly) {
    # ...
}

We can get rid of this line altogether now that tag is mandatory:

if([string]::IsNullOrWhiteSpace($tag)){($tag = Read-Host "Enter the tag")}

It's generally better to use Write-Output rather than Write-Host because you can't pipe Write-Host output. You couldn't for instance write it to a log.

Write-Host "$tag checked out, running clean up on $Currentlocation"

Please be consistent with your formatting. Why do you have FOREACH in caps? I find the inconsistency of your formatting in general to be extremely triggering to my OCD. It's best to stick to conventional formatting. That makes it easier for people to read.

FOREACH ($Item IN $ToDelete) {
    FOREACH ($File IN (Get-ChildItem -recurse | Where-Object {$_.name -like "$Item"})) {

-Filter is faster than -Include. I don't know if that's an issue here or not, but it's something to be aware of. You used -Filter earlier, by the way.

Get-ChildItem -Include .git -recurse -force | remove-item -force -recurse


The two loops are necessary:
to know the max value, you need to make one complete pass.
There's no way around it.
Only after you know the max value,
after checking all items,
you need a second pass to set the height to the max.

In terms of writing style,
there isn't really a standard,
and it may be a matter of taste,
but in any case I prefer this way:

var maxHeight = -1;
var elems = document.getElementsByClassName("features");

for (var i = 0; i < elems.length; i++) {
    maxHeight = maxHeight > elems[i].offsetHeight ? maxHeight : elems[i].offsetHeight;
}

for (var i = 0; i < elems.length; i++) {
    elems[i].style.height = maxHeight + "px";
}


Performance

You didn't post the mysqli_get_value code, but I would assume that it interacts with the database. Is this call really necessary? You don't seem to use the result. But if you do need it somewhere else: couldn't you just retrieve the id in the initial query?

Have you tried storing the path to an image in the database instead of storing the whole image?

As to your main query: ORDER BY RAND() is quite slow. Check out this question for faster solutions to select random rows from a big table. If you google for mysql select random values from table you should find a lot more results as well (for example here).

Also, do captcha_images and captcha_objects really need to be different tables? I don't know your whole db schema, but it seems that it could all go into the same table, thus saving you a join.

Misc

a line length of 323 characters is way too long, it will not fit on any screen. I would aim for 80 (maybe 120).
use curly braces, even for one-line statements (for readability and to prevent bugs).
use spaces around . (I think that it really helps with readability).


Asks the user to input 10 integers, and then prints the largest odd number

Here are a couple of places you might make your code more concise:

First, lines 2-11 take a lot of space, and you repeat these values again below when you assign list1. You might instead consider trying to combine these lines into one step. A list comprehension might allow you to perform these two actions in one step:

>>> def my_solution():
    numbers = [input('Enter a value: ') for i in range(10)]

A second list comprehension might further narrow down your results by removing even values:

    odds = [y for y in numbers if y % 2 != 0]

You could then see if your list contains any values. If it does not, no odd values were in your list. Otherwise, you could find the max of the values that remain in your list, which should all be odd:

    if odds:
        return max(odds)
    else:
        return 'All declared variables have even values.'

In total, then, you might use the following as a starting point for refining your code:

>>> def my_solution():
        numbers = [input('Enter a value: ') for i in range(10)]
        odds = [y for y in numbers if y % 2 != 0]
        if odds:
            return max(odds)
        else:
            return 'All declared variables have even values.'

>>> my_solution()
Enter a value: 10
Enter a value: 101
Enter a value: 48
Enter a value: 589
Enter a value: 96
Enter a value: 74
Enter a value: 945
Enter a value: 6
Enter a value: 3
Enter a value: 96
945


Implementation of OOP for retrieving list of objects from database

Very few things in life are free. C# default constructors are one of those, the compiler generates one automatically for you if your class doesn't explicitly have one! So unless you have another constructor (with parameters) and you also need a parameterless one, putting it in is just clutter.

Encapsulating database operations in a dedicated object (like you're doing with your People class), vs doing it all in a static method, is a step forward in the right direction.. but I don't see what the peoples property is trying to encapsulate.

Think of classes as abstractions - you have a Person abstraction which represents a single record in your database. Then you have a People abstraction which represents an object that can manipulate Person records. That's all nice and tidy and high-level - you don't want to mix this niceness with boilerplate-level SQL connections and queries. Doing that is writing code at the wrong level of abstraction.

So the next step forward would be to create another class that's responsible for dealing with these things - a type that would deal with setting up a connection, running a query and then disposing the connection and every other IDiposable along the way.

Once you've done that, you will (hopefully) realize you've just reinvented the wheel - and that your wheel is more than likely square. At this stage it's all good, the worst thing you could do is start with an Entity Data Model that does it all for you: you want to understand what's going on, if it feels automagic then you've skipped something.

So first (well, after you've written your square wheel!) take a look at Linq to SQL and see what a DataContext can do for you.


My opinion is that for simple tasks like in your situation, you should not complicate your XAML. Wrapping a StackPanel around two TextBlock-elements is still pretty clean.

Extracting the code and wrapping it in your own control where you would set the Label and Content surely is an option. But if this only to be done once, I think you're overdoing it. Only when you have to place the same code there a lot of times, your XAML will be cleaner using your own control.


I see a number of things wrong with this implementation:

First, You already have a CommuteData entity. Why are you using it to go back to the database to retrieve a property that's already on it (ie: commuteData.CommuteDataId)? This makes me very suspicious of any calling code (you may want to post a use case for clarity).

That point aside, if there's a possibility that the method will be unable to return, it should throw an exception if an invalid state is encountered, or not return a number that is invalid (ie: 0).

To combat this, you could go with one of these patterns:

// Throw an exception if there is no applicable CommuteDataId but one
// is always expected to be available when calling this method:
public static int GetCommuteDataId(CommuteData commuteData)
{
    ...
    // Tell EF that you only expect one and only one result.
    return something.Single()
}

// Return null if there is no applicable CommuteDataId...
public static int? GetCommuteDataId(CommuteData commuteData)

// Return true if commuteDataId contains a valid Id.
public static bool TryGetCommuteDataId(CommuteData commuteData, out commuteDataId)

The property names you're using are also very confusing. What's the difference between CommuteData.id and CommuteData.CommuteDataID? Furthermore, the casing of your properties are not consistent: id, CommuteDataID, SurveyId.

This code is also very suspicious:

commuteDataID = Convert.ToInt32(item.ToString());

It would appear that you are converting an int to a string, then back to an int. If it's not an int, the method should return it in it's true form instead of doing any misleading conversion that the caller has no idea about.

Lastly, you're pulling back too much information from the database. SQL (and thus EF) can return exactly what you want in a single call.

public static int? GetCommuteDataID(int commuteDataId)
{
    using (var db = new CarbonContext())
    {
        return db.CommuteDatas
                 .Where(cd => cd.id == commuteDataId)
                 .Select(cd => (int?)cd.CommuteDataID)
                 .SingleOrDefault();
    }
}

The updated example above still has several problems with it, but hopefully it illustrates some of the points I was trying to make.

UPDATE:

Your updated function is almost there, but there are still some things wrong/misleading about it:

public static int GetCommuteDataID(int? id, int surveyID, int surveyYear)

Why is id nullable here? This implies that either:

If id isn't provided, surveyId and surveyYear are enough to produce a unique result (otherwise you wouldn't be returning a single int).
id can be used along with surveyId and surveyYear to produce a unique result even when it's null (unlikely).

Next:

.Where(cd => cd.id == id &&
    cd.SurveyID == surveyID &&
    cd.SurveyYear == surveyYear)

Again, are you sure this is the criteria you want to use to ensure uniqueness? Why would id exist if it wasn't unique?

.Select(cd => (int)cd.CommuteDataID)
.SingleOrDefault();

Lastly, if CommuteDataID is already an int there's no need to cast it to one. SingleOrDefault has three outcomes:

The query produces no result: The default value for the type of query is returned. When you Select an int, the default value is 0 because that's the default value for an int. I was casting to int? in my example so it would return null (the default for int?) when no value was found.
The query produces one result: The result is used.
The query produces multiple results: An exception is thrown because it was expected that only 0 or 1 results would be returned based on the filters you provided.

If your inputs should produce one and only one result, then you should use Single(), which will throw an exception if 0 or multiple results are returned by the query. All of this would imply that your method arguments were enough to produce a single result which doesn't seem to be the case.


With something as lightweight as this, I don't think you are going to see any appreciable difference in javascript-based performance between plain Javascript and jQuery.  Now, downloading 7MB images is going to be relatively slow regardless as to whether you use javascript or jQUery, and my guess is that there is really no reason you should be loading images that size ever, unless you needed user to be able to zoom in on super high-quality images such that you need lots of pixels to support this.

The #1 thing you should do here, which could help performance to some extent, is to cache your jQuery collection results to variables.

There is no reason, for example that you should be querying $(".content"), $(".download-link"), etc. over and over again like you are doing.  This requires querying against the DOM (which is more expensive when querying by class than by ID because you must traverse the entire DOM) every single time.

Instead you should do something like this:

$(document).ready(function () {
    var $liPlaceholder = $('.li-placeholder');
    var $content = $('.content');
    var $downloadLink = $('.download-link');
    var $imgModal = $('.imgmodal');
    // and so on..

    // and then use these collections later on
    $('.prev-btn').on('click', function () {
        var current = $liPlaceholder.find("li.active");
        // etc.
    });
});

I think you have way too much code around traversing the collection for your prev/next buttons, along with a lot of repeated code for setting/removing active class and content/download link properties. I don't think you need to be looking for the active item at all.  Consider this code:

$(document).ready(function () {
    var $slides = $('.li-placeholder li');
    var $content = $('.content');
    var $downloadLink = $('.download-link');
    // default slide index to display on page load
    var slideIdx = 0;

    $('.prev-button').on('click', function() {
        slideIdx--;
        if(slideIdx < 0) {
            slideIdx = $slides.length - 1;
        }
        showSlide(slideIdx);
    });

    $('.next-button').on('click', function() {
        slideIdx++;
        if(slideIdx === $slides.length) {
            slideIdx = 0;
        }
        showSlide(slideIdx);
    });

    function showSlide(idx) {
        $slides.removeClass('active');
        var $current = $slides.eq(idx);
        var src = $current.attr('src');
        $current.addClass('active');
        $content.attr('src', src);
        $downloadLink.attr('href', src);
    }

   // set initial slide
   showSlide(slideIdx);
}

I am not exactly sure what the exam-file-span handler is doing without being able to see the code, but just looking at the way you are traversing the DOM and performing selectors here would make me think there is improvement to be had here as well.

$(".li-placeholder").html(clone);

You really should not be using html() method (which expects string) as means to inject a cloned DOM node into DOM.  You should really you append() here.

$liPlaceholder.append(clone);

You have some fundamental problems with your javascript that you should address:

If you are going to use semicolons to separate lines of code (as most writing javascript do, though it is optional), you need to be 100% consistent about it.  You have a few spots where you are missing the semicolon to terminate the line.
You are not properly initializing your variables using var (or let/const if in more modern versions of javascript).  You really need to get into this habit if you don't your code to work unexpectedly.
You are indenting your code inconsistently.
Every single one of your else statements in this code is avoidable.  You should get into the good habit of learning how to design else conditions away when possible.  The fewer parallel code paths you have in your code, the less complex (and therefore easier to test and easier to maintain) it will be.


To answer your comment, yes there are equivalent of PEP8 in java. I suggest checkstyle, this plugin works in lots of IDE / text editors and can be configured with your code style.

Code review

reverse_string method

In java, we try to use the upper-case version of Snake case only on constants / enums. For the methods and variables, I suggest that you use the Camel case style.

Before

private static String reverse_string(String my_string)
{
   //[..]
}

After

private static String reverseString(String myString)
{
   //[..]
}

When concatenating String in a loop, it's generally recommended to use a java.lang.StringBuilder to gain performance and take fewer operations.

private static String reverseString(String myString)
{
   StringBuilder reversedString = new StringBuilder();

   for (int j = myString.length() - 1; j >= 0; j--)
   {
      reversedString.append(myString.charAt(j));
   }

   return reversedString.toString();
}

If you want not to use it, then I suggest the += operator instead of the +; it will give the same result and make the code shorter.

Other observations

The code was missing a bit of formatting, but nothing too important, I sugest that you pick a formatter for your style (Horstmann style) depending on your IDE / text editor.

Refactored code

private static String reverseString(String myString)
{
   String reversedString = "";

   for (int j = myString.length() - 1; j >= 0; j--)
   {
      reversedString += myString.charAt(j);
   }

   return reversedString;
}

public static void main(String[] args)
{
   System.out.print("Insert a 'String': ");

   Scanner input = new Scanner(System.in);
   String userString = input.nextLine().toLowerCase().replace(" ", "");

   if (userString.equals(reverseString(userString)))
   {
      System.out.println("It is a palindrome.");
   }
   else
   {
      System.out.println("It is not a palindrome.");
   }
}


You should avoid while (true) { … } loops wherever it is possible to do so.  Here, it's very obviously avoidable!

while ("0123456789.".Contains((char)dataStream.Peek()))
{
    …
}

This parser leaves much to be desired in terms of handling

negative numbers (or you should document the fact that they are unsupported)
e notation for powers of ten
overflow and small numbers, due to excessive multiplying and dividing by powers of ten

Personally, I would avoid the entire headache by appending all plausible-looking characters to a StringBuilder, then calling double.Parse(string).


Replace string of class of button by class so that only one button is filled in using bootstrap buttons

Here's how I refactored your code:

$(document).ready(function () {

    $(".canvas_btn").on("click", function () {

        var idOfClickedElem = $(this).attr('id');
        $.each($('.canvas_btn'), function () {
            if (idOfClickedElem === $(this).attr('id')) {
                $(this).attr('class', getFilledClassName($(this).attr('class')))
            }
            else {
                $(this).attr('class', getOutlineClassName($(this).attr('class')))
            }
        });

    });

    function getOutlineClassName(currentClasses) {
        return currentClasses.replace("btn-outline-", "btn-").replace("btn-", "btn-outline-")
    }

    function getFilledClassName(currentClasses) {
        return currentClasses.replace("btn-outline", "btn")
    }

});

Instead of mixing jQuery and regular JavaScript selectors, I just used jQuery. I'm not a huge fan of the contents of getOutlineClassName(currentClasses) and getFilledClassName(currentClasses), but it's certainly less code than the way I probably would have written it if I had done so from scratch -- which would be to make a switch on the element's id and return the correct classes as a string accordingly.


"math.h" should be <cmath>.  The brackets are for system libraries whereas the quotes are for user-defined headers.  The .h ending is mostly for C.
You don't actually need return 0 at the end of main().  It will do this same return for you at the very end.
You should consider input validation, at least if you decide to expand on this outside of the class.  You could even allow the user the option to input via the command line, making this a bit more convenient.
You don't need those last two comments since they're already obvious.  Only use them where explanation is needed for you and/or the reader.
Consider having the calculation done in a function for better maintainability:

// add this to better explain that value
const int loan_term = 12;

double calculateMortgagePayment(int loan, double interest_rate)
{
    return (loan * interest_rate) / (1 - pow(1 + interest_rate, -loan_term));
}

int main()
{
    // ...

    // could also be const since value shouldn't change later
    const double mortgagePayment = calculateMortgagePayment(loan, interest_rate);

    // ...
}

I've taken into account@Conduit's advice regarding variable names.  I've also kept the double return type, which isn't really ideal for money.  There are resources online that explain more about that.


Using strings in themselves to determine the MeasurementType isn't the biggest problem, but you really don't need to create classes and subclasses and stuff for this.

Instead, use an enum!

public enum MeasurementType {
    DENSITY, ACCELERATION;
}

In this case you can use this code to grab the MeasurementType:

String type = ...;
MeasurementType mType = MeasurementType.valueOf(type.toLowerCase());

Note however that this will throw an exception if the type is not found. So instead, you might want to consider using a Map<String, MeasurementType> where you add all known MeasurementTypes (preferably in a static initializer block), or you can loop through MeasurementType.values() and scan for the one with the right name.

Also remember that enums can have methods, implement interfaces, override methods, and contain fields.

As I'm not sure what your ultimate goal is, here's an example of what an enum can do:

public enum MeasurementType {
    DENSITY("test"),
    ACCELERATION("test2") {
        @Override
        public int transform(int value) {
            return 0;
        }
    },
    SOMETHING_ELSE("test3")
    ;

    private final String test;

    private MeasurementType(String test) {
        this.test = test;
    }

    public int transform(int value) {
        return value;
    }
}


boiler :: ReadP Boiler
boiler
  =   Hobbyist <$ char 'H'
  <|> Locomotive <$ char 'L'
  <|> flip Boiler <$ char 'B'
    <*> (HighPressure <$ char 'H' <|> LowPressure <$ char 'L')
    <*> ((,,) <$ char '-'
      <*> (read <$> munch1 isDigit) <* char 'x'
      <*> (read <$> munch1 isDigit) <* char 'x'
      <*> (read <$> munch1 isDigit))

By changing the internal definition of Boiler you can clean up that flip.

By also changing the user interface you can use the Read instance deriver:

data Boiler = H | L | BL Int Int Int | BH Int Int Int deriving (Read, Show)

Your example would then look like BH 3 3 4.

By the way, whereever you're using the Eq instance of Tank, consider pattern matching instead.


static, and possibly public

I'd recommend having this method outside your binary tree class itself. It can operate on a binary tree, but it's not a method that requires to be specified directly inside the binary tree. Also, it doesn't use any state other than what is passed through its parameters. As such, I would make it static and probably also public.

First call

It's currently a bit weird to call this method from the start, the parentValue parameter is used for further recursions, but what value should it be passed originally? Considering this problem, I'd separate this method into a public part and a private part, such as:

public static <E extends Comparable<E>> E maximumElement(TreeNode<E> root) {
     return maximumElement(root, root.element);
}

private static <E extends Comparable<E>> E maximumElement(TreeNode<E> root, E parentValue) {
     ...
}

General stuff

It's good practice to always use braces. It improves readability and reduces the risk of bugs.
Using early returns helps reduce indentation and makes it more apparent how special cases are handled (otherwise you have to scroll down to make sure that the value isn't changed)

Rewritten version with some additional formatting improvements:

private static <E extends Comparable<E>> E maximumElement(TreeNode<E> root, E parentValue) {
    if (root == null) {
        return parentValue;
    }
    E max = root.element;
    E leftMax = maximumElement(root.left, max);
    E rightMax = maximumElement(root.right, max);
    if (rightMax.compareTo(max) > 0) {
        max = rightMax;
    }
    if (leftMax.compareTo(max) > 0) {
        max = leftMax;
    }
    return max;
}

If you want to remove the parentValue parameter, you would need to introduce a null check:

public static <E extends Comparable<E>> E maximumElement(TreeNode<E> root) {
    if (root == null) {
        throw new IllegalArgumentException("root cannot be null");
    }
    E max = root.element;
    if (root.left != null) {
        E leftMax = maximumElement(root.left);
        if (leftMax.compareTo(max) > 0) {
            max = leftMax;
        }
    }
    if (root.right != null) {
        E rightMax = maximumElement(root.right);
        if (rightMax.compareTo(max) > 0) {
            max = rightMax;
        }
    }
    return max;
}

This repeated != null checks and everything inside can be extracted to a method

private static <E extends Comparable<E>> E maxMaximum(E current, TreeNode<E> other) {
    if (other != null) {
        E otherMax = maximumElement(other);
        if (otherMax.compareTo(current) > 0) {
            return otherMax;
        }
    }
    return current;
}

Which leads to:

public static <E extends Comparable<E>> E maximumElement(TreeNode<E> root) {
    if (root == null) {
        throw new IllegalArgumentException("root cannot be null");
    }
    E max = root.element;
    max = maxMaximum(max, root.left);
    max = maxMaximum(max, root.right);
    return max;
}


Implementing binary output to a file in C++11

I would not write an adapter for a stream.
But rather a stream manipulator.

Try this:

#include <ostream>

// The object that does all the work.
class BBoolWrapper
{
    std::ostream&          str;
    mutable std::size_t    position;
    mutable std::bitset<sizeof(unsigned long) * CHAR_BIT> data;

    public:
        BBoolWrapper(std::ostream& str)
            : str(str)
            , position(0)
        {}
        ~BBoolWrapper()
        {
            // If there is data to be flushed when we destroy the
            // object then make sure it goes on the stream.
            flush();
        }

        // Testing state.
        bool empty() const      { return position == 0;}
        bool full() const       { return position == data.size();}

        // Just the way I do it.
        // You can add bits any way you like one at a time.
        void addBit(bool nextbit) const
        {
            data <<= 1;
            data[0] = nextbit;
            ++position;
            if (full())
            {
                flush();
            }
        }

        // Simple Flush to the stream (if there is any data).
        void flush() const
        {
            if (!empty())
            {
                unsigned long value = data.to_ulong();
                str.write(reinterpret_cast<char*>(&value), sizeof(unsigned long));
                position  = 0;
            }
        }

    // The interesting part.
    // If we have an object like this and a bool using the `<<` operator
    // Then add the bit and return this object so we are chaining the
    // `<<` operations.
    friend BBoolWrapper const& operator<<(BBoolWrapper const& stream, bool nextbit)
    {
        stream.addBit(nextbit);
        return stream;
    }

    // If we use any other type with `<<` operator then flush this object.
    // Return the underlying stream object to get back to normal stream
    // operations.
    template<typename T>
    friend std::ostream& operator<<(BBoolWrapper const& stream, T const& val)
    {
        stream.flush();
        return stream.str << val;
    }
};

// A simple empty class to start the streaming of bits
// via the above wrapper class.
struct BBool
{
    friend BBoolWrapper operator<<(std::ostream& stream, BBool const&)
    {
        return BBoolWrapper(stream);
    }
};

Example:

#include <iostream>
#include <ifstream>

int main()
{

    // Use the BBool() object on a stream to turn binary mode on.
    // It stays on until you add a non boolean object to the chain. (like "\n")
    std::ofstream log("log");
    log       << BBool() << false << true << false << false << false << false << false << true << "\n";
    std::cout << BBool() << false << true << false << false << false << false << false << true << "\n";
}


Naming

res, res1, res2? These names convey absolutely no meaning. flag? Sounds like some sort of boolean value to me; but you assign it a list. i, z? one-letter variable names are essentially used for integer indices, not characters or… what is z already… oh, a list.

Even morph sounds badly chosen, I’m laking a bit of context here to fully understand it, I guess, but I would have used origin_string or something alike.

Control flow

if len(flag) > 0:
    for z in flag:
        # do something

is twice as much complicate than it should be. Once because if len(flag) > 0 can be written if flag: empty container are considered False in a boolean context. And once again because the if is not needed: for z in flag will be a no-op if flag is an empty container.

Also, since you’re not modifying morph and the only thing you store in flag (if any) is [morph.rindex('ken'), ['k','e','n']], why not get rid of flag and directly use that list in the last part of your computation?

def char_filter(morph):
    char_dict = {'d': 'D', 't': 'D', 'a': 'A', 'e': 'A', 'ı': 'H', 'i': 'H', 'u': 'H', 'C': 'C', 'g': 'G', 'k': 'G'}
    res = []
    res1 = []

    for i in morph:
        res2 = i
        if i in char_dict:
            res2 = i.upper()
        res1.append(res2)

    if 'ken' in morph:
        i = morph.rindex('ken')
        res1[i:i+3] = ['k','e','n']
    res.append(string.join(res1, sep=''))
    return res[0]

Data structures

Most of the data structures you use are not suited to your needs. Why storing only one string as the first item of res if you extract it right after having assigned it. Store the string directly in res intead of res[0]. Better: do not use res and return the string right after building it, you’re not making any other use of res anyway:

return ''.join(res1)

Also note the prefered syntax for join which is an operator of the separator string.

You’re also building a dictionary in char_dict but never using the values stored into it, only checking for the existence of keys. Two possibilities:

either you have a bug and need to use res2 = char_dict[i] instead of res2 = i.upper();
or you just need to simplify the data structure and only store the characters that you want to test against. A list, a string or a set are better fit for this task.

I will consider the second option.

The last thing to note is that this collection will not be changed between calls so we can safely define it outside of the function to avoid building a new one each time we call char_filter.

A little bit on pythonic constructs

some_list = []
for variable in some_collection:
    value = some_function(variable)
    some_list.append(value)

Is better written with a list-comprehension: more readable and faster.

some_list = [some_function(variable) for variable in some_collection]

Proposed improvements

SPECIAL_CHARS = 'dtaeıiuCgk'

def char_filter(origin_string):
    filtered_letters = [char.upper() if char in SPECIAL_CHARS else char
                        for char in origin_string]

    if 'ken' in origin_string:
        i = origin_string.rindex('ken')
        filtered_letters[i:i+3] = ['k','e','n']

    return ''.join(filtered_letters)


Here:

if len(mslist) < 2:

I would write len(mslist) <= 1 because 1 is the interesting number here.

Here:

int(len(mslist)/2)

just write len(mslist)//2 which is explicit integer division.

Here:

            result.append(left[0])
            left.pop(0)

you can write result.append(left.pop()) since pop returns the element removed.

The elifs in the merge function are not properly aligned.

Notice that the use of the pop method could alter algorithm complexity (because I think that pop is \$O(n)\$). It could be better to use two indices to keep track of the position in the two lists.


Is this HTML structure and CSS DRY enough in this country selection menu?

This should be an ul. Even without CSS you will have a navigational structure. How about giving your nav a better suited name like .nav-localization?

Also I guess the div's inside your links will act like as sub navigations? These would be ul's as well then.

I've added comments to get rid of the whitespace between the list-items, since you're using display: inline-block;. This looks quite dirty, but it's the best solution for the whitespace issue and inline-block.

Here is the markup, I'd go for:

            North America

            Europe

            Korea

How you would select:

.nav-localization {}

.nav-localization > li {}

.nav-localization > li > a {}

.nav-localization .sub-nav {}


The switch has a bad reputation and is usually seen as a code smell.

In your case, I would first propose to replace the strings by one enum so that you have strong typing, you avoid typos errors and your Ide can warn you if you miss a case in your switch. By the way, it is a good practice to have a default case to handle and spot the unexpected cases (I usually throw a UnsupportedOperationException or IllegalArgumentException). You should of course avoid to have some MVC part into your AuthenticationService but that is a job for the adapters and his friends.

If you really want to remove this switch (I wish) then the idea is to use polymorphism. Basically, your AuthenticationService should return a subtype of a basic result class (LoginSuccess, LoginFailed) where the view name will be defined or computed.

About your controller itself, you should use @Autowired for Environment and AuthenticationService. Also note that Spring discourage the usage of autowired fields outside of tests classes.