JavaScript calculator with two inputs and four operations

To get the ball rolling, a few things that come to mind:
JavaScript
Storing DOM-elements
In getInputs and showOuput you use document.getElementById to get the same DOM elements over and over again. You can simply store or "cache" them in variable an re-use them anytime you want:
var inputX = document.getElementById('x'),
    inputY = document.getElementById('y'),
    output = document.getElementById('output');

showOutput which seems to have an unused value in its signature, would now look like:
var showOutput = function(value) {
    output.innerHTML = value;
}

Filter input
getInputs already uses parseInt to filter the user's input. This will still result in NaN for all inputs that can't be parsed to integer, like "hey".
You should test for this scenario and give the user a hint that something failed:
var operation = function(operationName) {
    var x = getInputs(inputX),
        y = getInputs(inputY);

    if (isNaN(x) || isNaN(y)) {
        // show an error message or give the inputs a red border etc.
        return;
    }

    // […]
};

By the way, your calculator doesn't make it clear, that it can only process integer values, which might lead to confusing results with inputs like this:

1.5 + 2.5 = 3

Improve the UX and leave the visitor a note.
manuplateAs
I think you meant to call the function manipulate. But why don't you simply call it calculate?
You can also use a switch-statement and shorter variable names to increase readability:
var calculate = function(operation, x, y) {
    switch(operation) {
        case 'add': return x + y;
        case 'sub': return x - y;
        case 'mul': return x * y;
        case 'div': return x / y;
    };
}

Again your calculator doesn't handle edge cases. For example it will show Infinity for division by 0 or NaN if numbers get to big.
You could test the result for NaN or Infinity and show a proper message to the user:
var result = calculate('div', x, y);

if (!isFinite(result)) {
    // show an error message
    return;
}

HTML
<head>
Event though it's a very simply example, add these two things in your header:
<meta charset="UTF-8">
<title>Simple Calculator</title>

It makes sure that:

The correct character set is chosen.
The user can find the tab with the calculator more easily.

Form
You're using form elements that are not descendants of a form element, nor do you link them to a form using the form-attribute. That is invalid HTML. Simply wrap everything into a form:
<form>
    <input type="number" id="x">
    <input type="number" id="y">
</form>

A button is by default a submit button. You can change this by setting the type-attribute:
<button type="button" onclick="operation('add')">Add</button>

To further improve UX create labels to couple your text with a corresponding input. This also makes sure, that the input is focused as soon as a user clicks the label's text:
<label>
    First number
    <input type="number" id="x">
</label>

Or alternatively:
<label for="x">First number</label>
<input type="number" id="x">

Personally I wouldn't use a h1-element to output the result. Maybe a disabled input field works here, too.


Transform a vector with the FFI in Haskell

calloc can fail

We start with the C code first, since it's somewhat shorter. Aside from the name bar, we see one problem: calloc might return 0. Therefore, we should check that:

double* bar(int n, double *arr){
    double* y;
    y = (double*) calloc(n, sizeof(double));

    if(!y) {
      return 0;
    }

    for(int i=0; i<n; i++){
      y[i] = arr[i]+1;
    }
    return y;
}

Who frees the memory?

However, there is still one problem. A user needs to know how add_one conjured that memory in order to use the correct free variant. That's something that can be handled with documentation. Still, there is no need for us to call calloc, we can just give the responsibility to the user:

double* add_one(double * dest, const double * src, size_t count){
    for(size_t i = 0; i < count; ++i) {
      dest[i] = src[i] + 1;
    }
    return dest;
}

Note that this uses const to make sure that we don't overwrite  src by accident. We also use size_t to be ready for any kind of size the user might throw at us. The user is now responsible to allocate the memory, so they will also know how to free it.

We return the pointer because we followed memcpy's interface, but we could also just make it a void function instead.

Haskell part

Let's go to Haskell. We can see that there is something off: you import newForeignPtr, but you use newForeignPtr_. That's probably since newForeignPtr needs the aforementioned free function. That's in Foreign.Marshal.Alloc:

fptr <- newForeignPtr finalizerFree ptr

But before we delve into that, let us take a step back and look at the foreign import:

foreign import ccall "bar" c_bar :: CInt -> Ptr CDouble -> Ptr CDouble

Unfortunately, your c_bar does not have that type. Remember, whenever you see A -> B in a function, you should always get the same B if you've used the same A:

all (== foo a) [foo a,foo a,foo a,foo a,foo a] -- all the same

But that does not hold for your function. It has a side-effect: every call will return another Ptr CDouble. We have to put it in IO:

foreign import ccall "bar" c_bar :: CInt -> Ptr CDouble -> IO (Ptr CDouble)

Note that you can use the unsafe keyword here. It basically means that bar will never call any Haskell function and will stay in its C world. With this, we would end up with

haskellBar :: SV.Vector CDouble -> IO (SV.Vector CDouble)
haskellBar sv = do
    let n = SV.length sv
    ptr <- SV.unsafeWith sv (c_bar (fromIntegral n))
    fptr <- newForeignPtr finalizerFree ptr
    return $ SV.unsafeFromForeignPtr0 fptr n

Which does not differ from your variant too much.

The add_one variant is similar:

foreign import ccall unsafe "add_one" c_addOne :: Ptr CDouble -> Ptr CDouble -> CSize -> IO (Ptr CDouble)

It's in IO, it uses unsafe to be a little bit faster (but must not call Haskell from C), and it uses the correct types. It's wrapper is almost the same, but this time, we allocate the memory in Haskell:

addOne :: SV.Vector CDouble -> IO (SV.Vector CDouble)
addOne sv = do
   fptr <- mallocForeignPtrArray n
   SV.unsafeWith sv $ \v -> withForeignPtr fptr $ \f -> c_addOne f v (fromIntegral n)
   return $ SV.unsafeFromForeignPtr0 fptr n
 where
   n = SV.length sv

The mallocForeignPtrArray makes sure that the memory gets freed correctly.


Your constants should be in UPPER_SNAKE_CASE

MAX_COUNT = 200
WIDTH = img.size[0]
HEIGHT = img.size[1]

Instead of nested for loops, you can use itertools.product which basically will perform the nested iteration you need:

from itertools import product

for row, col in product(range(height), range(width))

You don't use str_output, you should clean up unused values.

You should have whitespace either side of your mathematical operators and have a space after each comma in a comma separated list of values:

(col - float(width) / 2.0) * 5.0 / float(width),
draw.point((col, row), fill=(255 - iteration, 255 - iteration, 255 - iteration))

You should also keep lines below 79 characters as the Python style guide dictates. You can split lines quite easily when they're in paretheses:

    draw.point((col, row), fill=(255 - iteration, 255 - iteration,
                                 255 - iteration))

