Asking a user for the capital city of Peru, South America

It's kind of a limited code section, but let us go for a review ride:

Have everything enclosed in main() – The pythonic way of starting any code within a module is to have a main method called from the following if statement: if __name__ == '__main__':
Good naming of variables – You seem to name your variables good, that is in snake_case
Not so good while loop condition – Two slight errors here, first of all if using something like a flag it would have been better to do while not end_game instead of comparing against false. Even better would be to use your end of game indicator namely that there are no more attempts left: while attempts > 0:  (or possibly while attempts_left:
Introducing elif – The combination of else: immediately followed by an if can often be better written as elif (which reads as else if something)
Introducing the improved print() – In Python 3 the print is going to change into a function to make it everything a little more coherent, and whilst changing that, one could also get used to the format string syntax. Which changes print 'answer is %s' %(answer) into print('answer is {}'.format(answer))
Make functions multipurpose – Often it is good to make a function multi-purpose, albeit still letting it have one primary concern. In your case this could be asking for capital cities

With all of these changes we got the code looking like:

'''
Ask user for what is the capital city of a given land
'''

import random

def ask_for_capital_city(land, capital_city, attempts_left = 3):
    """Ask for the capital city of a land with 3 attempts by default"""
    question = 'What is the capital city of {}?'.format(land)
    answer = capital_city

    # Ask question
    print(question)

    while attempts_left:
        # Get user answer
        user_answer = raw_input('Enter your answer: ').capitalize()

        # Validate users answer
        if user_answer == answer:
            print('You got it right')
            return True

        elif attempts_left:
            attempts_left -= 1
            print('Wrong! Try again. You have {} attempts left'.format(attempts_left))

        else:
            print('You have no more attempts remaining.')
            print('The correct answer is {}'.format(answer))
            print('Oops!!! Game ended')

    return False

def main():
    capital_cities = [
       ('Peru', 'Lima'),
       ('the UK', 'London'),
       ('the US', 'Washington DC'),
       ('Norway', 'Oslo'),
       ('Spain', 'Madrid'),
       ('Portugal', 'Lisbon'),
       ('Brazil', 'Brasilia'),
    ]

    # Your original code
    ask_for_capital_city('Peru', 'Lima')

    # Lets test for some more capital cities
    correct_answers = 0

    while ask_for_capital_city(*random.choice(capital_cities)):
        correct_answers += 1
        print('You got {} correct capital cities\n'.format(correct_answers))

    print('Goodbye!')

if __name__ == '__main__':
    main()

Do extend the list at will!

NB! When presenting code here at Code Review, the code is supposed to work, and in your case there was a little indentation fault. A good tip to avoid that is to paste the code into the edit box, mark the entire code text and then to hit Ctrl + K which indents the code properly.


Rather strange to encode as a number instead of a (bit)string. And the way you do it takes quadratic time in the size of your list (because both the + and the << in bitstream += encoded_number << bitstream_length are linear). You could do it in linear time by building a string and then turning it into a number at the end.
This should take only a few seconds for your large test (removing the docstring just for brevity here):
def compress(numbers: List[int]) -> int:
    bitstream = []
    previous_number = 0
    for number in numbers:
        delta = number - previous_number # store deltas, much smaller numbers
        N = delta.bit_length() - 1
        encoded_number = bin(delta)[:1:-1] + '0' * N
        bitstream.append(encoded_number)
        previous_number = number
    bitstream.reverse()
    return int(''.join(bitstream), 2)

For decompression, I'd accordingly first turn the number into a string and then work with that.
Optimized version should take less than a second:
def compress(numbers: List[int]) -> int:
    bitstream = []
    append = bitstream.append
    memo = {}
    lookup = memo.get
    previous_number = 0
    for number in numbers:
        delta = number - previous_number # store deltas, much smaller numbers
        if not (encoded_number := lookup(delta)):
            N = delta.bit_length() - 1
            memo[delta] = encoded_number = bin(delta)[:1:-1] + '0' * N
        append(encoded_number)
        previous_number = number
    bitstream.reverse()
    return int(''.join(bitstream), 2)


Solving the Fibonacci series using a for loop

...what I believe to be a novel way of coding the Fibonacci series...

Ahrm, no. Has been done like that forever.

static int loopFibonacci(int num) {

Do not shorten variables just because you can, it makes the code harder to read and harder to maintain.
Everything without visibility modifiers is by default package-private. In my opinion package-private should be avoided as it leads very easily to hard to maintain coupling of classes and interfaces, and it is very easy to make non-extendable constructs with it.

throw new IllegalArgumentException("this number is not valid for fibonacci series");

Good example of a bad error message. The error message should tell me why the number is not usable, what the not usable number was and what a usable number would be, for example:
throw new IllegalArgumentException("Input argument must be a positive number greater or equal to 1, given <" + Integer.toString(number) + ">.");

for (int i=1;i<num;i++) {

I'm still a very persistent advocate of the rule to only use single-letter variable names when dealing with dimensions. For "simple" for loops using index or counter improve most of the time readability quite a bit.

sum+=prev;

As a note, a += b is not shorthand for a = a + b but for a = (TYPE_A)(a + b), which means that it might silently truncate data, for example when adding a float to an int.

        int sum = 1;
        int prev = 0;
        for (int i=1;i<num;i++) {
            sum+=prev;
            prev = sum-prev;
//            System.out.println("sum="+sum+" , prev = "+prev);
        }

Your logic is rather hard to follow, that is because before you really read it it seems to be doing something completely different. So what you want to do is clear that up, partly by using better names and partly by making the logic easier to follow:
int current = 1;
int previous = 0;

for (int counter = 0; counter < steps; counter++) {
    System.out.print(current);
    System.out.println(" ");

    int next = current + previous;

    previous = current;
    current = next;
}

That makes it rather clear how the logic operates.

Looking at possible performance implications is complicated, in my opinion, but let us look at the generated bytecode before jumping to conclusions:
This is the bytecode created for original solution:
0: iconst_1
1: istore_1        /* sum */
2: iconst_0
3: istore_2        /* prev */
4: iconst_1
5: istore_3        /* i */
6: goto            20
9: iload_1         /* sum */
10: iload_2         /* prev */
11: iadd
12: istore_1        /* sum */
13: iload_1         /* sum */
14: iload_2         /* prev */
15: isub
16: istore_2        /* prev */
17: iinc            i, 1
20: iload_3         /* i */
21: iload_0         /* num */
22: if_icmplt       9
25: iload_1         /* sum */
26: ireturn

And here is the bytecode for my revised solution:
0: iconst_1
1: istore_1        /* current */
2: iconst_0
3: istore_2        /* previous */
4: iconst_0
5: istore_3        /* counter */
6: goto            22
9: iload_1         /* current */
10: iload_2         /* previous */
11: iadd
12: istore          next
14: iload_1         /* current */
15: istore_2        /* previous */
16: iload           next
18: istore_1        /* current */
19: iinc            counter, 1
22: iload_3         /* counter */
23: iload_0         /* steps */
24: if_icmplt       9
27: iload_1         /* current */
28: ireturn

So both solutions are using 22 instructions to accomplish their goals. After removing any noise, the difference boils down to this (original to the left):
13: iload_1         /* sum */        14: iload_1         /* current */
14: iload_2         /* prev */       15: istore_2        /* previous */
15: isub                             16: iload           next
16: istore_2        /* prev */       18: istore_1        /* current */

So the only difference is one sub operation, which we trade for a store operation. The performance difference here will be miniscule, in my opinion.


void* is the standard to implement such generics in C. The trouble with union is that the end-user cannot put their own types/structs in it. With void * a pointer to a user-defined struct can be used. However, be careful about memory leaks!

The warnings you are getting is because you haven't consistently used void*.

llist.c:262:3: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘void *’

This indicates that you are printf'ing the data as if it were an int. But you don't what it is so you can't do that. Either don't provide printing options or provide a way to control how the object prints.

llist.c:27:7: note: expected ‘void *’ but argument is of type ‘int’

You have a void * and you are passing it to a function that takes int. Everything inside your library should be using void * not int. Only the actual code using your library should conver the void * into int or whatever they are using.


Let me share my async await solution for that:

Because Your fetch function is pretty similar till the res.text(), I would create an own function (fetchData ) for that, what is returning a Promise, what is resolving a res.text()
Now you can assign an async to your getLogsfunction
Lets reorganise your code above
Error handling is missing here, but take care about it

:
  fetchData = (url) => {
    return new Promise((res, rej) => {
      fetch(url)
        .then(r => r.text())
        .then(text => {
          res(text)
        })
        .catch(e => rej(e));
    });
  }

  getLogs = async () => {
    const { user } = this.props.auth;
    const regxmlPromise = fetchData(`http://127.0.0.1:60000/onexagent/api/registerclient?name=${user.id}`);
    const secondDataPromise = fetchData(`/api/avaya/getid/${user.id}`);

    const resolves = await Promise.all([regxmlPromise, secondDataPromise]);

    const [firstResultStepOne, secondResultStepOne] = resolves || [];

    const secondResultStepTwo = await fetchData(`http://127.0.0.1:60000/onexagent/api/nextnotification?clientid=${secondResultStepOne}`);

    if (firstResultStepOne) {
      const regxml = new XMLParser().parseFromString(firstResultStepOne);
      if (regxml.attributes.ResponseCode === "0") {
        axios.post(`/api/avaya/register/${user.id}`, regxml);
      }
      console.log(regxml);
    }

    if (secondResultStepTwo) {
      const xml = new XMLParser().parseFromString(secondResultStepTwo);
      axios.post(`/api/avaya/getlogs/${user.id}`, xml);
    }
  };


Finding the most common character in a string

Your algorithm has two loops, and that's really not necessary.

This question is looking for a special 'trick' to be done.... and that trick is to process the data in reverse order....

Consider this loop:

public static char getMax(String word) {
    if (word == null || word.isEmpty()) {
        throw new IllegalArgumentException("input word must have non-empty value.");
    }
    char maxchar = ' ';
    int maxcnt = 0;
    // if you are confident that your input will be only ascii, then this array can be size 128.
    int[] charcnt = new int[Character.MAX_VALUE + 1];
    for (int i = word.length() - 1; i >= 0; i--) {
        char ch = word.charAt(i);
        // increment this character's cnt and compare it to our max.
        if (++charcnt[ch] >= maxcnt) {
            maxcnt = charcnt[ch];
            maxchar = ch;
        }
    }
    return maxchar;
}

note the following things:

validate the input.
create an array of counters for each character.
work backwards... if this is the max count (or equal to it) then we have a new winner.
there is no validation on the input characters .... you should probably limit the chars to the a-zA-Z0-9 set that is specified.... the solution above will work for any String.

Some additional notes....

in Java, the standard code style puts the opening { brace on the same line as the block declaration (if condition, method declaration, etc.) Putting the brace on a new line is a C thing to do, and is frowned upon.
x is not a good variable name for anything unless it is a co-ordinate in a multidimensional array (normally linked with (x, y, ...) ). In your use case, you should use the variable j because that is the one that by convention is used inside the i loop.


Removeclass addclass multiple selectors optimization

Using $(this) is very helpful in situations where you have similar/same code.  The way it works, is if say you have a class .general , which 50 different div's on the page all have that class. But lets say, if a user clicks on any one of those 50 div's , you want ONLY that div that was clicked on to have a border of 5px solid red. So instead of writing

$('.general').click(function() {
    $('.general').css({border: '5px solid red'});
});

which would give all 50 div's a border, you can write this

$('.general').click(function() {
    $(this).css({border: '5px solid red'});
});

and now only the div that was clicked on will have the border. Also, it will work more than once, so if you then clicked on 10 other div's with class general, they would all get the border red as well.

This can be applied to your code like so : (only included the relevant info)

function displayContent() {

  var $links = $('.row.nav li a.bio, .row.nav li a.stylist, .row.nav li a.contact');

}

  $links.click(function (e) {  // so you just need one click function instead of 3
    e.stopPropagation();
    $links.removeClass('active');  // removes the class active from all $links
    $(this).addClass('active');  // gives the class active to the one clicked on

  });


Replacing simple jQuery methods for better use

I'd say you're on the right track with all your code. The trick is probably to abstract some of the oft-repeated code into functions/plugins.

For the "singleton selector", wrapping your code in a plugin would seem the way to go. But note that your current code might need tweaking. You have this line:

 $(".selected").removeClass("selected")

which will remove the selected class from elements anywhere on the page. In your example, you'd probably want only to remove the class from .entity elements within the #tempo element.

Here's a (very quick) sketch of a plugin, that should do what you want (and keep it limited to the container element):

$.fn.singleSelection = function(classSelector, handler) {
    return this.each(function() {
        var container = $(this);
        container.on("click", classSelector, function (event) {
            container.find(classSelector + ".selected").removeClass("selected");
            $(this).addClass("selected");
            if( typeof handler === "function" ) {
                handler.call(this, event);
            }
        });
    });
};

Your code can then be shortened to

$("#tempo").singleSelection(".entity"); // you can add a click handler too

Here's a demo.

But... jQueryUI already has this functionality, so if you feel like using that, go right ahead. It's certainly been tested better than what you see above :)
However, for such a simple thing, jQueryUI seems like overkill. But there are probably other, leaner plugins you can find, which'll do what you need - this is just an example.

For your second point, I'd probably wrap the code in an addFolder function somewhere. But it's a little hard to be more specific without knowing more about the context.

For your third point, you could again make a simple jQuery plugin that'd only forward events to your click handler if the element doesn't have the "clicked" class. There are also various "debounce" plugins out there to throttle clicks, but most simply impose a time limit rather than explicitly wait for an ajax operation to finish.

In any event, here's another (very quick) sketch of a jQuery plugin

$.fn.clickOnce = function(handler) {
    return this.each(function() {
        var element = $(this);
        element.on("click", function (event) {
            if( !element.hasClass("clicked") ) {
                element.addClass("clicked");
                if( typeof handler === "function" ) {
                    handler.call(this, event);
                }
            }
        });
    });
};

In your code you could then do:

$("button#new_game").clickOnce(function (event) {
    // this will only be called if the button wasn't already clicked
    var button = $(this);
    createAjaxCall(function (result) {
        // it's your responsibility to remove the "clicked" class
        button.removeClass("clicked");
    });
});

Here's a demo

Again, there are no doubt ready-made plugins that do this and do it better.

By the way, I personally find it easier to pass jQuery's XHR objects around, as they act as deferred objects/promises. I.e.:

var xhr = $.ajax(...); // create an XHR obj from any of jQuery's ajax functions

xhr.done(function (data) {
  // success handler
});

xhr.fail(function (err) {
  // failure handler
});

xhr.always(function () {
  // complete handler
});

So if your createAjaxCall() function returns an xhr object, you can attach a handler to the always "event", and use that to clear the clicked class. That seems more robust (and readable) to me.

p.s. You could use a data-* attribute (set with .attr() instead of .data()), and still have custom styling with CSS like

button[data-clicked='true'] { // CSS attribute selectors are neat!
  ...
}

but browser support is limited compared to using simple classes.


Clarity

Reformat to the presentation width.  Rather than incur slider bars,...

static void const* misc_bsearch_internal(void const** A, void const** Z, void const* K, bool (*cmp)(void const*, void const*))

... wrap code

    static void const* misc_bsearch_internal(void const** A, void const** Z,
        void const* K, bool (*cmp)(void const*, void const*))

One letter argument names convey little,.  Use more expressive names

// static void const* misc_bsearch_linear(void const** A,
//    void const** Z, void const* K, bool (*cmp)(void const*, void const*))
static void const* misc_bsearch_linear(void const** First,
    void const** Last, void const* Key, bool (*cmp)(void const*, void const*))

const void * and void const * are the same, yet the one used by OP does not match the one used by the C standard.  When looking for clarity, recommend following the standard's practice.
It is not stated if bool cmp() functions return true or false on match.  For clarity, that should be detailed.  OTOH. I eventually found it.  For clarity, that should be detailed more obviously - at the top.

// cmp should return true iff [arg1] < [arg2] (strictly).

Missing include.h files.  I'd expect at least something for NULL and <stdint.h> the the optional types intptr_t / uintptr_t.
A sample usage (commented) of the entry function misc_bsearch() would be helpful.  As it is, it is unclear how to use the function set.

Wider use

The compare functions used by the standard C library qsort() use a int cmp(....).  As this code uses a bool cmp(....), the same function is not usable directly in the other.  Consider changing this code change to use int cmp(....).

Limitation

"only sorts arrays of pointers."  --> Op's code handles pointers to objects.  Pointers to functions may be wider than void *.


Project Euler Problem 5: Smallest Multiple of 1 through 20

Two focus areas for this review, first some style and code comments, and then a little discussion on a more optimal solution.

Code and Style Comments

Mostly good and clean code – I like to see clean, properly spaced, well named code, as it makes it a whole lot easier to understand (and easier for you to maintain in the long run).
Stick to PascalCase – This is already commented upon in another answer, but having equal naming and standards throughout your code really helps readability and eases the understanding of code. Which in turns, makes your code maintable.
Avoid magic numbers – Within GetSmallestEvenDivisibleNumber() you use 2521. This number pops out of nowhere in the context of the code. Not good. In addition, it introduces a bug if you try to find the solution for any range with upperBound < 10.
Comment your code – It is not given what the IsEvenlyDivisible method actually does, and I would spend some time commenting upon what it does. Something along the lines of Checks whether value is a proper factor of all the numbers in the range lowerBound to upperBound.

Alternate Solution

Most Euler problems have at least two major solution: The brute force solution, and an optimal solution. You've implemented the brute force of testing each and every number to see if it matches the criteria. In some cases the brute force can be improved somewhat, like skipping all the odd numbers, check for ending of 0 or 5, verify that the value is dividable by 3, and so on... This will usually lead to a somewhat faster solution, but when tackling the higher Euler Problems that'll not be enough.

Therefore it is a good idea to start looking for optimal solutions, and what is really asked for. In this case what is the number 2520, and how have they derived at it? So what we now about that number:

Is is dividable by the numbers in the range 1 through 10
By nature of previous statement, it also needs to be dividable by all of the factors of each of numbers in the range, so let us decompose the range:

\begin{align}
1 & \rightarrow 1 \\
2 & \rightarrow 2 \\
3 & \rightarrow 3 \\
4 & \rightarrow 2 * 2 \\
5 & \rightarrow 5 \\
6 & \rightarrow 2 *3 \\
7 & \rightarrow 7 \\
8 & \rightarrow 2*2*2 \\
9 & \rightarrow 3*3 \\
10 & \rightarrow 2 * 5
\end{align}

Grouping these factors we find that we have 3 * 2's, 2 * 3's, 1 * 5, and 1 * 7. Based upon these factors, we can compose any of the range, and as it turns out: \$ 2 * 2 * 2 * 3 * 3 * 5 * 7 = 8 * 9 * 5 * 7 = 2520\$

In other words if you decompose each of the numbers of your range, and then count how many of each you need to create each of the numbers, this can be used to calculate the answer directly.

To help you get on the way for the range 1 through 20 let us decompose the final numbers as well:
\begin{align}
11 & \rightarrow \mathbf{11} \\
12 & \rightarrow 2 * 2 * 3 \\
13 & \rightarrow \mathbf{13} \\
14 & \rightarrow 2 * 7 \\
15 & \rightarrow 3 * 5 \\
16 & \rightarrow 2 * 2 * 2 * \mathbf{2} \\
17 & \rightarrow \mathbf{17} \\
18 & \rightarrow 2 * 3 * 3 \\
19 & \rightarrow \mathbf{19} \\
20 & \rightarrow 2 * 2 * 5  \\
\end{align}

I've bolded the numbers not already present in our set, and those are \$11 * 13 * 17 * 19 * 2 = 92738\$. So the end result will be: \$92738 * 2520 = 232792560\$.

So there you have yourself a new challenge: Implement this alternate, but more efficient algorithm.


Check for whether a string contains any duplicate characters

Missing return type

This function declaration is missing the return type:

isUnique(char* s1)

Sure, the default return type is int in C,
but it would be better to just write it anyway for clarity.

Use boolean

C99 has a bool type with true and false values,
which you can get from this #include:

#include <stdbool.h>

It would be better to rewrite isUnique to return a bool.
Even though, this will mean giving up the special value -1 for the NULL input case. But that doesn't seem so bad. A name like "is*" is commonly expected to return a boolean. If you really need a function that can handle the NULL case, you could create a wrapper function:

/* returns -1 on NULL input, 0 if not unique, 1 if unique */
int checkUnique(char* s1) {
    if (s1 == NULL) return -1;
    return isUnique(s1);
}

Note that the bool return value of isUnique will be converted to int, so that false is 0 and true is 1.

Avoid repeated calculations

You call strlen(s1) twice:

for(i = 0; i < (strlen(s1) -1); i++)
{
    holder = s1[i];
    for(j = i; j < (strlen(s1)-1); j++)

It would be better to call it once, store in a variable and reuse.

Time complexity

As you suspected, the time complexity of your algorithm is \$O(n^2)\$:
all characters are compared with all other.

You could improve that to \$O(n)\$ by using extra storage, the size of the alphabet.
You could create an array of bool, representing if a character was already seen or not:

All values are initialized to false
For character in the input, check if it was seen

If it was seen, return false
If it was not seen, mark it now (set value in the bool array to true)

If the end of the string is reached, return true

Something like this:

bool isUnique(char * string) {
    int len = strlen(string);

    bool seen[256];
    memset(seen, false, sizeof(seen));

    int i;
    for (i = 0; i < len; i++) {
        char c = string[i];
        if (seen[c]) {
            return false;
        }
        seen[c] = true;
    }
    return true;
}

Printing the result

This will print a 0 or 1:

int x;
char s1[] = "dog hi cobe!";
x = isUnique(s1);
printf("%d", x);

It would be more informative to print the strings that was tested, and "false"/"true" instead of 0/1:

char s1[] = "dog hi cobe!";
printf("%s -> %s\n", s1, isUnique(s1) ? "true" : "false");

Usability

It would be more interesting if the program took the strings from the command line, instead of using hardcoded values, for example:

void printWithResult(char* string) {
    printf("%s -> %s\n", string, isUnique(string) ? "true" : "false");
}

int main(int argc, char ** argv) {
    int i;
    for (i = 1; i < argc; i++) {
        printWithResult(argv[i]);
    }
}


Adding a link on page with current URL (including hash) in a querystring

I don't think this can possibly be improved.
The location hash may be changed by the client after the page is loaded,
by clicking on local anchors.
This is not visible by the asp.net,
and fully visible by the client-side javascript,
in the value of location.href.
And since you require the complete URL to be included as part of the query string,
it must be encoded with encodeURIComponent,
which you correctly did.


Short function to remove unnecessary whitespace

I think the shorter, the better. Since you are in Python 3, if you really want to make explicit that the function is returning a string, you can use type hints:

def trimString(string) -> str:

You can also specify it in the parameter:

def trimString(string: str) -> str:

(keep in mind that Python will ignore type hints, but some IDEs like PyCharm use it to detect warnings and errors)

On a side note, you should try to follow the PEP 8 styling conventions; the function name should be in camel case, so trim_string.


Structure aids understanding

Variable names, functions, classes... most of the code you actually write gets thrown away by the compiler, and is much more about readability and maintainability than anything else. Well structured code is also easier to spot holes in, easier to debug, etc.

So let's start by isolating the maths bit:

double evaluateSimpleExpression(double a, char op, double b)
{
    switch (op)
    {
    case '+': return a+b;
    case '-': return a-b;
    case 'x': return a*b;
    case '*': return a*b;
    case '/': return a/b;
    default:
        throw std::invalid_argument::invalid_argument("Invalid operator");
    }
}

This collects the logic for the actual expression evaluation given some input values, and also throws an error if the operator isn't valid. We've excluded the logic for getting user inputs in, so we could easily point this at a file of inputs or some other format with minimal effort. Using a standard error like this makes it easier to understand the type of error (just need to #include <stdexcept>).

It's still not quite free of the worries about inputs, which we can improve thus:

enum MathOp
{
    Plus = 0,
    Minus,
    Multiply,
    Divide,
    //...
    MathOp__LAST
};

MathOp interpretOperatorChar(char op)
{
    switch(op)
    {
        case '+': return Plus;
        case '-': return Minus;
        case 'x': return Multiply;
        case '*': return Multiply;
        case '/': return Divide;
        default: return MathOp__LAST;
    }
}

double evaluateSimpleExpression(double a, MathOp mop, double b)
{
    switch(mop)
    {
       case Plus: return a + b;
       case Minus: return a - b;
       case Multiply: return a * b;
       case Divide: return a / b;
       default:
         throw std::invalid_argument::invalid_argument("Invalid operator");
    }
}

Now we have separated the input-specific part (the characters used for operations, and the fact that there are two ways of entering a multiply) from the logic to perform the operation. If you wanted to add in a power operator '^'  then hopefully it would be clear what to add.

Clearly the second sample here is somewhat overkill for a little math processing, but it is the kind of structure you'd expect to see for a more comprehensive application; it would be easy, for example, to change the characters used for operations, or to interpret the expression and store it to evaluation later.

Separation of concerns

We have separated the logic from the specification of the inputs - we could easily run the evaluation function with completely different inputs like '10111PLUS11000'.

You'll notice that the operator interpreting function returns a non-value if it can't find the operator in its switch, and that the evaluation function throws if it can't process the given operator. These are the two different ways of coping with invalid inputs - we will use the interpret method generally, and then only evaluate the expression if we think we have a valid operator; the throw is there in case something goes exceptionally badly.

int main()
{
    cout << "Calculator..... " << endl;
    cout << "Type '3a3' to exit... " << endl;

    while(true)
    {
        double a=0 ,b=0;
        char op = 'a';

        bool parsedOK = cin >> a >> op >> b;
        if(!parsedOK)
        {
           cout << "Could not parse expression, expected form a + b"
                << endl;
           continue;
        }
        // 'a' is the exit operator, the value of the integers doesn't matter
        if(op == 'a')
           break;

        // attempt to parse operator
        MathOp gotOperator = interpretOperatorChar(op);
        if(gotOperator == MathOp__LAST)
        {
            cout << "Operator " << op << " invalid" << endl;
            continue;
        }

        // have a valid operator, attempt operation
        double result = _nan();
        try
        {
            result = evaluateSimpleExpression(a, gotOperator, b);
        }
        catch(std::invalid_argument e)
        {
            cout << "Operation failed: " << e.what();
            continue;
        }

        // print interpreted expression and result
        cout << a << " " << op << " " << b << " = " << result << endl;
    }
    return 0;
}

With this structure, we can progress through parsing and evaluating an expression in stages, and give appropriate errors that should inform the user. Now, we haven't included the divide by zero, but it's easy to see where to put it - it is the job of evaluateSimpleExpression to actually do the maths, so we should put it there:

double evaluateSimpleExpression(double a, MathOp mop, double b)
{
    switch(mop)
    case Plus: return a + b;
    case Minus: return a - b;
    case Multiply: return a * b;
    case Divide:
    {
      if(b == 0)
         throw std::invalid_argument::invalid_argument("Attempt to divide by zero");
      return a / b;
    }
    default:
      throw std::invalid_argument::invalid_argument("Invalid operator");
}

If, for example, we added a 'root' operator to get the bth root of a, we could add conditions for valid inputs (like only positive values of b, or only positive values of a when b is even), again providing error messages that give as much contextual information to the user as would help them understand it.


Vectorized approach:

res = sum(abs(x(:).'.^(2:numel(x)+1)))

Read more about vectorization techniques here.

Thus, your function would look like this:

function res = a3_funct(x)
    res = sum(abs(x(:).'.^(2:numel(x)+1)));
return


Display HTML based on user input (via checkbox selection)

You should execute most if not all your code inside the callback for the download click handler. Your code gives you the illusion that it's working because you're setting timeouts. If the user sits idle for longer than the timeouts your script will break.

Consider adding listeners to your checkboxes that bind to a model in your application. This will reduce the amount of dom parsing you have to do manually.

You also have some global variables defined in your script which might interfere with other scripts you've included in your page.

I...didn't test any of this though.

var checkboxPDF = (function($model, $config, $err, $data, $view) {

    //keeping the pdf config options here will let you determine how you want the pdf to look case by case everytime you use this module. It's how jquery plugins work anyway.
    return function(options) {
        $view.setBg();
        //uses a closure to keep track of the model outside the callback context
        $view.bindToModel($model);
        $view.readyDownload(function() {
            //setting up the pdf is the meat of your business logic
            var pdf = new jsPDF(options.orientation, options.pt, options.size);
            $view.update($model, $data);
            //I'm not entirely sure what is in your records div
            $view.addHtml(pdf);
            //In your code I don't know where the doc variable comes from
            if (doc)
                doc.save(pdf + $config.filename);
            else if (pdf)
                pdf.save(pdf + $config.filename);
            else
                alert($err['not defined']);
        });
    };

})(

//keep your model separate from your controller
{},

//pdf configuration, it can be here because it has nothing to do with your application logic
{ filename: 'test' extension: '.pdf' },

//you can keep your error configuration separate as well
{ 'not defined': 'Error 0xE001BADF' },

//static data here, or you could put this directly into the html and toggle classes between visible/hidden in your view logic.
{
    '#idA': 'item 1 box content: ...',
    '#idB': 'item 2 box content...',
    '#idC': 'item 3 box content...'
    '#idD': 'etc...'
},

//organized methods that are concerned with the view/model
{
    setBg: function() {
        $("#container").css('background', '#fff')
    },
    addHtml: function(pdf, callback) {
        pdf.addHTML(document.getElementById('records'), callback || null);
    },
    bindToModel: function(model) {
        $("input[type=checkbox]").on("click", function(e) {
            model[this.id] = e.target.value;
        });
    },
    readyDownload: function(callback) {
        $('.download-pdf').click(function() {
            callback();
        });
    },
    update: function(model, data) {
        for (var p in model) {
            if (model[p] === true) {
                $(p).show().html(data[p]);
            }
        }
    }
);

checkboxPDF({orientation: 'p', pt: 'pt', size: 'a4'}); //appends your listeners, waits for user to check boxes and downloads pdf once they click on a download handler


Start an EventHandler in different Thread

Don't reinvent the wheel: use EventArgs

The StateChanged event isn't compliant with established C# conventions for creating events.

public delegate void LightCommunicationStateChanged(LightCommunicationStateMachine Sender, LightCommunicationState OldState, LightCommunicationState NewState);
public event LightCommunicationStateChanged StateChanged;

That is non-standard. C# conventions recommend using an EventHandler<T> delegate, where T is a type derived from System.EventArgs - the type could be as simple as this:

public class StateChangedEventArgs : EventArgs
{
    public StateChangedEventArgs(LightCommunicationState oldState, LightCommunicationState newState)
    {
        _oldState = oldState;
        _newState = newState;
    }

    private readonly LightCommunicationState _oldState;
    public LightCommunicationState OldState { get { return _oldState; } }

    private readonly LightCommunicationState _newState;
    public LightCommunicationState NewState { get { return _newState; } }
}

In C# 6 it's even simpler - you can implement an actual immutable type with auto-properties:

public class StateChangedEventArgs : EventArgs
{
    public StateChangedEventArgs(LightCommunicationState oldState, LightCommunicationState newState)
    {
        OldState = oldState;
        NewState = newState;
    }

    public LightCommunicationState OldState { get; }
    public LightCommunicationState NewState { get; }
}

By encapsulating the event data inside an EventArgs class, you avoid needing to change the delegate signature (and all the cascading modifications it entails), should the event data ever need to change:

public event EventHandler<StateChangedEventArgs> StateChanged;

Using such a EventHandler<StateChangedEventArgs> delegate for the StateChanged event makes all handler signatures look like this:

private void HandleStateChanged(object sender, StateChangedEventArgs e)

The day business requirements change and you need to add some DateTime Timestamp property to StateChangedEventArgs, none of the handlers' signature needs to change to keep the code compilable.

Asynchronous?

Note that using a custom delegate for events does have its use: generics cannot be exposed through COM interop, therefore a public EventHandler<T> member can't be exposed if the event needs to be handled on the COM side, so a custom delegate is required. But then, invoking a handler on a different thread than the thread it was registered with, will consistently result in a null handler on the .net side.

Hence, I suspect what you really wanted was async handlers - something like this:

private async void HandleStateChanged(object sender, StateChangedEventArgs e)
{
    await DoSomething(e.OldState, e.NewState);
}

Possibly the code was written before .net 4.5 when async/await wasn't available; consider re-targeting the project to a more recent .net version and replacing that threading code with async/await.

Non-Standard Enum

The LightCommunicationState enum isn't standard either:

public enum LightCommunicationState: ushort
{
    notChoosen, Waiting, Communicating
}

Enum values are public members, and should be named as such, in PascalCase. It's also easier to follow and eventually decorate the members with XML-docs and attributes when the members are on their own line, for example:

public enum LightCommunicationState
{
    /// <summary>
    /// Indicates that the state machine is idle.
    /// </summary>
    NotChoosen,
    /// <summary>
    /// Indicates that the state machine is waiting for a signal.
    /// </summary>
    Waiting,
    /// <summary>
    /// Indicates that the state machine is communicating with a client.
    /// </summary>
    Communicating
}

There's seldom a valid reason to change the underlying type of an enum. Seems the ushort underlying type was chosen only to play nicely with the bit-shifting, but then the enum values aren't explicitly assigned, which I believe means adding a 4th value would have broken the logic - the 3 values are implicitly 0, 1 and 2 which happen to match the first few powers of 2, but the next value would be 3 when the next power of 2 would be 4... but that's all pointless: the whole bit-shifting logic was apparently only there to cram both oldState and newState into a single value, boxed into an object, to match the ParameterizedThreadStart delegate signature - which is ugly at best, and irrelevant given a proper EventHandler<T> event.

ThreadStart.Invoke

I don't think your solution is equivalent. ThreadStart is just a delegate - invoking it won't automagically run it on a separate thread, you need a Thread object somewhere!

Per the ParameterizedThreadStart topic on MSDN, the original code had it right. I believe your version simply runs your inline delegate (which merely invokes the handler) on the very same thread FireStateChanged is running on.

Thread Safety

An event reference is null whenever it has no registered handlers, and handlers can be added and removed at any time, by any thread. In both the original code and your own version, the event invocation isn't thread-safe:

if (StateChanged != null && OldState != NewState)
{
    // here, another thread could remove the last handler for StateChanged
    StateChanged(...);

The work-around is simple:

var handler = StateChanged;
if (handler != null && oldState != newState)
{
    // here, the handler reference is thread-local and can't ever be null
    handler.Invoke(...);

In C# 6 you can use the null-conditional operator directly on the event, instead of making a thread-local copy and explicitly checking for handler != null:

if (oldState != newState)
{
    StateChanged?.Invoke(...);

Notice I changed OldState and NewState to oldState and newState, respectively: parameters and local variables should be camelCase, not PascalCase (notice even the syntax highlighting picks it up!).

Also - and that's completely a personal preference - I prefer seeing an explicit .Invoke call on the event, rather than writing it to look like a standard method call - IMO the .Invoke makes a clear visual cue that we're invoking an event, not just another method.

My solution might have looked something like this:

protected void OnStateChanged(LightCommunicationState oldState, LightCommunicationState newState)
{
    var handler = StateChanged;
    if (handler == null || oldState == newState)
    {
        return;
    }

    var args = new StateChangedEventArgs(oldState, newState);
    var thread = new Thread(e => handler.Invoke(this, (StateChangedEventArgs)e));
    thread.Start(args);
}

Notice I named the method On[EventName] instead of Fire[EventName] - that's also a C# naming convention, see C# Naming Guidelines on MSDN. Note the cast from object to StateChangedEventArgs incurs no boxing, since only reference types are involved.

Also notice I'm making use of the compiler's type inference capabilities: you don't need to explicitly new up a ThreadStart delegate, using the => lambda operator instead: the compiler is able to infer the correct delegate type from the constructor overload.


As the input size is 10**6 and you're using Python 2 the first issue in that you're creating an unnecessary list of 10**6 integers just to do a loop.

Instead of that you should use xrange() which yields integers lazily:

>>> %timeit for _ in range(10**6): pass
10 loops, best of 3: 24.1 ms per loop
>>> %timeit for _ in xrange(10**6): pass
f100 loops, best of 3: 8.92 ms per loop

Another slight micro-optimization that you can do here is to use itertools.repeat with None. None is a singleton, so, only a single None ever exists in memory and it is the smallest object in CPython on the other hand creating 10**6 integers is expensive(well CPython caches some of them, but still they are unnecessary here)

>>> %timeit for _ in repeat(None, 10**6): pass
100 loops, best of 3: 7 ms per loop

As we're using the functions like raw_input, int multiple times in our code it's better to cache them as local variables, because otherwise we're looking for them at least 10**6 times in global dictionary. One way to cache them is to use them as default values to function attributes:

>>> def f_simple(n):
    for _ in xrange(n):
        foo = [int('1') for _ in xrange(15)]
...
>>> def f_cached(n, int=int):
    for _ in xrange(n):
        foo = [int('1') for _ in xrange(15)]
...
>>> %timeit f_simple(10**6)
1 loops, best of 3: 3.7 s per loop
>>> %timeit f_cached(10**6)
1 loops, best of 3: 3.52 s per loop

Instead of starting the result value with input_list[0] we can simply start with 0 and we can also prevent creation of that simple 15 items list:

result = 0
for x in raw_input().split():
    result ^= int(x)

Currently your first solution takes around 7.44 seconds on my system and my solution takes around 5.6 seconds, not a huge improvement.:

from itertools import islice
from functools import partial
import sys

def main5(int=int):
    t = int(raw_input())
    # Take a slice of sys.stdin of size (10**6)*2
    lines = islice(sys.stdin, t*2)
    # Now lines is an iterator which is going to yield one
    # line at a time, but we're also going to read the next line(to get X)
    # with each input, so instead of doing `next(lines)` each time in
    # the loop we can create a partial function.
    next_line = partial(next, lines)

    for line in lines:
        result = 0
        for x in line.split():
            result ^= int(x)
        if format(result, 'b').zfill(32).count('1') > int(next_line()):
            print 'YES'
        else:
            print 'NO'

Note that in the above solution we are writing to the stdout instantly, if we can store the output temporarily in a list(say 1000 items) and them write them at once then the above solution takes 5.52 seconds:

from itertools import islice
from functools import partial
import sys

def main6(int=int, len=len):
    t = int(raw_input())
    # store a reference sys.stdout.write to prevent 2 attribute lookups
    stdout_write = sys.stdout.write
    lines = islice(sys.stdin, t*2)
    next_line = partial(next, lines)
    out = []
    # Cache out.append to prevent attribute lookup
    out_append = out.append
    for line in lines:
        result = 0
        for x in line.split():
            result ^= int(x)
        if format(result, 'b').zfill(32).count('1') > int(next_line()):
            result = 'YES'
        else:
            result = 'NO'

        out_append(result)
        if len(out) == 1000:
            stdout_write('\n'.join(out))
            # empty out list; use list.clear() in Python 3
            del out[:]
    if out:
        stdout_write('\n'.join(out))


Edit string to concatenate word numbers in javascript

Is there an cleaner, more elegant, sexier way?

I guess regex makes it more elegant and sexier, but your implementation is fine:

String.prototype.concatWordNumber = function() {
  var i = 1;
  return this.replace(/\b\w+\b/g, function(word) {
    return word + i++;
  });
};

Or you could use map:

String.prototype.concatWordNumber = function() {
  var plusIdx = function(x,i) {
    return x + ++i;
  };
  return this.split(' ').map(plusIdx).join(' ');
};


How to improve this functional python trial division routine?

A functional recursive implementation:

def factorization(num, start=2):
    candidates = xrange(start, int(sqrt(num)) + 1)
    factor = next((x for x in candidates if num % x == 0), None)
    return ([factor] + factorization(num / factor, factor) if factor else [num])

print factorization(1100)
#=> [2, 2, 5, 5, 11]

Check this.


Is this code protected against SQL injection attacks?

Looks O.K. to me as well, as far as the SQL injection goes.

However, I'd suggest checking the return value of $sth->execute();, so you capture possible errors (i.e., DB being down).

You might also consider doing a case insensitive search for the existing usernames and e-mails, since "person@gmail.com" is the same address as "Person@GMail.com" and users "Person" and "person" are hard to distinguish.

I think empty($string) is more advisable than strlen($string) == 0.

Last, but not least, adding a "retype your password" field would be a good security against user mistyping what he wants for a password and then ending with a useless account (or having to use "I forgot my password" before the very first login).


Acquiring an ID from a newly inserted entry in an MSSQL database

You can use scope_identity as @RobH hinted in a comment, but the sexiest way IMO is to use the OUTPUT clause of the INSERT syntax:

DECLARE @result TABLE (Id INT NOT NULL);

INSERT INTO subscriptions (polygon,...)
VALUES (@polygon,...)
OUTPUT INSERTED.Id INTO @result;

SELECT Id FROM @result;

Now, having a whole multi-statement CommandText like this, even if it's parameterized, isn't desirable at all, and makes for pretty ugly C# code - why not put that T-SQL in a stored procedure, and call that instead?

Speaking of parameters, your code snippet, as small as it is, is showing us that your method is breaking SRP (Single Responsibility Principle):

   // Create Poly out of given geodata values
    var point = SqlGeography.Point(Double.Parse(lat), Double.Parse(lon), 4326);
    SqlGeography poly = point.BufferWithTolerance(Double.Parse(radius) * 1000, 0.01, true);

That logic doesn't belong there at all: you need a SqlGeography-type parameter, fine. That doesn't mean the logic for translating lat and lon values into one belongs in that method.

Side note, I get what lat and lon stand for in the context of creating a SqlGeography value, but these are bad variable names nonetheless: there's no reason to shorten the names like this - not even "it's faster to type"; with IntelliSense you type "lat" and it autocompletes "latitude" for you.

I'm going to make a little assumption here. This makes me think your method is returning something like a Dictionary<string,string>:

result.Add("success", "true");
result.Add("id", id.ToString());

That's a very error-prone way of working. The "success" value is useless, because if you have a value, you have a successful insert. If you don't have a value, you're dealing with an exception - and I see no try/catch block in your code, so I'm hoping the caller is handling such an exception...

You could have a class somewhere, with properties for each column of a database table / entity you're working with, and you should return that instead... but the simplest return type to use would be a Nullable<int>, so that the method either succeeded and returns the Id for the inserted record, or failed and returns null - for that to happen reliably, you'll need to wrap your logic in a try/catch block, and handle any SqlException that might be thrown in the process.

Another thing is that you're not properly disposing of your connection there. SqlConnection implements IDisposable, and the instance should be wrapped in a using block, too. Also I would try to open the connection before I start creating the command, so that I could pass the connection into the command's constructor (and not even bother instantiating it if the connection can't be opened). Keeps things cleaner I find:

try
{
    using (var connection = new SqlConnection(...))
    {
        connection.Open();
        using (var command = new SqlCommand(sql, connection))
        {
            //...
        }
    }
}
catch (SqlException)
{
    return null;
}

Lastly, I find that you're using confusing identifiers: in the top snippet your adapter is called cmd, and your command is called querySaveSubscription, as if it were a string containing the SQL statement (and the SQL string in question is called query... but doesn't query anything). ...but then in the bottom snippet a command is called a command and a reader is called a reader, and a connection that might never have successfully opened is called openCon. Would you ever work with a closedCon? Why not just call it connection then?


I found your code a little hard on the eyes because of the lack of formatting.

function anime(){
ob.each(function(i,item){$(item).animate({"top":"+="+nex+"px"},spd,

  "linear",function(){if ($(item).position().top == jleng*nex)
{$(item).css('top',-1*nex*(i+1))}});})
setTimeout(anime, 0);
}

Here is what it looks like with good formatting

function anime(){
    ob.each(function(i,item){
        $(item).animate(
            {"top":"+="+nex+"px"},
            spd,
            "linear",
            function(){
                if ($(item).position().top == jleng*nex) {
                    $(item).css('top',-1*nex*(i+1))
                }
            }
        );
    })
    setTimeout(anime, 0);
}


A couple of suggestions.

Throttle Infinite Loops:

The button loop has no throttle on its CPU usage.  If no buttons are pressed it is constantly doing IO.  If you reformulate the loop without any of the buttons being pressed the effective code looks like:

while True:
    GPIO.input(B1)
    GPIO.input(B2)
    GPIO.input(B3)

This code never gives the CPU a rest.  It should probably be more like:

while True:
    GPIO.input(B1)
    GPIO.input(B2)
    GPIO.input(B3)
    time.sleep(0.05)

Picking the actual sleep() time will depend on the system, but hopefully this demonstrates the likely problem.

So the loop with the if statements will look like:

while True:
    if GPIO.input(B1):
        ...

    if GPIO.input(B2):
        ...

    if GPIO.input(B3):
        ...

    time.sleep(0.05)

Use List Properties for Length Management

This code is using a variable to get the current pattern:

cpat = cpat + 1
if cpat >= numpats:
    cpat = 0

This can be more cleanly done with:

cpat = (cpat + 1) % len(colors)

The change removes two lines of code, and sets the variable limit based on the list indices, which can avoid bugs later.


Sorry the late reply,
Below is a lispy-er way to get to the same result :)

The main thing is to define a way to get from 2 ul's to a single ul.
(so we can use that as a step in a reduce)

basically what we want is, given two ul, to append the one of them to the last item of the other.

The algorithm would be something like this

take the last li from the parent.
append to it the whole second list.
pop it back in the parent

we can make a separate function that does exactly that.

let's call it append-li

(defn append-li
  "Appends given child to the last element with in the given parrent"
  [child parent]
  (let [ul-without-last-li (vec (butlast parent)) ;; take the parent with out the last element
        last-li (last parent)]) ;;take the last item from the parent
    (conj ul-without-last-li (conj last-li child))) ;; pop it back with the whole second list as a child

Using this append-li function ( could be named better but oh well :P )
we can implement our transformation algorithm like so

sort all elements in reverse order of h count (so the larger numbered headers are first (some thing like h3, h2, h1)
partition the list of headers by the type of header. so now we have a list of lists of headers, where each list only contains the same kind of headers
convert all headers to lis, so that now we have a list of groups of lis and the close to the front the list a group is, the deeper level it has
make every group a ul
flip the order of the lists (could have been done before), to make it so that the futher away the item
reduce with out append-li function.
profit :)

All this reversing is a bit annoying, but it ultimately maintains the original order of the items.

(small edit)
The reason we want to reverse the thing is that we want to build the tree of ul's in reverse order from the bottom up.
We could do it from the top down, but that would require a bit of recursion.

below is the full code with some (hopefully) helpful comments

Full Code:

(defn tag->li
  "Converts a header tag (or any tag) to a li"
  [[type & content]]
  (into [:li] content))

(defn append-li
  "Appends given child to the last element with in the given parrent"
  [child parent]
  (let [ul-without-last-li (vec (butlast parent))
        last-li (last parent)])
    (conj ul-without-last-li (conj last-li child)))

(defn listify-headings
  "Convers a list header tags to a nested unordered list"
  [nodes]
  (let [rev-sorted (sort-by first #(> %2 %1) nodes) ;;sorts by 'h' number, result is a sorted list where all h3 are before h2 etc
        types      (partition-by first rev-sorted)  ;;makes a list of lists, so that first list is only h3, second is only h2 etc...
        lis        (map #(map tag->li %) types)     ;;make the h's to li, we have order now so we don't care about what kind of h's it is, this gives a list of lists with 'lis in them'
        uls        (map #(into [:ul] %) lis)]       ;;raps each makes each list of 'li' to be a 'ul' with li's inside
    (reduce append-li (reverse uls))))              ;;concat each 'ul' to the previous (that's why we reverse) one to produce the tree of uls al lis

P.S.

while both your code and mine work and get the job done, i'm not sure if it's logically ok to do this.

from a semantic standpoint this does not make to much sens, as the desired output means that only the last header on the page has any sub-headers.

basically it would look like all chapters don't have any titles, and the last one has all of them.

i'm not sure whether or not that's the desired thing, but oh well :P


Python code that compares two files byte by byte

The code in the post calls os.path.getsize for each block read from the two files. This could be avoided by remembering the value in a local variable.
The code accumulates count in order to detect the end of the files being compared. But the read method will return an empty bytes object when the end of file is reached, so there is no need to maintain a count.

If you look at the implementation of the filecmp module, you'll see that file comparison is implemented like this:

def _do_cmp(f1, f2):
    bufsize = BUFSIZE
    with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2:
        while True:
            b1 = fp1.read(bufsize)
            b2 = fp2.read(bufsize)
            if b1 != b2:
                return False
            if not b1:
                return True


You're creating a lot of jQuery objects in there. It would be much more efficient to just create them once. For example:

var postData = {},
    cData = {},
    $this = $(this),
    $parent = $this.parent(),
    $balance = $parent.children(".balance");

As a general rule, I try to avoid calling any method on the same object more than once. For any methods you need to call repeatedly, just call it once and store the result.

The following line seems to be incorrect. You're passing an object to the .html() method (which it doesn't accept):

$('#desiredStatus').html(cData);

//Did you mean to do this instead?
$('#desiredStatus').html(cData.desiredStatus);

You are creating a new modal dialog every time a .editButton element is clicked. You could move the creation of the dialog outside of the event handler and just call $("#dialog").dialog("open") when you want it to appear.
The comparison balanceInqury == 'NaN' will never be true. JavaScript is funny like that, NaN !== NaN. There is a built-in isNaN function you can use though:

postData.balance = isNaN(balanceInqury) ? cData.Balance : balanceInqury;

For shorter code you could replace your call to $.ajax with a call to the shorthand $.post method. If you'd rather not do that, you can at least remove the error property from the options object, since it doesn't do anything in your case:

$.post('/url/to/postto', { postData: postData}, function (data) {
    //You make another unnecessary jQuery object in here. Cache the #dialog object!
});

Finally, you could change the code in the #changeStatus click event handler by passing a function to the .html method, which in my opinion is a bit neater:

$('#currentStatus').html(function () {
    return $(this).html() === "Disabled" ? "Enabled" : "Disabled"
});
$('#desiredStatus').html(function () {
    return $(this).html() === "disable" ? "enable" : "disable";
});


Load other files (from outside public_html) under index.php

You can simplify your regex pattern and you might like to combine your validation with the preparation step.  The following pattern is just like yours except it allows a single trailing slash and omits it from the capture group.

if (isset($_GET['do']) && preg_match('~^(\w+)/?$~', $_GET['do'], $valid)) {
    $file_name = $valid[1];
} else {
    $file_name = "home_page";
}

$fpath = FILESPATH . "{$file_name}.php";

if (!file_exists($fpath)) {
    // Error
    require_once('404.php');
    die();
}

It doesn't make sense to valid home_page with your pattern, you know it will pass every time. I suppose it could be possible that your home_page file may not exist in the directory.


T-SQL simplify repeated query unions for each day of the week

Syntax Issue

The derived table in the FROM clause needs to be surrounded by parentheses:

DECLARE @waypointId INT = 100;
DECLARE @Sunday INT = 1;
SELECT MIN(nextScheduleDateTime)
FROM
    SELECT MIN(CAST(CAST(DATEADD(dd, (6 - DATEPART(dw, GETDATE()) + @Sunday) % 7 + 1, GETDATE()) AS DATE) AS DATETIME) + CAST(ScheduleDetail.startTime AS TIME)) AS nextScheduleDateTime

Should be updated like this:

SELECT MIN(nextScheduleDateTime)
FROM
    (SELECT MIN(CAST(CAST(DATEADD(dd, (6 - DATEPART(dw, GETDATE()) + @Sunday) % 7 + 1, GETDATE()) AS DATE) AS DATETIME) + CAST(ScheduleDetail.startTime AS TIME)) AS nextScheduleDateTime

And then after the sub-queries:

    ) AS Subqueries

Simplifying sub-queries

I believe (but haven't tested, since I don't have your data and expected output) that the WHERE conditions can be updated like below, which would allow combining the sub-queries into one, eliminating the usage of UNION:

DECLARE @waypointId INT = 100;
DECLARE @Sunday INT = 1;

SELECT MIN(CAST(CAST(DATEADD(dd, (6 - DATEPART(dw, GETDATE()) + @Sunday) % 7 + 1, GETDATE()) AS DATE) AS DATETIME) + CAST(ScheduleDetail.startTime AS TIME)) AS nextScheduleDateTime
FROM WaypointEventLog INNER JOIN
     Schedule ON Schedule.scheduleRef = WaypointEventLog.ScheduleID INNER JOIN
     ScheduleDetail ON Schedule.scheduleRef = ScheduleDetail.scheduleRef
WHERE WaypointID = @waypointId
AND Completed = 0
AND Schedule.scheduleType = 6
AND
(( validSunday = 1 AND DATEPART(dw, GETDATE()) <> @Sunday ) OR
        ( validMonday  = 1 AND  DATEPART(dw, GETDATE()) <> @Sunday + 1) OR
        ( validTuesday = 1 AND  DATEPART(dw, GETDATE()) <> @Sunday + 2 ) OR
        ( validWednesday = 1 AND  DATEPART(dw, GETDATE()) <> @Sunday + 3 ) OR
        ( validThursday = 1 AND  DATEPART(dw, GETDATE()) <> @Sunday + 4 ) OR
        ( validFriday = 1 AND  DATEPART(dw, GETDATE()) <> @Sunday + 5) OR
        ( validSaturday = 1 AND  DATEPART(dw, GETDATE()) <> @Sunday + 6 ))

While it only contains the one table scheduleDetail, you can see this illustrated in this SQL fiddle. Feel free to update that fiddle and provide more details about the other tables, plus the data in those tables.

Programmatic way of generating the query above

One approach you could take is to define a CURSOR, and use that to loop through each field, adding the sub-queries to be joined via UNION to a long string. Originally I was thinking a varchar(5000) would be necessary but that was before I discovered the UNIONs could be eliminated.

DECLARE @name VARCHAR(50) -- field name
DECLARE @rowNum varchar(10) -- row number
DECLARE @sql VARCHAR(5000) = 'SELECT MIN(CAST(CAST(DATEADD(dd, (6 - DATEPART(dw, GETDATE()) + @Sunday) % 7 + 1, GETDATE()) AS DATE) AS DATETIME) + CAST(ScheduleDetail.startTime AS TIME)) AS nextScheduleDateTime
FROM WaypointEventLog INNER JOIN
     Schedule ON Schedule.scheduleRef = WaypointEventLog.ScheduleID INNER JOIN
     ScheduleDetail ON Schedule.scheduleRef = ScheduleDetail.scheduleRef
WHERE WaypointID = @waypointId
AND Completed = 0
AND Schedule.scheduleType = 6
AND ('

DECLARE db_cursor CURSOR FOR  -- fetch columns to loop over
SELECT COLUMN_NAME, ROW_NUMBER() OVER(ORDER BY ORDINAL_POSITION ASC) - 1 AS RowNum
FROM INFORMATION_SCHEMA.columns
WHERE table_NAME = 'ScheduleDetail' and COLUMN_NAME like 'valid%' and COLUMN_NAME not like '%holiday'
ORDER BY ORDINAL_POSITION

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name, @rowNum

WHILE @@FETCH_STATUS = 0
BEGIN
    --append WHERE condition
   SET @sql  = @sql + ' ('+ @name + ' = 1 AND DATEPART(dw, GETDATE()) <> @Sunday + ' + @rowNum + ' )'+char(10)+char(13)   -- + CR + LF

   FETCH NEXT FROM db_cursor INTO @name, @rowNum
   if @@FETCH_STATUS=0 -- all except last condition
    BEGIN
        SET @sql  = @sql + 'OR'+char(10)+char(13)   -- + CR + LF
    END
    ELSE
    BEGIN -- last condition
        SET @sql  = @sql + ')'+char(10)+char(13)   -- + CR + LF
    END
END

CLOSE db_cursor
DEALLOCATE db_cursor

print @sql

That could be used to generate a Table-valued function or View.


Evaluating association strengths of items

Even in the non-symmetric case you can speed this up by not having the explicit double for loop. Since your case is not even normalized (apparently an animal can appear together with more than one other animal at a time), you do need your df1 as the normalization (instead of just e.g. df2.sum(axis=1). This gives you the matrix of the associations:

assoc_matrix = (df2.T / df1.set_index("Animal").Count).T
print(assoc_matric)
#           Monkey     Tiger       Cat       Dog      Lion
# Monkey  0.461538  0.692308  0.307692  0.692308  0.615385
# Tiger   0.200000  0.150000  0.200000  0.250000  0.250000
# Cat     0.062500  0.312500  0.250000  0.312500  0.000000
# Dog     0.000000  0.133333  0.333333  0.200000  0.466667
# Lion    0.500000  0.388889  0.333333  0.000000  0.333333

(I figured out the needed transposes by trial and error until I got the same values as in your post...)

And then you can use pandas.melt to get it into your format:

assoc_df2 = pd.melt(assoc_matrix.reset_index(), id_vars="index")
assoc_df2.columns = "Animal 1", "Animal 2", "Association Strength"
print(assoc_df2)

#    Animal 1 Animal 2  Association Strength
# 0    Monkey   Monkey              0.461538
# 1     Tiger   Monkey              0.200000
# 2       Cat   Monkey              0.062500
# 3       Dog   Monkey              0.000000
# 4      Lion   Monkey              0.500000
# 5    Monkey    Tiger              0.692308
# 6     Tiger    Tiger              0.150000
# 7       Cat    Tiger              0.312500
# 8       Dog    Tiger              0.133333
# 9      Lion    Tiger              0.388889
# 10   Monkey      Cat              0.307692
# 11    Tiger      Cat              0.200000
# 12      Cat      Cat              0.250000
# 13      Dog      Cat              0.333333
# 14     Lion      Cat              0.333333
# 15   Monkey      Dog              0.692308
# 16    Tiger      Dog              0.250000
# 17      Cat      Dog              0.312500
# 18      Dog      Dog              0.200000
# 19     Lion      Dog              0.000000
# 20   Monkey     Lion              0.615385
# 21    Tiger     Lion              0.250000
# 22      Cat     Lion              0.000000
# 23      Dog     Lion              0.466667
# 24     Lion     Lion              0.333333

Note that the order is different to your solution and this also contains the association of each animal with itself (and it is not one in this example, due to the normalization). You can just filter it out, though, if needed:

assoc_df2 = assoc_df2[assoc_df2["Animal 1"] != assoc_df2["Animal 2"]]

Finally, all of this only works as long as the dataframes still fit into memory, of course.


Most efficient way to validate multiple textboxes against a tolerance value

I would write it like this

Dim m1 As TolerenceHelper
Dim flag As Boolean = True

m1 = New TolerenceHelper

flag = m1.IsInTolerence(Integer.Parse(txtT1.Text), Integer.Parse(txtA1.Text), Integer.Parse(txtTolerance.Text))

If flag = False Then
    lblTest.Text = "Out of tolerance"
Else
    lblTest.Text = "In tolerance"
End If

that function returns a boolean so you can just assign it the flag or you could do it like this and avoid creating the flag boolean as well

Dim m1 As TolerenceHelper
m1 = New TolerenceHelper

If m1.IsInTolerence(Integer.Parse(txtT1.Text), Integer.Parse(txtA1.Text), Integer.Parse(txtTolerance.Text)) Then
    lblTest.Text = "In tolerance"
Else
    lblTest.Text = "Out of tolerance"
End If

In your Function IsInTolerence you could eliminate some variables by writing it like this:

Public Function IsInTolerence(ByVal target As Integer, ByVal actual As Integer, ByVal tolerence As Integer) As Boolean

    If (target - tolerence <= actual AND actual =< target + tolerence)
        Return True
    Else
        Return False
    End If
End Function

Straight to the point.

check if it is true first, and then dump out in all other cases, this would cover a null or something else.

Remove Code Duplication with a list of TextBox Objects

I am thinking that you create a list of the text boxes, then you should be able to loop through that list, checking each text box for the following.

if it has a value entered
if the tolerance is met
some kind of highlighting to show that the tolerance was not met.

I am not sure on the syntax, but this would be a good way to do it, because you would only have to type out the logic once and then loop through the list of TextBoxes,  and it would be more maintainable because you could just add TextBoxes any time you like and it shouldn't affect the any of the other code.

dim TextBoxListActual as New List(Of TextBox)
TextBoxListActual.Add(txtT1)
TextBoxListActual.Add(txtT2)
TextBoxListActual.Add(txtT3)

Dim TextBoxListTarget as New List(Of TextBox)
TextBoxListTarget.Add(txtA1)
TextBoxListTarget.Add(txtA2)
TextBoxListTarget.Add(txtA3)

dim m1 As TolerenceHelper
m1 = New TolerenceHelper

For index As Integer = 0 To TextBoxListActual.Count
    If m1.IsInTolerence(Integer.Parse(TextBoxListTarget(index).value), Integer.Parse(TextBoxListActual(index).value), Integer.Parse(txtTolerance.Text))
        lblTest.Text = "In Tolerance"
    Else
        lblTest.Text = "Out of Tolerance"
    End If
Next

little bit of an example.  probably not perfect.


Make sure the user enters a valid floating-point number in C

@Justin advice is solid.  Read a line.

scanf_s("%f", &input) offers no advantage over the more portable scanf("%f", &input)
scanf_s/scanf("%f", &input) allows the user to enter multiple lines before the number - so a blank line of input is not detected.
scanf_s/scanf("%f", &input) does not detect trailing non-numeric input.
while (scanf_s("%f", &input) != 1) does not cope with non-numeric entries - they remain in stdin.
Overflow is UB with scanf() and friends.

Instead separate the task: input, parsing.

#define MAXLINE_SIZE 100
char buf[MAXLINE_SIZE];
if (fgets(buf, sizeof buf, stdin) == NULL) Handle_EOF();

size_t len = strlen(buf);
if (len == 0 || buf[len-1] != '\n') {
  // consider the line hostile and fail it.
  // consume rest of line
  clear_stream(stdin);
  return FAIL;
}

Parse using strtod() - Simple example.  Additional considerations if over/underflow detection needed.

errno = 0;
char *endptr;
float y = (float) strtod(buf, &endptr);

if (buf == endptr) Handle_NoConversion();
// consume trailing spaces
while (isspace((unsigned char) *endptr) endptr++;
if (*endptr) Handle_TrailingJunk().

// Good to go;
return y;

Good use of fflush(stdout); before input and after the re-prompt that may lack a \n.  I would not hard code in the re-prompt value, but pass it in.

Good use of int ch; when testing the return value of getc().

Using %f to print floating point is problematic should the float be small (output only 0.000000) or large (many to hundreds of digits).  Consider %.*e


Approximating sines and cosines using up to five terms of the Taylor series

Instead of computing Math.pow() from scratch, multiply the previous numerator by x2.  (I suspect that Math.pow() uses logarithms so that it can handle the general case.)  Also, instead of computing the factorial from scratch, multiply the previous denominator by the next two numbers.


Using foldl to add numbers, while validating that they are nonnegative

import Data.Foldable

addAll :: [Int] -> Either String Int
addAll = foldlM safeAdd 0 where
  safeAdd :: Int -> Int -> Either String Int
  safeAdd n next = if next < 0
    then Left (show next ++ " is not positive")
    else Right (n + next)

Refer http://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Foldable.html#v:foldlM


It's often best to write this kind of function along with its tests.  Let's start with a simple test:
import doctest;

def englishify(number):
    """Format NUMBER into standard English form.
    NUMBER must be in range [0..999999]
    >>> englishify(0)
    'Zero'
    """

    return 'Zero'

if __name__ == '__main__':
    doctest.testmod()

Now, start adding more tests and make each one pass before moving on to the next.
You'll find that when you reach the bigger numbers, there's a useful recursive property.  We can split off the thousands and the hundreds, format each non-zero part separately, and then join using one of the techniques from Joining words together with a comma, and “and”.  For example, consider these inputs:

123456 ⟶ 123 Thousand , 4 Hundred and 56
123056 ⟶ 123 Thousand and 56
123400 ⟶ 123 Thousand and 4 Hundred

Now those individual numbers can be formatted into words (and the last case will have two "and"s in normal English: "One hundred and twenty-three thousand, four hundred and fifty-six.'

Modified code
import doctest;

def englishify(number):
    """Format NUMBER into standard English form.
    NUMBER must be in range [0..999999]
    >>> englishify(0)
    'Zero'
    >>> englishify(10)
    'Ten'
    >>> englishify(20)
    'Twenty'
    >>> englishify(99)
    'Ninety Nine'
    >>> englishify(100)
    'One Hundred'
    >>> englishify(101)
    'One Hundred and One'
    >>> englishify(1001)
    'One Thousand and One'
    >>> englishify(1201)
    'One Thousand, Two Hundred and One'
    >>> englishify(123201)
    'One Hundred and Twenty Three Thousand, Two Hundred and One'
    """

    Units = [None, 'One', 'Two', 'Three', 'Four', 'Five',
             'Six', 'Seven', 'Eight', 'Nine',
             'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen',
             'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
    Tens = [None, None, 'Twenty', 'Thirty', 'Forty', 'Fifty',
            'Sixty', 'Seventy', 'Eighty', 'Ninety']

    if number < 20:
        return Units[number] or 'Zero'

    if number < 100:
        return ' '.join(filter(None, [Tens[number//10], Units[number%10]]))

    # Larger numbers - break down and englishify each part
    parts = list(filter(None,
                        map(lambda quantity, number:
                                englishify(number) + quantity if number else None,
                            [' Thousand', ' Hundred', ''],
                            [number // 1000, number // 100 % 10, number % 100])))

    if len(parts) == 1:
        return parts[0]
    return ' and '.join([', '.join(parts[:-1]), parts[-1]])

if __name__ == '__main__':
    doctest.testmod()

The extension to support millions and more should now be obvious - just add the unit and its extraction to the list passed to map().


Drop the Intermediate String

You're allocating compareString and strcpying into it just so that you can use strcmp. But instead, there's also memcmp, which lets you compare from the original string directly:

Fix the loop condition

You're not really looping from 0 to stringLength, you're looping from 0 to stringLength - patternLength. Splitting up those concerns in two is confusing.

Adjusting i

You have:

i--;
i+=patternLength; /* non overlapping find */

We can do both in one:

i += patternLength - 1;

Better solution:

size_t count(char *string, char *pat) {
    size_t patternLength = strlen(pat);
    size_t stringLength = strlen(string);
    size_t count = 0;

    for (int i = 0; i < stringLength - patternLength; i++) {
        if (memcmp(string+i, pat, patternLength) == 0) {
            count++;
            i += patternLength - 1;
        }

    }

    return count;
}


Looking up the name and event for a ticket

You can avoid writing exit() twice by adding a return statement at the deepest level, after passing all the checks. This should be equivalent to your code:

public function action_index()
{
    $id = $this->request->query('id');
    if (!empty($id)) {
        $ticket = ORM::factory('ticket')
            ->where('id', '=', $id)
            ->find();
        if (!empty($ticket)) {
            $event = ORM::factory('event')
                ->where('id', '=', $ticket->event_id)
                ->find();
            if (!empty($event)) {
                $this->template->ticket = $ticket->id;
                $this->template->name = $ticket->name;
                $this->template->event = $event->title;
                return;
            }
        }
        exit();
    }
}

That said, I find it a bit strange to exit() in the middle of a function.
It's an abrupt behavior in a program in general,
this kind of control is usually done at higher levels,
in order to do any necessary cleanup, such as releasing resources,
closing connections.


You can improve it by making it a loop instead of a recursive call. There is no need for the recursion, and it limits you in ways that a loop would not (for example, you are limited by your stack size with recursion).

Additionally, the loop implementation is simpler, and probably a bunch faster too.

If you do stick with the recursive call, you should make the recursive method private too.

The loop could be as simple as:

void ReverseArray<T>(T[] a)
{
    for (int lo = 0, hi = a.Length - 1; lo < hi; lo++, hi--)
    {
        var temp = a[lo];
        a[lo] = a[hi];
        a[hi] = temp;
    }
}

Normally I would take issue with the short variable names, but, in this context, with the generic array data type, a is not too bad of a name.

The only style issue I have other than the a, is that you need space around the operators in your conditions and assignments. The code:

ReverseArray(a,0,a.Length-1);
....
ReverseArray(a,lo+1,hi-1);

should be:

ReverseArray(a, 0, a.Length - 1);
....
ReverseArray(a, lo + 1, hi - 1);

Note, that if the recursive call is required as part of an exercise, then it is implemented correctly/functionally, and I can't see any problems other than the limited size of the array (I would guess about 40,000 elements is too many to handle).


The good

Short, focused methods. Methods should be short and have a single responsibility. With your conversion related methods, you've achieved this - nice job. Ruby especially encourages small methods; it's common to see them be as short as a single line.
It works. Your program appears to correctly convert between temperatures.
It's readable. You followed reasonably good formatting and style guidelines. Note that conventional Ruby style uses 2 spaces rather then tabs for indentation - I recommend adopting this.

Suggestions

One way you might shorten things up and dynamicize is as follows:
rather than having 6 methods handling each conversion, you could cut it in half by writing functions such as this:

def convert_to_fahrenheit(start_unit, temp)
  if start_unit == 'C'
    return temp * 1.8 + 32
  elsif start_unit == 'K'
    return temp * 9 / 5 - 459.67
  else
    raise ArgumentError, "Unit: #{start_unit} is invalid. Unit should only be K or C"
  end
end

With this solution, the tradeoff is that our methods get bigger but they're still reasonably short and each still has a single responsibility.

Of course with this solution you have to change the existing 1-6 numbery way of gathering input. Instead you might have methods like:

def print_starting_unit_request
  puts "Enter the temperature unit you have (C, F, K):"
end

def print_resulting_unit_request
  puts "Enter the temperature unit you want (C, F, K):"
end

def get_temperature_unit_input
  gets.chomp.upcase
end

def valid_input_temperature?(input)
  ['K', 'C', 'F'].include? input
end

def units_match?(starting_unit, resulting_unit)
  starting_unit == resulting_unit
end

This would eliminate the long series of repetitive case statements. You might have something like:

def convert_temperature(start_unit, end_unit, temp)
  if end_unit == 'C'
    convert_to_celcius(start_unit, temp)
  elsif end_unit == 'K'
    convert_to_kelvin(start_unit, temp)
  elsif end_unit == 'F'
    convert_to_fahrenheit(start_unit, temp)
  else
    raise ArgumentError, "Unit: #{end_unit} is invalid. Valid (K, C, F)."
  end
end

Do note that this is not an ideal solution. It is preferable to use an object-oriented class based solution rather than conditionals; I get the sense that you might not have learned OOP yet. This would be a good exercise in OOP by refactoring once you get more comfortable.

These are rough ideas to get you going and of course you'd have to set up the logic appropriately (looping, etc). A key idea here is that you want to be using methods often. Methods are self documenting and make code more readable.

One thing I noticed when looking at:

**1) Convert Celsius to Fahrenheit**
2) Convert Fahrenheit to Celsius
3) Convert Fahrenheit to Kelvin
4) Convert Kelvin to Fahrenheit
**5) Convert Celsius to Kelvin**
6) Convert Kelvin to Celsius
0) Quit

Every other combination of starting temperature seems sensibly grouped together but 1 & 5 unexpectedly are split up. I would have expected 5 to come right after 1. This might not seem like a big deal and it really isn't here but I think it illustrates a couple of important ideas of writing clean code to be mindful of: consistency and don't be arbitrary.

Consistency is often mentioned related to various aspects of writing good code; it's especially important when many people are touching the same software. The essential idea is that when things are consistent, they are more easily read and understood; when they're not, things tend to stick out, distract us, and interrupt the flow of whatever we're trying to do.

Don't be arbitrary is an idea I recently read from Clean Code, a popular book about writing... clean code:

  Have a reason for the way you structure your code, and make sure that reason is communi- cated by the structure of the code. If a structure appears arbitrary, others will feel empowered to change it. (Martin, 303)

This may seem overkill for a post like this, but hey, I just finished reading the book and want to help reinforce the concepts. But I think it's a good thing to be aware of no matter what level the programmer. In this situation, we structure our input capturing into intuitive grouping that the user might expect - therefore, it's not arbitrary.

Style note:
Prefer spaces between operations (and be consistent). You have both:

ans = c*1.8+32

ans = k * 9/5 - 459.67

Prefer the later.


The Security Aspect
Good to see that you're not just checking for a file extension in the name!!
Basically, yes, it's the minimal security needed. There aren't too many steps needed to make an image uploading script safe, however, doing it wrong could present some future issues.
Here's some notes though:

When renaming the file, what's the point in changing the name to something similar but with characters replaced? You could (not recommended) keep the original name, or you could completely alter the name to something unpredictable, and then use a look-up table (i.e. database) to point the user in the correct path. Instead of simply swapping out illegal characters with underscores, give the file a name that has no resemblance.

The permissions on your directory do look okay. It is however, not a bad idea to simply remove the images from the public directories, place them in say var/www/uploads/ and let a script get them for you. You don't want these images being in a directory where PHP (or any other server scripts) may run.

Simply appending $parts["extension"] onto the file seems risky to me. You did check the image type, however I'm not sure how it responds to files with multiple extensions. Someone with more knowledge here could extend this...

Non-Security Related

exit(); and exit; are used throughout. Please don't! Two things: be consistent, they're aliases (along with die); don't use them, they leave the end-user hangin'! These kill the page with no clean way to display an error.

Using names such as myFile are quite book/tutorial copy-and-pasted. Choose names that have meaning to your application.

 echo "
An error occurred.
"; Lot's of things I could say here. 1) An error!? No kidding! You kill the page right after this without even saying what the user should do to correct the error. (Doesn't matter if you're the only person using this)

$name, $parts, $success - more unhelpful variable names!

Other than that, it's a simple piece of code, and there's already tons of people who have done this, plus more. It's usually safer to work with a community run library than to create your own!


Don't store what you can calculate:

public class YouOweTheGovernment
{
    public float AmountToPay
    {
        get { return Salary * (ArbitraryTaxRate / 100); }
    }
    public float ArbitraryTaxRate { get; private set; }
    public float Salary { get; private set; }

    public YouOweTheGovernment(float taxRate, float salary)
    {
        this.ArbitraryTaxRate = taxRate;
        this.Salary = salary;
    }
}

Your AmountToPay field is basically a cache, and caching is notoriously problematic. Case in point: even your tiny code here has a cache invalidation bug. If you change the tax rate or salary, you aren't recalculating the amount to pay.

Every time you add a field, ask yourself "does this field store unique information that no other field stores?" If the answer is no, don't create the field. The less state you have, the easier it is to understand your code.


Scraping images from a webpage and saving it to a customized folder using vba

The code is quite clear to read and understand. There are only minor things I would improve:

better variable names - tempArr, for example, is a bad name - what about:

fileSource = Replace(html.src, "about", "http")
urlParts = Split(html.src, "/")
imageFileName = urlParts(UBound(urlParts))

and then use imageFileName instead of tempArr later on. Also think of better names for htmla and htmlas.
you can use with for the stream variable as well
avoid "hardcoding" - define "D:\Test\Images\" path as a constant, or as a parameter for your function
you can also iterate over the img elements directly if you do:

Set movieImages = htmldoc.querySelectorAll(".movie img")


Attempting to build template but Having Issue with gets and posts

Well a more elegant approach would be to use an MVC pattern as a starter framework I would suggest you to use Laravel it's very clear written and also an easy catch for people who are general new to MVC. The way your currently writing the code, you include to much business logic inside of it.

Which in the long term is terrible because the code becomes un-maintainable, for that the MVC Pattern is the best way to write clear and maintainable code, but check it out yourself. An good article to start with should be this one by Nettuts, called MVC for Noobs don't get irritated by the name the article is pretty good and should get you a basic understanding of the MVC pattern.

Hope I could be a little help :)


Passing JSON object through loop to be used in jQuery Dialog

The key problem I have with your code right now is that it doesn't separate data from presentation. This is a maintainability issue because it means now your data is inexplicably tied to your view, and you cannot change one without altering the other. How can we fix this?

As someone earlier suggested, you could use a template library. When I'm doing stand-alone development (i.e, not using a framework), I really like rivets. It's lightweight (6.2kb), simple and unopinionated.

I would have recommended dropping jQuery, but I see that you're using a plugin for jQuery, so I can't really suggest that. I would say that if you can find a way to avoid using jQuery here, that would be great. The reason I don't want you using jQuery is because it's a heavyweight library; it's 34kb, which is over 5x the size of Rivets.

The time-to-last-byte is very important in JavaScript development because until your consumer has received the last byte, your JavaScript is doing nothing, which potentially makes part of your site unusuable. As such, if you can remove any cruft from your site to make it load all of the script tags faster, the better off you will be.

First, we'll define a HTML layout for your tracking info. As your tracking info is tangential to the current information, we can make this use the  HTML element.

      ID
      Summary
      Class

        <button>Detail</button>

So above is the basic structure of your dialog. There's a lot of inline styling, and the only thing your "if" statement is for is to add alternating classes. No need to do that here! We can do that in CSS just fine. First of all, lets apply your styles with a bit of CSS. We'll add a .data-table class to your table, although I would definitely recommend naming it something more descriptive; .data-table is pretty ambigious. You want to describe the role this thing fulfills, not what it is. In other words, be more declarative with your css names. In addition, we'll add a .results-table class to the encapsulating . Whilst I'm not sure this is completely correct, it appears to be closest to what you are doing.

First, let's tackle the overarching styles of each of the tables:

.data-table {
  border: 0;
  width: 60%;
  align: center;
}

You'll notice I have not included the  styling. This is because the width of a  is decided by the browser and not the CSS. This makes sense if you are using truly tabular data. If you're not using tabular data (and I suspect you're not), then you should use a
.
 are definition lists which may be more suited for this sort of thing.

You appear to have some kind of alternate styling based on whether or not a .data-table is an even .data-table. I'm not sure what this styling is because it isn't supplied, but you can replicate this class by using the following CSS selector:

.results-table:nth-child(even) {
  // some CSS styling here
}

So far, we have this:

        <button>Detail</button>

Now, your data model looks something like this:

var model = {
  someNumericValue: {
    TrackInfo: {
      Attributes: {
        ID: 0
      },
      StatusSummary: "summary",
      Class: "first"
    }
  }
};

Wow, this looks a lot like an array! It might be, or it might not be. It's hard to tell because arrays are actually objects. This means that they have access to the hasOwnProperty of an object. Lets assume it is an array because that makes more sense.

var models = [
  {
    TrackInfo: {
      Attributes: {
        ID: 0
      },
      StatusSummary: "summary",
      Class: "first"
    }
  }
];

With this data model, we can easily slot this into our template using rivets bindings. Lets take a look at how it pans out (I've skipped the popup at the moment, we'll get into that in a bit).

        <button>Detail</button>

Now when we set up rivets on this element, as long as we pass in all of our models to "models" - voila, you'll have data binding. Of course, this isn't 100% perfect because we're still relying on our JavaScript to populate the data, however it's a good start; the HTML structure is there and it's declarative. Anyone reading over this file with some knowledge of how rivets works would be able to tell what this does, and the HTML isn't hidden away in JavaScript - the only thing we're getting from JavaScript is the repeating behaviour and the values. This is a good shift!

How would you use this, you might ask? Well, to bind the  to data, it really is as simple as this:

var dialog = document.querySelector('aside.results-table');
rivets.bind(dialog, { order: models });

Where, obviously, models is your array of data. This will ensure that all of your data is bound correctly. Note that this is only one-way data binding though, so any changes you make (DOM -> Model, such as a form) will not be reflected in the change to the view - only model changes will update the view.

Alright, so we have the basic setup done. Now, how do we tackle the fact that we have a pop up that is displayed as well? Well, this gets a bit tricky because you're using a jQuery plugin. It's going to be difficult to neatly display a popup based on DOM elements without doing some nasty fudging. The easiest way would be to continue using jQuery like you're doing now. However, this presents some nasty stuff, namely that you're using numbered IDs to access the dialogs. Ouch! Instead, I would suggest creating a Dialog in HTML and not using JQuery. Like this:

<dialog>
  <title>Detailed View</title>

        <button>OK</button>

</dialog>

Note that the <dialog> element is a HTML5 element, so you may want to change this to a
 if you need to support browsers that aren't HTML5. However, given that I've used  and
 you would need to do that for everything else as well. Worst case scenario, use a HTML5 polyfill. Let's put this all together and add the functionality for the pop-up to be closed/opened after the button is clicked..

            <button rv-on-click='showMoreInfo'>Detail</button>

    <dialog rv-if='order.displayMoreInfo'>
      <title>Detailed View</title>

            <button rv-on-click='hideMoreInfo'>OK</button>

    </dialog>

Note how I've moved the rv-each-order to a
 that encapsulates both the
 and the <dialog>. This makes it easier to group the elements together and better represents that they are a single, isolated section of content compared to the other orders you've put in here. On clicking of the "Detail" button, the dialog will be shown. When the dialog "OK" button is clicked, the dialog will be hidden. Simple stuff, right? (Note: Shown and hidden is not a good analogy. What actually happens is that the entire <dialog> will be removed/added to the DOM. If you wish to instead actually show/hide the <dialog> - for performance reasons, maybe - then use rv-show/rv-hide).

Now, lets add the final bootstrapping logic..

function hideMoreInfo(event, context) {
  var currentOrder = context.order;
  currentOrder.displayMoreInfo = false;
}

function showMoreInfo(event, context) {
  var currentOrder = context.order;
  currentOrder.displayMoreInfo = true;
}

var resultsTable = document.querySelector('.results-table');
rivets.bind(resultsTable, {
  hideMoreInfo: hideMoreInfo,
  showMoreInfo: showMoreInfo,
  orders: models
});

That's it - we're done with the logic side of things! The only thing left would be to do CSS. Unfortunately, I can't do more CSS than what I've done for you because you haven't actually linked any, but if you would like some more help on tht please let me know and I'll gladly oblige.

To summarize, here's the finalised code:

HTML

            <button rv-on-click='showMoreInfo'>Detail</button>

    <dialog rv-if='order.displayMoreInfo'>
      <title>Detailed View</title>

            <button rv-on-click='hideMoreInfo'>OK</button>

    </dialog>

JavaScript

function hideMoreInfo(event, context) {
  var currentOrder = context.order;
  currentOrder.displayMoreInfo = false;
}

function showMoreInfo(event, context) {
  var currentOrder = context.order;
  currentOrder.displayMoreInfo = true;
}

var resultsTable = document.querySelector('.results-table');
rivets.bind(resultsTable, {
  hideMoreInfo: hideMoreInfo,
  showMoreInfo: showMoreInfo,
  orders: models
});

CSS

.data-table {
  border: 0;
  width: 60%;
  align: center;
}


In cases where your value is determined by a string key, a key-value mapping is often the way to go. In this case, we store your icon JSX and questions in objects keyed by description. Then you simply access them using the current description as key.

const icons = {
  Happy: <FontAwesomeIcon icon={faSmile} />,
  OK: <FontAwesomeIcon icon={faMeh} />,
  Angry: <FontAwesomeIcon icon={faAngry} />
}

const questions = {
  Happy: 'You answered happy. Why?',
  OK: 'You answered OK. Why?',
  Angry: 'You answered angry. Why?'
}

class myQuestion extends PureComponent {
  render() {
    const { description } = this.props.question
    const icon = icons[description] || ''
    const question = questions[description] || ''

    return (
      <div>
        <Question
          icon={icon}
          description={description}
          question={question}
        />
      </div>
    )
  }
}