Selecting multiple checkboxes to show similar but different boxes

A few notes on your code:

If you don't need supporting of very old or non-standard browsers, and given that your project does not relies heavily on jQuery, vanilla JavaScript can do the same work, without jQuery's overhead.
On each checkbox click, all coloured divs are queried again and again (jQuery('.box')), which is unnecessary as there are no changes in the DOM.
All checkboxes are queried multiple times, instead of selecting them once.
The if-then structure is quite cumbersome: if #red is checked, show .red.box. Then, if #green is also checked, hide .red.box and show .redgreen.box. Then, if #blue is checked too, hide .redgreen.box and show .rbg.box. One way for improving this part would be to first determine exactly which box should be checked and show only that box.
Personally, I would have used combinations of the .red/.green/.blue classes, instead of putting a different class for each combination (e.g. .box.red.green.blue instead of .box.rgb). That way each checkbox corresponds with a particular div class.

Here is my take on the problem/homework/exercise, that addresses most of the above remarks (no CSS/HTML changes; still using jQuery):
        const RED = 1;
        const GREEN = 2;
        const BLUE = 4;

        const DIV_CLASSES_MAP = [null, '.red', '.green', '.redgreen', '.blue', '.redblue', '.greenblue', '.rgb'];
        const DIVS = $('.box');
        const RED_TICK = $('#red');
        const GREEN_TICK = $('#green');
        const BLUE_TICK = $('#blue');

        let activeDiv = DIVS.filter(':visible');
        $('input[name="colorCheckbox"]').on('click', onCheckboxChange);

        function onCheckboxChange() {
            const redBit = RED_TICK.is(':checked') ? RED : 0;
            const greenBit = GREEN_TICK.is(':checked') ? GREEN : 0;
            const blueBit = BLUE_TICK.is(':checked') ? BLUE : 0;
            const mask = redBit + greenBit + blueBit;
            const activeClass = DIV_CLASSES_MAP[mask];
            activeDiv.hide();
            activeDiv = DIVS.filter(activeClass).show();
        }


Computing the integer square root of large numbers

Your function is rather unnecessary. When converted to double, all 64-bit integers retain 1 sign bit and at least 52 precision bits. So the error is at most 11 bit; which means for any number N, the error $$dN<=\frac{2^{11}}{2^{63}}N=2^{-52}N$$
With simple calculus, the error of sqrt() is $$d(\sqrt{N})=\frac{dN}{2\sqrt{N}}<=\frac{2^{-52}N}{2\sqrt{N}}=2^{-53}\sqrt{N}<2^{-53}*2^{32}=2^{-21}<<1$$
In any case the error must be smaller than 1. With rounding/truncation, it can only be -1, 0, or 1.

So your code can be

func isqrt(_ n: Int) -> Int {
    var r = Int(Double(n).squareRoot()) // Initial approximation
    if r * r > n { r -= 1 }
    else if (r + 1) * (r + 1) <= n { r += 1}
    return r
}

edit:
There will be time that (r + 1) * (r + 1) be larger than Int.max and causes error. Instead of using multipliedReportingOverflow, I would do it this way

func isqrt(_ n: Int) -> Int {
    if n >= 3037000499 * 3037000499 {return 3037000499}
    var r = Int(Double(n).squareRoot()) // Initial approximation
    if r * r > n { r -= 1 }
    else if (r + 1) * (r + 1) <= n { r += 1}
    return r
}

edit 2:
To deal with different possible Int sizes:

func isqrt(_ n: Int) -> Int {
  #if arch(i386) || arch(arm)
    if n >= 46340 * 46340 {return 46340}
  #else
    if n >= 3037000499 * 3037000499 {return 3037000499}
  #endif

  var r = Int(Double(n).squareRoot()) // Initial approximation
  if r * r > n { r -= 1 }
  else if (r + 1) * (r + 1) <= n { r += 1}
  return r
}


Using RestTemplate for HTTP request timeout

In the example you linked, RestTemplate is annotated with @Bean:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate(clientHttpRequestFactory());
}

Beans are (normally) singletons in Spring, intended for reuse. This related post also confirms that RestTemplate is thread-safe, and it would be wasteful to recreate it every time.

It would be best to configure RestTemplate as in the linked article, and inject into your setup using Spring's annotations based configuration. Or, you could make it a private final member of your class.

class RequestHandler {
    private final RestTemplate restTemplate;

    public RequestHandler() {
        restTemplate = new RestTemplate(clientHttpRequestFactory());
    }

    public RestTemplate getRestTemplate() {
        return restTemplate;
    }
}


Although you've probably already solved this problem, I'll still post my review for completion's sake.
1. Performance
Just as Loki said, you should use std::lower_bound() and std::distance() to solve this task, because std::find() has higher complexity.
2. General tips

Do not include unused libraries (in this case, <cmath> and <cstdio>).

Only declare variables when you need them. Declaring all the variables at the beginning of the program is old C style practice, which is discouraged in C++.

Prefer prefix to postfix operator++. The postfix version creates a copy, so if you do not need that copy, you should use the prefix version.

If you have access to C++11, you should consider using auto more. It'll make your code easier to read and save you some typing.

You can safely omit return 0 from main();

[C++11: 3.6.1/5]: A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;.

Give your variables better names. Although other variable names in your code are good, a vector named v is not very descriptive.

Use const_iterators for functions that do not alter the original range.

3. Final code
#include <vector>
#include <iostream>
#include <algorithm>

int main() {
    int N;
    std::cin >> N;

    std::vector<int> numbers(N);
    //populate the vector
     for(int i = 0; i < N; ++i) {
         std::cin >> numbers[i];
     }

    int queryLength;
    std::cin >> queryLength;

    for(int j = 0; j < queryLength; ++j) {
        int query;
        std::cin >> query;
        auto lowerBoundIt = std::lower_bound(numbers.cbegin(), numbers.cend(), query);
        if(*lowerBoundIt == query) {
            std::cout << "Yes ";
        }
        else {
            std::cout << "No ";
        }
        std::cout << std::distance(numbers.cbegin(), lowerBoundIt) + 1 << '\n';
    }
}


Simple builder pattern implementation for building immutable objects

First of all, very good job.

Now I will point out a few things that I think can be improved on.

Code Duplication

You have copied over all the private fields from Person to the Builder, which is necessary when the fields are declared final. As coderodde pointed out, using a final declaration is not necessary here when the fields are private and there are no setters.

Now that the fields are no longer declared final, it is possible to hold an unfinished version of your Person object in your builder. Now all the fields from Person no longer need to be copied over.

This also prevents the need for the getter methods on your Builder and the weird constructor of Person that takes a Builder as a parameter. The Person class should not be initializing itself via the state of the Builder object. The Builder should be building the Person, hence the name of the pattern.

Excessive commenting

You use comments a lot, even at places where they aren't needed and are generally just noisy. For example:

// getters

and

// getters, these will be used in private constructor
// of Person class`.

The first one is simply redundant, since all the methods below it are called get..., clearly indicating a getter function. The second one also provides little useful information. Note that generally, someone will read a code file from top to bottom, unless they might be looking for the details on a specific method. This would mean that they have already scrolled past your constructor and seen the getters being used there.

But there is a bigger point I want to make here with regards to the comments. In general, using comments to express what your code does, means that you have failed to express yourself in code, which can document itself when names are chosen carefully.

Coming back to the second comment I mentioned. You probably wrote that because you felt that you had to explain yourself for having public getters on your Builder class. When placing a comment like this, take a step back and ask yourself why you placed that comment and if your code would still seem logical without it. If your code seems weird without the comment, which I think public getters on a Builder class do, then you need to fix that issue instead of commenting about why you did it.

Now by moving the initialization of the Person to the Builder class where it belongs, as mentioned above, the Builder no longer needs these methods and the comment can be removed.

The same goes for the comment about the temporary member variables, which can now be removed as the Builder simply holds an instance of the Person class, which makes perfect sense on its own.

I went on a bit of a rant about comments, but I hope you can see what I mean.

Naming

Overall, job well done with the naming. A few remarks though:

I'd rename PersonBuilder to Builder. It's an inner class of Person so there really is no need for it. Person.Builder is perfectly fine.
I'd also rename the individual building methods for id, name, surname and isOccupied to setId, setName, setSurname and setOccupied, since they are all effectively setters.

Reworked Code

When incorporating these points into your code, it should look a little something like this.

public final class Person {
    private int id;
    private String name;
    private String surname;
    private boolean isOccupied;

    private Person() {}

    public static class Builder {
        private Person personToBuild;

        Builder() {
            personToBuild = new Person();
        }

        Person build() {
            Person builtPerson = personToBuild;
            personToBuild = new Person();

            return builtPerson;
        }

        public Builder setId(int id) {
            this.personToBuild.id = id;
            return this;
        }

        public Builder setName(String name) {
            this.personToBuild.name = name;
            return this;
        }

        public Builder setSurname(String surname) {
            this.personToBuild.surname = surname;
            return this;
        }

        public Builder setOccupied(boolean isOccupied) {
            this.personToBuild.isOccupied = isOccupied;
            return this;
        }
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getSurname() {
        return surname;
    }

    public boolean isOccupied() {
        return isOccupied;
    }

