thanks for sharing your code.

There are a few things I wanted to talk about.

You shouldn't try / except an IndexError as a form of control flow.

An IndexError here would be the programmer's mistake, you should make sure that your code can't even raise an IndexError in the first place by using correct conditions in your loops. You can also removed the try/except sections completely and your code still behaves the same way.

Recursion

BubbleSort is an inefficient sorting algorithm when dealing with large inputs. The sheer number of comparisons done with larger inputs will cause some serious problems if you recursively call the function.

With the example input you gave, your function gets called 568 times. I tried sorting a list of double the size and got this

RecursionError: maximum recursion depth exceeded in comparison

Using a more straightforward iterative approach would be much more efficient.

def bubble_sort(details):
    """compares two consecutive integers in a list and shifts the smaller one to left """
    for i in range(len(details) - 1):
        swapped = False
        for j in range(len(details) - 1):
            if details[j] > details[j+1]:
                temp = details[j]
                details[j] = details[j+1]
                details[j+1] = temp
                swapped = True

        if not swapped:
            break

    return details

sort_me = [11,127,56,2,1,5,7,9,11] * 100 # give it a large input
print sort_me
print bubble_sort(sort_me)

A few additional things,

Consider implementing a version that doesn't modify the original list, think sorted(list) vs list.sort().
Your current implementation sorts the method in place but also returns the same list. If your method is mutating the list, consider not having a return value (or returning None instead).

Hopefully this was useful for you!


Bounds checking simplification

Your bounds checking code is overly complicated.  This total overlap check:

/* Total overlap */
if(node->start >= start && node->start <= end)
{
    if(node->end <= end && node->end >= start)
        return node->sum;
}

could be reduced to:

/* Total overlap */
if(node->start >= start && node->end <= end)
{
    return node->sum;
}

In this partial overlap check:

/* Partial overlap */
if((start >= node->start && start <= node->end) ||
       (end >= node->end && end <= node->start) ||
       (start <= node->start && end >= node->start))

I noticed that the second of the three conditions always evaluates to false.  Some of the other parts are also unnecessary.  In fact the whole thing could be rewritten as:

/* Partial overlap */
if (start <= node->end && end >= node->start)

Use of globals

The function build_tree() references the array ra directly.  It would be better for that array to be passed in as an argument.  Otherwise that function can't be used for any other segment tree.


Preparing and executing MySQL SELECT query from parameters

Right off the bat, there are a couple of things about your code that make me feel uneasy. I'll start by running through your code, almost line by line, explaining what I feel could be done to improve on what you have right now:

function select_query($parameter){
    require('database.php');

    $select = $parameter['select'];
    $type = $parameter['type'];
    $from = $parameter['from'];

For starters, you declare a function, that takes just one single argument. What type the function expects is an unknown, unless you actually bother to check the code of the function itself. $parameter (not the best name for the argument, IMHO), is expected to be an array, so your function signature should reflect that:

function selectQuery(array $parameter)
{
}

That would tell anyone who wants to use your function that they need to pass an array, not a string or object. If they pass anything else, they'll get a fatal error.

Next up, your function starts by require-ing a file. Not require_once, or checking if the file has already been processed by PHP, it just requires it. The result will probably be a lot of disk IO (which is bad for performance), and a function with an external dependency. Suppose someone opened the database.php file, and decided to change a thing or two. The variables declared within that file might change names, and you're left with a function that doesn't work anymore, for no apparent reason. To me, it seems like all you really need from that database.php file, is a mysqli connection object (or PDO, but since you've tagged your question mysqli, I'm assuming that that's what $conn is).

A far more common (and all-round better) way to obtain a DB connection would be to have the caller pass the connection of their choice to your function, again, as an argument. Here, you can use type-hints, too, to ensure the argument is indeed a mysqli instance/resource:

function selectQuery(mysqli $conn, array $parameter)
{}

That way, the caller can choose what DB should be used to query, what user, and -crucially- the caller can decide to re-use the connection for other tasks (other queries), and your function is no longer responsable for closing the connection, that falls to the caller.

The last thing about this piece of code that I'd change is this:

    $select = $parameter['select'];
    $type = $parameter['type'];
    $from = $parameter['from'];

Yes, using type-hints, you can ensure that the caller can only pass an array to your function, but an array is actually a rather vague thing, especially in PHP. Consider this:

function needsArray(array $argument)
{
    return $argument['total'] - $argument['costs'];
}

Now, these attempts at calling this function will fail:

needsArray(123);
needsArray(null);
needsArray('string');
needsArray(new stdClass);

But these are, going by the signature, correct invocations of the function:

needsArray([]);
needsArray((array) new stdClass);
needsArray(['total' => 'some string', 'costs']);
needsArray(['total' => 123456, 'costs' => 60]);

Yet, only the last call is actually valid, the others will emit notices (undefined index), or won't do anything even remotely meaningful.
At the very least, you'll have to check for every expected key in the $parameter array using isset or array_key_exists, and then you'll still have to ensure that the value of each key is what you expect it to be. That's going to add a lot of silly-looking if's and else's to the code. What's more: if one of the keys doesn't exist, or doesn't contain the type of data you expect it to contain, what do you do? You'll probably have to throw an exception. Let's take our dummy needsArray function, and re-write it in a safe way. Note that we're only expecting a 1D array, with just 2 keys, but just look at the amount of added code we need to add to ensure the array looks the part:

function needsArray(array $argument)
{
    if (!isset($argument['total']) || !is_numeric($argument['total']))
    {
        throw new InvalidArgumentException(
            sprintf(
                '%s expects array argument with key "total" set to a numeric value'
                __FUNCTION__
            )
        );
    }
    if (!isset($argument['costs']) || !is_numeric($argument['costs']))
    {
        throw new InvalidArgumentException(
            sprintf(
                '%s expects array argument with key "costs" set to a numeric value'
                __FUNCTION__
            )
        );
    }
    return $argument['total'] - $argument['costs'];
}

That's just an awful lot of clutter. Especially if you consider the fact that it's more than likely that the array you're passing to this function will be passed to several other functions, each of which might perform the same checks over and over.

TL;TR

If your function requires something (like a DB connection), don't have your function literally require a file to resolve its dependencies: force the caller to supply it by means of arguments.

If you need complex arguments, like your $parameter argument, either split that argument up into hintable, simple arguments:

function selectQuery(mysqli $conn, array $select, $from, ...)

Or create a class. The getters can validate the data, and you can write the setters to return the data in whatever format you like. Then, just type-hint that class where you need it:

class SelectParam
{
    protected $select = ['*'];//default value
    public function setSelect(array $select)
    {
        $this->select = $select;
        return $this;
    }
    public function getSelect($asString = false)
    {
        $select = $this->select;
        if ($asString)
            $select = implode(', ', $select);
        return $select;
    }
}
function selectQuery(mysqli $conn, SelectParam $param)
{}

Other issues have been covered by other answers. Issues like

Unused vars: $columns -> it's never used, and what it contains just doesn't seem to make much sense, IMHO
Weird variable names: $wr, $wc are meaningless. It's only because of the context in which they are used that we can deduce wr means "whereRow". But if the code gets any bigger, and I have to start scrolling to where the vars are first used to figure out what they actually are, that maintaining the code will be a pain. Even if the maintainer is the one who wrote the code in the first place
Lack of comments. Yes, I've not commented my code snippets here to save space, but if you haven't added the actual comments in your real-life code either, you should do so ASAP. Any half-decent API uses the doc-blocks of functions/methods for auto-completion and provides you with information about the method you're calling:

/**

Executes a SELECT query on the connection, returns the results as an array of assoc arrays
@param mysqli $conn
@param SelectParam $param
@return array
*/
function selectQuery(mysqli $conn, SelectParam $param)
{}

With that doc-block, an editor like PHPStorm will display the description text when you've typed selectQuery, and it'll notify the developer if any of the arguments you're passing is of an incompatible type:

$conn = new PDO();
selectQuery($conn, 123);//PHPStorm will pick up on the wrong types

These kinds of features IDE's have can, and often do, significantly reduce the time spent debugging, and prevent countless bugs from ever being committed in the first place.


Unit test for a method that populates a dictionary from an API call

There is a better way than using a string, there is a Namespace that you can import called Json or System.Json

after you have imported this you have access to JsonValue Arrays which allows you to nest JavaScript Objects creating a JSON Document.

it actually looks like you are already using the Namespace to deserialize the string into an object, not sure why you aren't just creating the JSON Objects themselves. they are just collections of KeyValuePairs of Of String, JsonValue  (Dictionaries, Collections, or Enumerables)


Don't use either - PDO is much more user-friendly and feature-rich.  Generally a class will be nicer to write code around, and now that we have PDO we don't need to write that class.  The following example is largely stolen from here: https://phpdelusions.net/pdo

$DBUser = "root";
$DBPass = "";
$DBName = "test";
$DBCharset = 'utf8mb4';

$dsn = "mysql:host=$DBServer;dbname=$DBName;charset=$DBCharset";
$DBOptions = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
try {
     $pdo = new PDO($dsn, $DBUser, $DBPass, $DBOptions);
} catch (\PDOException $e) {
     // to avoid a potential credentials leak through a stack trace
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

$stmt = $pdo->prepare("SELECT * FROM test WHERE lname = ?");
$stmt->execute([$_GET['l_name']]);
$data = $stmt->fetchAll();

foreach ($data as $row) {
    echo "{$row['f_name']} {$row['l_name']}<br>";
}


Convert MS SQL datetime to Oracle varchar(32) interval

As my data for LABEL_YYY_MM_DD_HH24_MI will always be the same length I can simply write:

left(convert(varchar(32),convert(smalldatetime,floor(cast(q.InTimeStart as float)*(24/.25))/(24/.25)),120),16) as LABEL_YYYY_MM_DD_HH24_MI,

If the results were of a dynamic length and we needed to remove the last three we would need to use len(x,-3):

left(convert(varchar(32),convert(smalldatetime,floor(cast(q.InTimeStart as float)*(24/.25))/(24/.25)),120),
 len(convert(varchar(32),convert(smalldatetime,floor(cast(q.InTimeStart as float)*(24/.25))/(24/.25)),120)) -3) as LABEL_YYYY_MM_DD_HH24_MI,


I don't see anything wrong with the smoothness of the animation.  However, I would simplify the code by introducing another container inside the .slide-item-wrapper; that whole container moves up, so that you don't have to animate each .box-item separately.  Furthermore, I would eliminate the special case for rewinding the animation to its original position.

var offset = 0;
var count = $(".slide-item-wrapper > * > *").length;
window.setInterval(
  function() {
    offset = (offset - 104) % (count * 104); // 104px div height (incl margin)
    $(".slide-item-wrapper > *").css({
      "transform": "translateY(" + offset + "px)",
    });
  }, 3000);
body {
  margin: 100px
}

.slide-item-wrapper {
  width: 300px;
  height: 84px;
  overflow: hidden;
}

.slide-item-wrapper > * {
  transition: .5s ease-in-out;
}

.box-item {
  display: flex;
  justify-content: center;
  align-items: center;
  background: red;
  color: white;
  width: 300px;
  height: 84px;
  margin-bottom: 20px;
}

      Lipsum

      Lipsum2

      Lipsum3

      Lipsum4

      Lipsum5

      Lipsum6


Randomizing all class variables in constructor c++

In theory, I think this is allowed because your Items are trivial types, but this is pretty ugly.

I think you can do better using std::array.

struct _color { uint8_t r; uint8_t g; uint8_t b; uint8_t a;};

could be

struct _color {
    auto& r() { return data[0]; }
    // etc
    void randomize() { /* fill data with random stuff */ }
    private:
        std::array<uint8_t, 4> data;
};

P.S. I think you will find that uniformly randomly setting r, g, b, and a doesn't look random to humans.

P.P.S.  There is a proposal to add something like this:

_color color;
for... (auto& component : std::meta::members(color)) {
    // do stuff with component
}

I haven't followed this proposal but it sounds like it would help here.


Functions
Split your code into individual smaller functions, doing singular tasks. A few examples would be validating the expression, extracting variables and so on.
if __name__ block
For scripts, it is a good practice to put your executable feature inside the if __name__ == "__main__" clause.
Comments
The comments like in:
while len(chars) < 10: # If there are less that 10 different mystery numbers

are pointless. The condition already explains what you write in 10 words. A more important comment here could've been what the mystery numbers are?
This applies to almost all of the comments you have added in your program. Once you split to functions, add docstrings to those functions explaining what and maybe why the function does. The code should be self-explanatory on the how.
Execution logic
From what I understand of the program, you are:

asking user for expression
validating if there are any invalid characters
extracting variables (and creating a forced list of 10 elements)
Not sure about the findall('\d+', exp) validation, and later the same thing is being achieved by a different regex pattern
check if the expression is mathematically consistent
permute all elements from variables list (created above)
iterate on all permutations and replace into the expression
evaluate expression and print if successful

A lot of the code seems duplicated, for eg. the exp.replace calls, the findall validation etc. You have to work with 2 nested loops just because there are no helper functions to assist you.
For the permutations themselves, you can obviously permute over a forced set of length 10, or you can just permute over the integers range(10) selecting as many elements as there are variables. Since you anyway need those integers (using enumerate), I'd go for this.
As a side note, instead of printing all valid results in the main loop, use a generator and yield valid results.

Example rewrite
from typing import Tuple, Set
from itertools import count, permutations

OPERATORS = '+-*/( ).='
VARIABLES = 'abcdefghijklmnopqrstuvwxyz'
NUMERALS = '1234567890'
VALID_CHARACTERS = OPERATORS + VARIABLES + NUMERALS

def is_expression_valid(expression: str) -> bool:
    return all(c in VALID_CHARACTERS for c in expression)

def is_expression_consistent(expression: str, variables: Set[str]) -> bool:
    for index, value in zip(count(1), variables):
        expression = expression.replace(value, str(index))
    try:
        eval(expression.replace("=", "=="))
    except SyntaxError:
        return False
    return True

def extract_variables(expression: str) -> Set[str]:
    variables = {char for char in expression if char in VARIABLES}
    if len(variables) > 10:
        raise ValueError()
    return variables

def get_expression() -> Tuple[str, Set[str]]:
    while True:
        expression = input(">>> ")
        if not is_expression_valid(expression):
            print(f"Invalid characters in the expression. Use only from: {VALID_CHARACTERS}")
            continue
        try:
            variables = extract_variables(expression)
        except ValueError:
            print("Expected at most 9 variable/letters!")
            continue
        if not is_expression_consistent(expression, variables):
            print("Invalid syntax!")
            continue
        break
    return expression, variables

def substitute_expression_format(expression: str) -> str:
    return "".join(r"{}" if c in VARIABLES else c for c in expression)

def valid_results(expression: str, variables: Set[str]) -> str:
    formatted_expression = substitute_expression_format(expression)
    for permute in permutations(range(10), len(variables)):
        variation = formatted_expression.format(*permute)
        if eval(variation.replace("=", "==")):
            yield variation

def main():
    expression, variables = get_expression()
    for result in valid_results(expression, variables):
        print(result)

if __name__ == "__main__":
    main()

Notice in is_expression_consistent, I've use zip with itertools.count, so that the dependency on regex is removed.
Now, the above fails for invalid token check, when the first substitution is \$ 0 \$; which can be resolved by having a try-except in the generator:
def valid_results(expression: str, variables: Set[str]) -> str:
    formatted_expression = substitute_expression_format(expression)
    for permute in permutations(range(10), len(variables)):
        variation = formatted_expression.format(*permute)
        try:
            if eval(variation.replace("=", "==")):
                yield variation
        except SyntaxError:
            continue

You can check the code on tio.run.

EDIT
For fixing the issue mentioned in comments (about repeated letters):
def substitute_expression_format(expression: str) -> str:
    return "".join(f"{{{c}}}" if c in VARIABLES else c for c in expression)

def valid_results(expression: str, variables: Set[str]) -> str:
    formatted_expression = substitute_expression_format(expression)
    for permute in permutations(range(10), len(variables)):
        variation = formatted_expression.format(**dict(zip(variables, permute)))
        try:
            if eval(variation.replace("=", "==")):
                yield variation
        except SyntaxError:
            continue

Updated example on tio.run.


Partition Equal Subset Sum Challenge LeetCode

No need for full matrix
Although your dynamic programming solution works, you are using a matrix of size [sum/2][n] when you only need to allocate a single vector of size [sum/2].  Not only are you using more memory than necessary, but this could also affect performance because of caching.
Use a quick return
Your solution runs the full double loop to completion before determining whether the answer is possible.  It is possible to create a solution that returns as soon as it finds a valid solution.  This could potentially cut down on the time by a lot for inputs that have solutions.
Additionally, I found that sorting the inputs and looping through them from largest to smallest works best in conjunction with the quick return.
Sample rewrite
Here is how I would write the program, using only a single dimensional vector for the DP part, sorting the inputs, and allowing for a quick return:
#include <iostream>
#include <vector>
#include <algorithm>

int main(void)
{
    int n;
    int sum = 0;

    // Read in numbers.
    std::cin >> n;
    std::vector<int> nums(n);
    for (int i=0; i<n; i++) {
        int num;
        std::cin >> num;
        nums[i] = num;
        sum    += num;
    }

    // Quick check to see if sum is even.
    if (sum & 1) {
        std::cout << "false" << std::endl;
        return 0;
    }
    // Cut sum in half.  Sum is now the target to reach.
    sum >>= 1;

    // Sort numbers so we can use the largest ones first.
    sort(nums.begin(), nums.end());

    // Iterate through each number from largest to smallest, updating the
    // possible array and trying to find out if [sum] is possible.
    std::vector<bool> possible(sum);
    possible[0] = true;
    for (int i=n-1; i>=0; i--) {
        int val = nums[i];
        // Quick return if we find we can reach [sum].
        if (sum - val >= 0 && possible[sum - val]) {
            std::cout << "true" << std::endl;
            return 0;
        }
        for (int j=sum-val-1; j >= 0; j--) {
            if (possible[j])
                possible[j + val] = true;
        }
    }

    std::cout << "false" << std::endl;
    return 0;
}


Conversion helper with support for enumerations and Nullable

/// <summary>
///     Returns an object of type <typeparamref name="T"/> whose value is equivalent to that of the specified
///     object.
/// </summary>

...

/// <returns>
///     An object whose type is <typeparamref name="T"/> and whose value is equivalent to <paramref name="value"/>.
/// </returns>

I don't see any reason to repeat what was said in <summary> in <returns>. I wouldn't write <returns> here at all. (Unless you're writing a library with very high demands on documentation, like the .Net framework itself.)

underlyingNullableType ?? type

You're repeating this expression several times. You should probably extract it into a variable.

You should be consistent: either use if-else if-else and ignore the returns, or acknowledge the returns and use if-if-nothing.


If the request is already being served over HTTPS, then it would be a good idea to add a Strict-Transport-Security header to the response. Strict-Transport-Security tells the browser that, as a matter of policy, your site wants all requests to your domain to be made over HTTPS.

Be aware that redirecting an HTTP POST request would cause the browser to make an HTTP GET request. To cause the second request to also be made as a POST, you would need to respond with a a 307 status code.  Of course, the benefit of a 307 redirect of a POST is questionable, as any sensitive POST data will have already been transmitted unencrypted already.


Serializing user data to send to another API

Below I have written how I tackled your code. I hope the approach is clear from the explanations and code example. Feel free to use this approach yourself.

When I took a closer look at your code I began looking for similarities which could easily be extracted into its own class. This in turn made some of the harder things to extract easier. I have tried (I am writing from a tablet :D) to write down my implementation of your problem. It has been a little hard though because I properly lack some context, so feel free to modify the code example if you decide to use it.

The first thing I changed was your dependency of the XMLSerializer into a dependency for a common interface. This will help you if you some time in the future decide to change the serialization format into JSON instead of XML. With a common interface you can swap the actual implementation during the method call as long as the new implementation also adhere to the common interface. This will also help mitigate your tight coupling concerns.

interface Serializer {

    /*
     * I could not see the use of the second argument from your
     * code, so I added an extra one just in case:D
     */
    public function serializeObj($object, $someUnknownFlag);

}

I then extracted the serialization logic and generation of the value object into its own class. This helped mitigate your code duplication concerns. When you read through the code example you might find that specifying which parameters are required is too much duplication, but I could not find a more flexible solution without making this too 'magical'.

I also think I corrected a possible bug in your code since the property new_user_obj is not instantiated anywhere.

How the class works are documented with comments throughout the code. I feel this gives you some freedom by having the serialization logic be free of how the actual data is fetched and let the extending class worry about that instead. This also makes it easier to add or remove required data parameters and/or change the behavior of the concrete class (UserCustomer, UserAddress etc.) without altering the serialization logic.

abstract class UserDataSerializer {

    private $data     = [];
    private $required = [];

    /**
     * @param array $data     An associative array of data that can be serialized.
     * @param array $required A sequential array of required data parameters.
     */
    public function __construct(array $data, array $required)
    {
        $this->data     = $data;
        $this->required = $required;
    }

    /**
     * Serializes the passed user data into the appropriate format.
     *
     * @param Serializer $serializer Here I have used an interface instead of a concrete implementation.
     *                               This will allow you to change to way the objects are serialized from
     *                               XML to maybe JSON by substituting to serializer implementation with
     *                               another serializer implementing the same interface.
     *
     * @return string Returns the data serialized into a string.
     */
    final public function serialize(Serializer $serializer)
    {

        /*
         * This method is made FINAL to ensure child classes doesn't
         * overwrite the implementation.
         */

        /*
         * By first executing the setData method now, we ensure
         * we only use instantiate a new object when it is actually needed.
         */
        $obj = $this->setData($this->data);

        return $serializer->serializeObj($obj, true);

    }

    private function setData(array $data) {

        /*
         * Check if all required parameters are present in the
         * associative array of data.
         *
         * First we calculate the differences from the required parameters
         * and the array keys (which are our names) from the data array.
         */
        $difference = array_diff($this->required, array_keys($data));

        /*
         * If the difference array is bigger than zero we are missing
         * one ore more required parameters.
         */
        if(count($difference) > 0) {
            throw new InvalidArgumentException('Insufficient data parameters provided. Missing: ' . implode(', ', $difference));
        }

        /*
         * We create a value object by using the ArrayObject and declaring
         * the access method for properties as class properties. This is done with
         * the STD_PROP_LIST flag.
         */
        return new ArrayObject($data, ArrayObject::STD_PROP_LIST);

    }

}

I have then extracted the specific logic regarding the required data and how the data is fetched to the class extending the UserDataSerializer.

class UserCustomer extends UserDataSerializer {

    public function __construct(array $data)
    {
        /*
         * We make a sequential array of required parameters for the
         * customer user type.
         */
        $required = ['id', 'firstname', 'lastname'];

        /*
         * Configure the parent class by declaring required data parameters
         * and providing the corresponding values.
         */
        parent::__construct($data, $required);

    }

    /*
     * Here you can implement specific methods for the
     * customer user type.
     */

}

class UserAddress extends UserDataSerializer {

    /*
     * Here the constructor take individual arguments and you can
     * decide which should be serialized and which of them should be
     * used for other purposes related to the class.
     */
    public function __construct($id, $address, $postcode, $otherInto)
    {
        /*
         * We make a sequential array of required parameters for the
         * address user type.
         */
        $required = ['id', 'address', 'postcode'];

        /*
         * We generate a data array of with the required parameters as keys
         * and the provided arguments as values.
         */
        $data = array_combine($required, [$id, $address, $postcode]);

        /*
         * Configure the parent class by declaring required data parameters
         * and providing the corresponding values.
         */
        parent::__construct($data, $required);

    }

    /*
     * Here you can implement specific methods for the
     * address user type.
     */

}

The usage is now a little different. In your code the passed data is fetched from an object, where my example uses an associative array. This is just because it is more convenient, when checking if all required parameters are present. Usage is as follows:

$serializer = new XMLSerializer(); // This implements the common Serializer interface.

$customer = new UserCustomer([
  'id'        => 123,
  'firstname' => 'awesomeness',
  'lastname'  => 'himself'
]);

$customer->serialize($serializer);

$serializer = new JSONSerializer(); // New serializer implementation.

$address = new UserAddress([
    'id'       => 123,
    'address'  => 'Cool Street 1',
    'postcode' => 'over 9000'
]);

$address->serialize($serializer);

Regarding your concern for using the same big data array.

  I'm sending the same big data array with a lot of 'waste' to each class

The first and properly the best way to avoid this, is to only pass the necessary information to the constructor like I have done in the UserAddress class. Usage would be:

$address = new UserAddress(
        $data->id,
        $data->address,
        $data->postcode,
        $data->otherInto
    );

This can also be changed by only extracting the required information for each class like you do. But as the data is set in the constructor we should take care not doing too much work inside it (it may already be too much for some). We could extract the gathering of only the necessary information into its own private method. I have named it prepare. I am also assuming the big data array is an object of type User, but it could be anything.

private function prepare(User $user)
{

    return [
        'id'       => $user->getId(),
        'address'  => $user->getAddress(),
        'postcode' => $user->getPostcode()
    ];

}

You must then alter your constructor. Here the User value object is passed as an argument.

public function __construct(User $user)
{
    /*
     * We make a sequential array of required parameters for the
     * address user type.
     */
    $required = ['id', 'address', 'postcode'];

    /*
     * We prepare the required data by extracting only the
     * necessary information from the user object.
     */
    $data = $this->prepare($user);

    parent::__construct($data, $required);

}

Other things

I have changed your naming convention to CamelCase.

I have changed the way data is fetched from the big data array to individual methods. This help ensure encapsulation of the data, by only providing setters for the properties which CAN be altered.

I have a bit of trouble understanding the reason to why the class UserAddress exist. To me an address consists of a string which could be a property inside a class. If you want more detail it could be an associative array where each element is given a value during instantiation of the class.

private $address = [
    'number'   => null,
    'street'   => null,
    'city'     => null,
    'postcode' => null,
    'country'  => null
];

I hope this can help guide you, happy coding!


Don't make unnecessary type aliases

using string_t = std::string;
using CharT = string_t::value_type;

Those neither add readability nor make the existing facilities easy to use. When seeing those, I always recall the matlab C++ code generator, and the code it generated was frankly rubbish (Your code is good, it's just that those aliases trigger the feeling of disgust).

Take by std::string_view

I know you tagged this as C++14, but support for C++17 language is already good on all compilers, and standard library implementations are catching up. std::string_view is just more explicit way of saying that you don't need a copy of a string, just wanna read it.

Less verbose ways to overload

I'd be inclined to use if constexpr or tag based dispatch. The latter would probably end up the same length as current code.

Don't inhibit RVO

auto s = std::move(format(str, std::forward<Ts>(args)...));

RVO/NRVO (named return value optimization) is an optimization performed by compiler which is a form of copy elision. Compilers are allowed to eliminate a copy in some cases (can't recall strictly in which cases) Move would happen anyway, and in C++17 the guaranteed copy elision would work anyway, too.

Easy to use correctly, hard to use incorrectly

Perhaps I read too much of "Nobody wants to read your sh*t", but I see some similarity between what Scott Meyers writes and what Steven Pressfield describes. Both try to convey idea of being user/reader-friendly. Guiding them at the correct usage/idea, rather than expecting them to know it (or at least to try one's best). At the moment, the code doesn't throw exception if number of arguments is not equal to number of replacement symbols in the format string, nor any other warning/error. Not everybody knows that the functions don't support custom types with operator<< overloaded. C++ users usually use std::fstream, or some other custom build streams, which the code doesn't support. Very few C++ programmers are paranoid about ADL, which the code will invoke in case the intended print didn't compile. Some ADL calls are extremely evil.

People praise code for being nice, and great interface and reasonable performance is sufficient definition of nice (IMO). Implementation can be amended as time goes by, but changing interface/contracts is rarely an option. Although implementation matters, having great interface offers much greater possibilities of optimizations.

Executable size is not that important

Size of iostream gets dwarfed by the rest of application, usually. Using standard library algorithms, or especially boost, will make additional size of iostream insignificant. It might be important in some cases, but those who encounter would usually have no std::FILE either, as they want to output to embedded 8*8 LED screen or something like that.

Alternative implementation

I would use pseudo runtime tuple indexing to access elements, rather than recursing. That would eliminate the weird edge case of no arguments, and make everything more consistent.

Important excerpt:

template <std::size_t static_index, typename ... ArgumentTypes>
std::string runtime_get(std::size_t runtime_index, std::tuple<ArgumentTypes...>&& rest) {
    if constexpr (static_index == std::size_t(-1)) {
        throw std::invalid_argument("number of format symbols is more than arguments");
    }
    else {
        if (runtime_index == static_index)
            return to_string(std::get<static_index>(rest));
        else
            return to_string(runtime_get<static_index - 1>(runtime_index, std::move(rest)));
    }
}

template <typename... Ts>
string_t format(const CharT *str, const Ts &... args) {
    std::size_t current_index = 0;
    string_t res;
    for (; *str; str++) {
        if (*str != '%') {
            res += *str;
            continue;
        }
        if (*(str + 1) == '%') {
            res += '%';
            ++str;
        }
        else {
            res += runtime_get<sizeof...(Ts) - 1>(current_index,
                std::forward_as_tuple(args...));
            ++current_index;
        }
    }
    return res;
}

It is easy to see that one can only pass data into a function, but trying to get the wanted element is impossible due to type being different depending on runtime index. The function usually compiles into a loop for differing user defined types, and into jump table in case of the same or only built in types.

Full code of alternative implementation:

#include <cstdlib>
#include <string>
#include <stdexcept>
#include <tuple>

namespace gupta {
    using string_t = std::string;
    using CharT = string_t::value_type;

    template <typename T> inline string_t to_string(const T &f) { return std::to_string(f); }
    inline string_t to_string(const char *str) { return std::string{ str }; }
    inline string_t to_string(string_t s) { return (s); }

    template <std::size_t static_index, typename ... ArgumentTypes>
    std::string runtime_get(std::size_t runtime_index, std::tuple<ArgumentTypes...>&& rest) {
        if constexpr (static_index == std::size_t(-1)) {
            throw std::invalid_argument("number of format symbols is more than arguments");
        }
        else {
            if (runtime_index == static_index)
                return to_string(std::get<static_index>(rest));
            else
                return to_string(runtime_get<static_index - 1>(runtime_index, std::move(rest)));
        }
    }

    template <typename... Ts>
    string_t format(const CharT *str, const Ts &... args) {
        std::size_t current_index = 0;
        string_t res;
        for (; *str; str++) {
            if (*str != '%') {
                res += *str;
                continue;
            }
            if (*(str + 1) == '%') {
                res += '%';
                ++str;
            }
            else {
                res += runtime_get<sizeof...(Ts) - 1>(current_index,
                    std::forward_as_tuple(args...));
                ++current_index;
            }
        }
        return res;
    }

    template <typename... Ts> auto fprint(std::FILE *f, const char *str, Ts &&... args) {
        auto s = std::move(format(str, std::forward<Ts>(args)...));
        return fwrite(s.data(), 1, s.size(), f);
    }

    template <typename... Ts> inline auto print(const char *str, Ts &&... args) {
        return fprint(stdout, str, std::forward<Ts>(args)...);
    }

    template <typename... Ts> inline auto debug(const char *str, Ts &&... args) {
        return fprint(stderr, str, std::forward<Ts>(args)...);
    }

    namespace detail {
        class _stdout_object {};
        class _stderr_object {};
    } // namespace detail

    namespace printing_shortcuts {

        template <typename T> detail::_stdout_object operator<<(detail::_stdout_object f, const T &arg) {
            auto s = to_string(arg);
            fwrite(s.data(), 1, s.size(), stdout);
            return f;
        }

        template <typename T> detail::_stderr_object operator<<(detail::_stderr_object f, const T &arg) {
            auto s = to_string(arg);
            fwrite(s.data(), 1, s.size(), stderr);
            return f;
        }

        detail::_stdout_object print() { return {}; }
        detail::_stderr_object debug() { return {}; }

    } // namespace printing_shortcuts

    using namespace printing_shortcuts;

} // namespace gupta

using namespace gupta::printing_shortcuts;

class test {};

std::string to_string(const test &) { return "test"; }

#include <assert.h>
#include <iostream>

int main() {
    using namespace gupta;
    std::cout << format("%% %", 12) << '\n';
    assert(format("%% %", 12) == "% 12");
}

Demo on Wandbox


Idiomatic ruby to calculate distance to points on a graph

Enumerable.each_cons(n) will pass the array items in groups of n, using a sliding window.  So [pt1, pt2], [pt2, pt3], [pt3, pt4], etc.

After that you can use inject to calculate the distance and sum the points.

def manhattan(pt1, pt2)
  (pt1[0]-pt2[0]).abs + (pt1[1]-pt2[1]).abs
end

def cost
  @random_tour
    .each_cons(2)
    .inject(0) { |sum, pts| sum + manhattan(pts[0], pts[1]) }
end


Shortening boolean with if statement for document version comparison

Sure. Use the Not operator.

if (!documentComparer.Equals(version, imported))
{
    changedDocument.Add(imported);
}

To explain a little, it's bad practice to do things like this.

bool boolean = true;
if (boolean == false)
{
//...

because it's completely equivalent to saying

if (true == false)

and can be simplified down to

if (false)


Is the usage of SQL Cursor appropriate here?

This code can be simplified a lot, and in to a single update without the cursor. This may be a problem, though if your transaction log is not large enough to accommodate a mass update to all your records.

Right, how to simplify the update?

First, build the case statement in to the @UserCodeList logical table... Consider this:

INSERT INTO @UserCodeList (Title, UserCodeListIdentifier, RepaymentTypeToUpdate)
SELECT Title, UserCodeListIdentifier,
       case
           when title like '%some_text_1%' then 1
           when title like '%some_text_2%' then 2
           .....
       end
FROM tblUserCodeList;

Now, in that table, you have the correct RepaymentType cross reference for the update.

Your update now simply becomes:

UPDATE dbo.tblEmployment
SET RepaymentTypeIdentifier = (
    select UserCodeListIdentifier
    from @UserCodeList
    where RepaymentType = RepaymentTypeToUpdate
)

The above update can be done in a few different ways.... a CTE would be my preference:

with UpdateMap as (
    SELECT Title,
           UserCodeListIdentifier,
           case
               when title like '%some_text_1%' then 1
               when title like '%some_text_2%' then 2
               .....
           end as MatchRepayment
    FROM tblUserCodeList;
)
UPDATE dbo.tblEmployment
SET RepaymentTypeIdentifier = UserCodeListIdentifier
FROM UpdateMap
where MatchRepayment = RepaymentType

Having said all that, let's revisit your questions:

Firstly, is the use of a cursor an overkill here?

Probably. If your database transaction log is small, though, it may be better to break your updates in to batches that fit. A single large update may fail, and roll back, if there's not enough space to log it as a single operation. Your cursor breaks it doen to a sinlge record each time, and there's plenty of space for that, though. Ask your DBA, or just try it... if you are uncertain.
Is there a simpler way to do what I'm doing in SQL?

SQL is a set-based language. If you have a set-based way of thinking about it, then my suggestions are 'simpler'. Certainly, it is more concise.
Could the script go terribly wrong?

Yes.... it could. Take a backup first, and verify everything!
I have limited SQL experience, how does it look? Any standards that I'm not following?

Your conventions, for what you are doing, are reasonably good. There's very little in the way of 'standards' for SQL style... consistency is the key factor to look for.


The move variable seems unnecessary - you pass it to getValidMove() but never use it inside the function.
The language has loops for repetitive tasks. In the drawPlayfield() you may do

for(int i=0; i<9; i++)
    System.out.println("|"+table[i]);
System.out.println("|");

instead of

System.out.println("|"+table[0]+"|"+table[1]+"|"+table[2]+
        "|"+table[3]+"|"+table[4]+"|"+table[5]+"|"+table[6]+"|"+table[7]
+"|"+table[8]+"|");

This costs 10 calls instead of two, but 1) saves strings addition, 2) makes the code easy expandable (you just need to replace the 9 with another expression).
The getValidMove() function returns just one int value. Why do you allocate a table for it? declare the return type as int instead of int [] and save unnecessary work.
There is some problem with reponsibilities of functions. Function getValidMove() not only gets a valid move, as its name says, but it also removes the chosen piece from the table with assignment table[start] = " "; That is a part of performing the actual move. However I can't see where the move is completed. Where do you do table[destination] = "x"; or table[destination] = "o";? And where do you store the shape of the piece removed by table[start] = " "; to be reinserted at destination?

Critical problems are fixed now - but one important remains:

The part to input user's move is unsafe. The first loop tests for both numbers being in the required range and repeats asking for input until data are correct – or until -1 appears, which terminates the program.

Then, however, another loop starts, which tests if the chosen destination position is free – and this loop does no longer validate values for being between 1 and 8. It also does not validate data for conforming the game rules (i.e. whether the jump is no more than 2 positions long).

IMHO there should be one loop, looking more or less like this:

do
{
    do
    {
        System.out.println("Input start position (0-8)");
        start = sc.nextInt();
        if (start == -1)
        {
            System.exit(0);
        }
    } while (start < 0 || start > 8);

    do
    {
        System.out.println("Input destination position (0-8)");
        destination = sc.nextInt();
        if (destination == -1)
        {
            System.exit(0);
        }
    } while (destination < 0 || destination > 8);

    if (destination == start)
    {
        System.out.println("Destination must differ from start!");
        continue;
    }
    if (destination < start - 2 || destination > start + 2)
    {
        System.out.println("Destination must not differ from start more than by 2!");
        continue;
    }

    if (table[destination] != ' ')
    {
        System.out.println("The destination position is not empty!");
        continue;
    }
} while (false);   // the input is OK now

Of course the two inner loops are asking for replacing them with a call to some helper function...


The first thing I should say is that your code looks very messy and requires "cleaning up". I don't know for sure if this is because of formatting problems when transferring from IDE to Code Review, but if it is not, then formatting needs work.
After formatting, it looks like this:
public class Test {

    public static void main(String[] args) {
        StockItem item_1 = new StockItem("A654Y", 1000, 50, 500, 5);
        System.out.println("Day" + "\t" + "Stock" + "\t" + "Order Status");
        System.out.println();
        int reOrderThreshold = 600;
        int orderTravelTime = 0;
        boolean orderInTravel = false;
        int quantityIn = item_1.getQuantityInStock();
        for (int n = 1; n <= 50; n++) {
            String out = "";
            quantityIn -= item_1.getDailyDemand();
            out += n;
            out += " " + "\t" + quantityIn + "\t";
            if (orderInTravel && orderTravelTime < item_1.getLeadTime()) {
                orderTravelTime++;
                out += "In Transit -" + "\t";
            } else if (orderInTravel && orderTravelTime >= item_1.getLeadTime()) {
                orderTravelTime = 0;
                orderInTravel = false;
                quantityIn += item_1.getReOrder();
                out += "New Stock Delivered ("
                        + item_1.getReOrder()
                        + ")   and Will be Added to Quantity in Stock the Next Day";
            }
            if (quantityIn < reOrderThreshold) {
                orderInTravel = true;
                out += "Ordered";
            }
            System.out.println(out);
        }
    }
}

class StockItem {

    String inventoryCode;
    int quantityInStock;
    int dailyDemand;
    int reOrder;
    int leadTime;

    public StockItem(String inventoryCode, int quantityInStock,
            int dailyDemand, int reOrder, int leadTime) {
        this.inventoryCode = inventoryCode;
        this.quantityInStock = quantityInStock;
        this.dailyDemand = dailyDemand;
        this.reOrder = reOrder;
        this.leadTime = leadTime;
    }

    public String getInventoryCode() {
        return inventoryCode;
    }

    public int getQuantityInStock() {
        return quantityInStock;
    }

    public int getDailyDemand() {
        return dailyDemand;
    }

    public int getReOrder() {
        return reOrder;
    }

    public int getLeadTime() {
        return leadTime;
    }

}

Note that this is not the final result. There are a lot more to add before it's good.
Now to the actual code...
First of all...
In the main method, there is this:
System.out.println("Day" + "\t" + "Stock" + "\t" + "Order Status");
System.out.println();

This could be easily changed to:
System.out.println("Day\tStock\tOrder Status\n");

This improves efficiency by reducing the time required to concatenate the Strings, as well as removing the requirement of the empty System.out.println(). In fact, you split the Strings where no split is necessary. " " + "\t" can just simply be " \t".
String out = "";

Remember that Strings are immutable. Since out is concatenated multiple times, you should use StringBuilder, and add Strings with out.append(...).
All the code in the for loop can be at least broken down into two methods. But before we do that, the variables should be instantiated outside of main, with static.
static StockItem item_1 = new StockItem("A654Y", 1000, 50, 500, 5);
static int reOrderThreshold = 600;
static int orderTravelTime = 0;
static boolean orderInTravel = false;
static int quantityIn = item_1.getQuantityInStock();

Then, let's break it away from the main method:
public static void main(String[] args) {
    System.out.println("Day\tStock\tOrder Status\n");
    for (int n = 1; n <= 50; n++) {
        doDay(n);
    }
}

private static void doDay(int day) {
    StringBuilder out = new StringBuilder();
    quantityIn -= item_1.getDailyDemand();
    out.append(day).append(" \t").append(quantityIn).append("\t");
    if (orderInTravel && orderTravelTime < item_1.getLeadTime()) {
        orderTravelTime++;
        out.append("In Transit -\t");
    } else if (orderInTravel && orderTravelTime >= item_1.getLeadTime()) {
        orderTravelTime = 0;
        orderInTravel = false;
        quantityIn += item_1.getReOrder();
        out.append("New Stock Delivered (").append(item_1.getReOrder()).append(")   and Will be Added to Quantity in Stock the Next Day");
    }
    if (quantityIn < reOrderThreshold) {
        orderInTravel = true;
        out.append("Ordered");
    }
    System.out.println(out);
}

And then draw out the if statements:
private static void doDay(int day) {
    StringBuilder out = new StringBuilder();
    quantityIn -= item_1.getDailyDemand();
    out.append(day).append(" \t").append(quantityIn).append("\t");
    checkOrder(out);
    checkStock(out);
    System.out.println(out);
}

private static void checkOrder(StringBuilder output) {
    if (orderInTravel && orderTravelTime < item_1.getLeadTime()) {
        orderTravelTime++;
        output.append("In Transit -\t");
    } else if (orderInTravel && orderTravelTime >= item_1.getLeadTime()) {
        orderTravelTime = 0;
        orderInTravel = false;
        quantityIn += item_1.getReOrder();
        output.append("New Stock Delivered (").append(item_1.getReOrder()).append(")   and Will be Added to Quantity in Stock the Next Day");
    }
}

private static void checkStock(StringBuilder output) {
    if (quantityIn < reOrderThreshold) {
        orderInTravel = true;
        output.append("Ordered");
    }
}

And there you go, small methods!
As for the extra methods, I think they are unnecessary.
Final code:
public class Main {

    static StockItem item_1 = new StockItem("A654Y", 1000, 50, 500, 5);
    static int reOrderThreshold = 600;
    static int orderTravelTime = 0;
    static boolean orderInTravel = false;
    static int quantityIn = item_1.getQuantityInStock();

    public static void main(String[] args) {
        System.out.println("Day\tStock\tOrder Status\n");
        for (int n = 1; n <= 50; n++) {
            doDay(n);
        }
    }

    private static void doDay(int day) {
        StringBuilder out = new StringBuilder();
        quantityIn -= item_1.getDailyDemand();
        out.append(day).append(" \t").append(quantityIn).append("\t");
        checkOrder(out);
        checkStock(out);
        System.out.println(out);
    }

    private static void checkOrder(StringBuilder output) {
        if (orderInTravel && orderTravelTime < item_1.getLeadTime()) {
            orderTravelTime++;
            output.append("In Transit -\t");
        } else if (orderInTravel && orderTravelTime >= item_1.getLeadTime()) {
            orderTravelTime = 0;
            orderInTravel = false;
            quantityIn += item_1.getReOrder();
            output.append("New Stock Delivered (")
                    .append(item_1.getReOrder())
                    .append(")   and Will be Added to Quantity in Stock the Next Day");
        }
    }

    private static void checkStock(StringBuilder output) {
        if (quantityIn < reOrderThreshold) {
            orderInTravel = true;
            output.append("Ordered");
        }
    }

}

class StockItem {

    String inventoryCode;
    int quantityInStock;
    int dailyDemand;
    int reOrder;
    int leadTime;

    public StockItem(String inventoryCode, int quantityInStock,
            int dailyDemand, int reOrder, int leadTime) {
        this.inventoryCode = inventoryCode;
        this.quantityInStock = quantityInStock;
        this.dailyDemand = dailyDemand;
        this.reOrder = reOrder;
        this.leadTime = leadTime;
    }

    public String getInventoryCode() {
        return inventoryCode;
    }

    public int getQuantityInStock() {
        return quantityInStock;
    }

    public int getDailyDemand() {
        return dailyDemand;
    }

    public int getReOrder() {
        return reOrder;
    }

    public int getLeadTime() {
        return leadTime;
    }

}


Project Euler problem 3: Largest prime factor in JavaScript

Your code looks pretty, and it is a very literal naïve implementation of the requirements. Unfortunately, the algorithm you are using is extremely inefficient.

Factoring large numbers is hard work! The difficulty of factoring large numbers is, in fact, what keeps cryptographic algorithms like RSA safe.  In your findFactors() function, just counting up to 600 billion will take a while; having to check for divisibility within the loop is even slower!

For a quick algorithm that will give the answer in about one second, see this answer.


Is there a better way of doing Task cancellation than the one I implemented

There's no task cancellation implemented here. By passing a token to Task.Run you just make the returned task IsCanceled equal to true in case it cancels itself (without, it gets IsFaulted by the OperationCanceledException). But you need (at least) to pass the token to DoSomeWork, because that has to check the token and cancel itself.

Task cancellation works through cooperation of the to-be-canceled task and has nothing to do with Thread.Abort.


Which one is more readable for mutually exclusive but mandatory command line parameters validation?

I would put all validations first, and then extract to a method.  Better, trying using a parsing framework like JCommander that might be able to handle that for you, so that your code is just business logic


If you look at the doc for cbind, which you already use, you will see that it can take whole matrices, data.frames, and vectors as inputs. This means you can just do:

TableWithResiduals <- cbind(iris, Residual_value = resid(lmfit))

You could also have done:

TableWithResiduals <- iris
TableWithResiduals$Residual_value <- resid(lmfit)

If it were not for these solutions, there are a few things that could be improved in your code. First, you could have used row directly instead of the out_index variable you created. Second, the last two lines of your code could have been merged into one: names(TableWithResiduals) <- c(names(iris), "Residual_value"). Also, if you look at the doc for lm, you could have saved yourself some typing by doing lm(Petal.Width ~ Sepal.Length + Sepal.Width, iris)


Simple Javascript Widget without cluttering global namespace?

You should throw Error objects rather than strings:

throw new Error("Invalid width or height specified for Little Black Book");

This provides a stack trace.


Find entry in hash depending on hash's data

When you want to find a particular matching value in a data structure, using Array.prototype.find is usually the right way to go. It's complicated by the fact that the condition involves the value of the object, but you want the key of the object to be found, so to iterate over the keys and values at once, use Object.entries. It'll give you an array of [key, value] subarrays, and you can return the first item in the resulting subarray to get the key, if anything is found:

const idProperty = 'id';
const schema = {
  id: { type: 'number' },
  code: { type: 'number', autoIncrement: true },
  email: { type: 'string', trim: 512 }
};

const autoIncrementSchemaFieldName = Object.entries(schema)
  .find(([, value]) => value.autoIncrement)
  ?.[0] // Extract the key from the found entry
  ?? idProperty; // Otherwise, if no entry was found, use idProperty

console.log('RESULT:', autoIncrementSchemaFieldName)

That's what I'd prefer, but there are a few compatibility caveats:

Object.entries was introduced in 2017. It's not new, but it's not old either
I'm using optional chaining and the nullish coalescing operator for conciseness, which is only supported in environments built in 2020 and later

As always, the usual professional solution to compatibility problems is to use Babel to transpile syntax down to ES5 or ES6, and use polyfills to add new built-in objects and methods.
Without ES2020, it'd look like:

const idProperty = 'id';
const schema = {
  id: { type: 'number' },
  code: { type: 'number', autoIncrement: true },
  email: { type: 'string', trim: 512 }
};

const entry = Object.entries(schema)
  .find(([, value]) => value.autoIncrement);
const autoIncrementSchemaFieldName = entry
  ? entry[0]
  : idProperty;

console.log('RESULT:', autoIncrementSchemaFieldName)


Don't force a class where a function is perfectly fine.
The namespace std is not designed for wholesale importation, see "Why is “using namespace std” considered bad practice?" for more detail.
Identifiers starting with an underscore followed by an uppercase letter are reserved.
Input is generally unreliable. But you don't test for error at all.
Always recomputing the current result from first principles, instead of just updating it with the newest addition, is a waste of time.
Flushing is expensive, so avoid std::endl and explicitly request it with std::flush where unavoidable.
You should probably follow the requested output-format...
You know that int in unsigned int is implicit?
In C++ and C99+, return 0; is implicit for main().
I wonder why you sometimes surround binary operators with space, and sometimes don't.
Having over-long lines is very cumbersome to read. Admittedly, you need not make a hard cut at 79 nowadays.
You should double-check whether duplicate inputs can occurr (there are none in the example), and if so whether they should cause anything but repeated output.
I assumed duplicated possible, and they only cause output.

Duplicates have an effect would destroy ranges instead of adding them, thus needing an ordered std::set.
Duplicates not possible would mean the std::unordered_set can be dispensed with.

#include <cstdlib>
#include <iostream>
#include <unordered_set>

int main() {
    unsigned n, m, x;
    std::cin >> n >> m;
    if (!std::cin || !n) {
        std::cerr << "Bad Input!\n";
        return EXIT_FAILURE;
    }
    std::unordered_set<unsigned> nums;
    auto r = 0ULL;
    while (--m) {
        std::cin >> x;
        if (!std::cin || x < 1 || x > n) {
            std::cerr << "Bad Input!\n";
            return EXIT_FAILURE;
        }
        auto [iter, created] = nums.insert(x);
        if (created)
            r += 2 * x;
        std::cout << r << '\n';
    }
}


I'm not sure if it will make your query faster but here is my take on it:

If I read the code correctly you want to create orders for all gift transactions related to gift ids which are not covered by an order yet.

usedGifts.SelectMany(g => g.GiftTransactions)
         .Select(gt => gt.GiftId)
         .Where(gi => !string.IsNullOrEmpty(gi))
         .Except(orderList.Select(o => o.GiftId)) // This will yield all gift ids which are not covered by an order
         .Select(gi => OrderHelper.PopulateSingleOrder(orderRepository, sessionRepository, gi))  // generate the orders
         .Where(o => o != null)
         .ToList();

Unfortunately this requires an extra pass over the usedGifts list to add all the references

giftReferenceList.AddRange(usedGifts.Select(g => g.GiftReference));


Return a new array where each element is the number of smaller elements to the right of that element in the original input

Performance

The posted implementations are quadratic.
A log-linear solution exists.
Here's a hint:

   What if you insert values from right to left into a sorted list?

Avoid mutations in functional implementations

Can you spot the mutation on this line?

const numberOfSmallerElem = lst => lst.map((x,i) => lst.slice(i + 1).reduce((acc,y) => y < x ? acc++ : acc, 0));

It's actually not easy to spot it when the line is so long!
I suggest to break it up, for readability.
And then eliminate the mutation.

   Replace acc++ with acc + 1


One major improvement would be to just use what is supplied through .NET:

Convert.ToString(int, 2);

where int is your supplied argument.

Convert.ToString Method (Int32, Int32)

  Converts the value of a 32-bit signed integer to its equivalent string representation in a specified base.

Note that this returns you a string value like 10000110100001, which is the representation of a binary number. In your code you store them as string representations and in separate entries in your collection, which is not the way a number should be stored. It's like creating an array with values "1" and "2" to represent the number 12.

If this is your intention then you can always work towards that of course but it might be an indication that something else is wrong for needing it like that.

However if you want to stay with your own implementation, there are a few things you could change around:

public List<string> Conversion2(int x)
{
   var bitConversion = new List<string>();
   while (x >= 0)
   {
       if (x == 0)
       {
           bitConversion.Add("0");
           break;
       }
       bitConversion.Add((x % 2).ToString(CultureInfo.InvariantCulture));
       x /=  2;
   }
  bitConversion.Reverse();
  return bitConversion;
}

Remove the unnecessary result variable
Contract x = x / 2 to x /= 2 (compound assignment operator)


Is there a PHP security exploit with $_POST in my code?

Since you validate that $_POST['surveyid'] contains at least one digit and contains only digits, your query is safe.

However, the CREATE TABLE operation that you are trying to do strikes me as a horrible thing to do.  CREATE TABLE is a Data Definition Language operation, and DDL commands should be executed only in special situations.

Basically, if you routinely create a new table to store responses from each survey, your database schema will be an unmaintainable mess.  I strongly recommend that you post your database schema and describe what you are trying to do in a question to http://dba.stackexchange.com to develop a sane schema that does not require new tables to be created routinely.


Please correct me if I am wrong, but isn't such scenario possible with accepted answer?

public T Swap()
{
    var swappedBuffer = Interlocked.Exchange(ref _current, Next); // 1
    Next = swappedBuffer; // 2
    return swappedBuffer; // 3
}

And it goes like that: (A and B denotes some object of type T):

_current = A
Next = B

Thread 1 executes Line 1:
swappedBuffer = A
_current = B
Next = B

Thread 2 executes Line 1:
swappedBuffer = B
_current = B
Next = B

Thread 1 executes Line 2:
Next = A

Thread 2 executes Line 2:
Next = B

Now both _current and Next are references to B.


Efficiently calculate value of Pascal's Triangle using memoization and recursion

Your code is clearly organized and well presented, but it suffers from a number of problems, from the trivial to the profound.

var i = 0 is never used and doesn't need to be there.
safety: There's no check for bad input. pascal(2,1) will happily java.lang.StackOverflowError.
Your code indicates a lack of familiarity with the Scala Standard Library. Initializing the cache, for example, can be accomplished with a single statement.

var cache: Map[(Int,Int), Int] =
  (0 to r).flatMap(n => Seq((0,n)->1, (n,n)->1)).toMap

Likewise, instead of an immutable Map in a var variable for the cache, if you use a mutable Map in a val variable then getPascalValue() can be reduced to a single statement.

def getPascalValue(c: Int, r: Int): Int =
  cache.getOrElseUpdate((c,r), getPascalValue(c, r-1) +
                               getPascalValue(c-1, r-1))

But the real problem here is that you're putting in a lot of overhead for no reward.

small problem: The cache is initialized with some values that may never be referenced.
big problem: The cache is updated with values that will never be referenced.

That's right. Nothing added to the cache, after initialization, serves any purpose. It's just inefficient busywork.
And the reason your cache isn't working: each iteration (recursion) starts with the original, initialized, cache. That version is updated, +=, with the newly computed pascal number, but that update is lost when the stack frame pops and execution returns to the caller.


Performance of mask (1,2,4,8,16) convertor in python

Code block 1

Please don't use variable names like object, i or y.
Standard indentation in Python is 4 spaces, not a mix between 2 and 4.
Mutating values out of a functions scope isn't best practice. This is because it leads to confusing code.
The following snippet is not needed. You can just use names[i].

y = "{0}".format(i + 1)
names[int(y)-1]

Rather than findbits I would make a function find_names. Which will return the names that can use the object.
Your bit mask, num & 1 << i, is good. But you can change it to use while num: to allow you to not waste any loops. Since the input you've provided us only goes to 1 << 4, there's not much point in looping all the way to 128. And so we can bitshift the other way.

def find_names(number, names):
    index = 0
    while number:
        if number & 1:
            yield names[index][1]
        number >>= 1
        index += 1

def main(map, ownership):
    output = []
    for obj, number in ownership:
        for name in find_names(int(number), map):
            output.append([name, obj])
    return output

if __name__ == '__main__':
    print(main(
        [['1','alex'],['2','ben'],['4','clark'],['8','dean'],['16','eric']],
        [['radio','3'],['telly','31']],
    ))

Both my solution and your solution are similar, however my solution bitshifts number downwards, where yours shifts i upwards. This means that you're constantly making 1 << i larger and comparing with number. This means on the first iteration 1 << i is \$1\$, in binary form, where on the third iteration it's \$100\$, in binary form.

Mine however works the opposite way checking the least significant bit, with number & 1. And so on the first iteration number would be something like \$10001001\$. Where on the third iteration it would be \$100010\$. This is as >> discards the least significant bit.

I find the following table to highlight the increase and decrease in size of the numbers to help. It's apparent that yours grows to match the bitlength of the original number, where mine shrinks until it reaches zero. The red highlights the bit that we're comparing with on each iteration.

$$
\begin{array}{l l r l}
\text{iteration} & \text{matching bit}   & \text{Yours - 1 << i} & \text{Mine - number} \\
0                & 1000100\color{red}{1} &        \color{red}{1} & 1000100\color{red}{1}\\
1                & 100010\color{red}{0}1 &       \color{red}{1}0 & 100010\color{red}{0} \\
2                & 10001\color{red}{0}01 &      \color{red}{1}00 & 10001\color{red}{0}  \\
3                & 1000\color{red}{1}001 &     \color{red}{1}000 & 1000\color{red}{1}   \\
4                & 100\color{red}{0}1001 &    \color{red}{1}0000 & 100\color{red}{0}    \\
5                & 10\color{red}{0}01001 &   \color{red}{1}00000 & 10\color{red}{0}     \\
6                & 1\color{red}{0}001001 &  \color{red}{1}000000 & 1\color{red}{0}      \\
7                & \color{red}{1}0001001 & \color{red}{1}0000000 & \color{red}{1}       \\
\end{array}
$$

Code block 2

We can transfer a lot of the changes from the above code block to the second.
I would split the objects comprehension over multiple lines, as I find it helps with readability.
The variable m is never used and so you can use the name _ to denote that it is never used.
I would move the mask iterator into get_ownerships and just generate one in the for. This allows you to generate both the name and the mask with ease.

import random
import string

def generate_ownerships(amount, limit):
    for _ in range(amount):
        object_name = ''.join(
            random.choice(string.ascii_letters)
            for _ in range(4)
        )
        mask = random.randrange(1, limit)
        yield [object_name, mask]

def find_names(number, names):
    index = 0
    while number:
        if number & 1:
            yield names[index][1]
        number >>= 1
        index += 1

def main(map, ownership):
    output = []
    for obj, number in ownership:
        for name in find_names(int(number), map):
            output.append([name, obj])
    return output

if __name__ == '__main__':
    main(
        [['1','al'],['2','be'],['4','cl'],['8','de'],['16','er'],['32','fa'],['64','ga'],['128','ha'],['256','ia'],['512','ja'],['1024','ka'],['2048','la'],['4096','ma'],['8192','na'],['16384','oa']],
        generate_ownerships(1000, 32767),
    )

Further comments

The first value in names is never used. As only names[index][1] is used. This means you can change your input so that you only specify the names.

If you would still like to specify the value in any order, [['2', 'be'], ['1', 'al']], then you can normalize the names. This requires ordering the names by the first value.
Since this is tagged performance you may be able to get a performance increase if you use an LRU cache from functools. This will store the \$n\$ most recently used values to a function so you don't need to regenerate the output.

This would require a small change to find_names to return an iterable rather than an iterator, and to only take hashables. For best performance it would only take number.

It should be noted that this may not lead to a performance gain. The amount of performance gain you get may also change depending on the size of \$n\$ and so you should test the performance on your data with different values.

If you have both space and time constraints then you can utilize the generalized birthday problem to find a rough number to limit the cache to. As it's 50% chance for hits at a fraction the size of the maximum input is a good way to save on both. If this is needed then I will leave it to you to implement.

import functools

def normalize_names(names):
    return [name for _, name in sorted(names, key=lambda i: int(i[0]))]

@functools.lru_cache(maxsize=None)
def find_names(number):
    output = ()
    index = 0
    while number:
        if number & 1:
            output += (index,)
        number >>= 1
        index += 1
    return output

def main(map, ownership):
    output = []
    for obj, number in ownership:
        for index in find_names(int(number)):
            output.append([map[index], obj])
    return output

if __name__ == '__main__':
    print(main(
        normalize_names(
            [['2','ben'],['1','alex'],['4','clark'],['8','dean'],['16','eric']],
        ),
        [['radio','3'],['telly','31']],
    ))


Accessing the only element of Java ResultSet

Here is a bit reworked version of you code. Some explanation:

Assume _TABLE_NAME is a constant, so there is no need to build query in every method call.
Force getting connection and close resources to avoid side effects.
Propagate SQLException to caller (caller should decide what to do with thrown exception).

Code:

private final static String GET_DATA_BY_ID = "select * from " + _TABLE_NAME + " where id = ?";

public Map<String, String> getById(long id) throws SQLException {

    Connection conn = null;
    Map<String, String> result = new HashMap<String, String>();

    try {
        conn = getConnection();

        PreparedStatement preparedStatement = null;

        ResultSet rs = null;
        try {
            preparedStatement = conn.prepareStatement(GET_DATA_BY_ID);
            preparedStatement.setLong(1, id);
            try {
                rs = preparedStatement.executeQuery();

                if (rs.next()) {
                    ResultSetMetaData rsmd = rs.getMetaData();
                    int fieldsCount = rsmd.getColumnCount();

                    for (int i = 1; i < fieldsCount + 1; i++) {
                        String cName = rsmd.getColumnName(i);
                        result.put(cName, rs.getString(cName));
                    }
                }
            } finally {
                if (rs != null)
                    rs.close();
            }
        } finally {
            if (preparedStatement != null)
                preparedStatement.close();
        }
    } finally {
        if (conn != null)
            conn.close();
    }
    return result;
}


Adding SecureString support to Lib2GitSharp

I don't see a problem with how the SecureString objects are handled - seems pretty solid to me, but I've never used those so I'm possibly missing something that someone else could point out here.

Sealed Class
I haven't looked at the actual project's source code, but general design guidelines have this to say about sealing classes:

DO NOT seal classes without having a good reason to do so.

However it also defines a number of "good reasons" for sealing a class, including:

The class stores security-sensitive secrets in inherited protected members.

In other words, a sealed class seems warranted here.

InvalidOperationException
Out of all possible existing exception classes in the framework, and instead of creating your own derived exception class, you chose to throw an InvalidOperationException in the implementation of the GitCredentialHandler override.
MSDN describes this exception as follows:

The exception that is thrown when a method call is invalid for the object's current state.

Turns out this was, in my own humble opinion, the best decision to make: throwing any other exception type here would violate POLS - when client code is calling this method and the object's state shouldn't allow it, the programmer has all rights to expect an InvalidOperationException to be thrown.

XML Documentation
This is an API - having complete and accurate XML documentation is ideal.

    /// <summary>
    /// Callback to acquire a credential object.
    /// </summary>
    /// <param name="cred">The newly created credential object.</param>
    /// <returns>0 for success, &lt; 0 to indicate an error, &gt; 0 to indicate no credential was acquired.</returns>

I think this documentation could be better, but looking at the base class on GitHub I see that you've copied most of it from the base class, which is a good idea.
However the method can throw an InvalidOperationException - you could add something like this:
/// <exception cref="InvalidOperationException">
/// Thrown if this method is called when either <see cref="UserName"/> or <see cref="Password"/> is <c>null</c>.
/// </exception>

Style
You know me, I think this is too verbose:

IntPtr passwordPtr = IntPtr.Zero;
IntPtr userNamePtr = IntPtr.Zero;

Compared to:
var passwordPtr = IntPtr.Zero;
var userNamePtr = IntPtr.Zero;

Which is just as clear IMO. Not much gain here though. And given that the rest of the code seems to prefer the verbose way, sticking to the existing style is the best decision you could make.
And not only for usage of var:

I would use a constructor, but it's the style of the project to use an object initializer.
It's also in the style of the project to place the properties at the bottom like you'll see below.

UserName vs. Password
A user name can be sensitive information in certain circumstances - and although I don't think this is one, there's a saying that summarizes everything I'd have to say about whether or not having the user name as a SecureString is overkill:

Better safe than sorry.
-- unknown

However, the ironic part is this:
return NativeMethods.git_cred_userpass_plaintext_new(...);

Given that credentials end up being passed as plain text, I think I'd keep the user name as a plain string.


I have found a way to use a runtime struct instead of a closure. Logger needs to borrow the runtime, and it must implement Drop so that Runtime::drop is not called before Logger::drop.

mod logger {

    use std::marker::PhantomData;
    use std::sync::mpsc::{channel, Sender};
    use std::thread::JoinHandle;
    use time::now;

    pub type LogError = std::sync::mpsc::SendError<String>;

    pub struct Runtime {
        sender: Option<Sender<String>>,
        thread_handle: Option<JoinHandle<()>>,
    }

    impl Runtime {
        pub fn new() -> Self {
            let (sender, receiver) = channel();
            let thread_handle = std::thread::spawn(move || {
                while let Ok(msg) = receiver.recv() {
                    println!("{}", msg);
                }
                println!("LOG FINISHED");
            });

            Runtime {
                sender: Some(sender),
                thread_handle: Some(thread_handle),
            }
        }

        pub fn logger(&self) -> Logger {
            Logger {
                sender: self.sender.clone().unwrap(),
                _marker: PhantomData,
            }
        }
    }

    impl Drop for Runtime {
        fn drop(&mut self) {
            // Removes the last sender alive, so that the thread quits.
            let _ = self.sender.take();

            if let Some(handle) = self.thread_handle.take() {
                if let Err(e) = handle.join() {
                    eprintln!("Error while exiting the logger manager: {:?}", e);
                }
            }
        }
    }

    /// The actual logger.
    #[derive(Clone)]
    pub struct Logger<'a> {
        sender: Sender<String>,
        _marker: PhantomData<&'a ()>,
    }

    impl Logger<'_> {
        /// Logs an information.
        pub fn info(&self, s: impl std::fmt::Display) -> Result<(), LogError> {
            let s = format!("[{}] [INFO ] {}", now().rfc3339(), s);

            self.sender.send(s)
        }

        /// Logs an error.
        pub fn error(&self, s: impl std::fmt::Display) -> Result<(), LogError> {
            let s = format!("[{}] [ERROR] {}", now().rfc3339(), s);

            self.sender.send(s)
        }
    }

    impl Drop for Logger<'_> {
        fn drop(&mut self) {
            // The non-trivial drop prevents the logger to outlives the manager.
        }
    }
}

// Demontration:
fn main() -> Result<(), logger::LogError> {
    let log_manager = logger::Runtime::new();
    let logger = log_manager.logger();

    logger.info("Hello world")?;
    // Cloning without overhead:
    logger.clone().error("Oops, error")?;

    Ok(())
}

If one try to make a logger outlive the runtime, it will not compile:

fn main() -> Result<(), logger::LogError> {
    let log_manager = logger::Runtime::new();
    let logger = log_manager.logger();

    logger.clone().info("Hello world")
}

Gives:

error[E0597]: `log_manager` does not live long enough
  --> src/main.rs:85:18
   |
85 |     let logger = log_manager.logger();
   |                  ^^^^^^^^^^^ borrowed value does not live long enough
86 |
87 |     logger.clone().info("Hello world")
   |     -------------- a temporary with access to the borrow is created here ...
88 | }
   | -
   | |
   | `log_manager` dropped here while still borrowed
   | ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `logger::Logger`
   |
   = note: The temporary is part of an expression at the end of a block. Consider forcing this temporary to be dropped sooner, before the block's local variables are dropped. For example, you could save the expression's value in a new local variable `x` and then make `x` be the expression at the end of the block.


Generate regular expression based on inputted number

One thing I would do is that str_replace can receive an array of items to look for and an array of its replacement:

PHP str_replace

// Provides: You should eat pizza, beer, and ice cream every day
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

instead of going line by line to do it.

Just nit-picking but

sizeof() is an alias of count() and count() is more widely used, so use something that is more general in the PHP community

Also $_POST != null would typically be !isset($_POST) rather as explained in this post


Sorting an int[] array using insertion sort algorithm - follow-up

Nice job.  It looks like you have implemented a correct insertion sort.

The inner loop could be better written: the j > 0 condition is giving an incomplete picture of how the loop terminates.

One other change you should make is to take a size parameter for the array size.  Without it, you have a function that only works on arrays of a specific size!  If you look at examples of functions in the C library, almost every function that takes an array also takes another parameter to specify its size.  Usually, the type of that parameter is an unsigned int, but called size_t to make its purpose clear.

#include <stdlib.h>

void insertionSort(int arr[], size_t size)
{
    for (int i = 1; i < size; i++)
    {
        int value = arr[i];
        int j;
        /* Shift elements over by one slot to make way for the insertion */
        for (j = i; j > 0 && value < arr[j - 1]; j--)
        {
            arr[j] = arr[j - 1];
        }
        arr[j] = value;
    }
}

Your implementation is better than the book you're learning from.  In fact, I would recommend using a different book, if the code examples are so poor.  Specifically, the biggest problem is the done flag.  Setting a flag to be inspected by a conditional elsewhere is a cumbersome way to implement flow control.  Your break is much more direct and assertive, and I think that my loop condition is even clearer.


JavaScript change image every three seconds

The script tag default type is text/javascript and thus is not needed.
Keep your script out of the global scope. This can become a problem when more JS is added to the page and you get name conflicts. The easiest way to encapsulate your code is to wrap it in a function. In this case it would be best to wait for the page to load before starting image cycle. You can use either DOMContentLoaded or load events but if you use the first be sure that the CSS has loaded.
Drop the comments they add nothing that is not self evident in the code itself, and are but noise. If you find that the code does not contain the information needed to understand it, first can you rename to make it clear, if not then comments are the last resort.
Define a CSS class for hidden images rather than setting the style properties directly. (see example)
Use the CSS class to define style properties. Do not set style properties in the HTML document. Its just easier to manage.
Use querySelectorAll it is more flexible in the long run.
Use for of loop rather than for(;;) loops as it cleaner and requires less code.
You don't need to query for the images every 3 seconds. Do it once at the start.
Use const for variables that do not change.
The variable name x is a bad name. slideImages of slides would be more fitting. Note that I use the plural signifying that it is array, or array like.
Start with the images hidden, then ever 3 seconds all you need to do is hide one and show one.
Use the remainder operator % to cycle a value (see example)

Example


Program to find unique chars in a String (and also to find number of occurences of chars in a String)

There are a couple of improvements that can be made, mostly readability improvements as I believe your solution is quite efficient.

Format your code with proper indentation and spacing

Indentation is important for readability, so is spacing; don't be afraid to throw in plenty of whitespace if it makes things easier to read. Notice how I indented on every bracket level and put in white space in between some lines and put spaces in for loops etc.

public static String uniqueValues(String str) {
    char[] arr = str.toCharArray();
    int[] result = NumberOfOccurences.numberOfOccurencesOfLetters(arr);
    StringBuilder sb = new StringBuilder();

    for(int i = 0; i < result.length; i++) {
        if(result[i]==1) {
            sb.append((char)(i+97));
            sb.append(" ");
        }
    }

    return sb.toString();
}

//in the other class i wrote this method
public static int[] numberOfOccurencesOfLetters(char[] arr) {
    int[] result = new int[26];
    int num;

    for(int i = 0; i < arr.length; i++) {
        num = (arr[i]-97);
        result[num]++;
    }

    return result;
}

Pass in a string to numberOfOccurencesOfLetters instead of a char[].

Assuming you'll be using this method mostly of strings, you should pass in a string and do the conversion inside numberOfOccurencesOfLetters rather than before calling it every time.

public static int[] numberOfOccurencesOfLetters(String str) {
        char[] arr = str.toCharArray();
        int[] result = new int[26];
        int num;

        for(int i = 0; i < arr.length; i++) {
            num = (arr[i]-97);
            result[num]++;
        }

        return result;
    }

Declare variables closest to where they're used and limit their scope as much as possible.

For example int num; can exist only within the for loop instead of the whole function scope as we only use it inside the for loop.

        for(int i = 0; i < arr.length; i++) {
            int num = (arr[i]-97);
            result[num]++;
        }

Return a HashMap instead of int[] for numberOfOccurencesOfLetters.

Google what is a map in Java. This sacrifices some speed, but you'll get much more readable code with a return type that's easier to manipulate. Also, you won't be limited to the 26 characters that you have now and you'll be able to have upper-case letters and special characters as well.

This is how your whole code would look like with this implementation. If it doesn't compile I'll fix it when I get home.

import java.util.HashMap;

public static String uniqueValues(String str) {
    HashMap<Character, Integer> result = NumberOfOccurences.numberOfOccurencesOfLetters(str);
    StringBuilder sb = new StringBuilder();

    for (Character key : result.keySet()) {
        sb.append(key);
        sb.append(" ");
    }

    return sb.toString();
}

public static Map<Character, Integer> numberOfOccurencesOfLetters(String str) {
        HashMap<Character, Integer> hmap = new HashMap<Character, Integer>();
        char[] arr = str.toCharArray();

        for(int i = 0; i < arr.length; i++) {
            Character key = arr[i];
            hmap.put(key, hmap.getOrDefault(key, 0) + 1);
        }

        return hmap;
 }


Reacting to Boolean state in reactive ViewModels

You need to format your code neatly; this will improve readability, which will decrease bugs.  First, you have this:

public bool IsAuthenticated {
get { return _isAuthenticated; }
set { this.RaiseAndSetIfChanged (ref _isAuthenticated, value); }}

This should be:

public bool IsAuthenticated
{
    get { return _isAuthenticated; }
    set { this.RaiseAndSetIfChanged (ref _isAuthenticated, value); }
}

The if/else statement should be written like this:

IsAuthenticatedCommand.Subscribe (_ => {
    if (_) { this.IsAuthenticated = true; }
    else { this.NeedsToLogin = true; }
});

Also, you need to be consistent with your spacing; sometimes you have a space between braces, sometimes you don't:

if (_) { this.IsAuthenticated = true;} else {this.NeedsToLogin = true;}

I am no expert at lambda statements, but your lambda with the if/else looks fine to me.


Ruby - class definition for connecting to external API

CONFIG = YAML.load_file(File.join(Rails.root, 'config', 'mark.yml'))

This does not belong inside the class, it makes it impossible for others to change the configuration depending on environment (dev, test, prod). You can either pass in a map of options to the constructor or say in Rails use an initializer class to read in the appropriate configuration and apply it.

raise ArgumentError, "No args can be nil." if league.nil? || start_date.nil? || end_date.nil?

It's good to validate your arguments, however this message doesn't help the developer/user of the class because it doesn't indicate which argument was nil. As tedious as it is I would validate each arg separately and indicate which argument was nil in the message.

Regarding the use of @url and @url_params sgmorrison is correct and you should not be using class instance variables especially in a static class. If their values were immutable then fine but that is not the case. A simple change would be to pass both url and urlparams as options/args to call_http_service and so forth.

Another option would be to separate the two concerns of this class into individual classes. One that is a service class and one that is a connection class. Then you can encapsulate all connection logic into one (likely none static) class, and the user can interface with the service class. Should you choose this method you could then use a factory and/or mock out the connection to make unit testing easier.


You cannot get rid of those if-else checks, but you can get rid of the nesting. For example:

if foo:
    if bar:
        return foo + bar

could be flattened to

if not foo:
    return None
if not bar:
    return None
return foo + bar

While this is is in fact longer, such code tends to be easier to read.

If we apply that to your code (and fix some style issues like putting a space after each comma), then we end up with:

def grab_properties(url, html):
    soup = BeautifulSoup(html)

    link = soup.find('iframe', {"src": "e.smth.com"})
    if link is None:
        return None
    link = link.get("src")

    id = re.match(".*\[(\w+)\].*", link).group(1)
    if (id is None) or (id in ids):
        return None

    name = soup.find('span', {"class": "project_name"})
    if name is None:
        return None
    name = re.sub(r'[«,»]', '', name.text)

    image_element = soup.find('img', {"id": "item0image"})
    if image_element is None:
        return None
    img_url = image_element.get('src')

    price = soup.find('span', {"class": "project_price"})
    if price is None:
        price = u"Call us!"
    else
        price = re.sub(u'[руб,\., ]', '', price.text)

    return [attr.encode('utf8') for atr in (id, name, url, img_url, price)]

Notice that I created the image_element variable to avoid searching for the same element multiple times, that I used a list comprehension to encode various strings to UTF-8, and that I used empty lines to separate the code for unrelated attributes, thus making the code easier to understand. I also swapped the if price is not None condition around to avoid a confusing negation.

We should now talk about regular expressions (see also the re library documentation). The […] is a character class. It matches any of the contained characters, so [abc] will match either a or b or c, but not the whole string abc. The comma is not special inside a character class, so [«,»] will match left or right guillemets, or a comma. To match just the angled quotation marks, use [«»]. Similarly, [руб,\., ] will match either р or у or б or a comma or a period or a space. Note that inside a character class, the period is not a metacharacter and does not have to be escaped. So that charclass would be equivalent to [р,у б.] (the order of characters does not matter). If you want to match alternative patterns, use the | regex operator: руб|[. ], which matches either the substring руб or a period or a space.

You could also consider precompiling your regular expressions, which might improve performance if you call your function very often:

RE_GUILLEMETS = re.compile('[«»]')

def ...:
    ...
    name = RE_GUILLEMETS.sub('', name.text)


The using of a public field should be avoided and instead you should use a method to get the value.

If you take into account that the class will be extended (like written in the problem statement), I would suggest that you add a getRandomQuote() method to the Quote class.

Also you should make your String array QUOTES private. I don't know what the conventions for the array braces [] are , but I would write it private static final String[] QUOTES

A Random should be created once and then used as often one needs.So I would suggest to create it at the constructor.

private Random random;
public Quotes(){
    random = new Random();
}

public String getRandomQuote(){
// return your random quote here

}

You should always name your variables and methods in a meaningful easily readable way. So I have renamed rand to random.


Efficiency of binary search and improvements

While loop termination

The while loop condition is:

while(!found) {

But when you find your answer, you already do a break.  Therefore, the while loop condition could just be:

while (1) {

But there's more.  This statement here is not quite right:

if( (min==max) && (anArray[max]!=userNumber) )
    break;

First of all, it is possible that min could actually go beyond max.  For example, if originally min is 6, max is 7, and avg is 6, then it could be the case that max becomes 5 afterwards.  So you really need to check if min > max and break when that happens.

Secondly, if min == max, there's no need to do an extra equality check and break.  You can just loop around one more time.

Putting that all together, I would actually remove that whole if statement and change your while loop to:

while (min <= max) {
    avg = (min+max) / 2;
    if (anArray[avg] == userNumber) {
        found = true;
        break;
    }
    if (anArray[avg] < userNumber)
        min = avg+1;
    else
        max = avg-1;
}

Unnecessary if

Notice I also removed the check for anArray[avg] > userNumber because at that point, it wasn't equal or less than, so it had to be greater than.


Testability
Whilst not a prerequisite for a review, @Marc is correct that unit tests would be helpful here and you would usually want to include them in your exercise submission.  You want to demonstrate both that you know the code works as importantly that you've considered how easy it is to test.  Time in particular can be challenging to unit test if classes have not been constructed with it as a consideration.  You may wish to take a look at this Stack overflow question for some suggestions about how you could improve your time testability.
Naming
One of the things that struck me as a little odd was that your blocking methods are called acquire and your non-blocking method is called tryConsume.  I'm not sure I understand the disconnect, is there a reason it couldn't be called tryAcquire?  Have you been asked to provide both blocking and non-blocking versions of the limiter as part of the exercise?
final
Fields that don't change after they've been initialized (such as refillRate) should be marked as final to indicate that you're not planning on changing them.
Starvation and Flooding
Lets take your example of 5 requests every 2 seconds.  If I call acquire(500), nothing happens for 200 seconds, then 500 messages get sent (probably within a single second).  Is this the expected behaviour?  During the wait time while the number of required allocations are being waited on, no other threads are able to acquire and send either.  It's possible that this is expected/desired behaviour, however it seems like a potential flaw, particularly since a greedy blocking call could mean that the non-blocking request is never successful, so something I'd expect them to ask about if you get to interview.  Things to consider are do you need to allow a single call to reserve X permits, or would it be better to have them acquire single permits at a time as they send each message?  If you need to support multiple permits, should there be a limit on the maximum number of permits that can be requested in one go (such as the size of the window or maxCapacity).