Also your mileage may vary on whether or not this is more readable but you could use a ternary for your final if condition. Like this:

    draw.point((col, row), fill=("black" if abs(z) < 2 else
                                 (255 - iteration, 255 - iteration,
                                  255 - iteration))

The formatting is definitely more awkward, but I personally like these structures because it makes it clear that the only difference in the two results is that one condition.


So, I am going to answer you javascript question using python code because I think the concepts are identical and I was too lazy to make sure my javascript syntax was right.

A couple of ways to simplify your expression include:

Use a lookup table:

I find this implementation more intuitive and much easier to debug.

double_letter_cells = [
    #ABCDEFGHIJKLMNO
    '...1.......1...',  # 1
    '...............',  # 2
    '......1.1......',  # 3
    '1......1......1',  # 4
    '...............',  # 5
    '...............',  # 6
    '..1...1.1...1..',  # 7
    '...1.......1...',  # 8
    '..1...1.1...1..',  # 9
    '...............',  # 10
    '...............',  # 11
    '1......1......1',  # 12
    '......1.1......',  # 12
    '...............',  # 14
    '...1.......1...',  # 15
]

def checkDoubleLetterCell(row, col):
    return double_letter_cells[row][col] == '1'

Build some intermediate products:

If you really need the stacked logic, you can produce some intermediate products which are then much easier to verify and understand.

SCRABBLE_SIZE = 15
middle = int(SCRABBLE_SIZE / 2)

def checkDoubleLetterCell(row, col):
    one_off_middle_row = (row == middle - 1) or (row == middle + 1)
    one_off_middle_col = (col == middle - 1) or (col == middle + 1)
    outer_middle_row = (
        row == 0 or row == SCRABBLE_SIZE - 1 or row == middle)
    outer_middle_col = (
        col == 0 or col == SCRABBLE_SIZE - 1 or col == middle)

    middle_middle_row = row == middle + int(middle / 2) + 1 or \
                        row == middle - int(middle / 2) - 1
    middle_middle_col = col == middle + int(middle / 2) + 1 or \
                        col == middle - int(middle / 2) - 1

    middle_middle_plus_row = row == middle + int(middle / 2) + 2 or \
                             row == middle - int(middle / 2) - 2
    middle_middle_plus_col = col == middle + int(middle / 2) + 2 or \
                             col == middle - int(middle / 2) - 2

    return (
        one_off_middle_row and one_off_middle_col or
        outer_middle_row and middle_middle_col or
        outer_middle_col and middle_middle_row or
        one_off_middle_col and middle_middle_plus_row or
        one_off_middle_row and middle_middle_plus_col
    )

Test Code:

And for completeness, here is the code I used to test the above.

for i in range(SCRABBLE_SIZE):
    for j in range(SCRABBLE_SIZE):
        assert (double_letter_cells[i][j] == '1') \
               == checkDoubleLetterCell(i, j)


Why so slow

It's important to consider the time complexity of all the operations in your program.

Take a closer looks at this part I extracted from your code:

for(String s: strs)
{
 // ...

    pos.add(Arrays.asList(strs).indexOf(s));

For each s, converting a String[] to a List<String>, in order to use the indexOf method to find the index of s? That doesn't sound so good. How about making that a counting loop?

for (int i = 0; i < strs.length; i++) {
    // ...

    pos.add(i);

But why use indexes at all? Why not make this method return a Map<String, List<String>> instead?

for (String s : strs) {
    // ...

    pos.add(s);

If you do that, then the implementation of the other method becomes simply:

public List<List<String>> groupAnagrams(String[] strs) {
    return new ArrayList<>(createMap(strs).values());
}

Good practices

The code violates many good practices and common conventions:

Never use raw types, for example use HashMap<String, List<String>> instead of just HashMap without type parameters
Prefer to declare variables with interface types, for example Map<String, List<String>> instead of HashMap<String, List<String>>
Use the diamond operator <> when possible, for example new HashMap<> instead of new HashMap<String, List<String>>
Use consistent indentation, and please place braces they way I did in my examples above


Calling a FormatCurrency function on multiple textboses

You can loop through the elements using a for loop:

for(var i = 65; i <= 78; i++) {
    var box = document.getElementById("TextBox" + String.fromCharCode(i) + "_TextBox");
    box.value = FormatCurrency(box.value);
}


I think it would be worth explaining the terms you are using : what is a liar ? what is a witness ?

Except for that, the code is well presented and well tested (so many thanks for that).

Making code more simple in fermat_witness

You could easily rewrite fermat_witness: return pow(test_num, possible_prime-1) % possible_prime != 1.

Making code more simple in fermat_witness_liar_count

You could also rewrite fermat_witness_liar_count with less variables because you can get rid of liar_count by writing :

if witness_count != 0:
    return witness_count, temp_liar_count
return 0, 0

You can also get rid of temp_liar_count by writing :

witness_count = 0
for test_num in range(1, possible_prime):
    if fermat_witness(test_num, possible_prime):
        witness_count += 1
if witness_count != 0:
    return witness_count, possible_prime - witness_count - 1
return 0, 0

Then, you can use the fact that non-zero integers are considered as true values and try to write a single return:

return witness_count, possible_prime - witness_count - 1 if witness_count else 0

Finally, if you want to count, you can use sum and simply write :

witness_count = sum(1 for test_num in range(1, possible_prime)
    if fermat_witness(test_num, possible_prime))

The whole function becomes :

witness_count = sum(1 for test_num in range(1, possible_prime)
    if fermat_witness(test_num, possible_prime))

# When there are Fermat witnesses, all test_nums that arent are Fermat liars
return witness_count, possible_prime - witness_count - 1 if witness_count else 0

pow is a pow-erful builtin

pow handles what you are trying to do in a more efficient way :

  if z is present, return x to the power y, modulo z (computed more
  efficiently than pow(x, y) % z)

fermat_witness becomes :

return pow(test_num, possible_prime-1, possible_prime) != 1

Then, I guess more mathematical optimisations could be performed but I haven't tried at all.


Add 1 to an integer represented as an array of digits

Simpler implementation

You can simplify a lot the iteration through the digits. Resizing with an ArrayList would definitely be worse, as it's simply a wrapper of an array and you would need to box/unbox the ints to Integer.

This uses the same algorithm, but with less instructions and it will therefore be a bit faster:

public int[] plusOne(int[] digits) {
  int len = digits.length;
  if (len == 0)
    return digits;

  for (int i = len - 1; i >= 0; i--) {
    if (digits[i] == 9) {
      digits[i] = 0;
    } else {
      digits[i]++;
      return digits;
    }
  }

  return newArray(len + 1);
}

New array

In the case where we create a new array, we know that it will be filled by a 1 followed by all zeros. Since in Java all variables not explicitly initialized have their default values (0 in case of int), we can simply do:

private int[] newArray(int size) {
  int[] arr = new int[size];
  arr[0] = 1;
  return arr;
}

This will save us one read and one write for every position.

Benchmark

I did a test with JMH, comparing both solutions.

Parameters:

# Warmup: 5 iterations, 1 s each
# Measurement: 5 iterations, 1 s each
# Benchmark mode: Average time, time/op

Input data sets:

"mixed": Starts with {0,0,0,0,0,0,0,0,0,0}, and gets increased in every iteration;
"10000x9": It's an array composed of 10 000 '9's, like {9, 9, 9, 9, ...}. This is reset back to all-9s in every iteration.

Results:

Benchmark              Mode  Cnt      Score     Error  Units
Test.fill              avgt    5   1852.195 ▒ 101.178  ns/op
Test.new_10000x9       avgt    5   8793.836 ▒ 176.757  ns/op
Test.new_mix           avgt    5      3.957 ▒   0.040  ns/op
Test.original_10000x9  avgt    5  15761.188 ▒  46.132  ns/op
Test.original_mix      avgt    5      4.209 ▒   0.026  ns/op

The fill test case was just to figure out the approximate overhead of resetting the array to 9's in the 10000x9 tests. If we remove that time from the results of the 10000x9 test cases, we see that the new implementation is about twice as fast.


As suggested by @911992, why not moving that "logic" into the database. Not as a function/stored-procedure/view but as a combination of all your queries :
SELECT * FROM items WHERE name=? AND country_code=? AND currencyCode=?
UNION
SELECT * FROM items WHERE name=? AND country_code='US' AND currencyCode=?
UNION
SELECT * FROM items WHERE name=? AND country_code=? AND currencyCode='USD'
UNION
SELECT * FROM items WHERE name=? AND country_code=?
UNION
SELECT * FROM items WHERE name=? AND currencyCode=?

You can limit that query to one row to avoid too much results.
If want to keep everything into the code and are looking for a design pattern, you can search for the chain of responsibility.


Helper function to solve Project Euler question 26

I'm just going to comment on your gcd function.

The docstring mixes up the function's interface ("computes gcd of a, b") with its implementation ("using Euclidean algorithm"). It's best to restrict the docstring to the interface (which is what the user needs to know); if you also need to document the implementation, put it in comments.
Your gcd implementation returns None if its arguments are not integers. This behaviour should be mentioned in the docstring.
But returning exceptional values is generally a bad idea: it pushes the complexity of error handling onto the caller, where it would be easy to forget to do the checking. And in fact you have failed to check that the result is not None:

g = gcd(abs_p, abs_q)
p = abs_p / g   # What if g is None here?

It is better for a function to raise an exception if it is given the wrong arguments: that way the caller doesn't need to take any special precautions, but the error is reliably detected and reported.
The test isinstance(a, int) is too restrictive. Euclid's GCD algorithm will work on other kinds of numbers too, and it would be nice to be able to support:

>>> from fractions import Fraction
>>> gcd(Fraction(1, 3), Fraction(1,4))
Fraction(1, 12)

or:

>>> from decimal import Decimal
>>> gcd(Decimal('11.1'), Decimal('2.1'))
Decimal('0.3')

instead of having to write separate gcd implementations for these other types.

So in fact the best thing to do is not to have any type-checking at all in your gcd function. If someone calls it with the wrong type of object, they will get a TypeError:

>>> gcd('hello', 'world')
Traceback (most recent call last):
    ...
TypeError: not all arguments converted during string formatting

You call abs on the arguments a and b. But in fact you only ever call gcd with arguments that have non-negative values already. So the extra calls to abs are wasted.
So in summary, I would write the gcd function like this:

def gcd(a, b):
    """Return the greatest common divisor of a and b."""
    while b != 0:
        a, b = b, a % b
    return a

But in fact Python already has a built-in gcd function (in the fractions module), so all you actually have to do is write:

from fractions import gcd


One MAJOR problems here.

char sent[20] = "";

Don't use global variables. Globally mutable state makes your code hard to debug/test and generally behave correctly. You not only need to know what a function does but also what external state the function depends on. Pass all state into functions via the parameters (that way you know exactly what it depends on).

Note: Global constants are fine.

This is not a valid declaration of main() even in C

void main()

/* TRY */

int main(void)
/* OR */
int main(int argc, char* argv[])

Lets declare and initialize variables on the same line:

   StackNode *stackTop;
   stackTop = NULL;

   /* Try */
   StackNode *stackTop = NULL;

Note if you correct main you will also need to correct the return statement so it returns a value.

   return;

But when the function is void there seems little point in putting a return statement.

OK. This reads a line.

void insertData(StackNode **stackTop)

But there are already functions that do that.
You can use the scanf series of commands. Your code drops any non alphabetic characters (but you could read a line then post processes to remove and invalid characters).

You should read up on the functions for handling characters.

isalpha()       /* Note it is locale aware and thus will return true
                   for characters other than a-z A-Z if your locale is
                   not set to the default (which is C)
                 */

tolower()       /* Lowercases letters. No affect on anything else */

I would have done:

char  data[50]; /* You wanted a max of 20 letters.
                   But if the user types a space between every word
                   it can get longer and we post processes to remove
                   space so. So we will cut off at 50.
                */

fscanf(stdin, "%50[^\n]", data); /* read upto 50 characters
                                    that are not '\n'
                                    into data
                                 */
fscanf(stdin, "%*[^\n]");        /* Read the rest of the line if
                                    the user types more than 50 and
                                    throw it away
                                 */
fscanf(stdin, "\n");             /* Read the '\n' off the input */

/* Now remove any non letter characters and lowercase at the same time */
int removed = 0;
for(int loop = 0; data[loop]; ++loop)
{
    if (!isalpha(data[loop]))
    {
        removed++;
        continue;       // starts next iteration.
    }
    data[loop-removed] = tolower(data[loop]);
}
data[loop-removed] = '\0';  /* Add string terminator */

Back to reviewing your version.

This is going to enter an infinite loop if you hit an error or end of file before you hit '\n'.

    while( ( ( c = getchar() ) != '\n'))

Then end of file is a real possibility if somebody pipes a file into your command from the command line.

    cat file | ./palindromeCommand

This check:

        if( ( ( c>='a' &&c<='z') || (c>='A' && c<='Z')))

Is really covered by: isalpha()

This check:

            if((c>='A' && c<='Z'))
            {
                int rem;
                rem = c-'A';
                c='a' + rem;
            }

Is the same as:  c = tolower(c);

This string append:

            len = strlen(sent);
            sent[len++]=c;
            sent[len]='\0';

Can be achieved with: strncat(sent, &c, 1);

Normally I don't want checking functions to mutate the state of any objects. The name "check" implies I am looking not modifying.

void checkData(StackNode **stackTop)

Also you are mixing business logic and presentation logic into a single function. Make this function check to see if it a palindrome and return an appropriate value (0 for false and non zero for true (for example)). The code can then use this function to check for a palindrome and take appropriate action (like display text) in the display logic:

Initialize and declare in the same line:

    StackNode *pNew;
    pNew = *stackTop;

    /* Easier to read as */
    StackNode *pNew = *stackTop;

Overall I think you overcomplicated the processes with your StackNode concept. But it works. It would have been much simpler to use pointers to either end of the sent array and work towards the middle checking letters.

int checkForPalindrome(char* sent, int length)
{
     char*    st   = sent;
     char*    ed   = sent + length - 1;

     int   result = true;

     while(st < ed && result)
     {
         if (*st != *ed) { result = false;}
         ++st;
         --ed;
     }
     return result;
}


Implementing widgets within a main window

While there is no hard and fast rule, it seems to make code more readable and modular (i.e., Pythonic) to have a separate class for something that is effectively a new Qt widget. This is especially true if there is any chance that new widget might be something you want to break out and use in another project.

See the example labelledwidgets.py from Chapter 11 of Summerfield's book.


Messy formatting

The first thing I noticed about this script is the messy formatting.
Poorly formatted code is hard to read and maintain.

Extract complex conditions to helper functions

The code has many complex conditions.
It would be more readable if you extracted them into helper functions.

For example, instead of this:

  if [[ $proxy =~ ^https:// && $proxy =~ :[0-9]{1,5}$ ]]; then
    # ...

You could introduce this helper function:

isHttpsWithPort() {
  [[ $proxy =~ ^https:// && $proxy =~ :[0-9]{1,5}$ ]]
}

And then use it with:

if isHttpsWithPort; then
  # ...

I recommend to change all complex conditions like that,
and the code will be more readable,
thanks to self-explanatory names of the functions.

Make yesno return success or failure

After calling the yesno function you check the value of REPLY.
This is not very ergonomic.
You could make yesno return success for "yes" and failure for "no":

yesno() {
  while read -n1 -r -p "[y/n/QUIT] > "; do
    case $REPLY in
      y) return 0;;
      n) return 1;;
      q) echo; echo; exit 1;;
      *) printf "\nERROR - Invalid response, please enter Yes OR No.\n";;
    esac
  done
}

When written this way,
instead of this:

    yesno
    if [[ $REPLY == "n" ]]; then
      startover
    fi

You could simplify to:

yesno || startover

Similarly, instead of this:

  yesno
  if [[ $REPLY == "y" ]]; then

You could write:

if yesno; then

Loop not looping

The main while loop doesn't actually loop, so it should be removed:

while true; do
  # ...
  break
done


Coding style

There is an official coding style guide for Python called PEP8. Give it a good read and follow it. For example, the most glaring violations:

Spacing around operators: instead of v=v+j[2], write as v = v + j[2]
For function names, snake_case is preferred over camelCase
Put exactly two blank lines before each function definition

Coding practices

Don't put code in the global namespace, put inside a function.
This protects you from bad practices like using global variables, whether intentionally or by accident.

For example, you could move all the code current code in the global namespace inside a main function:

def main():
    fig = plt.figure()
    ax = plt.axes(projection='3d')
    P = [(0, 0, 0), (2, 0, 0), (2, 2, 0), (0, 2, 0), (0, 2, 2), (2, 2, 2), (0, 0, 2)]
    F = [[0, 1, 2, 3], [2, 3, 4, 5], [0, 3, 4, 6]]
    # ...

And call the main function like this:

if __name__ == '__main__':
    main()

Avoid unused imports:

import numpy as np

Naming

The biggest issue with this code is the naming of variables.
You're overusing single-letter or very short variable names,
and it's hard to guess what is what without searching for where they come from and how they are used.

Simplify

You have many expressions that can be simplified, for example:

# instead of: v = v + j[2]
v += j[2]

# instead of: v = v / 4.
v /= 4.


Calling a function from a dynamically loaded DLL

Short answer: No, but I won't hold it against you. ;)

I'd suggest reading up on using C++ with DLLs in a compatible fashion, and would suggest this excellent article as a good place to start. This article also touches on exporting STL types, which your code is doing.

So, the question is, how portable/robust do you need/expect your approach to be? If you need developers from anywhere to be able to plug into your system, stick to a C interface if possible (avoiding STL types -- pass a char** across the boundary, and convert that on the C++ side to an STL vector<string>). Otherwise, upgrade to a virtual class based system -- and make sure that you don't directly use STL, but instead use virtual class wrappers for those types as well. Note that this carries on -- e.g., if you want to use an iterator class used by the STL type you're wrapping, you'll need another abstract (iterator) class that your abstract (iterable) class references, so it can get a little ugly.

Minor code notes...

fFreeResult is assigned, but never used.
fRunTimeLinkSuccess is not set (after initialization).
The "convert" string might better be contained in a macro (or a small set of macros), so that your plugin clients can declare a convert function, and you can refer to that function name without the possibility of typo.
Your example plugin refers to argc and argv that don't exist.


Dijkstra implementation for large graphs

Don't use QT objects when you are not working with QT constructs. There is no benefit to it.
Your node::_id is unsigned shirt, which for MSVS has a range of 0 to 65,535. Be aware of that when you graph grows.
Do not use a map. A std::vector is way faster/bettter for traversing than a std::map.
You do a lot of copying data around:

QMap<Node*, unsigned short> nextNodes = minNode->nextNodes();

That is a copy of all neighbors everytime you access a node during your search. If you really need the temporary, which you dont then at least make this a reference.


Exposing a web API wrapper library to consumers

What you're looking for is actually the factory pattern.

Your implementation could be something like

public class YahooFinanceFactory{

   public IYahooFinanceQuotes GetQuotes()
   {
     return new YahooFinanceQuotesConreteImplementation();
   }

[...]

}

The concrete implementations are still marked as internal so they are not exposed.

Alternatively, you could use reflection for this.

public static T ResolveConcreteType<T>()
{
    return (from t in Assembly.GetExecutingAssembly().GetTypes()
            where t.GetInterfaces().Contains(typeof(T))
            && t.IsClass //Find the classes that implement the interface we want
            select (T)Activator.CreateInstance(t, null))
        .SingleOrDefault();

}

Usage:

var quotes = YahooFinanceFactory.ResolveConcreteType<IYahooQuotes>();

This makes the assumption that your concrete types support empty constructors however.


Count number of square integers in a given range of ints (faster function?)

You are correct that your solution is O(n). However, there is a possible solution for O(1). If you find the root of the first square (first) and the last square (last), then all of the numbers between first and last will yield squares in the range.
function numSquares(min,max) {
    const first = Math.ceil(Math.sqrt(min));
    const last = Math.floor(Math.sqrt(max));
    return last-first+1;
}

console.log(numSquares(465868129, 988379794));


Exercism: clean and format a phone number in Clojure

I'm still learning clojure, but I'll contribute what I can.

I don't know if it is prefered or not, but if you wanted to get rid of the let, you could do something like (apply (partial format "(%s) %s-%s") trio) or (apply format (concat '["(%s) %s-%s"] trio)) instead.
Naming seems ok.
No comment.
I don't know.
Your regex for parts is suboptimal.  '.' will pick up any character, but you really only want digits.  Something like "^1?(\d{3})(\d{3})(\d{4})$" would be more accurate.


In general, your code is very well written. PEP8 compliance is very good, names make sense, you have docstrings, you use if __name__ == '__main__:.

Here's a few comments on what I would do differently:

# Get table
try:
    table = soup.find('table')
except AttributeError as e:
    print 'No tables found, exiting'
    return 1

# Get rows
try:
    rows = table.find_all('tr')
except AttributeError as e:
    print 'No table rows found, exiting'
    return 1

This is essentially the same code duplicated twice. The fact that you differentiate between not finding a table and not finding rows within it is nice, but ultimately useless, as a table with nothing in it might as well be no table at all.

Therefore, I propose changing it to detect a valid table, that is one with rows. This tidies up the code a bit like so:

try:
    table = soup.find('table')
    rows = table.find_all('tr')
except AttributeError as e:
    raise ValueError("No valid table found")

You'll notice I eliminated the print and the return 1. Errors should be errors, they shouldn't magically become print statements. The only exception to this is if this is supposed to be for end users, then you will want to retain the print. Secondly, sys.exit() is unnecessary as the script will end automatically when it reaches the end of the file. Therefore, all the return 1's are unnecessary and are extra fluff.

Lastly, let's talk about your comments. Most of them are useless.

# Make soup

Is that really the best description? You are retrieving a url and reading the HTML. THAT should be your comment.

# Get table

# Get rows

As I said, I think these two can be wonderfully merged. Also, I'm pretty sure the names are more than sufficient to understand that you are retrieving the table and the rows of the table.

# Get data
table_data = parse_rows(rows)

Hmm... what else could table_data be? This is a comment that seems pretty useless and adds un-needed fluff.

# Print data

This one I actually think should be more descriptive, such as:

# Print table data

As indicated in the comments, it is suggested that you remove all of your comments, as they are largely plain fluff considering your naming is so well done.

Another last thing to note is that

if args.url:

Is a completely useless check. It is guaranteed that args.url will always exist as per how the argparse module functions. If you made the url an optional parameter, that would be a different story, but then your program would be useless.


more elegant way when call parent method with the same name

Two ways to rewrite it:

When you know which version of the method you want to call you can name it directly, but in that case need to pass self as an argument:

    return Formatter.resp_in_hash(self, content)

Not necessarily more elegant.

Python 3 introduced a new cleaner super format for the common case when you want to step up from the current class and pass self (the first argument):

    return super().resp_in_hash(content)

This only works in python 3, though.


Guessing a number, but comments concerning

Welcome to the hell of comments, and personal taste. There are multiple answers to your core question that may be right:

You have not commented enough.
You have commented all the wrong things.
You have commented too much.
Your comments are in the wrong format.
You are missing the formal comments.

To be clear though, nothing we can say will be in line with what your marks are based on, unless you can tell us why you were marked down... ;-)

About Comments in general
OK, comments are supposed to make plain what the code does not tell us already.
Let me say that again.

Comments are supposed to make plain what the code does not tell us already.

Now, whether you are marked on that, or not, is a different story. I have found that the academic application of marks for comments is often contrary to the need for comments... particularly when the code is good code.
Good code seldom needs comments.
Let me say that again:

Good code seldom needs comments.

So, follow this logic through, and then follow the inverse back...

Comments make plain what the code does not tell us already.
Good code seldom needs comments.

thus....

Good code seldom needs comments.
Good code must make plain what the code does without the need for additional explanation.

Applied to your code
Let's start at the top....

import java.util.*; //so I can use scanner

Now, if your code was:
import java.util.Scanner;

then it would not need the comment.
Your next comment is here:

  int max = 100; //sets limit on the random number generator

Well, that is, actually, not a horrible comment, or code. But, it could be better, if we gave it a decent name:
int randomGeneratorLimit = 100;

It would be even better if we made that magic number a constant:
private static final int RANDOM_GENERATOR_LIMIT = 100;

Now, no need for a comment at all.
Next up, this line:

  while (play) { //so game will restart after a win

Well, this one is interesting.... the comment is actually needed here because of the loop you are using.
If you convert this to a do-while loop, and use some functional extraction... then you can convert your code to a self-documenting, commentless block:
private static boolean playAgain() {
    System.out.print("Do you want to play again? ");
    String answer = input.nextLine();
    char firstLetter = answer.charAt(0);
    return firstLetter == 'y' || firstLetter == 'Y';
}

then you can use that function as follows:
do {

    ....... // game logic

} while (playAgain());

No need for a comment (or a play variable).
Similarly, you have the code:

     //so user can continue guessing until correct
     boolean win = false;
     while (!win) {

This should be a do-while as well, and should look like:
do {
     ..... // game logic
} while (guess != numberToGuess);

Again, that makes the logic clear, no need for a comment.
I believe that has now eliminated all of your comments..... and replaced them with code that does not need a comment, because the code is self-explanatory.
In other news, if you had more functions, with good names, then your code would be simpler to read as well.
Bottom line, though, is that the comments in your code should fill in the blanks that your code does not. In addition, your comments should give details on the motivation, and not the application of your code. You should, in general, comment only on why your code does things, not what your code is doing.
That leads on to the other comments you are missing... JavaDoc.
JavaDoc is documentation that should explain what your code does at an abstract level.
You have no JavaDoc, and you likely should. JavaDoc is where you describe what your code does, because, typically, the people reading the javadoc are not reading the code, so they need something else to tell them what the code does.


Testing whether to launch debugger based on build & command line arguments

Use #if Debug. It will be a lot more expected to have to remove/disable that than to change the if and remember to remove the then-dead GetDebugData method. (Principle of Least Astonishment, right?)
Don't specify STAThread. It's just useless. First, it would be extremely surprising if someone tries to use multithreading 10 years down the road and it failed. Second, it doesn't provide any significant overhead (if any at all) to not use this. Finally, console apps run single-threaded by default. There is no excuse to disable multi-threading in the whole app. There is excuse to disable multi-threading in parts that can't be multi-threaded because of whatever (maybe it calls into code running on a STA thread), but those instances can be handled on a case-by-case basis with explanation in comments.

Now, assuming for some reason I haven't comprehended, you absolutely have to use this.

You are defining whether a build is a "debug" or "release" based on whether the code is optimized. That has nothing to do with Visual Studio's definition (and therefore the standard definition) of what a "debug" or "release" build is. That and the output paths are the only changes I can think of off-hand between the default "debug" and "release" candidates. However, you could define a "debug" build as one compiled against C# 7.2 and a "release" build as one compiled against C# 6 and leave optimization on or off in both for whatever reason. I wouldn't use the terminology "debug" vs. "release" here; I'd just check whether debug symbols were enabled when I determined whether to kick off the debugger.
If you change what I suggest above, I'd recommend renaming DebugOutput to just Output and assigning it whether the code is optimized or not. I can compile as None, Full, Pdb-Only, Portable, or Embedded with JIT-optimization enabled anyway.


Producer and Consumer

You properly synchronize on the sharedList.
Both Producer and Consumer fail to use the proper wait() idiom to guard against spurious wake up.

Producer waits until the list is empty :

while(!sharedList.isEmpty())
    sharedList.wait();

Consumer waits until the list is not empty :

while(sharedList.isEmpty())
    sharedList.wait();

Given that both wait on the same monitor with a different condition you must use notifyAll() instead of notify() :

  Single notify can be used instead of notifyAllonly when both of the
  following conditions hold:

  Uniform waiters. Only one condition predicate is associated with the condition queue, and each thread executes the same logic upon
  re-turning from wait
  One-in, one-out. A notification on the condition variable enables at most one thread to proceed.

(from Java Concurrency in Practice)
You set the threads in motion, but you have no way of stopping them. Consider using interruption for this.

Check the interrupted flag in your loop condition :

while (!Thread.currentThread().isInterrupted())

Properly deal with InterruptedException by restoring the interrupted state so the interruption is not lost.

Call Thread.interrupt() in the catch block :

} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}

I assume this is some sort of exercise. Typically to connect producers and consumers you would use a blocking bounded queue.

Latstly : while println() gives you some nice output, it can give you a false sense of thread safety, as it does synchronisation under the hood, and in doing so introduces memory boundaries that may hide problems with your code, that will surface once you substitute them with actual production code.

WaterCooler

There is no reason to make list volatile. It is never reassigned. In fact it would be better to mark it final, to make sure this never happens.
Creating a thread, and starting it, gives you little control over it. (how will you stop them?)


From what I understand, you want to make sure that new objects are not created when they are identical to what has been created before.

This is relatively easy, and would include either having a static map or a map inside another object, such as a ReflectionFactory. I'd personally go with ReflectionFactory as I don't like static things when you can avoid them.

Here's an example factory:

public class ReflexionFactory {
    private final Map<Integer, Reflexion> map = new HashMap<>();

    public ReflexionFactory() {
       for (boolean x : tf) {
            for (boolean y : tf) {
                for (boolean z : tf) {
                    Reflexion refl = new Reflexion(this, x, y, z);
                    map.put(refl.getKey(), refl);
                }
            }
        }
    }

    private Reflexion getReflection(int value) {
        return map.get(value);
    }

    Reflexion get(boolean x, boolean y, boolean z) {
        int value = 0;
        if (x) value += 1;
        if (y) value += 2;
        if (z) value += 4;
        return get(value);
    }

    public Set<Reflexion> all(Reflexion r) {
        ...
        for (boolean x : tf) {
            for (boolean y : tf) {
                for (boolean z : tf) {
                    out.add(this.get(x, y, z));
                }
            }
        }
        return out;
    }
}

Some changes in the Reflexion class:

public class Reflexion {

    Reflexion(ReflexionFactory factory, boolean x, boolean y, boolean z) {
        this.factory = factory;
        ...
    }

    public int getKey() {
        int value = 0;
        if (isFlippedX()) value += 1;
        if (isFlippedY()) value += 2;
        if (isFlippedZ()) value += 4;
        return value;
    }
}

There are a few methods I've left up to you to implement, but I hope you get the idea of them.

So what is the most important change?

The idea is to keep a map of all created reflections, stored with an id, and when you previously created the new reflection, you look them up through the factory (which contains the map).

Essentially, this creates what would be called a "Multiton". A class which has a limited amount of instances. (Compared to a "singleton" which only has one instance)


Demonstration of processing a queue of no-op threads

You could skip the join loop here

for t in threads:
    t.join()

while not que.empty():
    out.append(que.get())

and let Queue.get wait instead:

for _ in range(len(threads)):
    out.append(que.get())

And no, you don't need an explicit threading.Lock in this program because Queue handles the synchronization.

Note that for i in range(1, repeat) loops repeat-1 times, which is probably not what you meant.


The style of you code is good. Here is not much of it but it looks like you understand the concept of closures well.

The logic of the original task is changed so even if you code returns the right values, they are calculated differently. The original task calculates it as i + f.length. It is questionable how to calculate length of an object. There are some ways but we can simply guess that the initialization of f is incorrect and f should be an array.

Another question is how to capture the current state of the array in the closure. Because it is object the closure will get the reference to it so it should be copied. The simplest way of copying an array it to call f.slice().

The last issue (reported by jshint) is that the function created in the loop is always the same. So you can move it outside of the loop and just call in the loop.

Update: Some notes on capturing objects in closures.

The closure captures variable by reference. If you have a loop with an index variable and capture this variable and then invoke the closure you will have not the value of the variable on the corresponding loop iteration. What you will get is the final value on the last loop iteration.

To capture the value the variable should be copied to some temporary context. In the languages with statement scope it is enough to declare local variable, but in JS with function scope you need to capture the variable by running the function. That is why in your code you have this function(number) { - it copies the index variable i to the function parameter number and when value of i is changed, value of number remains.

But when you capturing objects the situation is different, because objects are passed into function scope by reference too. So if the state of the object is changed, it will be changed in both parent and function scope. So in your example later, while invoking, the function will add the final length of the array to the variable, not the length of the array from the corresponding loop iteration.

So the length somehow should be preserved in the closure. It can be passed as number but it will be too boring - you already know how to deal with them. So it is better to think how to pass the copy of the array itself.

    f[i] = (function(number, array) {
        return function() {
            alert("sum=" + number + array.length);
        }
    }(i, f.slice()));


A "master class" is a very close relative to a singleton or a global.  It can easily be a design which violates the Dependency Injection principle, and leaves you with non-modular code.  In this case your engine is also violating the Single Responsibility principle, as it's doing a lot of unrelated tasks:  it's handling windows, providing the game's main driver, moving the ball, drawing the screen, and hosting all kinds of different data.

Try this task:  write a unit test that exercises just the engine::handleWindow() routine without needing to create a real ball, enemy, or player.  It's hard, because your constructor builds all of those objects.

You've already got a start.  For example, you can easily write a unit test that tests engine::eventDraw without creating a real RenderWindow, because you can pass a mock RenderWindow on the engine constructor.  You're using dependency injection.

As you're going to have a singleton in main (and every program does at some level), I recommend you try to keep that singleton as thin as possible.

It's not that your existing code isn't going to work, but it's going to be a problem to maintain, especially as you extend it to add functionality.  Where does scorekeeping come in?  Player preferences?  High score table?  Head-to-head play with two people?  The more you want to add to this, the more you're going to need to change engine, and the less confident you're going to be that you aren't breaking something else.


Loading text into an array when fields are in random order

A more compact and extensible solution would be to use pattern matching to try and take common parts of your field names and use them to map the uneven field headers you get in your csv files.

But I don't think this will work in your case, because you don't seem to have common patterns for all your field names. For instance, adress and street are field headers that should match to the Address field, but as you can see, there's no common usable pattern there. And in cases where there is a common pattern like cust, it won't work either because it could be for the fields CustName or CustNo.

So in this particular case I think you will definitively need to provide the full list of possible field names for each field. Now, you can do this in a more compact way using a VBScript dictionary that allows you to check in one line if certain field name (key) exists using dict.Exists(key), or see the field address matching a particular field name using dict.item(key). You still need to add all possible combinations of field names and addresses to the dictionary, but after doing that (just one time), you can use your dictionary very efficiently to get the address for all your headers.


You know it is not running correctly, the ratio is supposed to be 66%, not 50%.... what you really want is some help debugging it.....

Your issue is in your random number generation.... you are only ever setting, and choosing 2 of the three doors. Have a look at this common problem:

https://stackoverflow.com/questions/363681/generating-random-numbers-in-a-range-with-java

You are not using the ranges properly:

    //door range
    int min = 1;
    int max = 3;
    //generate random correct door
    Random r = new Random();
    int i = r.nextInt(max - min) + min;

in this code, max-min is 2, and nextInt(2) is going to be either 0, or 1., add that to min you get either 1 or 2.

You should not care about the min and max, you should just use:

int i = r.nextInt(doorcount); // assuming doorcount == 3

which will return 0, 1, or 2

If you fix this in both the getGuess and getDoors method then you will get the correct ratio of 66%.

Your code has a number of other problems too.

there is no need to create a new Random instance each time you want a random number. Create a single instance and share it.
do not call your method run. This will lead to confusion with the java.lang.Runnable interface
the line: double ratio = wins / wins + losses does not do what you think it does.

I think you should fix your program, then resubmit it for review....


The visual style of your tabs is actually independent of their functionality. That is, they all behave as tabs, regardless of how they look.

So, while you could make your code more generic by making the selector strings on the fly ($(".tab-content-" + styleName) etc.), I'd recommend something different.

I'd start by separating the classes that describe style from the ones that describe function. Then I'd use the structure of the markup to figure out the rest; not everything needs a class name.

I.e. given this markup, which is slightly changed/simplified from yours

Tab One

Tab Two

Tab Three

Tab Four

Lorem ipsum...

Duis aute...

Ut enim...

Sed do eiusmod...

The code can be shortened to

$(".tabs").each(function () {
  var container = $(this);
  container.find(".tabs-list li").on("click", function () {
    var tab = $(this),
        target = tab.data("tab");
    tab.addClass("current")
      .siblings().removeClass("current");
    container.children("#" + target).addClass("current")
      .siblings("div").removeClass("current");
  });
});

for any and all "tab areas" on the page. It'll also work if you add new styles later, or remove any of ones you have. I.e. the visual style is decoupled from the behavior. Also, you only need to change the class name in one place to re-style an entire tab area.

CSS-wise, simply scope your rules to .style1, .style2 etc. and perhaps use the direct-descendant operator, while keeping the base styling common for all styles

.tabs-style1 .tabs-list { ... }
.tabs-style1 .tabs-list li { ... }
.tabs-style1 > div { /* tab content styling */ }

Here's a demo (it's ugly - just demonstrating the functionality)


C# Winforms: Is there any way to improve this simple custom Textbox code?


I'll answer your question by providing an alternative solution. IDK why you're over complicating this when everything that has to be done is to combine the two lists, then simply sort them:

def merge(array1, array2):
    array1.extend(array2)

    return sorted(array1)

print(merge([1, 3, 4, 7], [0, 2, 5, 6, 8, 9]))
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The advantages of the above solution are:

there's less code so it's easier to maintain / read
it's using only two built-in functions (so assuming the lists are of a reasonable size, it should be quicker than implementing the sorting/merging in a loop)

There's also a one-liner which is even simpler than the above solution:

def merge(array1, array2):
    return sorted(array1 + array2)

print(merge([1, 3, 4, 7], [0, 2, 5, 6, 8, 9]))
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

You could also use the built-in heapq.merge for this.

Of course, if the lists are very large (like very large), merging two lists will totally make sense.

According to this SO answer unless len(array1 + array2) ~ 1000000 use:

L = array1 + array2
L.sort()

Those are just my 2-cents regarding the subject. I'll let somebody else comment on your code.

Extra: Even if practicing algorithms is a good idea, an even nicer aspect is knowing when / where to apply them.


Counting SQL guids from a server log and printing stats

Your timer function should probably go away, to use the built-in timeit instead; or at least timer should wrap timeit.

I'm unclear on why re1 and re2 are separate. Just have them in the same string. If you want to make it clear that they're separate parts of the regex, you could show the construction of the regex as a concatenation, i.e.

rg = re.compile('.*?'  # Prefix to do foo
                # This is a SQL GUID
                '([A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12})',
                re.IGNORECASE | re.DOTALL)

Also, you should not have an outer group on that regex.

Your else after return guid1 is redundant, since the previous block has already returned.

lines = dict() should be lines = {}. There's a reason for this: generally, shorter code is considered more "Pythonic" (as long as it doesn't become arcane or difficult to understand). A dictionary literal is short, simple, and easy to understand.