    @Override
    public String toString() {
        return String.format(
                "Id:\t\t%d\nName:\t\t%s\nSurname:\t%s\nIsOccupied:\t%s\n"
                , id, name, surname, isOccupied);
    }
}


this isn't much shorter but instead of

; add the hyphens between each block
data: insert skip data 8 "-"
data: insert skip data 4 "-"
data: insert skip data 4 "-"
data: insert skip data 4 "-"

head data

you could write

parse data [8 skip insert "-" 3 [5 skip insert "-"] to end]
data

And you don't need a for loop

loop 30 [print makeuuid]


Find almost-shortest path more efficiently

Here's a partial/basic structured implementation of the problem. It works for the first two cases, but the last case comes back twice as large. I saw this question on SO and thought your version was highly over complicated and probably inefficient due to data structure choices. There isn't any reason to provide and pass around multi-dimensional vectors and such, and there's no doubt you could drop that priority_queue.

Take a look at mine and see if you could simplify yours. Since your logic, I'm assuming, works you should be able to catch the last case without too much effort. I wasn't intending to finish it I just wanted to see if it could easily be done without such complexity. It isn't meant to replace yours, it's just to provide a second opinion on it.

Take a look:

Note: Some of the variable are there because of the problem distription.
      Some validations are missing because the test data didn't require them.

#include <iostream>
#include <vector>
#include <algorithm>

using std::cin;
using std::cout;
using std::vector;
using std::sort;

const int START = 0;
const int END   = 1;
const int DIST  = 2;

vector<int> getPaths(int **, int, int, int);
int getDistance(int **, int , int , int , int , int&);

int main (void)
{

    int input = 0;
    int n = 0, m = 0, s = 0, d = 0, u = 0, v = 0, p = 0;
    int shortestPath = 0;
    int nextShortestPath = 0;
    int **pathPtr;
    vector<int> allDistances;

    cin >> n;
    if (n >= 2 && n <= 500) {
        cin >> m;
        if (m >= 1 && m <= 100000) {
            cin >> s;
            cin >> d;
            pathPtr = new int*[m];
            for (int i = 0; i < m; ++i) {
                pathPtr[i] = new int[3];
            }
            for (int i = 0; i < m; ++i) {
                for (int j = 0; j < 3; ++j) {
                    cin >> input;
                    pathPtr[i][j] = input;
                }
            }
            allDistances = getPaths(pathPtr, m, s, d);
            sort(allDistances.begin(), allDistances.end());
            for (unsigned int i = 0; i < allDistances.size(); ++i) {
                if (allDistances[i] != 0) {
                    shortestPath = allDistances[i];
                    if (i + 1 < allDistances.size()) {
                        nextShortestPath = allDistances[i + 1];
                        break;
                    } else {
                        nextShortestPath = -1;
                        break;
                    }
                }
            }
            cout << nextShortestPath;
        }
    }
    cin.get();
    return 0;
}

vector<int> getPaths(int **paths, const int m, const int s, const int d) {
    vector<int> distances;
    int distance = 0;
    int shortest = 0;
    int tempShort = 0;
    for (int i = 0; i < m; ++i) {
        if (paths[i][START] == s) {
            distance = 0;
            if (paths[i][END] == d) {
                distances.push_back(paths[i][DIST]);
            } else {
                distances.push_back(getDistance(paths, i, i + 1, m, d, distance));
            }
        }
    }
    return distances;
}

int getDistance(int **paths, int i, int j, int m, int d, int &distance) {
    if (paths[j][START] == paths[i][END]) {
        distance += paths[i][DIST];
        if (paths[j][END] != d) {
            if (j < m) {
                distance += getDistance(paths, j, j + 1, m, d, distance);
            } else {
                distance = 0;
            }
        } else {
            distance += paths[j][DIST];
        }
    } else {
        getDistance(paths, i, j + 1, m, d, distance);
    }
    return distance;
}

Let me know if it improved your running time any. Good Luck!


Using Delegates and BeginInvoke with .NET 2.0 WebServices

This Stack Overflow answer to the question "Is there a VB.NET equivalent of C# out parameters" is pretty clear:

  No, there is no equivalent construct that allows a non-initialised variable to be passed to a method without a warning [...]

However specifying the <Out()> attribute, despite being ignored by VB (ByRef is all you need, really), does allow a C# client to use it as an out parameter - so good call then!

Declaring the delegate at the bottom of the module, after it's being used, makes it uselessly confusing and prompts for unnecessary scrolling; I would have put it at the top... actually, I would have made the delegate a public member of the WebService class:

Public Class WebService
    Inherits System.Web.Services.WebService

    Public Delegate Function AsyncDoStuff(ByVal callDuration As Integer, <Out()> ByRef threadID As Integer) As String