Here:

if str(element) in line:

You've already stated in the function doc that element is assumed to be a string, so you don't need to convert it using str.

Here:

unique_ids_dict[element] = find_device_IDs(path, element)

Your data structure use is a little strange. You're constructing a dictionary by element of single-key dictionaries by element of GUIDs. It would probably make more sense to change find_device_IDs such that it doesn't return a dictionary, and instead just returns a set.

Speed tips:

Sort out your data structure strategy, mentioned above
Don't re-compile your regex every time an inner function is called. Compile your regex once, at the global level

This:

num_exceptions_dict = dict()
    for elem in search_list:
        num_exceptions_dict[elem] = find_num_occurences(path, elem,
            search_with_in_deviceID, list(unique_ids_dict[elem].values())[0])

should probably be reduced to something like

num_exceptions_dict = {
    elem: find_num_occurences(path, elem, search_with_in_deviceID,
                              unique_ids_dict[elem].values())
    for elem in search_list
}

The performance-affecting change is to avoid re-constructing an inner list. But there's something more sinister going on there. A dictionary is unordered, but you're taking element [0] of an arbitrarily ordered list of values(). If you actually do intend to pull a non-deterministic value from the dictionary, then fine; but this is probably not your intention.

This:

search_with_in_deviceID = ["Exception occurred", "Packet record has been added"]

should be a tuple instead of a list, since you aren't changing it; so:

search_within_device_ID = ('Exception occurred', 'Packet record has been added')

I'm going to suggest that you attempt to address the issues that I've raised, above, in particular with respect to the structure of your dictionary and the non-deterministic behaviour of your values call; and then submit a new question so that further performance issues may be addressed.


Retry storing HTTP response into a variable until specific code

The 1.times ... redo thing is just awful. Replace that with an until loop, like this:

success = false
until success
  ...
  case response.code
  ...
  when "200"
    success = true
    "ok"
  else
    ...
  end
end


The classes' hierarchy and their names don't make much sense to me. Ideally, a class should represent one well-defined entity. What kind of entity is StartQuiz? The name is confusing and there's no documentation to clarify it. I'd recommend naming it properly (something like QuestionsLoader) and appropriate doc comments.

It also mixes up reading the input and choosing random questions. These are different things so they belong to different methods (and possibly even different classes).

The DisplayAnswer is also a very strange class name (it's something like  OutputFormatter, isn't it?). I ask the same question again: "What kind of entities do its instance represent?" and I can't really answer it. The inheritance doesn't make any sense here. Inheritance represent "is-a" relation. Is a DisplayAnswer a StartQuiz? With such names, the question sounds very weird, but even with proper renaming the answer is clearly no (I don't see any rationale behind an affirmative answer here).

The same applies to the DisplayQuestion class.

There's one more thing: there's pretty much no point in having a class that has one method that prints something to the output and doesn't encapsulate any state. You're even using it as a function: DisplayAnswer(startQuiz.set_up()[0], startQuiz.set_up()[1]).show_answer(). It could be just a function show_answer, couldn't it? The situation with the DisplayQuestion is the same here.

Even if you want to keep them all as classes, I'd strongly recommend taking a step back and redesigning your system. Having classes for the sake of having classes makes no sense. There should be some kind of "physical" (or "real world") meaning to them. You can start with the following questions:

What kind of entities are there in this problem? Typically, an entity can and should be described with a noun like loader, formatter and so on.
Once you know what these entities are, you can think of the classes to implement them (but again, the "physical" meaning comes first. If something is just one simple stateless action, I'd rather make it a function).
This part also includes designing the relations between the classes. Inheritance means "is-a". Before building a hierarchy, ask yourself: "Is X really Y?").

There're a lot of other issues with this code (hardcoded file names, improper default arguments use, lack of documentation and tests and so on), but I think that fixing the high-level design is the first thing to do right now. It's impossible to write good code without modeling the problem properly, so that comes first.


This might sound like a goofy answer, but if you already have Windows' file indexing service set up and running on your system, you can search the database contents of the index results using simple SQL terminology.

Here is an article that shows you how

In this way, you're not traversing the directory tree each time you search, but rather you're letting Windows Indexing Service log each new file when it is entered, and then searching the resulting database of information.


Is this implementation of factory design pattern in C#?

In your implementation you have smashed together two separate roles: Product and Creator.
Your implementation is equivalent with the following:
public class GoldCreditCard : CreditCard
{
    private GoldCreditCard(decimal creditLimit, decimal annualCharge)
    {
        CardType = CardType.Gold;
        CreditLimit = creditLimit;
        AnnualCharge = annualCharge;
    }

    public GoldCreditCard()
    {
        CardType = CardType.Gold;
        CreditLimit = 15000;
        AnnualCharge = 100;
    }
}

Or almost with this one (this provides more flexibility):
public class GoldCreditCard : CreditCard
{
    public GoldCreditCard(decimal creditLimit = 15000, decimal annualCharge = 100)
    {
        CardType = CardType.Gold;
        CreditLimit = creditLimit;
        AnnualCharge = annualCharge;
    }
}

The whole point of the pattern is that only the Creator (Factory) knows how to setup a concrete product. In your case your class knows how to initialize itself.


You could store the response in a variable and only call return once. That seems cleaner. Also, put constants like messages and HTTP codes into constant variables.


The first thing you should do is assess the visibility of your methods.  Some should be public, and others private.  I don't see any that should stay package-protected as you have them now.

Next, instead of having a printStack() method, you should consider overriding the toString() method.  Just a Java standard.

Now, I don't know if you're as far as multi-threading in your modules, but I can see some cases where your Stack is not thread-safe (particularly around the sorting).  I'll leave the problem of how to solve this as an exercise to the questioner.


Your test case looks relatively comprehensive in the sense that, yes, it fires off the 100 concurrent threads, but, you ask "how to make it more 'at the same time' ?"
There are two aspects I can suggest:

Use an ExecutorService
Use a CountDownLatch

ExecutorService
One of the novelties about the ExecutorService system is the concept of the Future, and it's foundation, the Callable class. The Callable interface is similar to the Runnable, except it can return a value, and throw an exception. These are two important differences.
The exception thrown in a Callable is trapped, and then re-thrown when the Future's get() method is called. This means that exceptions in remote threads can be collected in the calling thread.
In your case, throwing the exception is the most significant.
Consider the following code that sets up your threads appropriately:
@Test
public void test() throws Exception {
    ExecutorService threads = Executors.newFixedThreadPool(size);
    List<Callable<Boolean>> torun = new ArrayList<>(size);
    for (int i = 0; i < size; i++) {
        torun.add(new Callable<Integer>() {
            public Boolean call() throws B2BException {
                b2b.execute(request);
                return Boolean.TRUE;
            }
        });
    }

    // all tasks executed in different threads, at 'once'.
    List<Future<Boolean>> futures = threads.invokeAll(torun);

    // no more need for the threadpool
    threads.shutdown();
    // check the results of the tasks...throwing the first exception, if any.
    for (Future<Boolean> fut : futures) {
        fut.get();
    }

    //check the threadpool is now in fact complete
    if (!threads.isShutDown()) {
        // something went wrong... our accounting is off...
    }

}

OK, that is a better way of setting up the threads, and gets the exceptions to be thrown inside the test thread, rather than inside the remote threads.
CountDownLatch
If you are concerned that the threads should all be doing things more 'at the same time', and not worrying about start up time, etc. then consider using a count-down latch.
This device is set with a counter, and, when triggered, it will count down by one, and then lock, until all the counts are counted down.
You can use it in the above example code like:
@Test
public void test() throws Exception {
    ExecutorService threads = Executors.newFixedThreadPool(size);
    List<Callable<Boolean>> torun = new ArrayList<>(size);
    final CountDownLatch countdown = new CountDownLatch(size);
    for (int i = 0; i < size; i++) {
        toron.add(new Callable<Integer>() {
            public Boolean call() throws B2BException, InterruptedException {
                countdown.countDown();
                countdown.await();
                b2b.execute(request);
                return Boolean.TRUE;
            }
        });
    }

    // all tasks executed in different threads, at 'once'.
    List<Future<Boolean>> futures = threads.invokeAll(torun);

    // no more need for the threadpool
    threads.shutdown();
    // check the results of the tasks...throwing the first exception, if any.
    for (Future<Boolean> fut : futures) {
        fut.get();
    }

    //check the threadpool is now in fact complete
    if (!threads.isShutDown()) {
        // something went wrong... our accounting is off...
    }

}

The above system will set up all the threads, so they are all 'runnable', and then only when every thread is established and ready, will the locks be released.
You will still not get complete concurrent use, but it will/may be better having more threads start 'at once'.
Other....
You should consider using a custom ThreadFactory for the thread pool, like I suggested in this answer.


Support multi functionality in server.js

I wouldn't pass file folders/files to a fn like that, I'd rather pass the functionality subject like:

myModule.addNewFunctionlity('geoMapping');
myModule.addNewFunctionlity('cookieService');

then refactor you fn nomenclature, maybe

myModule.addNewFunctionlity('geo.geoMapping');
myModule.addNewFunctionlity('frontend.cookieService');

If you think you really need to setup file/folder structure, then apply maybe a setupPath() fn:

myModule.setupPath({ folderPath:__dirname + '/files2'} );

so that in 5-7 years you and others will understand at a glance what
addNewFunctionlity() and setupPath() is about :)