    '...

I very, very seldom declare my own delegate types, if at all. I don't like ref ByRef and out <Out()> parameters either - I think they should be avoided.

In this case I would have gone with a Func<int,AsyncStuffResult> (please excuse the C# notation), where the int parameter is the callDuration, and the AsyncStuffResult is a class that encapsulates everything you want to return from the function call - whatever that is.

This way if/when you need to return more things, your signature doesn't need to change, you only add new members to your result class - note that the EventArgs class fulfills the same goal.

Public Class AsyncStuffResult
    '- expose ThreadId as a get-only property
    '- expose your String result as a get-only property, too
    '- expose a constructor to assign the members
End Class


Let's play Rock, Paper, Scissors with Ruby

Fix your formatting. While the computer doesn't care about indentation, humans do. And code is read (by humans) many more times than it's written. And this code is hard to read.

The whole "draws" logic can be replaced with a simple check: human == comp.

Determining the winner of a "hand" in rock-paper-scissors can be done in many, many, many ways. You're checking it "manually" in a sense, by writing out all the possible combinations. But you could also assign numeric values to the choices (for instance, their index in an array), and compare those numbers instead. Or so something like this, where the player's choice is used to determine what the winning response would be and see if the computer picked that:

choices = %w(rock paper scissors).reverse

index = choices.index(player_choice)
winning_choice = choices[index - 1]

if computer_choice == winning_choice
  # computer wins
else
  # human wins
end

(this assumes that player_choice and computer_choice have already been set and that you've checked for draws.)


Efficiently sample a single row of an array at random

I can only comment on the C++ code, as I've never used R nor Rcpp.

For an ignorant reader such as myself, it would have helped to omit the using namespace Rcpp;, so that I could see which names come from that library (I did quite a bit of external reading to even understand the code).

Assuming I'm right that sample() returns an array of length k, then we can use range-based for to iterate through its values (since IntegerVector has suitable begin() and end()):

// sample k values from x, without replacement
const Rcpp::IntegerVector ind_index = Rcpp::RcppArmadillo::sample(x, k, false);

// how many different values do they index in pop_ptr?
std::set<int> distinct_container;
for (int i: ind_index) {
    distinct_container.insert(pop_ptr[i]);
}

In accumulate() (which name I dislike, because it sounds like std::accumulate()), we can reduce the scope of i, j, k and pop_ptr quite simply:

for (int i = 0; i < K; ++i) {
    for (int k = 0;  k < num_specs;  ++k) {
        for (int j = 0;  j < perms;  ++j) {
            const int *const pop_ptr = &(pop(sample_one(perms), 0, sample_one(K)));
            res(j, k, i) = sample_n_distinct(specs_C, k + 1, pop_ptr);
        }
    }
}

Also, I'd be inclined to show that the creation of specs_C is more than just a conversion from specs - 1 - that's actually a constructor argument specifying the length of the new vector:

IntegerVector specs_C(specs - 1);

I don't see any code that ever modifies this vector; if it's supposed to remain full of zeros, then it can be declared const.

With those changes, and an automated re-indent, we get something like this for those two functions (I've compiled, but not tested this):

int sample_one(int n)
{
    return n * R::unif_rand();
}

int sample_n_distinct(const Rcpp::IntegerVector& x,
                      int k,
                      const int * pop_ptr)
{
    // sample k values from x, without replacement
    const auto ind_index = Rcpp::RcppArmadillo::sample(x, k, false);

    // how many different values do they index in pop_ptr?
    std::set<int> distinct_container;
    for (int i: ind_index) {
        distinct_container.insert(pop_ptr[i]);
    }

    return distinct_container.size();
}

// [[Rcpp::export]]
arma::Cube<int> accumulate(const arma::Cube<int>& pop,
                           const Rcpp::IntegerVector& specs,
                           int perms,
                           int K)
{
    auto const num_specs = specs.size();
    arma::Cube<int> res(perms, num_specs, K);

    Rcpp::IntegerVector specs_C(specs - 1);

    for (int i = 0;  i < K;  ++i) {
        for (int k = 0;  k < num_specs; ++k) {
            for (int j = 0;  j < perms; ++j) {
                const auto& sampled = pop(sample_one(perms), 0, sample_one(K));
                res(j, k, i) = sample_n_distinct(specs_C, k + 1, &sampled);
            }
        }
    }
    return res;
}

Sadly, I don't have the domain knowledge to suggest more meaningful improvements other than these fairly mechanical changes that improve readability.

In particular, I don't understand why we have to pass specs_C to accumulate() instead of sampling directly from pop_ptr.

I'm also very wary of taking the address of the element returned by pop() - that seems to assume a memory layout that could vary between platforms, for instance.  I'd expect to use one of the subcube view operations to construct the population:

int sample_n_distinct(const Rcpp::IntegerVector& population, int k)
{
    // sample k values from population, without replacement
    const auto sampled = Rcpp::RcppArmadillo::sample(population, k, false);

    // how many different values do have?
    std::set<int> distinct(sampled.begin(), sampled.end());

    return distinct.size();
}

// [[Rcpp::export]]
arma::Cube<int> accumulate(const arma::Cube<int>& pop,
                           const Rcpp::IntegerVector& specs,
                           int perms,
                           int K)
{
    auto const num_specs = specs.size();
    arma::Cube<int> res(perms, num_specs, K);

    for (int i = 0;  i < K;  ++i) {
        for (int k = 0;  k < num_specs; ++k) {
            for (int j = 0;  j < perms; ++j) {
                const auto& sampled = pop.tube(sample_one(perms), sample_one(K));
                const auto sampled_vector
                    = Rcpp::IntegerVector(sampled.begin(), sampled.end());
                res(j, k, i) = sample_n_distinct(sampled_vector, k + 1);
            }
        }
    }
    return res;
}

I may be wrong on exactly what subcube view is required, so pop.tube() may need to be a different call, but you get the idea.  See how much simpler life is when you can use iterators instead of grubbing around with pointers?


Instead of doing this all in code behind, a different alternative is to use MVC (Model, View and Controller pattern), and let the table be generated by providing a partial view, and then propagate the allRows directly to the partial view. But it could be that using MVC is not available to (or not wanted by) you.

Related to the click event, I'm assuming that all of the buttons are executing the same action, and as such you could use one general save method, which picks up the id from the row where you clicked the button. See following html code example:

  ...

      <input type="file" id="uploadVideo" runat="server" />
      <input type="file" id="uploadPDF" runat="server" />
      <input type="file" id="uploadImg" runat="server" />
      <button runat="server" class="btn">Save</button>

  ...

It is rather easy to make a general save handler, which would pick up the id from the
's data element, and the action url from the
's data element. In addition the html code looks cleaner and is easier to read and handle.

I once built an entire system using data-attributes for different actions, and made general javascript for doing inline editing, deleting, addition. In the backend there were general methods which returned the modified partial view of the edited row. This system allowed me to maintain larger tables, with a minimum of traffic between client and server.


Shellcheck points out this one:

pid="$(pidof $procname)"
if [[ ! $? == 0 ]]
then

We can write that more clearly
if ! pid="$(pidof $procname)"
then

Shortly after that is:

# don't rotate anything if the application is not running
echo "$procname process not running"

That looks like an error message - redirect that to &2.
I'm a little concerned about

# find the active logfile (should be the last one) and delete it from the array

If the daemon didn't get around to opening a new file by the time we reach here, then we'll be out of sync.  That said, it probably doesn't matter - we'll just have one more unrotated file around until we next run, which isn't a big concern.
Take care with commands like this:

gzip "${list[@]}"

It's a good idea to use -- so we can be sure that filenames beginning with - aren't interpreted as options.
Also, commands such as gzip can fail - do we really want to keep going if they do?  (This question isn't so simple to answer, as one of the likely reasons is "no space on device", and in that case we do want to delete some files!)


In order to determine whether two numbers are co-prime (relatively prime), you can check whether their gcd (greatest common divisor) is greater than 1.
The gcd can be calculated by Euclid's  algorithm:

unsigned int gcd (unsigned int a, unsigned int b)
    {
      unsigned int x;
      while (b)
        {
          x = a % b;
          a = b;
          b = x;
        }
      return a;
    }

if gcd(x,y) > 1: the numbers are not co-prime.

If the code is supposed to run on a platform with slow integer division, you can use the so called binary gcd instead.


I strongly oppose testing for file existence. It introduces a race condition: the path may exist at the time of test and disappear by the time of use; yes I am paranoid. Besides, it really impedes dry runs/unit testing - to try an interesting case you need to actually create a file. The pythonic way is to ask forgiveness, not permission:

try:
    os.rename(old_path, new_path)
except OSError:
    pass # or an error message

Notice that it would also take care of other failures of os.rename, such as new_path already exists or is too long; the directory is read-only, etc.
I am also not sure that "sanitization" is to be done unconditionally. A command line option would be nice.
Typically a debugging/diagnostic messages are sent to stderr. A quiet (or verbose) option is also desirable.
fun doesn't strike as a particularly good name.


Swift solution to Leetcode “Longest Substring Without Repeating Characters”

The Swift standard library does not have a built-in method to access the
n'th character of a string. It is tempting to fill that gap with a custom
extension like you did, but the problem is that

self[self.startIndex.advancedBy(index)]

is a \$ O(index) \$  operation. In contrast to other languages where a
"character" is a fixed-size object (and accessing the n'th character of
a string a  \$ O(1) \$  operation), a Swift Character represents a
"Unicode grapheme cluster" which consists of one or more Unicode scalar
values, see e.g. Strings in Swift 2 in the Swift blog.

That makes

for i in 0...s.characters.count-1 {
    // access `s[i]` with your custom subscript method
}

a O(n^2) operation where n is the number of characters in the string.
It is much more efficient to iterate over the characters with

for c in s.characters {
    // do something with `c`
}

More remarks:

The explicit type annotations in

var str:String = ""
var longest:Int = Int.min

are not necessary, the compiler can infer the type automatically.
If you start with var longest = 0 then the special case

if s.isEmpty
{
    return 0
}

becomes obsolete.
There are actually two errors in your code. If a repeating
character is found then the new substring candidate consists of
that character, i.e.

 longest = max(longest, str.characters.count)
 str = ""

should be

 longest = max(longest, str.characters.count)
 str = String(s[i])

otherwise lengthOfLongestSubstring("aabcdd") returns 3 instead
of 4.

And the longest substring length must also be updated at the end
of the string:

longest = max(longest, str.characters.count)
return longest

otherwise lengthOfLongestSubstring("aabcd") returns 1 instead
of 4.

Putting all that together, the method becomes

func lengthOfLongestSubstring(s: String) -> Int {
    var str = ""
    var longest = 0

    for c in s.characters {
        if !str.characters.contains(c) {
            str.append(c)
        } else {
            longest = max(longest, str.characters.count)
            str = String(c)
        }
    }
    longest = max(longest, str.characters.count)
    return longest
}

which should be faster than your code.

Another possible improvement is to store the characters of the
current substring in an Array or a Set instead of a String.
Which one is faster depends on the size of the strings, here is
an example with an array:

func lengthOfLongestSubstring(s: String) -> Int {
    var substringChars: [Character] = []
    var longest = 0

    for c in s.characters {
        if !substringChars.contains(c) {
            substringChars.append(c)
        } else {
            longest = max(longest, substringChars.count)
            substringChars = [c]
        }
    }
    longest = max(longest, substringChars.count)
    return longest
}

As of Swift 4, a Swift string is a collection of its characters
again, so  for c in s.characters can be simplified to for c in s.


Remove a key from a hash table efficiently

C++, not C

First things first, I note that remove is a free function. But that's not how we would do something like this in C++. We would prefer to have a type HashTable in which we'd write:

class HashTable {
public:
   ...
   bool remove(int key);
   ...

private:
   int hash(int );

   std::vector<int> table; // vector is better than int*
                           // table is a better name than H
};

Your naming also could use some work - what is x and what is m? I'm guessing m is the capacity and x is the key that we're erasing, but where are the values? We just have int H[], so is this more like a hash set than a hash table? It's unclear.

Looping and separation of concerns

The hash function should just do the hashing (and thus shouldn't take in the capacity). The loop itself should loop over slots, not indices - this will localize your modulo operation so it doesn't creep in everywhere:

int next(int i) {
    return (i+1) % table.size();
}

bool remove(int key) {
    int i = hash(key) % table.size();
    if (table[i] == EMPTY) {          // break early
        return false;
    }

    for (; table[i] != EMPTY; i = next(i)) {
        if (table[i] == key) {
            table[i] = EMPTY;

            for (int k = next(i); table[k] != EMPTY; k = next(k)) {
               ...
            }

            return true;
        }
    }

    return false;
}

Once you reorient looping over additive indices to looping over actual indices, the inner body becomes more straightforward too:

int old_key = table[k];
table[k] = EMPTY;
insert(old_key);

Find the slot

Your i loop is all about finding the slot where the key is at. The body of that loop isn't really a loop, it's a find-type algorithm. So let's rewrite it like one:

bool remove(int key) {
    int i = hash(key) % table.size();
    for (; table[i] != key; i = next(i)) {
        if (table[i] == EMPTY) {          // break early
            return false;
        }
    }

    // now, table[i] == key
    table[i] = EMPTY;
    for (int k = next(i); table[k] != EMPTY; k = next(k)) {
        int old_key = table[k];
        table[k] = EMPTY;
        insert(old_key);
    }

    return true;
}

EMPTY

In addition to not really being a hash table, you're seemingly limiting the possible valid keys to exclude something like 0 or -1 or whatever the value of EMPTY is. May be worth separating the key from the empty concept.


Is there a way to avoid repetitive code in the following switch statement?

Replace the if-else statements under each case with inline if statements. You can remove the if-else repetitions. For example..

SuperimposeHeaderCheckbox = found ? null : filter.SplitOver;

You can use turn filterProperty into an enumeration (instead of a string).

enum flags {SuperImpose=1, Normalize=2, Legend=4, all=7};

Finally, replace the switch-case statement with simple if statements. You can remove the repetitions for the case all.

if (filterProperty & flags.SuperImpose) {
 // your code here
}
if (filterProperty & flags.Normalize) {
 // your code here
}
if (filterProperty & flags.Legend) {
 // your code here
}
// No need for a fourth if statement.

If you furthur want to reduce the number of the above if statements, you can map the properties in filter to the values in the enumeration and loop through the map.


Flexible presentation of a user's name based on a combination of available properties

First
Idiomatic javascript is to camelCase property names. consider the following:
{
    name: "No Light",
    id: 132,
    firstname: null,
    lastname: null,
    nickname: null
}

Your yesProp and noProp variables are very bad design. Hoisting allows the i variable to be in scope through es3 (to my recollection), but you should never try to take advantage of that. These functions should be rewritten to take the object they are operating on as a parameter.
Additionally, unless there should be some third undefined state, the opposite of yesProp should be !yesProp, not a different detection method.
yesProp is a poor description for the method as well. Consider something describing what it does like hasProperty.
Consider the following:
function hasNotNullProperty(target, property) {
    return target.hasOwnProperty(property) && target[property] !== null;
}

Second
Javascript is a truthy language, undefined and null are considered false. Your yesProp and my hasNotNullProperty method can go away entirely with a simple if (target[property]) { /* do stuff */ }. If the property is undefined or evaluates to a falsy value, then it will not execute the block.
Again in this section, data is a poor description of what we are expecting. Consider using a more descriptive value such as people.
There is no need to return data; at the end of the function -- You've modified the objects that were passed in.
Consider the following:
function formatPeople(people) {
    for (var i = 0, len = people.length; i < len; i += 1) {
        var displayName;

        // Lastname was defined and not null
        if (people[i].lastname) {
            displayName = people[i].lastname;
            // Firstname was defined and not null
            if (people[i].firstname) {
                displayName+= ', ' + people[i].firstname;
            }
            // Firstname was not defined or was null, but Nickname is defined and not null
            else if (data[i].nickname) {
                displayName += ', ' + people[i].nickname;
            }
        }
        // Lastname was undefined or null, but Firstname is defined and not null
        else if (people[i].firstname) {
            displayName = people[i].firstname;
            if (people[i].Nickname) {
                displayName += ', ' + people[i].nickname;
            }
        }
        // Lastname and Firstname were undefined or null, Nickname is defined and not null
        else if (people[i].nickname) {
            displayName = people[i].nickname;
        }

        if (displayName) {
            people[i].displayValue = displayName
        }
    }
}

That still leaves a lot of duplicate code. We will want to clean that up.
Finally
The truthy nature of javascript allows us to do this as well:
var falsy = null;
var truthy = {}; // an anonymous object
var isDefinedAndNotNull = undefined || falsy || truthy; // assigns truthy to isDefinedAndNotNull

This allows us to short-circuit the assignment of a value such as a name.
Let's remove some of that duplicate code, and make a few more names clearer.
function setDisplayNamesForPeople(people) {
    var lastname, firstname, nickname, defaultName, displayName;

    for (var i = 0, length = people.length; i < length; i++) {
        lastname = people[i].lastname;
        firstname = people[i].firstname;
        nickname = people[i].nickname;
        defaultname = people[i].name;
        displayName = formatName(lastname, firstname, nickname, defaultname);

        if (displayName) {
            people[i].displayValue = displayName;
        }
    }
}

//formatName format is (lastname [', ' (firstname | nickname)] | (firstname [', ' nickname]) | nickname | defaultname)
function formatName(lastname, firstname, nickname, defaultname) {
    var formattedName = "";
    if (lastname && (firstname || nickname)) {
        formattedName = ', ' + (firstname || nickname);
    }
    else if (firstname && nickname) {
        formattedName = ', ' + nickname;
    }

    formattedName = (lastname || firstname || nickname || defaultname) + formattedName;

    return formattedName;
}


Before anything, I'll let you search on the web why this might not be such a good idea and I'll just focus on the code.

You probably should retrieve $_SERVER['HTTP_USER_AGENT'] and store it in a variable in order to avoid repeated code. Also, you might want to check if the variable is set properly before accessing it to avoid warnings/errors.
You can rewrite if ($variable == true) as if ($variable)
You could avoid the boilerplate and repeated code if you were storing the interesting parts of your logic in an array and write the common parts only once :

    $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    $redir = array(
        "Android" => 'android',
        "BB10"    => 'blackberry',
        "iOS"     => 'ios',
        "Windows" => 'windows',
        "Mac"     => 'mac'
    );
    if (isset($redir[$ua]))
    {
        header('Location: http://www.example.com/' . $redir[$ua]);
    }

I hope this helps!


As mentioned in the comments your code doesn't seem to do what you intend; however, if you take a look at the Jordan Curve theorem then one aspect of the proof demonstrates that if you consider a point and a continuous loop (or polygon) and take a ray emanating from that point then: if it intersects the loop (polygon) an odd number of times then the point is inside the loop (polygon); and if it intersects an even number of times then the point is outside the loop (polygon).

We can use this to implement a test for this property but it is useful to define some data structures first.

Starting with a namespace:

Geometery = {};

Then defining a point "class":

Geometery.Point2D = function(x,y){
    if ( isNaN( x ) || !isFinite( x ) )
    {
        throw "Point2D - x co-ordinate is not a number.";
    }
    if ( isNaN( y ) || !isFinite( y ) )
    {
        throw "Point2D - y co-ordinate is not a number.";
    }
    this.x = x;
    this.y = y;
}

Geometery.Point2D.prototype.equals = function( point ){
    return point === this
        || ( point instanceof Geometery.Point2D &&
             point.x === this.x &&
             point.y === this.y
           );
}

Geometery.Point2D.prototype.toString = function(){
    return '(' + this.x + ',' + this.y + ')';
}

Geometery.Point2D.prototype.DRAW_RADIUS = 2;

Geometery.Point2D.prototype.draw = function( context ){
    context.beginPath();
    context.arc( this.x, this.y, this.DRAW_RADIUS, 0, 2 * Math.PI, false );
    context.fill();
    context.closePath();
    context.stroke();
}

Next it is useful to have some common functionality for a set of points:

Geometery.Point2DSet = function(){
    this.points = [];

    var index;
    var point;
    for ( index = 0; index < arguments.length; index++ )
    {
        point = arguments[index];
        if ( !( point instanceof Geometery.Point2D ) )
        {
            throw "Point2DSet - Constructor argument is not a Point2D.";
        }
        this.points.push( point );
    }
};

(function(){
    var calcBoundaryCoord = function(coord,fnct){
        return function(){
            var index;
            var val = this.points.length ? this.points[0][coord] : undefined;
            for ( index = 1; index < this.points.length; ++index )
            {
                val = Math[fnct]( val, this.points[index][coord] );
            }
            return val;
        }
    };

    Geometery.Point2DSet.prototype.minX = (calcBoundaryCoord('x','min'));
    Geometery.Point2DSet.prototype.minY = (calcBoundaryCoord('y','min'));
    Geometery.Point2DSet.prototype.maxX = (calcBoundaryCoord('x','max'));
    Geometery.Point2DSet.prototype.maxY = (calcBoundaryCoord('y','max'));
})();

Geometery.Point2DSet.prototype.draw = function( context ){
    for ( var index = 0; index < this.points.length; ++index )
    {
        this.points[index].draw( context );
    }
}

Geometery.Point2DSet.prototype.toString = function(){
    return '<' + this.points.join(',') + '>';
}

This can then be extended to define a line "class":

Geometery.Line2D = function(){
    if ( arguments.length != 2 )
    {
        throw "Line2D - A line must have exactly two end-points.";
    }
    Geometery.Point2DSet.apply( this, arguments );
    if ( this.points[0].equals( this.points[1] ) )
    {
        throw "Line2D - A line must have two distinct end-points.";
    }
}

Geometery.Line2D.prototype = Object.create( Geometery.Point2DSet.prototype );
Geometery.Line2D.prototype.constructor = Geometery.Line2D;

Geometery.Line2D.prototype.getGradient = function(){
    var p1 = this.points[0];
    var p2 = this.points[1];
    if ( p1.x == p2.x )
    {
        if ( p1.y < p2.y )
        {
            return Number.POSITIVE_INFINITY;
        }
        else
        {
            return Number.NEGATIVE_INFINITY;
        }
    }
    return ( p2.y - p1.y ) / ( p2.x - p1.x );
}

Geometery.Line2D.prototype.draw = function( context, startPath, endPath ){
    if ( startPath !== false )
    {
        context.beginPath();
        context.moveTo(this.points[0].x, this.points[0].y );
    }
    context.lineTo(this.points[1].x, this.points[1].y );
    if ( endPath !== false )
    {
        context.closePath();
        context.stroke();
    }
}

We can also determine how many times a ray emanating vertically upwards from a point intersects a line:

Geometery.Line2D.prototype.countIntersectionsOfVerticalRayAbovePoint = function( point ){
    // If it is to the left/right of the bounding box then return null.
    if ( point.x < this.minX() || point.x > this.maxX() )
    {
        return 0;
    }
    // If it is above the bounding box then return ABOVE.
    if ( point.y > this.maxY() )
    {
        return 0;
    }
    // If it is below the bounding box then return BELOW.
    if ( point.y < this.minY() )
    {
        return 1;
    }
    var p1 = this.points[0];
    var p2 = this.points[1];
    // Check for the special case of a vertical line.
    if ( p1.x == p2.x )
    {
        return null;
    }
    var deltaY = point.y - this.getGradient()*(point.x - p1.x) - p1.y;
    if ( deltaY == 0 )
    {
        return null;
    }
    else if ( deltaY > 0 )
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

We can then extend the concept of a set of points to be a polygon:

Geometery.Polygon2D = function(){
    if ( arguments.length < 3 )
    {
        throw "Polygon2D - A polygon must have at least 3 vertices."
    }
    Geometery.Point2DSet.apply( this, arguments );
    this.lines = [];
    var p1 = this.points[ this.points.length - 1 ];
    var p2;
    for ( var index = 0; index < this.points.length; ++index )
    {
        p2 = this.points[ index ];
        this.lines.push( new Geometery.Line2D( p1, p2 ) );
        p1 = p2;
    }
}

Geometery.Polygon2D.prototype = Object.create( Geometery.Point2DSet.prototype );
Geometery.Polygon2D.prototype.constructor = Geometery.Polygon2D;

Geometery.Polygon2D.prototype.draw = function( context ){
    for ( var index = 0; index < this.lines.length; ++index )
    {
        this.lines[index].draw( context, index == 0, false );
    }
    context.closePath();
    context.fill();
    context.stroke();
    Geometery.Point2DSet.prototype.draw.apply( this, arguments );
}

And finally we can check if a point is contained within a polygon by checking the number of intersections with lines in the polygon (and if the point is on any lines):

Geometery.Polygon2D.INSIDE   = 1;
Geometery.Polygon2D.OUTSIDE  = -1;
Geometery.Polygon2D.ONBORDER = 0;

Geometery.Polygon2D.prototype.contains = function( point ){
    var numRaysCrossing = 0;
    for ( var index = 0; index < this.lines.length; ++index )
    {
        var count = this.lines[index].countIntersectionsOfVerticalRayAbovePoint( point );
        if ( count === null )
        {
            return Geometery.Polygon2D.ONBORDER;
        }
        numRaysCrossing += count;
    }
    if ( numRaysCrossing % 2 )
    {
        return Geometery.Polygon2D.INSIDE;
    }
    else
    {
        return Geometery.Polygon2D.OUTSIDE;
    }
}

You can write your own function to then iterate over multiple points and count if they are inside/outside a polygon.

Here is a basic example of using the above:

var polygon = new Geometery.Polygon2D(
    new Geometery.Point2D( 20, 140 ),
    new Geometery.Point2D( 20, 60 ),
    new Geometery.Point2D( 60, 20 ),
    new Geometery.Point2D( 100, 60 ),

    new Geometery.Point2D( 100, 84 ),
    new Geometery.Point2D( 95, 84 ),
    new Geometery.Point2D( 95, 70 ),
    new Geometery.Point2D( 75, 70 ),
    new Geometery.Point2D( 75, 85 ),
    new Geometery.Point2D( 100, 85 ),

    new Geometery.Point2D( 100, 124 ),
    new Geometery.Point2D( 95, 124 ),
    new Geometery.Point2D( 95, 110 ),
    new Geometery.Point2D( 75, 110 ),
    new Geometery.Point2D( 75, 125 ),
    new Geometery.Point2D( 100, 125 ),

    new Geometery.Point2D( 100, 140 ),
    new Geometery.Point2D( 65, 140 ),
    new Geometery.Point2D( 65, 110 ),
    new Geometery.Point2D( 55, 110 ),
    new Geometery.Point2D( 55, 140 )
);

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.fillStyle   = 'red';
context.lineWidth   = 1;
context.strokeStyle = 'black';

polygon.draw( context );

var points = new Geometery.Point2DSet(
    new Geometery.Point2D( 85, 117 ),
    new Geometery.Point2D( 85, 100 ),
    new Geometery.Point2D( 85, 85 ),
    new Geometery.Point2D( 85, 78 ),
    new Geometery.Point2D( 85, 60 ),
    new Geometery.Point2D( 85, 45 ),
    new Geometery.Point2D( 85, 40 ),
    new Geometery.Point2D( 100, 100 ),
    new Geometery.Point2D( 60, 100 ),
    new Geometery.Point2D( 60, 130 ),
    new Geometery.Point2D( 10, 10 )
);

for ( var i = 0; i < points.points.length; ++i )
{
    var point = points.points[i];
    var contains = polygon.contains( point );
    if ( contains == Geometery.Polygon2D.OUTSIDE )
    {
        context.fillStyle   = 'green';
    }
    else if ( contains == Geometery.Polygon2D.ONBORDER )
    {
        context.fillStyle   = 'yellow';
    }
    else
    {
        context.fillStyle   = 'blue';
    }
    point.draw( context );
}


Updating MySQL with shuffled numbers between 1 and 50

As I'm sure you've noticed, executing any SQL query in a loop is a bad idea.  It would be much better to formulate a statement that accomplishes the entire batch of changes at once.

To achieve that goal, you'll need to combine several ideas:

Shuffling using ORDER BY RAND().  Admittedly, the documentation admits:

  RAND() is not meant to be a perfect random generator. It is a fast way to generate random numbers on demand that is portable between platforms for the same MySQL version."

So, you'll have to decide whether MySQL's idea of randomness is as good as Scala's.
A row number generator.  Unfortunately, MySQL has no row_number() or rank() function, like some other databases, so you'll need to use a hack.
UPDATE using multiple table references.

A statement that you could use is:

UPDATE `groupInformation`
    INNER JOIN (
            SELECT *
                FROM `groupInformation`
                ORDER BY RAND() LIMIT 50
        ) AS shuffled
            ON `groupInformation`.userId = shuffled.userId
    INNER JOIN (
            SELECT @row := 0
        ) AS row_var_decl
    SET `groupInformation`.rank = @row := @row + 1
    WHERE `groupInformation`.groupId = {groupId};

Here's an SQL Fiddle as a demonstration.

As you've noted, the behaviour of the query above is different from the original when there are fewer than 50 matching rows in groupInformation.


Identifying numeric substrings of an alphanumeric string, and summing them

Learning to use, and using the debugger are fantastic ideas. It is a valuable skill that will serve you well. Understanding how your code works (and breaks) is very valuable, and the debugger helps you through there.

The remainder of your specific questions are somewhat linked to your actual implementation, and I am going to suggest that your implementation would be simpler with a String split operation. The specification says:

  Given a string, return the sum of the numbers appearing in the string,
  ignoring all other characters. A number is a series of 1 or more digit
  chars in a row.

Taking this literally, I would code this up as a Regular expresison system matching digits. Something like:

private static final Pattern NUMBERS = Pattern.compile("[0-9]+");

private static int digitSum(String s) {
    Matcher matcher = NUMBERS.matcher(s);
    int sum = 0;
    while (matcher.find()) {
        sum += Integer.parseInt(matcher.group());
    }
    return sum;
}

The Pattern says "Look in the string for a sequence of digits".

The method loops through all digit sequences, converts them to integers, and totals them.


It's a couple of decades (!) since I did any CGI, but I'll cast a quick eye over this.  I hope other reviewers will pitch in and fill the gaps (or correct my errors).

It's an interesting choice to use the same TITLE for success and failure.  It might be better to write a small function:

header()
{
cat <<EOT
Content-type: text/html; charset=us-ascii

<!doctype html>

                <title>$*</title>
                <link rel="icon" href="/favicon.png">

EOT
}

Note also the form of function declaration - that's more portable than the function keyword, and to be preferred.  We now use it like

if [ "$REQUEST_METHOD" != "POST" ] || [ ! "$POST" ]
then
    header 'Error'
    echo '
Error

Wrong HTTP method; please go back and try again
';
    exit 1;
fi

Also, for that exit, I'd exit 0 there, because the script has succeeded in its job (to report the status to the user).  There's no error as far as the caller (the Web server) is concerned - everything is working correctly.

A further refinement: if we add another cat to the end of header(), it can write the message, too:

#renamed to reflect new purpose
write_html()
{
cat <<EOT
Content-type: text/html; charset=us-ascii

<!doctype html>

                <title>$*</title>
                <link rel="icon" href="/favicon.png">

$*

EOT
cat
}

if [ "$REQUEST_METHOD" != "POST" ] || [ ! "$POST" ]
then
    write_html 'Error' <<"EOT"

Wrong HTTP method; please go back and try again

EOT
fi

There seems to be a couple of errors in the sed command in input():

s/^.*$1=\([^&]\+\)&.*$/\1/

The most obvious is the requirement for & after the target parameter - this means we'll be unable to extract the last parameter in the line.  The more subtle bug is that we can be confused if one parameter is a suffix of another, because we didn't anchor the beginning of $1 at all.  Finally, if $1 isn't present in the string, we'll use the entire request as value; we can fix that by printing only if there's a substitution:

# untested
sed -n 's/^.*[?&]'"$1"'=\([^&]\+\).*$/\1/p'

Here, I rely on the greediness of + to take us to the next & or end of line.

Do have another look through the Python library to see if there's something there to help us unpack POST data - since we're using Python anyway for decoding characters, there's no penalty to adding code there.

Since we're using Bash, we could write sed <<<"$POST" instead of echo in that function.

BTW, good job getting the quoting right there!

From here onwards, nothing I haven't already mentioned.


I've slightly reorganised your code to make it easier to follow.

void merge_parts(int arr[], int length)
{
    /*
    Sorts into increasing order
    For decreasing order change the comparison in for-loop
    */
    int ans[length];
    //This for and next if-else puts the merged array into temporary array ans
    //in a sorted manner
    int mid = length/2;
    int i = 0, k = 0, j = mid;
    while (i < mid && j < length){
        ans[k++] = (arr[i] < arr[j]) ? arr[i++] : arr[j++];
    }

    // Only one of the two loops will apply
    while(j < length){
        ans[k++] = arr[j++];
    }
    while(i < mid){
        ans[k++] = arr[i++];
    }

    //This for-loop puts array ans into original array arr
    for(int i = 0; i < length; i++){
        arr[i] = ans[i];
    }
}

void merge_sort(int arr[], int length)
{
    if(length > 1)
    {
        int mid = length/2;
        merge_sort(arr,     mid);
        merge_sort(arr+mid, length - mid);
        merge_parts(arr, length);
    }
}

int main()
{
    int length;
    for (;;)
    {
        printf("\nEnter a positive length: ");
        scanf("%d", &length);
        printf("\nYou entered length = %d\n", length);
        if (length>=1) break;
    }

    int *arr = malloc(sizeof(int) * length);
    if (!arr)
    {
        perror("The following error occurred");
        exit(-1);
    }

    for (int i = 0; i < length; i++){
        scanf("%d", &arr[i]);
    }

    merge_sort(arr, length);

    for (int i = 0; i < length; i++){
        printf("%d ", arr[i]);
    }

    free(arr);
    return 0;
}

Then for the only optimisation I can think of, you could avoid some copying : when j < length after the main loop, it corresponds to a situation where the end of arr is already sorted in the right place. Thus, you don't need to copy it from arr to ans and then from ans to arr.

int mid = length/2;
int i = 0, k = 0, j = mid;
while (i < mid && j < length){
    ans[k++] = (arr[i] < arr[j]) ? arr[i++] : arr[j++];
}

while(i < mid){
    ans[k++] = arr[i++];
}

//This for-loop puts array ans into original array arr
for(i = 0; i < j; i++){
    arr[i] = ans[i];
}


Number of paths in a grid (lattice) graph

It works pretty good with small value for rows and columns but for bigger values it throws OutOfMemoryError.

That's hard to believe as I can't see any allocation there besides new int[row][col], which is no problem unless the dimensions get much bigger than a few thousands. I guess they do and you'll need a smarter algorithm. As the whole computation runs top-down, you don't have to store the whole matrix. A single row should do.

// TODO Auto-generated method stub

Are you sure you need it???

String[] s1 = inp.readLine().split(" ");
int row = Integer.parseInt(s1[0]);
int col = Integer.parseInt(s1[1]); //Input for the value of row & col

Inline comments are fine as long as they belong to the command in their line. But this is a block comment and should precede the block. It could be a also a comment for s1, but not col.

int r1 = Integer.parseInt(s2[0]);

Are we supposed to guess what r1 means? What about naming it topLeft?

private static int numOfPaths(int A[][], int row,int col)
{

Java uses "Egyptian brackets" (no line break before the opening brace). There should be a space after every comma. Passing row and col is redundant as they're obtainable from A.

if( A[0][0] == 0)

Spacing! I doubt that this special case handling is necessary.

{
    return 0;
}
else
{

The nice thing about "early return" is that it allows you to handle special cases upfront without increasing the nesting depth. Your "else" after "return" is wrong.

int i,j;
for(i=0; i<col; i++)

Use for (int i=...) instead, so that the scope of every variable is as small as possible.

if( A[0][i] == 0 )
            break; // exit from the for loop, and set remaining elements the first row set to ZERO
        B[0][i] = A[0][i];

Spacing! So you first exit the loop and then (inside of the loop) set the remaining part to zero? This can't work.

But you're lucky as all int array elements are initialized to zero anyway.

I guess all what's needed is

for (i = 1; i < row; i++) {
    for (j = 1; j < col; j++) {
        if (A[i][j] != 0) {
            B[i][j] = (int) (((B[i - 1][j] % mod) + (B[i][j - 1] % mod)) % mod);
        }
    }
}

Note the formatting (done by Eclipse for free). Also note that it's recommended to always use braces (you know "goto-fail", right?).


When all of your code is the same, just with different numbers, you want to use data-directed programming.

WINS = [
  [0, 1, 2], [3, 4, 5], [6, 7, 8],  # <-- Horizontal wins
  [0, 3, 6], [1, 4, 7], [2, 5, 8],  # <-- Vertical wins
  [0, 4, 8], [2, 4, 6],             # <-- Diagonal wins
]

def check_lines
  if WINS.any? { |line| line.all? { |square| @squares[square] == @player } }
    @win = @player
  end
end


Implement The Singleton Pattern for Persistency managers Swift

This seems to be an extremely common way of handling networking in iOS and Swift probably because it is very simple to reason about a single global singleton object for services.

I would recommend thinking carefully about using a singleton.

Why not just have a NetworkManager object that you initialize?

Even better why not separate out the services into a few logical classes? One service per class may get a bit arduous, but if you think critically you will likely be able to group services together appropriately. If you then find yourself with many Service objects, you can combine these objects with a facade pattern, that groups functionality when appropriate for a given View/ViewModel.

You will want to use classes, or structs with non static functions because when something isn't a singleton you can use dependency injection. Instead of accessing the static methods of your singleton you can inject a NetworkProvider object into the class in the constructor that uses it. This will make your code far more robust and testable. The injected object, if you created an appropriate Protocol, can be mocked.

Personally, I prefer something like Moya https://github.com/Moya/Moya/blob/master/docs/CommunityProjects.md. Its very swifty, logical, and well formatted. It also makes the relationships between services very clear. As your project gets larger, you will want to create multiple provider objects, but it provides a very concise way of writing your service layer.

Summary - Use dependency injection and normal non static structs or classes. If you have multiple services, separate them out into a separate struct/class based on similarity or simply separate out one service into a single struct or class. A library like Moya can help to structure your code to make it more readable.


You can do it in only one event. Get sums of all value on each changement like this :

$(".js-question-score").change(function(){
  var res=0;
  $(".js-question-score").each(function()
  {
    res+=parseInt($(this).val());
  });
   $(".js-total-user-score").text(res);
});

<form>
  <input class="js-question-score" name="first" min="0" max="20"  value="0" type="number"/>
  <input class="js-question-score" name="second" min="0" max="20"  value="0" type="number"/>
  <input class="js-question-score" name="third" min="0" max="20"  value="0" type="number"/>
</form>

  User total score:

    0


Never write login code

This is much harder than you think. Leave it to the experts you will get some security piece wrong.

Code Review

Don't use this:

using namespace std;

See Why is “using namespace std;” considered bad practice?.

The reason the "standard namespace" is called std is so that it is not a big deal to type std:: before each standard object/function/type. Don't be lazy type the extra 5 characters.

I don't see declarations for username or password I hope they are not global variables.

cout << "Please enter a username" << endl;
getline(cin,username);

cout << "Please enter a password" << endl;
getline(cin,password);

You have used a while loop.

while(username_input != username || password_input != password)
{
}

You may want to look at a do while loop. As the test is not done till the end of the input code. If somebody had an empty username and password then it would match before the loop was entered and you would never get asked.

do
{
}
while(username_input != username || password_input != password);

Hint

Passwords should NEVER be stored (or encrypted). You should only ever store the hash of the password (properly salted). When a user enters a password hash it with the appropriate salt and compare it to the stored hash of the password.

A hash can be though of as one way encryption. You can encrypt it, but because it is lossy you can not decrypt the hash back to a password. So if people get hold of the your password file all they have is a set of hashes and no passwords.


Creating dynamic threads for a SMS text API

static public BlockingCollection<int> Queue
static public BlockingCollection<int> Finished
static public BlockingCollection<Thread> Threads
static public int QUCount
static public int THCount
static public int FNCount

There is no need to make any of these fields public. You shouldn't change the visibility from the default of private unless you have a reason to do it.

for (long i = 0; i < 5000; i++)
{
    Random RandomNum = new Random();
    int Num = RandomNum.Next(1, 2);
    Queue.Add(Num);
}

This is a very complicated way to generate 5000 1s. If you actually want to generate random numbers, you can't create a new Random for each iteration, you should instead create it once before the loop and then just call Next() inside it. That's because Random is initialized by the current time by default, and the time as measured by .Net doesn't change that often. That means you would get runs of the same number, which is not random.

THCount = Threads.Count;
FNCount = Finished.Count;

These lines don't do anything here, both collections are going to be empty at this point. In fact, the Count fields are completely useless, you should just use the Count property of each collection instead.

while (QUCount > 0)
{
    if (THCount < 20)
    {
        Thread th1 = new Thread(LoopMethod);
        th1.Start();
    }
}

This code doesn't make much sense. It's certainly possible that it will start all 20 threads even if there's just a single item in the queue, because you could create all of the threads before the first one starts.

What's much worse is that it will keep on iterating while the other threads are working. This means a whole single core of your CPU will be fully busy, doing basically nothing.

Thread th1 = new Thread(LoopMethod);

Threads are relatively heavy-weight, you should usually create a new thread only for a long running operation. If you have thousands of operations, you shouldn't create thousands of threads. Instead, you should create just a few of them and have a loop inside each.

Threads.Add(th1);

There is no need to do this. You don't actually need a collection of threads, you just need to know their count. So you should use an int field for that, and increment that value in a thread-safe manner.

Thread CurTh = Thread.CurrentThread;
Threads.TryTake(out CurTh);

This code looks like it's trying to take the current thread out of the collection. In fact, it does no such thing. Instead, it removes the first item from the collection (i.e. the oldest item that hasn't yet been removed from the collection) and assigns that to the CurTh variable. The out modifier means, among other things, that the parameter is used for output only and if it has some value before the method is called, it's going to be ignored.

int QUCount
int THCount
int FNCount
Thread th1

You shouldn't abbreviate your field and variable names like this. You should write their names in full, (e.g. QueueCount or thread), because code is read more often than it is written, so it makes sense to strive for code that is easy to read, not code that is easy to write. (And it doesn't even make much difference with autocompletion.)

Usually, it's much better to use TPL for parallel processing, instead of manually using threads. Using GetConsumingEnumerable() and Parallel.ForEach() would make your code shorter, more readable and much more efficient. (CPU efficiency usually doesn't matter much for code like this, but you're wasting CPU a lot.)

class Program
{
    static BlockingCollection<int> Queue = new BlockingCollection<int>();
    static BlockingCollection<int> Finished = new BlockingCollection<int>();

    static void Main()
    {
        BuildList();

        Parallel.ForEach(
            Queue.GetConsumingEnumerable(),
            new ParallelOptions { MaxDegreeOfParallelism = 20 },
            ProcessItem);
    }

    static void ProcessItem(int i)
    {
        int result = /* somehow calculate the result here */;
        Finished.Add(result);
    }
}

(I have also removed your logging for brevity.)


I recommend nesting dictionaries for your conversions. Usually if you have a long chain of elif comparisons to a string or number, you should use a dictionary.

You can store the first unit as the primary key, and then the second value is the key of the second unit. The values then all need to be a number that you can multiply by in order to perform the conversion. So to divide by 1000, instead the value to multiply by is 1/1000. You could technically store functions to call in order to evaluate the conversions but just numbers is simpler.

conversions = {
                "mm": {"mm": 1, "cm": 1/10, "m": 1/1000, "km": 1/1000000},
                "cm": {"mm": 10, "cm": 1, "m": 1/100, "km": 1/100000},
                "m":  {"mm": 1000, "cm": 100, "m": 1, "km": 1/1000},
                "km": {"mm": 100000, "cm": 10000, "m": 1000, "km": 1},
              }

This makes it easier to see if all of them are implemented, they're kept in neat rows so you can make sure none of the math seems off. Another advantage is that you can automatically generate a list of values to tell the user about.

unit1 = raw_input ("Which unit would you like to convert from?\n"
                   "We support: " + ", ".join(conversions.keys()))
unit2 = raw_input ("Which unit would you like to convert to?\n")
                   "We support: " + ", ".join(conversions[unit1].keys()))

Also you could now make sure that the user is typing in a valid key this way.

while True:
    try:
        unit1 = raw_input ("Which unit would you like to convert from?\n"
                           "We support: "
                           ", ".join(conversions.keys())).lower()
        unit2 = raw_input ("Which unit would you like to convert to?\m")
                           "We support: "
                           ", ".join(conversions[unit1].keys())).lower()
        convert = conversions[unit1][unit2]
    except KeyError:
        print ("That is not a valid key, please try again")

conversions[unit1][unit2] is just called in order to test whether the key exists and will raise an error if it doesn't so that the user will be told to enter new keys. I also added .lower() so that if the user inputs CM, Cm or even cM they'll all be converted to cm to match the key.

I recommend wrapping the number input similarly, as it prevents errors later.

while True:
    try:
        num1 = float(raw_input("Enter your value: " ))
    except ValueError:
        print ("That is not a valid float, please try again.")

Now when it comes to the actual logic, it's really quite simple since both values are already prepared:

ans = num1 * convert


Random alphanumeric string generator function (C, Windows, bcrypt.h)

The output is not uniformly distributed
The resulting characters in the output string are not uniformly distributed. In fact, some characters never occur in the output. After shifting a random byte right by two, if the result is larger than or equal to 32, you always clear the second least significant bit. So all values up to 32 are possible, but then it is 32, 33, 36, 37, 40, 41 and so on. And each value >= 32 that your algorithm generates is twice as likely as each value < 32.
The best solution is to first shift the random byte right by two, and then check i it is smaller than 62. If so, use it as it is. Otherwise, generate a new random byte and repeat the process.
Avoid allocating an array of random bytes
You are allocating an array to store the random bytes in. While it might seem efficient to do this, because you assumed you then only need one call to BCryptGenRandom(), this might be an issue if you want to generate large random strings. Also, if you want to have a proper uniformly distributed output, you might need to generate more random bytes than you originally anticipated.
Consider having a small array on the stack that you fill with random bytes, and use those to generate the alphanumeric characters. If you used up all the bytes, you fill the array with a new batch of random bytes.


You should generally avoid redundancy when programming.

I'd make a list and loop through it

QUESTIONS = [("A vehicle with the national registration code ‘PK’ would originate from which country?", "Pakistan"),
             ("In which English county is Blenheim Palace?", "Oxfordshire")] # Add more to this list

for n,(question, answer) in enumerate(QUESTIONS, 1):
    time.sleep(2)
    print("Question", n)
    time.sleep(2)
    user_answer = input(question)
    if user_answer.lower() == answer.lower():
        print("Correct answer")
        score += 1
    else:
        print("Incorrect answer, the correct answer is", answer)

And so on

Hope this helps :-)


You say you want to search a text string from a database, but are not showing the database part.  This is key to think about, as I am guessing you could cut out all this work if you made appropriate search requests against an appropriately designed data store.  Most any modern relational database supports some level of natural language search, which would allow you to actually do this across more than a single string at a time.

This is not to mention the existence of data stores both open source and commercial geared specifically towards search cases, even allowing the ability to return search matches with context as you are trying to do.

Consider doing this sort of work with a tool that is optimized for this purpose.

Thoughts on code:

You are clearly working with multibyte strings yet are not using the multibyte versions of the the standards string manipulation functions.  This could lead to unexpected behavior. If you need to have string functions overloaded with mb counterparts, you might consider a comment in the code noting that this PHP setting needs to be turned on for this code to operate properly.
you should add vertical white space to you code around logical sections to help ease of reading. Think of empty lines like you would paragraphs in writing. They help break up your thoughts.
you are casting to lowercase only on haystack and not on needle.  Why is this? Typically if you are doing case insensitive search, you would cast both in same manner.
you may consider using regex with appropriate substring pattern capture and compare from a performance standpoint. I am not sure if it will perform as well, but it could certainly simplify your code, which can sometimes holds more value if performance is not too big of a trade off.
your code isn't designed to handle multiple matches. This may be OK with regards to the design, but figured I would point this out.  You could take your example haystack and search for "the", and never get the second occurrence found.
what happens if space is passed as search string?
what happens if single character is passed or other similar trivial or ambiguous search term? Do you have something up the call stack which weeds out these potentially undesirable use cases?


There is nothing I can test here, so I will only make a couple superficial remarks.
You do not offer a lot of insight into your application. If you say you have a problem with overlapping queries, then you should address the root of the problem. I have the impression that you simply devised a workaround. It may do the job but at the expense of performance or reliability. It could also create more problems.
Repetition
What is immediately apparent is that you have a hardcoded path repeated multiple times across your code.
At the top of your code you should define a variable for '/root/progress_data'. Then if you decide to change the file name or path you will have only one line to change.
But Python has a library for temp files: https://docs.python.org/3/library/tempfile.html. This is what you should be using.
The date format "%Y-%m-%d" could be made a variable too.
Security
Does your program really need to run as root ?
Maximize your try/catch/finally blocks
You repeat this twice:
os.remove(f'/root/progress_data/{progress_hash}')

To ensure that the file gets removed at the end of the process you could place this line of code in a finally block.
Same goes for the return value:
return json_response({
    "success": False,
    'result': "Error while generating report",
})

return json_response({
    "success": True,
    'data': report,
})

Keep only one return but use variables for the response depending on the outcome of the execution.
Thus your code will be shorter, more straightforward and easier to comprehend. But I still think the idea is wrong.
I would probably use a database instead of temp files. It can be a small self-contained DB file like SQLite. You need a simple table with details of the job, some kind of unique identifier and a column to update the status of the job. Then your API can query the table and say "ready" when the column has been to updated to the finished status.
This looks clumsy to me. I would ditch the idea and go back to the drawing board. If you are stuck my suggestion would be to post on Stack Overflow for guidance but add more context to your question, explain how the API is used, what your constraints are.


Your after() function is actually doing two things: it returns nod_ptr->next, but with the stipulation that the list starting at first_ptr contains nod_ptr.  Therefore, you should decompose it into two functions.

/**
 * Returns the content node if it is contained in the list starting at
 * head, otherwise NULL.  The list must not contain a cycle.
 */
node *find(node *head, node *content)
{
    for (node *n = head; n != NULL; n = n->next)
    {
        if (n == content)
        {
            return content;
        }
    }
    return NULL;
}

/**
 * If the list starting at head contains content, returns content->next.
 * Otherwise, returns NULL.
 */
node *after(node *head, node *content)
{
    return (content != NULL && find(head, content)) ? content->next
                                                    : NULL;
}


Dynamic memory management for a class hierarchy of geometric shapes

Dynamic Memory Management

  Am I doing it right in terms of memory menagment?

You should rather use smart pointers to store the Shape instances in the vector:

 std::vector<std::unique_ptr<Shape>> shapes;

and

 std::unique_ptr<Shape> generateRandomShape() {
     int Shape; // Take care! Some compilers don't like it if variables
                // arenamed the same as defined types
     Shape = rand() % 3;

         switch (Shape)  {
         case 0: {
             int sideA = rand() % 100;
             std::cout << "Square was generated, side: " << sideA << std::endl;
             return std::make_unique<Square>(sideA);
         } break; // Put the break out side the case scope block
         case 1: {
             int sideA = rand() % 100;
             int sideB = rand() % 100;
             std::cout << "Rectangle was generated, side A: " << sideA << " side B: " << sideB << std::endl;
             return std::make_unique<Rectangle>(sideA, sideB);
         } break;
         // ...
     }
     // No need for the default case
     return std::unique_ptr<Shape>();
}

thus you can completetly omit

 for (auto v : shapes) { delete v; } //cleanup

  Will my figures generated inside generateRandomShape() by new Square() etc. last in memory outside this function untill I manually delete them?

Yes, but handling new and delete on your own turns out to be error prone and semantically unclear.

Use virtual destructors for dynamic polymorphic inheritance

For formal correctness you should declare virtual destructors for your abstract base class and the derived classes

class Shape {
public:
    float area() = 0;
    virtual ~Shape() = default; // <<<<<<<<<<<<<<<<<<<<
};

This isn't done automatically for compiler generated destructors (see an explanation here).

Use const class members whenever appropriate

Use const whenever appropriate. The area() calculation doesn't change any of the internal states of a Shape instance, so it should be declared as a const member function:

class Shape {
public:
    float area() const = 0;
              // ^^^^^
};

This improves your classes to be used in wider contexts, e.g. with temporary class instances.

Also you could rewrite your function signature

void compareAreasOffigures(Shape* a, Shape* b);

like that then1)

void compareAreasOffigures(const Shape* a, const Shape* b);

or even better

void compareAreasOffigures(const Shape& a, const Shape& b);

Note: Do that as soon as possible in your class designs, adding later is much harder than removing that constraint in a later refactoring or override.

Prefer const variable definitions over using preprocessor macros

Instead of

 #define M_PI       3.14159265358979323846

rather use

const double M_PI = 3.14159265358979323846;

or

constexpr double M_PI = 3.14159265358979323846;

for sake of type safety and clarity.

Don't use srand(), rand() with modern c++

Use a better random number generator than

srand(time(0));

// ...

rand();

There are various random generators available with the current standard in the numerics library.

Don't use == to compare floating point values

Don't use equality comparison for floating point types like

if (a->area() == b->area())

it's unlikely these will be exactly equal.

Rather test against std::numeric_limits::epsilon, there's a comprehensive example in the linked documentation.

Your purpose of using _USE_MATH_DEFINES is unclear and inconsistent

Your use of _USE_MATH_DEFINES and defining M_PI yourself is inconsistent.

The purpose of #define _USE_MATH_DEFINES is to use the predefined constants from cmath or math.h, but you define M_PI yourself anyways.

As mentioned here it should be defined before any of the #include statements to guarantee it works

#define _USE_MATH_DEFINES
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <vector>

since you cannot know if any of the other header files already includes cmath or math.h.

The highlight of your solution

After so many points of critique, I want to emphasize one bonus point of your solution:

You weren't trapped by the Square is not a Rectangle confusion and provided unrelated classes for these (same for Circle is not an Ellipse).

Beginners often use inheritance like

class Rectangle {
protected:
    float sideA, sideB;
};

class Square : public Rectangle {
};

and run into trouble to keep the class member variables consistent (here's a more detailed resource).

1As mentioned by @Tamoghna Chowdhury before.


How can I simplify this JQuery validation process?

I see you removed the calls to $('#loadingDiv').show(); from the many conditional blocks and moved that before the call to the AJAX call - I was going to suggest that.
I see the ecmascript-6 features like the Class syntax are used, so other ES-6 features could be used - like the object initializer shorthand notation - i.e. on this line:

 $.post('process/editUser.php', {uobj:uobj}, function(data)

The second argument can be simplified:
$.post('process/editUser.php', {uobj}, function(data)

There is no need to use the else keyword since all previous conditional blocks have a return statement.
The callback to the AJAX call has a variable modal:

var modal = "#addUserModal";

The variable is only used one time so the value can be used in the call to dataCheck and the variable eliminated. Additionally, unless there is a good reason like needing a global variable, don't use var. Use const and then if you determine re-assignment is necessary use let.
Instead of using .indexOf() to determine if a string does or does not contain a substring, String.prototype.includes() could be used unless browser compatibility is an issue.
I know that the PHP PSRs recommend having opening braces on a new line but this is less common in JavaScript.


Buggy behavior

First you're checking the length of the passwords, and then if they are null:

if(pass1.length() < 1 || pass2.length() < 1 )retVal.append("Empty fields
");

if (pass1 != null && pass2 != null) {

This is not going to work well: if any of the passwords were null, you would get a NullPointerException when you check length.

Also, a better way to check if a string is empty is using pass1.isEmpty().

Also, this is pointless and potentially confusing:

pass1 = pass2;

Simplify the validation logic

It would be better and more efficient to create private final Pattern members that are compiled regular expressions, and reusable multiple times:

private final Pattern hasUppercase = Pattern.compile("[A-Z]");
private final Pattern hasLowercase = Pattern.compile("[a-z]");
private final Pattern hasNumber = Pattern.compile("\\d");
private final Pattern hasSpecialChar = Pattern.compile("[^a-zA-Z0-9 ]");

For example, this returns true if pass1 contains an uppercase character:

hasUppercase.matcher(pass1).find()

Notice the patter for hasSpecialChar: match non-alphabetic, non-digit, non-space.

Suggested implementation

Based on the above tips, you can simplify your implementation like this:

private final Pattern hasUppercase = Pattern.compile("[A-Z]");
private final Pattern hasLowercase = Pattern.compile("[a-z]");
private final Pattern hasNumber = Pattern.compile("\\d");
private final Pattern hasSpecialChar = Pattern.compile("[^a-zA-Z0-9 ]");

public String validateNewPass(String pass1, String pass2) {
    if (pass1 == null || pass2 == null) {
        logger.info("Passwords = null");
        return "One or both passwords are null";
    }

    StringBuilder retVal = new StringBuilder();

    if (pass1.isEmpty() || pass2.isEmpty()) {
        retVal.append("Empty fields
");
    }

    if (pass1.equals(pass2)) {
        logger.info(pass1 + " = " + pass2);

        if (pass1.length() < 11) {
            logger.info(pass1 + " is length < 11");
            retVal.append("Password is too short. Needs to have 11 characters
");
        }

        if (!hasUppercase.matcher(pass1).find()) {
            logger.info(pass1 + " <-- needs uppercase");
            retVal.append("Password needs an upper case
");
        }

        if (!hasLowercase.matcher(pass1).find()) {
            logger.info(pass1 + " <-- needs lowercase");
            retVal.append("Password needs a lowercase
");
        }

        if (!hasNumber.matcher(pass1).find()) {
            logger.info(pass1 + "<-- needs a number");
            retVal.append("Password needs a number
");
        }

        if (!hasSpecialChar.matcher(pass1).find()) {
            logger.info(pass1 + "<-- needs a specail character");
            retVal.append("Password needs a special character i.e. !,@,#, etc.
");
        }
    } else {
        logger.info(pass1 + " != " + pass2);
        retVal.append("Passwords don't match
");
    }
    if (retVal.length() == 0) {
        logger.info("Password validates");
        retVal.append("Success");
    }

    return retVal.toString();
}

Support for unicode

If you want to allow unicode characters in the password, define the patterns using the special java character classes, as documented in the javadoc:

private final Pattern hasUppercase = Pattern.compile("\\p{javaUpperCase}");
private final Pattern hasLowercase = Pattern.compile("\\p{javaLowerCase}");
private final Pattern hasNumber = Pattern.compile("\\p{javaDigit}");
private final Pattern hasSpecialChar = Pattern.compile("[^\\p{javaLetterOrDigit} ]");


Ensuring a non-zero radius when constructing a circle

As mentioned in the comments by 200_success:

Why is zero the default, if it's invalid?
And: What about a negative radius?

Conceptually, a circle with a zero or negative radius might not make a lot of sense, but there's nothing in your code that would break because of it. The area will never be negative since the radius is multiplied by itself. The area might be zero, but again, that is the area of a zero-radius circle, so strictly speaking it's still valid.

You're also checking the type of the radius argument. You can argue either way if that's a good idea. It just raises a RuntimeError, with no extra explanation of what went wrong. If the check wasn't there, and you called, say, Circle.new("banana", "banana").area, you'd just get a NoMethodError instead. Not saying that's better, just saying that it's much worse either. Of course the current check happens in the constructor, which might be nice, but is it necessary?

For most cases, I lean toward saying "Garbage in, garbage out". If you've set the radius to "banana", then don't expect the math to make sense. Since Ruby isn't strictly typed and there's no compile step, the exceptions will occur at runtime anyway. So even if you try to add a lot of type-checking, it's debatable how much value it adds. Especially in this case, since raising a RuntimeError with no extra explanation seems less useful than letting, say, a NoMethodError occur, which will at least tell you things like undefined method**' for "banana"`.

Regardless, no reason to be dogmatic either way; type-checking definitely has its uses, and I'm not saying to always avoid it. Just make sure it adds some value.

Besides, it'd be better to raise an TypeError, since that's a lot more specific to this case than a general things-just-kinda-broke-RuntimeError.

I'd still argue that radius can indeed be zero, and that's fine. It's a strange circle to contemplate, but it's not impossible.

Again, I'd probably just skip the checking entirely, but if I were to add it, I'd write

raise TypeError.new("Radius must be numeric") unless radius.is_a?(Numeric)

And if you do want to avoid strange radii, you can add a separate check after that:

raise ArgumentError.new("Radius must be > 0") if radius <= 0


Without changing your algorithm we can make your code simpler in a few places. I'd say the algorithm is quite sensible, I would've chosen the same approach.

Comments and docstrings
Providing some comments here and there and explaining the general algorithmic approach in a docstring would be good start for increasing readability. In particular, it's not intuitively obvious why while change_directions < size:
is the correct approach.

Nested functions
I find nested functions to be relatively hard to read. Especially when they start using variables from the outer scope (the outer function), thereby mixing namespaces. Personally, I generally try to avoid them. In the case of check_collision I'd say it might improve readability as it reduces the maximum indentation level. That's generally a good thing, since every indentation level is another layer of context to keep track of.

get_change_values()
We can easily get rid of this function by taking a closer look at the underlying logic. We don't actually need to pass around direction strings, since we always follow the same pattern RIGHT -> DOWN -> LEFT -> UP -> RIGHT -> .... The itertools module from the standard library provides cycle, which basically provides an endless iterator for a given iterable (example from the docs: cycle('ABCD') --> A B C D A B C D A B C D ...). So we might want to cycle(['right', 'down', 'left', 'up']). But since we only need the strings to get the corresponding change_x, change_y values, we can replace them by those values directly:
directions = cycle(((1, 0), (0, 1), (-1, 0), (0, -1)))

We now replace
direction = directions[change_directions % 4]
change_x, change_y = get_change_values()

by
change_x, change_y = next(directions)

and get rid of get_change_values().

0 <= variable < limit
Conditions that follow the pattern 0 <= variable < limit can be replaced by variable in range(limit). I personally find this to be more readable, but it's not always preferable and up to personal preference.

check_collision()
This function can be simplified to the point where we could directly put it into our nested while loop. This is a valid option here. But as mentioned above you might want to keep it in a seperate function to reduce the maximum indentation level.
We don't actually need to check for the direction:
if direction in ('right', 'left'):
    if spiral[y][x + change_x * 2]:
        return True
elif direction in ('down', 'up'):
    if spiral[y + change_y * 2][x]:
        return True

if we simply check
if spiral[y + change_y * 2][x + change_x * 2] == 1:
    return True

We can also directly return:
def check_collision() -> bool:
    if y + change_y * 2 in range(size) and x + change_x * 2 in range(size):
        return spiral[y + change_y * 2][x + change_x * 2] == 1

    return False

I find exit conditions to generally improve code readability as well. They're usually closer to the reader's thought process ("If the step is out of bounds there's no collision, so we don't need to ckeck anything else. Otherwise check if the step leads to a 1."):
def check_collision() -> bool:
    if y + change_y * 2 not in range(size) or x + change_x * 2 not in range(size):
        return False

    return spiral[y + change_y * 2][x + change_x * 2] == 1

Both options are already pretty clean. I personally prefer this branchless approach:
def check_collision() -> bool:
    step_inside_bounds = y + change_y * 2 in range(size) and x + change_x * 2 in range(size)
    return step_inside_bounds and spiral[y + change_y * 2][x + change_x * 2] == 1

This works because and is evaluated lazily, so if step_inside_bounds is False, the rest of the condition is not evaluated.

spiral initialization
Instead of
spiral = [[0 for _ in range(size)] for _ in range(size)]

we can initialize spiral like this
spiral = [[0] * size for _ in range(size)]

This again is just another way to do things, and I wouldn't say it's definitely better for multi-dimensional lists. For one-dimensional lists, I would prefer the suggested syntax. Compare these examples:
my_list = [0 for _ in range(my_length)]
my_list = [0] * my_length

Complete code
I renamed change_directions to direction_changes and check_collision to collision_in_two_steps. I also added type hints (PEP 484).
from itertools import cycle

def spiralize(size: int) -> list[list[int]]:
    def collision_in_two_steps() -> bool:
        step_inside_bounds = y + change_y * 2 in range(size) and x + change_x * 2 in range(size)
        return step_inside_bounds and spiral[y + change_y * 2][x + change_x * 2] == 1

    directions = cycle(((1, 0), (0, 1), (-1, 0), (0, -1)))

    spiral = [[0] * size for _ in range(size)]
    x, y = 0, 0
    direction_changes = 0

    while direction_changes < size:
        change_x, change_y = next(directions)

        while y + change_y in range(size) and x + change_x in range(size):
            spiral[y][x] = 1

            if collision_in_two_steps():
                break

            y += change_y
            x += change_x

        direction_changes += 1

    return spiral


Check if all objects have the property value of all other objects

From the question and the comment I'd argue that your object model needs refactoring. There should be an Action object (you might come up with a better name...) tat contains the date and both of the processes Inflate and Deflate (not having a date themselves).

However...

This is how I would approach this by avoiding to iterate processAmounts excessively

public void fixMissingProcesses(){
    Map<String,Map<Date,ProcessAmount>> processesPerName = separateProcessesByName();
    List<String> processNames = new ArrayList<>(processesPerName.keySet());
    for(int i=1;i<processNames.length();i++)
      for(int j=0;j<i;j++)
         addMissingProcesses(processNames.get(i),processNames.get(j), processesPerName);
}

private void separateProcessesByName(){
    Map<String,Map<Date,ProcessAmount>> processesPerName = new HasMap<>();
    for (ProcessAmount processAmount : processAmounts) {
      if(null!=processAmount.getProcessName()){
         Map<Date,ProcessAmount> processesPerDate=  processesPerName.getOrDefault(processAmount.getProcessName(),new HashMap<>());
         processesPerDate.put(processAmount.getDate(),processAmount);
         processesPerName.put(processAmount.getProcessName(),processesPerDate)
      }
    }
    return processesPerName;
}

private void addMissingProcesses(String sourceProcessName, String targetProcessName, Map<String,Map<Date,ProcessAmount>> processesPerName);
    for(Date checkDate: processesPerName.get(sourceProcessName).keySet()){
       if(!processesPerName.get(targetProcessName).containsKey(checkDate)){
         processAmounts.add(new  ProcessAmount(checkDate, 0, targetProcessName)
       }
    }
}


Thanks to itsbruce this runs much faster:

sed -e "s,^.* DEBUG,$(tput setaf 2)&$(tput sgr0)," \
    -e "s,^.* INFO,$(tput setaf 2)&$(tput sgr0)," \
    -e "s,^.* WARN,$(tput setaf 3)&$(tput sgr0)," \
    -e "s,^.* ERROR,$(tput setaf 1)&$(tput sgr0)," \
    -e "s,^.* SEVERE,$(tput setaf 1)$(tput bold)&$(tput sgr0),"

Note: first two and the last line are removed.

Since sed takes the STDIN, this basically starts one sed instance for whole stream in contrast to one per line.


A c++ classs for recording audio samples

There are a lot of things here you should definitely improve on:

Where are your includes? Your first file is missing the includes for cstdint and cstring, your second file for cstdint, cstdio, whatever header WavFile belongs to, the header for CWaveRecorder, for SYSTEMTIME and so on and so forth. It's a miracle that your code even compiles successfully.
Everything from standard headers must be prefixed with std::. This applies to all the [u]int**_t types as well as to printf, memcpy, etc.
class WavFile wf; is superfluous; Wavfile wf; will do fine. This is not C.
Why do you bother with printf, _getch and the like? This is C++, and it has a standard library that offers a great range of very handy tools for such things, such as std::cout and std::cin. Don't reinvent the wheel. Again, this is not C.
Don't use NULL, use nullptr. This is not C.
Why does Recorder have a private: followed by nothing? Remove that.
Why are all of Recorder's member variables public? This violates data encapsulation. Instead, provide getters and setters for data that should be accessible to the public.
To answer the second question of yours: Yes, it is perfectly possible here to use std::vector and you should definitely opt to do so. First of all, std::vector provides a method named data() which allows access to the underlying array. Secondly, there is also std::copy, which you should prefer in almost all cases.

This answer is by far not comprehensive, but I suggest you go and rework your code, then come back for another review.

I am not going to sugarcoat it for you: Your code is horrible by C++ standards. You freely mix C legacy functions with code bearing only the slightest resemblance with what is called modern C++.

There is a middle ground between C and C++ which is called "C with classes" by most people. If you want to write code that's closer to C, you could consider sticking with that. Otherwise, I strongly recommend you to pick up a good book and learn how to write reasonably good C++ first.


Firstly, avoid the non-n versions of (w)str_ functions. You've got a buffer overflow just begging to happen here - if amount.length() > 100 - 8, it'll overflow your buffer, causing undefined behaviour and general bad times. Use wcsncat instead:

static const unsigned kstrMax = 100;
wchar_t strAmount[kstrMax] = L"Amount: ";
wchar_t* ptr = wcsncat(strAmount, amount.c_str(), kstrMax - amount.length() - 1);

In fact, we have to be even more careful here, because there's still a bug in the above code (I left it in because I only caught it when modifying my example - it's easy to make mistakes). Say amount.length() > kstrMax, then you'd think the value kstrMax - amount.length() would be below zero, but being unsigned, it will silently overflow, and will instead be some very large positive value, hence we could still easily overwrite the buffer size with this if amount is large enough.

static const unsigned kstrMax = 100;
unsigned currentBufferSize = kstrMax;
wchar_t strAmount[kstrMax] = L"Amount: ";
if(amount.length() >= kstrMax - 8) {
    //find out the difference, remake your buffer and copy across
    currentBufferSize = newBufferSize;
}
wchar_t* ptr = wcsncat(strAmount, amount.c_str(), currentBufferSize - amount.length());

From the looks of it, the amount entered is meant to be a small numeric value. Never assume anything about input. Anything that a user touches must be sanitized before you blindly use it.

std::wstring would make this fiddling about go away:

std::wstring strAmount("Amount: ");
strAmount += amount.c_str();
final.set(strAmount.c_str(), strAmount.size());


Notes:

Using uniq in a combinatorics problem is most likely a code smell. It means that you are generating more elements that you need (waste of space and time) and later you have to remove them (waste of more time).
The natural way seems to be  passing down which is the maximum subtraction value allowed, that way you won't repeat values in different orders.
I wouldn't extend Integer for a method like this, it does not seem a general enough abstraction.
Note that map + flatten(1) -> flat_map.

I'd write (also in functional style, as your code):

module Combinatorics
  def self.sets_with_sum(value, max = value)
    if value == 0
      [[]]
    else
      1.upto(max).flat_map do |n|
        sets_with_sum(value - n, [value, n].min).map do |ns|
          [n] + ns
        end
      end
    end
  end
end

p Combinatorics.sets_with_sum(4)
p Combinatorics.sets_with_sum(50).size

Even though I don't memoize anything, the performance is acceptable:

$ time ruby sum-combination.rb
[[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]
204226

real    0m8.416s