The whole if..else..if..else inside the first loop is senseless because each branch does exactly the same.

Using Split('|') and combining the resulting array with one space " " is the same like replacing | by a space.

The Regex regx = new Regex(sentenceSeparator); is superflous because you don't use regex at all.

The loop

for (int i = 1; i < matches.Count; ++i)
{
    phrase = phrase
        .Replace(matches[i].Value,
        Environment.NewLine + matches[i].Value);
}

is superflous because you aren't using phrase afterwards.

As it seems (untested) you can use Zip() with a MatchCollection if you use .NET Core 3.0.100 but to make your code runnable without .NET Core you should change

Dictionary<Match, string> dic = matches.Zip(sentences, (x, y)
             => new { Key = x, Value = y }).ToDictionary(x => x.Key, y => y.Value);

to

Dictionary<Match, string> dic = matches.Cast<Match>().Zip(sentences, (x, y)
             => new { Key = x, Value = y }).ToDictionary(x => x.Key, y => y.Value);

It comes for sure from copying the code (which seems to be posted using Shift + Enter for phrase) from this question to the IDE....if you inspect the result of dict you will see that from the second item on the Value is prepended by a \n. This can be prevented by using TrimStart('\n') on y at new { Key = x, Value = y }.

Implementing the mentioned points will lead to

   static void Main(string[] args)
    {
        string phrase = @"MHD001|LOCCOD|GRCACS|20191117|133601|CB|trx_grcacs_tsk_20191117133601498|TSK001|GLS|GRCACS|59144|59144|2|TU|93000161357|TRACE|INF|DE 800|please send us the completely address information-thanks|68481|20191117|133555|TSA001|X|TSI001|3655|please send us the completely address information-thanks|66510|TSI001|5637|80337|61335|TSI001|5841|DE|61313|MTR001|5|";

        string[] sentences = phrase.Replace('|',' ').Split('\r');
        string sentencePattern = @"\b[A-Z]{3}\d{3}\b";

        MatchCollection matches = Regex.
            Matches(phrase, sentencePattern,
            RegexOptions.Compiled |
            RegexOptions.CultureInvariant);

        Dictionary<Match, string> dic = matches.Cast<Match>().Zip(sentences, (x, y)
             => new { Key = x, Value = y.TrimStart('\n') }).ToDictionary(x => x.Key, y => y.Value);

        foreach (KeyValuePair<Match, string> kvp in dic)
        {
            Console.WriteLine("Key = {0}" + Environment.NewLine + "Value = {1}", kvp.Key, kvp.Value);
        }
    }


The basic construct you're looking for is a loop. This is what you should reach for any time you find yourself writing the same code (performing the same operation) over and over again, but in a regular pattern (e.g., on columns A–ED).

There are several different types of loops supported by VBA (consult your favorite language reference for details), but you probably want a ranged loop here, since you want to loop through columns A through ED (or whatever maximum column). In VBA parlance, that would be a For loop; something like this:

Sub ShowMsgForErrorColumns()
    Application.FindFormat.Interior.Color = vbRed

    For col = 1 To 134
        Dim match
        Set match = Sheet1.Columns(col).Find(What:="", SearchFormat:=True)

        If Not match Is Nothing Then
            MsgBox "There is an issue with column " & col & "; please review."
        End If
    Next
End Sub

Notice that I have made the following additional improvements to your original code:

I have replaced MSG with a meaningful and descriptive name for the subroutine. This might not be the perfect name, but it is certainly a major improvement. It's also less likely to conflict with other identifiers (msg is pretty common, and VBA isn't case-sensitive).
The With…EndWith construct is only useful when you are setting multiple properties at a particular level of nesting. Your With block only had one statement inside of it, so I've removed it and replaced it with a single statement.
I believe variables should be declared as close as possible to the point of use. Ideally, they would be declared and initialized all at once, but if I remember correctly, VBA doesn't actually support this; you have to break it up into two separate lines. Still, keep 'em close! Also, keep them as narrowly scoped as possible—notice that here, I've put the variable declaration inside of the loop, instead of outside.
If a subroutine takes only one argument, you should not wrap its argument list in parentheses. Thus, I've removed the parentheses around the string passed in the call to the MsgBox subroutine.

But the code I've written above isn't quite what you want—we still need to fix a couple more things!

The first issue is that it will display a message box containing the numeric ID of the problematic column, rather than the alphabetic ID displayed in the Excel UI. For your user's sake, you probably want to change this. Since you're using a loop with the numeric column ID as the loop counter, you need an algorithm to systematically convert that numeric ID to the alphabetic ID. I would define a reusable function for this. The following function is adapted from one appearing in a Microsoft support article:

Function ColumnNumberToLetter(col As Integer) As String
    Dim alpha As Integer
    alpha = col \ 27

    Dim remainder As Integer
    remainder = col - (alpha * 26)

    If alpha > 0 Then
        ColumnNumberToLetter = Chr(alpha + 64)
    End If

    If remainder > 0 Then
        ColumnNumberToLetter = ColumnNumberToLetter & Chr(remainder + 64)
    End If
End Function

Then, just plug in a call to this function in the appropriate spot:

Sub ShowMsgForErrorColumns()
    Application.FindFormat.Interior.Color = vbRed

    For col = 1 To 134
        Dim match
        Set match = Sheet1.Columns(col).Find(What:="", SearchFormat:=True)

        If Not match Is Nothing Then
            MsgBox "There is an issue with column " & ColumnNumberToLetter(col) & "; please review."
        End If
    Next
End Sub

Also, now that we've got a loop, we no longer have to arbitrarily limit ourselves to going through column ED. It is simple to tweak this code to support any number of columns in a sheet—you just make the loop's upper bound the sheet's last column:

Sub ShowMsgForErrorColumns()
    Application.FindFormat.Interior.Color = vbRed

    Dim totalColumns As Integer
    totalColumns = Sheet1.Columns.Count

    For col = 1 To totalColumns
        Dim match
        Set match = Sheet1.Columns(col).Find(What:="", SearchFormat:=True)

        If Not match Is Nothing Then
            MsgBox "There is an issue with column " & ColumnNumberToLetter(col) & "; please review."
        End If
    Next
End Sub

In fact, though, we can do even better. VBA supports a special type of For loop that can be used to automatically iterate through an entire collection of values (in this case, all of the columns in a sheet). This is the For Each loop, and it can be used like so:

Sub ShowMsgForErrorColumns()
    Application.FindFormat.Interior.Color = vbRed

    For Each col In Sheet1.Columns
        Dim match
        Set match = Sheet1.Columns(col).Find(What:="", SearchFormat:=True)

        If Not match Is Nothing Then
            MsgBox "There is an issue with column " & ColumnNumberToLetter(col) & "; please review."
        End If
    Next
End Sub

This is much clearer, less error-prone (it no longer makes assumptions about what the first column is), and more extensible. Almost perfect!

One last thing—instead of hard-coding which sheet you want this function to work on, consider passing in the sheet as an argument:

Sub ShowMsgForErrorColumns(sheet As Worksheet)
    Application.FindFormat.Interior.Color = vbRed

    For Each col In sheet.Columns
        Dim match
        Set match = sheet.Columns(col).Find(What:="", SearchFormat:=True)

        If Not match Is Nothing Then
            MsgBox "There is an issue with column " & ColumnNumberToLetter(col) & "; please review."
        End If
    Next
End Sub

That makes this function reusable. You don't want to go too far with reusability (YAGNI), but at the same time, you don't want to hard-code assumptions or arbitrarily box yourself in. Sometimes, it's just more natural to parameterize a function.

The only thing that bothers me about this code is that setting the Application.FindFormat.Interior.Color property has global side-effects that are visible outside of the function. This bothers me for the same reason that global variables make my skin crawl. One way to solve this would be to save the original value at the top of the function, and then restore it at the end. But that might not be worth it, if you are disciplined about always making sure to set this property to the desired value before any calls to the Find function.


You don't need to manually call f.close(), that's what the with is for.
It looks like line = line.replace(line, "".join(dummy)) can just be line = "".join(dummy).
It's clearer to define dummy in the if statement:

This means that it's in the correct scope, meaning we don't have to look out for it being used elsewhere.
It also means that you can remove dummy.clear().

Personally I would merge your two if statements together, to reduce the arrow anti-pattern.
It looks like dummy and your for loop can be replaced with str.maketrans and str.translate.

untested

file_name = "test.v"
test = ".test"
tezt = ".tezt"
trans_table = str.maketrans({'(': '(/*', ')': '*/)'})

with open(file_name, "r+") as f:
    lines = f.readlines()
    f.seek(0)
    f.truncate()
    for line in lines:
        if ((test in line or tezt in line)
            and line[line.index('(') + 1] != '/'
        ):
            line = line.translate(trans_table)
        f.write(line)


Improve if-statement for multiple strings

i assume that you don't want to proceed the request, and send error message about missing string  to the user, and also you are not using any MVC framework.

First you need to define a list of parameter names.  Then define the below method,

 List<String> paramNames =  ... // you prepared a list of parameter names

List<String> validate(HttpServletRequest req ) {
   List<String> emptyParams = new ArrayList<>();

   for(String name : paramNames ){
      if(StringUtils.isBlank( req.getParameter(name))){
          emptyParams.add(param);
       }
   }

   return emptyParams;
 }

Note: StringUtils class comes from the apache common library.

now the above method can tell you what parameters are empty. you can decide what to do based on the result.

if you use any mvc framework,  it is better to use form binding logic and validation provided by the framework.


Remove and move elements in a WebBrowser Control page

I think all your 4 lines of code are very necessary in your application, but you forgot for example about error handling. If one of your four IDs disappear you'll get a juicy exception.


Java console version Conway's Game of Life

Object fields

    String [][] grid;
    int [][] neighbors;

I would make both of these private rather than the default package-protected visibility.  Unless of course you are actually planning to access these from another class in the package.

    private String [][] grid;
    private int [][] neighborCounts;

I also changed the name of neighbors, as I found the original inaccurate.  I would expect a variable called neighbors to hold some kind of reference to the neighbors.  Instead, this counts the neighbors, which is necessary for Conway's Game of Life.  So let's call it what it is.

I'd also consider changing the grid to be some other kind of object rather than String.  But that's something of a judgment call.  One advantage of doing that would be that you could get rid of neighbors altogether.  Instead, each cell would track its own neighbors.

Class constants

        int [][] directions = {{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};

You make this a regular object field, but it never changes and is the same for all instances of the class.

        private static final int [][] directions
                = {{0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}, {-1,0}, {-1,1}};

Now only one copy will be initialized for the application.

Constructor initialization

                this.neighbors = new int [gridSize][gridSize];
                this.grid = new String[gridSize][gridSize];

Personally, I think that eight-column indent is a bit much.

            grid = new String[gridSize][gridSize];
            neighborCounts = new int[grid.length][grid[0].length];

Four-column indent is more common in Java.

If you do use an eight-column indent, consider adopting the same rule as the Linux source:  only two levels of indent inside a function.  That will help keep function contents from shooting off the edge.  It also helps keep functions simple, without too much nested logic.

I prefer not to use the this. with object fields.  Java doesn't require it, so I only use it when necessary to disambiguate from parameters with the same name.

You want neighborCounts to be the same size as grid.  So make sure of that by setting it to the same dimensions dependently rather than in parallel.  Parallel logic is fragile.

Don't run inside the constructor

At the end of the constructor, you

                this.getNeihbors();

First, that's misspelled (missing a 'g').  It should be getNeighbors.

Second, it's not idiomatic.  I would expect a method called getNeighbors to return the contents of an object field neighbors which holds the neighbors of something.  This fills out the neighbors multidimensional array.  I would probably call it countNeighbors.

Third, if you start the simulation from the constructor, then you have no way of constructing an object without starting the simulation.

Consider removing all current calls to getNeighbors and showGrid and instead adding to main something like

        while (true) {
            c.countNeighbors();
            c.showGrid();
        }

That also has the advantage of not filling up the stack with recursive calls.

Simplifying

                                for (int drow = 0; drow < this.directions.length; drow++) {
                                        int x = (this.directions[drow][this.directions[drow].length-this.directions[drow].length]);
                                        int y = (this.directions[drow][this.directions[drow].length - 1]);
                                        x = row + x;
                                        y = col + y;

This could be as simple as

                for (int[] direction : directions) {
                    int y = row + direction[0];
                    int x = col + direction[1];

And

                                        } else if (x + 1 > this.grid.length) {
                                                 x -= x;

could be

                    } else if (x >= grid.length) {
                        x -= grid.length;

Now if you change the rules to allow neighbors that aren't adjacent, this will still work.

And we don't have to do an extra, unnecessary math operation.

Descriptive names

                int i = 0;

I would find this easier to follow as

        int count = 0;

When I see a variable named i, I expect it to be a loop iteration variable.  This isn't.  We're counting the neighbors.  Why not name it based on that?


Can I somehow tidy up this (overuse?) of generics?

Having so many new operations -- seems like you'd want to use some kind of a factory, injected in the constructor, or the instances themselves injected in the constructor, instead of constructing the classes inside the constructor.


Use Java's THreadLocal type to wrap your SimpleDateFormat objects.

ThreadLocal<SimpleDateFormat> oriFormatHolder = new ThreadLocal<SimpleDateFormat>() {

    @Override
    protected SimpleDateFormat initialValue() {
        return new SimpleDateFormat("MMyyyy");
    }
};

final SimpleDateFormat oriMonthYear = oriFormatHolder.get();

The reason for this is because SimpleDateFormat is not thread safe.

  Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

Read more here

I actually ran into this problem.  In a multi threaded env we were sharing a SimpleDateFormat object across many threads and started getting bad results.  By wrapping it with ThreadLocal the problem went away.


Perl CGI script to respond to erroneous Base64 image requests

The only real problem I see is that if the browser is really "last century" it probably won't support a long enough query string to contain the full image. So your returned image might be incomplete. Another thing is that this would waste a lot of bandwidth.

I see two options

To suppress those error messages you could just handle those URLs like you and make a header redirect (to use the browser cache!) to an error/empty image.
Use conditional comments to load inline images on IE < 8 with a normal img:src attribute. Since your culprit is most likely an Internet Explorer (people who install alternate browsers usually keep them up to date)

I would use the first actually, as it does not involve changing code.

To test whether your solution works, start Internet Explorer (9), open the Web Development tools, and dial it back to IE 6 or 7 (best try both)


Angular/bootstrap radio button directive

items : '=dwjItems',
changeFn : '=dwjChangefn',
selectedItem: "=dwjBoundvalue",
unselectable: "=dwjUnselectable",
align:          "=dwjAlign"

Your indentation needs some work.

scope : {
    items : '=dwjItems',
    changeFn : '=dwjChangefn',
    selectedItem: "=dwjBoundvalue",
    unselectable: "=dwjUnselectable",
    align:          "=dwjAlign"
},

Not sure why you need to prefix "dwj" to your directive attributes. It's not like it will collide with anything else. Besides, you're using the directive as an element. No potential DOM attribute name collisions.

scope.unselectable =scope.unselectable === 'true';                          //default false
scope.align = scope.align === "vertical"? "vertical": "horizontal";         //default horizontal

//http://onehungrymind.com/angularjs-dynamic-templates/
var content = getTemplate(scope.align);
console.log(content);
element.html(content);
$compile(element.contents())(scope);

Not entirely sure why you need to dynamically compile the template. You can simply just define both layouts in the same template and hide one of them when the other is selected. You can use ng-if for that. A developer can come in and say "Oh, two layouts for a directive" than "Oh, I have to take care of 2 template files."


Filtering query by date built from integers

Here is the revised SQL I came up with

Below this code is a list of tips for writing better SQL.

ALTER PROCEDURE [dbo].[Stats]
      @network VARCHAR(9) = NULL
    , @name VARCHAR(100) = NULL
    , @version VARCHAR(15) = NULL
    , @year INT = NULL
    , @month INT = NULL
    , @day INT = NULL
    , @from DATE = NULL
    , @to DATE = NULL
AS

BEGIN

    BEGIN TRY

        SET NOCOUNT ON;

        WITH
        contract_address_list
        AS
        (
            SELECT DISTINCT
                [contractaddress]
            FROM
                [dbo].[game]
            WHERE
                1=1
                AND [name] = @name
                AND [version] = @version
                AND [network] = @network
        )
        SELECT
              GS.[contractaddress]
            , GS.[network]
            , GS.[rounds]
            , GS.[sessions]
            , GS.[handle]
            , GS.[hold]
            , GS.[year]
            , GS.[month]
            , GS.[day]
            , G.[name]
            , G.[version]
            , [Date] = DATEFROMPARTS(GS.[Year], GS.[Month], GS.[Day])
        FROM
            [dbo].[gamestatsdaily] AS GS
            INNER JOIN [dbo].[game] AS G ON GS.[contractaddress] = G.[contractaddress]
            LEFT JOIN contract_address_list AS CAL ON CAL.[contractaddress] = GS.[contractaddress]
        WHERE
            1=1
            AND (@name IS NULL OR CAL.[name] IS NOT NULL)
            AND (@network IS NULL OR (GS.network = UPPER(@network)) )
            AND (@year IS NULL OR GS.[Year] = @year )
            AND (@month IS NULL OR GS.[Month] = @month )
            AND (@day IS NULL OR GS.[Day] = @day )
            AND (
                @from IS NULL
                OR (
                        GS.[Year] >= DATEPART(year, @from)
                    AND GS.[Year] <= COALESCE(DATEPART(year, @to), DATEPART(year, @from))
                    AND GS.[Month] >= DATEPART(month, @from)
                    AND GS.[Month] <= COALESCE(DATEPART(month, @to), DATEPART(month, @from))
                    AND GS.[Day] >= DATEPART(day, @from)
                    AND GS.[Day] <= DATEPART(day, @to)
                    )
                )
        ORDER BY
              GS.[year] ASC
            , GS.[month] ASC
            , GS.[day] ASC

    END TRY
    BEGIN CATCH
        SELECT
                [ErrorNumber] = ERROR_NUMBER()
            , [ErrorSeverity] = ERROR_SEVERITY()
            , [ErrorState] = ERROR_STATE()
            , [ErrorProcedure] = ERROR_PROCEDURE()
            , [ErrorLine] = ERROR_LINE()
            , [ErrorMessage] = ERROR_MESSAGE();
    END CATCH

END

Tips for your SQL

For formatting, I would download the following tool, Poor Man's T-Sql Formatter and on GitHub. I use it when I have to edit other developer's code.

  Here are the settings I used

I would put the commas in front to clearly define new columns. Versus code wrapped in multiple lines. It also makes trouble-shooting code easier.
If you put 1=1 at the top of a WHERE condition, it enables you to freely change the rest of the conditions when debugging a query. The SQL query engine will end up ignoring the 1=1 so it should have no performance impact. Reference
If you use common table expressions (CTE) in your SQL it helps with documentation. The expression name can then let other developers know why you used that expression e.g. contract_address_list or active_projects.
Use the COALESCE function to evaluate the expression in the WHERE clause for the DATEPARTS.
I find it more convenient to see column alias's referenced from the left side e.g. , [Date] = DATEFROMPARTS(GS.[Year], GS.[Month], GS.[Day])
Avoid using keywords as object names. Microsoft Reference
Check the Estimated Execution Plan Ctrl + L in Microsoft SQL Server Management Studio (SSMS) to check the performance of the query by pasting both SQL statements in a query window.

Here's an example.


All possible ways of merging two lists while keeping their order

Since lists are built last to first and you want output to read first to last, we need to reverse the inputs. We will also need two accumulator (one for the permutation and one for results so far and some sort of recursion. Given that it's just a matter of messaging the logic into place.

(define (ordered-merge3 l1 l2)
  (let loop ((lefts (reverse l1)) (rights (reverse l2))
             (permu '()) (acc '()))
     (cond ((or (null? lefts) (null? rights))
            (let ((new-permu (if (null? lefts)
                                 (append (reverse rights) permu)
                                 (append (reverse lefts)  permu))))
               (cons new-permu acc)))
        ;;base case, if either lefts or rights is null there is only one in-order permutation that can be formed.
          (else (loop lefts
                      (cdr rights)
                      (cons (car rights) permu)
                      (loop (cdr lefts)
                            rights
                            (cons (car lefts) permu)
                            acc))))))

The last bit is the hard part to explain. When asked for the in-order permutation of lefts and rights, you can start forming the next permutation with either the car of lefts or the car of rights. In the nested loops here the inner loop is evaluated first because the scheme interpreter does eager evaluation. The value returned by examining the permutations that involve picking the left side is going to be one or more permutations tacked onto the existing known permutation at that point in the calculation. This returned value is used as the accumulator when examining the permutations that involve picking the car of the right side instead.

As far as effeciency, this loop executes once for every element in every permutation. Nothing fancy there, but it will do it in a memory stack no deeper than the sum of the length of the inputs.

(ordered-merge (list 1 2) (list 'a 'b))

;Value 14: ((1 2 a b) (1 a 2 b) (a 1 2 b) (1 a b 2) (a 1 b 2) (a b 1 2))

Overall the shape of how I would approach it is very similar to your second attempt.  Just a few critiques.  Generally cons is the way to build lists. Secondly by mapping up from prior results you are keeping quite a bit extra of data on the stack.

1 ]=> (ordered-merge2 '(1 2 3 4) '(a b c))
(10 0 0)
1 ]=> (ordered-merge3 '(1 2 3 4) '(a b c))
(0 0 1)
1 ]=> (ordered-merge2 '(1 2 3 4 5 6 7 8 9) '(a b c d e f g h))
(170 0 173)
1 ]=> (ordered-merge3 '(1 2 3 4 5 6 7 8 9) '(a b c d e f g h))
(70 0 72)
1 ]=> (ordered-merge2 '(1 2 3 4 5 6 7 8 9) '(a b c d e f g h j k l m o p))
;Aborting!: out of memory
1 ]=> (ordered-merge2 '(1 2 3 4 5 6 7 8 9) '(a b c d e f g h j k l m ))
(2540 1090 3633)
1 ]=> (ordered-merge3 '(1 2 3 4 5 6 7 8 9) '(a b c d e f g h j k l m ))
(860 50 905)
 ]=> (ordered-merge3 '(1 2 3 4 5 6 7 8 9) '(a b c d e f g h j k l m o p q))
(3820 1080 4902)
1 ]=>(ordered-merge3 '(1 2 3 4 5 6 7 8 9) '(a b c d e f g h j k l m o p q r))
;Aborting!: out of memory

Results are timings (cpu-time garbage-collection-time real-time)

Addendum:

I also figure out that my output list was sharing internal list structure where possible.

(define test2 (ordered-merge2 (list 1 2 3) (list 'a 'b 'c)))
(define test (ordered-merge3 (list 1 2 3) (list 'a 'b 'c))
(for-each (lambda (x) (begin (display x) (newline))) test)
(for-each (lambda (x) (begin (display x) (newline))) test2)

Compare the sublists (1 a 2 3 b c) and (a 1 2 3 b c) which in test are elements 2 and 3, and in test2 are 4 and 6. eq? is only true for lists if they are the same object in memory

1 ]=>(eq? (cddr (list-ref test 2)) (cddr (list-ref test 3)))
;Value: #t

1 ]=> (eq? (cddr (list-ref test2 4)) (cddr (list-ref test2 10)))
;Value: #f

1 ]=> (equal? (cddr (list-ref test2 4)) (cddr (list-ref test2 10)))
;Value: #t


Finding the missing value in a proportion

public static double CombinedGasLaw ( double [] original, double [] end, String query)

As a general rule, methods have verb names.  Noun names represent objects or classes.

To get what you want, you need a way to represent a missing value.  One possibility in Java is a null.  Consider

public class CombinedGasLaw {

    private double pressure;
    private double volume;
    private double temperature;
    private double constant;

    public CombinedGasLaw(double pressure, double volume, double temperature) {
        this.pressure = pressure;
        this.volume = volume;
        this.temperature = temperature;
        constant = pressure * volume / temperature;
    }

    public CombinedGasLaw(double[] values) {
        this(values[0], values[1], values[2]);
    }

    public double getConstant() {
        return constant;
    }

    public static int findIndexOfNull(Object [] values) {
        for (int i = 0; i < values.length; i++) {
            if (values[i] == null) {
                return i;
            }
        }

        return -1;
    }

    public Double solve(Double [] end) {
        switch (findIndexOfNull(end)) {
        case 0:
            return constant * end[2] / end[1];
        case 1:
            return constant * end[2] / end[0];
        case 2:
            return end[0] * end[1] / constant;
        }

        return null;
    }

    public static void main(String[] args) {
        CombinedGasLaw original = new CombinedGasLaw(1, 1, 1);
        Double [] end = {1.0, null, 1.0};
        Double fin = original.solve(end);
        System.out.println("The missing value:  " + fin);
    }

}

Now we have a class named CombinedGasLaw and we can name the method solve, as in solve for the missing value.

We pass the array of values with one missing.

We search for the missing value with a for loop.  Note that this will break if there is more than one missing value.

This version also allows us to find multiple triples and only calculates the constant value once.

There are two constructors because I don't know how you get your input.  I wouldn't use an array for original but perhaps you had some reason to do so.  So I made it so that you can call the constructor with an array.  If so, it just calls the other constructor.  I don't use that constructor though, so you could just delete it.

If there is a name used both by an object field and a method parameter, Java defaults to using the parameter.  You can override this by saying this.pressure, which tells it to use the field instead.  So one easy way to assign values to fields in a constructor is to use the same name for both sides.

The this. is not needed any other time, although you can use it if you want.  It's basically saying that it is the pressure associated with the current object.  Absent a method parameter with the same name, that's the default, so you don't normally need it.  Documentation.


My first review in awhile, this is short, sorry. I'm sure others will add more.

Please stop doing using namespace std. Read
this.
Using double for representing currency is
bad.
But since this is an assignment, it probably won't matter much.
Use constant variables to represent magic numbers like .15 and
3.0. Create a const variable named TAX_RATE for instance.
You are returning an int yet salary is of type double?
time_t curTime = time(NULL);

Use
nullptr
(C++11).


Bubble Sort: Time and Space Complexities

BubbleSort is not an efficient algorithm. Talking time-complexity it runs in \$O(n^2)\$ which is okay given a very small array, but for a larger amount of numbers its almost unusable.

This is a comparison between a few sorting algorithms that i wrote in C#. As you can see the only advantage of BubbleSort over the other algorithms is that it is very easy to program.

Anyway - back to your code. I would your implementation is good although i find the first one way more readable.
All in all if you just wanted to implement BubbleSort you did a good job, but if you really want to sort a list, you should  definitely consider another algorithm that runs in \$O(log(n))\$.


In javascript, strings are immutable

  For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See Object.defineProperty() for more information.)

So this was either a trick question or the creator was not aware.

The only "mutable string representation" of a javascript string would be an array.

So if the question accepts using an array as the representation of the string, you could do something like this:

function reverse(str){
  const mutable = str.split("");

  for(let i = 0; i < mutable.length/2; i++){
    const j = mutable.length-1-i;
    const c = mutable[i];
    mutable[i] = mutable[j];
    mutable[j] = c;
  }

  return mutable.join("");
}

const res = reverse("hello world");

console.log(res);


//countQuery mirrors query through the filter assignments

I don't think that's necessary. You could have only one query for the first part of the method, then do recordCount = query.Count(); and then keep using query as you do now.

This way, you have less code and less chance of the count getting out of sync.

query.Where("IsActive = true")

I realize Dynamic Linq is an option, but I think you shouldn't use it when you don't have to. If possible, I would constraint TEntity to some Entity base class or IEntity interface (maybe you already do that) and then write:

query.Where(entity => entity.IsActive);

query = query.Skip(_start);
query = query.Take(perPage);

I don't see any reason why spread this over two lines:

query = query.Skip(_start).Take(perPage);

List<TEntity> page;

…

page = query.ToList();

return page;

The variable page does not serve any purpose, get rid of it:

return query.ToList();


The only alternative is using a for comprehension:

for {
  hasAccess <- canAccessPreferences(id)
  result <- if (hasAccess)
    Future.successful(Forbidden)
  else
    doGetPreferences(id)

} yield result

Unfortunately you cannot use the if guard of the for because then you would get an exception if hasAccess is false. And since you're composing Future monads there's no way around the Future.successful either.