Get a nested property of a complex object at any level of depth

You can take advantage of the JSON.stringify's replacer argument.
This way it becomes much more simple:

var app =
  findProperty: function(data, name) {
    var result = {
      isFound: false,
      value: null
    };
    JSON.stringify(data, function(k, v) {
      if (k == name) {
        result.isFound = true;
        result.value = v;
        return undefined; // stop stringification
      } else {
        return v; // continue with same value
      }
    });
    return result;
  }
}

Compared to your original function, there are two points to consider:

one little caveat is that a Date object is returned stringified, e.g. for a15 in your dataexample:

has an original value of new Date.
is returned as Date {Thu Jan 14 2016 18:34:10 GMT+0100} by your function.
is returned as 2016-01-14T17:34:10.220Z by the mine.

your function excludes Array objects, while the mine processes them, e.g. calling app.findProperty(data, '0') will return red (from a6: ['red', 'blue', true] in your dataexample).

My version seems to be faster (approximatively x2) using your data example, but it's not certain how it'll be in any case.

The snippet below tries to illustrate it, simultaneously controlling the results between the two versions:

var data = {
  a: {
    a1: 'hello',
    a2: true,
    a3: false,
    a4: {},
    a5: [],
    a6: ['red', 'blue', true],
    a61: {a61a: 'red', a61b: 'blue'},
    a7: null,
    a8: undefined,
    a9: NaN,
    a10: function() {},
    a11: Math,
    a12: JSON,
    a13: /a-z/,
    a14: new ReferenceError,
    a15: new Date,
    a16: new Number(7),
    a17: new String("abc"),
    a18: new Boolean(true)
  },
  b: {
    b1: {
      b1a: true,
      b1b: 100
    },
    b2: {
      b2a: true,
      b2b: false,
      b2c: 10.10
    }
  }
}

var app = {
  findProperty: function(data, name) {
    var toType = function(obj) {
      return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
    };
    var data = data,
      process = true,
      result = {
        isFound: false,
        value: null
      };
    var recursion = function(data, name) {
      var type = toType(data);
      if (type === 'object') {
        Object.keys(data).forEach(function(property) {
          if (process) {
            if (name in data) {
              process = false;
              result.isFound = true;
              result.value = data[name];
            } else if (typeof data[property] === 'object') {
              recursion(data[property], name);
            }
          }
        });
      }
    };
    recursion(data, name);
    return result;
  },

  findProp: function(data, name) {
    var result = {
      isFound: false,
      value: null
    };
    JSON.stringify(data, function(k, v) {
      if (k == name) {
        result.isFound = true;
        result.value = v;
        return undefined; // stop stringification
      } else {
        return v; // continue with same value
      }
    });
    return result;
  }
}

var names = [
  'a', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a61', 'a61a', 'a7', 'a8', 'a9',
  'a10', 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a17', 'a18',
  'b', 'b1', 'b2', 'b1a', 'b1b', 'b2a', 'b2b', 'b2c', 'xxx', 'yyy'
];
var results = {};

function exec(func) {
  results[func] = [];
  begTime = Date.now();
  for (var i = 0, n = names.length; i < n; i++) {
    var name = names[i],
        result = app[func](data, name);
    results[func][i] = result.value;
    console.log(name, result.isFound, result.value);
  }
  console.log(
    '--- using ', func + ':', (Date.now() - begTime) + 'ms');
}

console.clear();
exec('findProperty');
exec('findProp');
for (var i = 0, n = results.findProperty.length; i < n; i++) {
  if (results.findProperty[i] !== results.findProp[i]) {
    console.log(
      '*** Error in ' + i + ':',
      results.findProperty[i], '<-->', results.findProp[i]
    );
  }
}

Apart from the already mentioned Date difference, you'll see an "error" on the NaN value: this is normal since NaN is equal to nothing, even itself.


Ensure instance of class is initialized before using

A couple of quick points.

If you are setting up a class, don't encapsulate a Type inside of it - you are only repeating what a class does! I am not sure where this anti-pattern comes from.

Within VBA do not raise errors unless absolutely necessary. Error raising and trapping will lead to unintended consequences and you can never be confident that they will be handled properly. Always handle the error explicitly. For starters, they can disrupt global variables.

You can create a Function in a module (let's call it NewFoo) with the correct signature - which creates the Foo instance and runs the Init method. This will make it a bit easier in the rest of your code to ensure you have the right sequence.

In Excel, you could make use of the xlError values to return an error if not initialised. This means that all your properties would be Variants (which has its own issues), something along the line of:

Public Property Get Prop1() As Variant
    Prop1 = IIF(m_initialised, CBool(Prop1_var), CVErr(xlErrNA))
End Property

Also, explicitly set m_initialised in the Class_Initialize routine to False. In theory not needed, but I prefer to be explicit.


Wait loops
I don't think that this:
    try:
        while True:
            time.sleep(SLEEP_TIME)
    except:
        self.observer.stop()
        print("Observer Stopped")

should be necessary. I would expect that if you simply join, it would do what you want - block until the observer is done.
Even if you retained the above structure, you're not using your try correctly. That except should be a finally. In other words, you don't want to stop when something goes wrong; you want to stop whether something goes wrong or not.
Pathlib
on_any_event contains a lot of os.path calls. You'll find that replacing these with pathlib.Path equivalents is better-structured. It's a more object-oriented and "syntactically sugary" way of manipulating paths.
Overall
I'm not convinced that writing these generic watchdog wrappers (Handler, OnMyWatch) is useful. It's subtracting from the utility of watchdog. What if you want code of your own to run once Handler.on_any_event changes some of its attributes? You could subclass Handler and override on_any_event, calling super().on_any_event to set those attributes, but that's a fairly poor data-passing pattern.
You'd be better off writing a purpose-built FileSystemEventHandler that does not have those file-component attributes, does not look at event.event_type, and handles specifically the event you care about.
In other words, this is abstraction that hurts rather than helps you, and introduces functions with side-effects that set attributes that don't make sense as attributes.


Consistent whitespace

    cout << "\nthe median of the merged array is : " << findMedian(a, b,  m,  n)<< '\n';

isn't even consistent within the same line about whether << should have spaces on both sides or not. I'm surprised your editor didn't auto-format it.

There is also a wide variety of whitespace in the strings which are used to prompt for input.

Also in this category,

                return min(max_of_left,min_of_right);

appears to be indented too far. Well, either that or there are some missing {} to include it with the previous statement in a single block.

Memory management

void main()
{
    ...
    a = new int[m];
    ...
    b = new int[n];
    ...
    free(b);
    free(a);
}

Are you sure? This looks fishy to me. There's no call to malloc or friends, so why is there a call to free?.

Warning

Let's simplify the code a bit...

int findMedian(int a[], int b[], int m, int n)
{
    int imin = 0, imax = m, half_len = (m + n + 1) / 2;
    int i, j, max_of_left, min_of_right;

    while (imin <= imax)
    {
        ...
    }
}

Now can you see why "not all control paths return a value"?

Hint: what's the loop invariant?

Performance claims

The title of this question is "Find median of two sorted arrays, with complexity of min(log(m),log(n))". That's impossible: if I guarantee that the second array is of length at most 1, you're promising to find the median of the other array with complexity bounded above by 0.

I think you can claim \$\log(m+n)\$, but some comments to justify correctness and performance would be nice.


How to write this method with similar checks and multiple returns more elegantly?

I think it's a personal thing, but I prefer == null checks with early exits, because that way you have all exception paths at the beginning and the normal execution path is less indented.
For your string concatenation you could make a ternary if and have one return statement less.

private String get(Details details, Value value){
    Type type = Type.getEvent(details.getType());
    if(type == null) {
      return StringUtils.contains(details.getSpin(), SPIN) ? BACKUP : DEFAULT_VAL;
    }

    if("SAMPLE".equals(type.typeDesc())) {
        String prefix = SPIN.equals(details.getSpin()) ? BACKUP : DEFAULT_VAL;
        return prefix + SAMPLE + value.getId();
    }
    return value.getRoute();
}

Now looking at this, you check the spin for equals and contains. Is this intentional? If not you could further reduce the code by pulling the prefix part up like this:

private String get(Details details, Value value){
    String prefix = SPIN.equals(details.getSpin()) ? BACKUP : DEFAULT_VAL;

    Type type = Type.getEvent(details.getType());
    if(type == null) {
      return prefix;
    }

    if("SAMPLE".equals(type.typeDesc())) {

        return prefix + SAMPLE + value.getId();
    }
    return value.getRoute();
}

In general you should use StringBuilder for string concatenation.


Handling potentially missing props of an object

It depends on what you want to make better. Personally, I find the code readable as you have it, however, depending on how many url options might still come, I guess you can make it yourself a bit easier.

A first start I would do, would be to split the query from the url itself, maybe you will not always add a query, so, I would change the utils class to:

let utils = {
    url: 'https://stackoverflow.com/jobs/feed',
    query: 'q=',
    location: "&l=",
    unit: "&u=",
    techLiked: "&tl=",
    techDisliked: "&td="
};

Furthermore, I also camelCased the properties of the utils object, I don't see no reason why they should be PascalCased. But I guess that could depend on some code guidelines you are following.

The same thing goes for the UrlBuilder. I would expect that PascalCased functions are classes, but since you return a string at the end of the function, it would not be the case. So you should also use camelCasing for simple functions. Together with that change, you could also introduce default values for your props parameter, so you wouldn't have to do checks for undefined/null values, like so:

/**
 * @method urlBuilder
 * @param {{query: string=, location: string=, td: string=, tl: string=, unit: string=}} props
 * @returns Full url needed to query rss feed
 */
function urlBuilder(props = {}) { ... }

If you expect a certain type of input parameters, it never hurts to document what does might be. It would help you further in the future when maintaining this code.

Now, the biggest difference I could imagine making is inside the urlBuilder function. One major change you could make is to choose for a more obvious name, urlBuilder itself sounds a bit like a wizard function to which you could add more options in a fluent language style. Maybe you could change it to getSpecificUrlFor(props = {}) which would indicate that you would receive a url based on the properties itself.

Now, inside the function, I added a small map that maps the expected properties of your argument to the properties in your utils object.

const map = {
  query: 'query',
  location: 'location',
  unit: 'unit',
  tl: 'techLiked',
  td: 'techDisliked'
};

The property of the map will indicate the expected property for your props object, and the value would link to the property on your utils object.

The biggest advantage you have here is that you can expand or reduce the parameters like you want to, if you would implement the check in the following way:

let result = [];
// iterate the full props object by it's key
for (const key of Object.keys( props )) {
  if (!map[key]) {
    // no matching prop found
    continue;
  }
  // found a key, so add it
  result.push(utils[map[key]]);
  result.push(props[key]);
}

Only if a property is defined on the map, it will add the utils value to your result set, together with the value of the props.

As the query is no longer part of the UrlPrefix property, you could now either return the url with potentially found parameters, or just return the default url, like so:

if (!result.length) {
  // no matching props
  return utils.url;
}
// return the url
return utils.url + '?' + result.join('');

There is no overly pragmatic reason for choosing the array.Join method, but rather a habit from using StringBuilder in other languages, so concatenating your strings as in your example is perfectly fine as well.

In the end, the full change looks like this, I added some example outputs as well so you could validate if it is now working as you expect it to work.

let utils = {
    url: 'https://stackoverflow.com/jobs/feed',
    query: 'q=',
    location: "&l=",
    unit: "&u=",
    techLiked: "&tl=",
    techDisliked: "&td="
};

/**
 * @method getSpecificUrlFor
 * @param {{query: string=, location: string=, td: string=, tl: string=, unit: string=}} props
 * @returns Full url needed to query rss feed
 */
function getSpecificUrlFor(props = {}) {
  const map = {
    query: 'query',
    location: 'location',
    unit: 'unit',
    tl: 'techLiked',
    td: 'techDisliked'
  };
  let result = [];
  // iterate the full props object by it's key
  for (const key of Object.keys( props )) {
    if (!map[key]) {
      // no matching prop found
      continue;
    }
    // found a key, so add it
    result.push(utils[map[key]]);
    result.push(props[key]);
  }
  if (!result.length) {
    // no matching props
    return utils.url;
  }
  // return the url
  return utils.url + '?' + result.join('');
}

// some valid inputs
console.log( getSpecificUrlFor({query: 'javascript'}) );
console.log( getSpecificUrlFor({query: 'javascript', tl: 'react'}) );
console.log( getSpecificUrlFor() ); // props would be at least an empty object, so expect the urlPrefix

// overwriting props that are not in the map doesn't work
console.log( getSpecificUrlFor({query: 'javascript', url: 'http://www.google.com'}) );

// invalid input -> gets ignored
console.log( getSpecificUrlFor(5) );
console.log( getSpecificUrlFor('a') );

One more thing you could still add, is to make sure that your parameters are properly encoded, you could do this with encodeURIComponent or something similar for nodejs


Here's a shorter function that does the same thing. It doesn't create lists for the columns you're not interested in.

def _get_values_from_csv(self, column_title, response_body):
    dicts = csv.DictReader(response_body.split("\r\n"))
    return sorted(set(d[column_title] for d in dicts))


Asking and checking if the answer is correct

Congrats on getting something like this working! I obviously don't know anything about the background of the project, so keep in mind that while my feedback may be valuable, if it's just a small side project you might not want to overengineer it.
Regardless, here are some points for you to regard:

External scripts: While embedding scripts into the document directly is a slight performance gain, using an external script gives you the luxury of

Mixed languages: While mostly an oddity while reading, it's generally a bad user experience to have two languages mixed together. For concistency in terms of UX, I'd advise that you stick to either one.

Reducing duplicated code: When writing code, it's always nice that if you have to change something, you only have to change it in one place, instead of multiple. This makes your code less error prone to spontaneous changes made by you. Considering this, we could refactor the following:

let input = document.querySelector('input');
if (input.value === '17') {
    input.style.backgroundColor = 'green';
    document.querySelector('#A2').innerHTML = 'Правильно';
} else {
    input.style.backgroundColor = 'red';
    document.querySelector('#A2').innerHTML = 'Неправильно';
}

... into ...
const input = document.querySelector('input');
const answer = document.querySelector('#A2');

if (input.value === '17') {
    input.style.backgroundColor = 'green';
    answer.innerHTML = 'Правильно';
} else {
    input.style.backgroundColor = 'red';
    answer.innerHTML = 'Неправильно';
}

HTML cleanup: If you need to query the document to fetch elements, it's always good to be as explicit as possible. On one line you are querying for input, but what if the page contains multiple input elements later? You should try to get a consistent and explicit HTML structure going for the questions/answers (which also ties in with the point made later on below). An example could be this:

...

    <input type="text"></input>
    <button class="check">Check</button>

...

Each of the elements in this node can be uniquely identified simply by the fact that they are a child of the unique(!) question element with the ID "q1". Queries that looked for input before would now look for #q1 > input instead.
You could also try to remove redundant classes, unless they are used for styling. In the first question, there is one button with the "correct" class, with all others being "incorrect". But the fact that every button that is not explicitely "correct" should be incorrect should be natural, hence you could consider removing these excessive classes.

The points mentioned above will probably increase the overall readability and maintainability of the project, but the biggest concern currently is the extendibility.
Look at it this way: Currently, every time you want to add a new question to the quiz, you need to modify your source code, mostly adding duplicated statements to check correct/incorrect answers. If you give your questions a more concrete structure, you could write reusable code, that is valid for any question that you add!
The exact implementation for this is up to you, but it could help to generate an object from an HTML node, grabbing the question title, description, answering possibilities (and the correct one obviously!) and setting up the question/answer handling.
Always remember: It's almost always better to have something that is extendible and/or scalable without having to modify the source code, just by modifying the markup or configuration.


Since you're using cstdarg and va_list is a complete type, it should be std::va_list.

va_start with a std::string is undefined behavior. This means that you actually cannot use std::string as your format (at least not if you plan on using only the stdargs facilities).

It's literally impossible, since there's no way to forward the ... idea, but instead you can only forward a va_list, which of course presents a problem since you can't obtain a va_list with a std::string parameter.

Using vsnprintf implies that you're using C++11. Given this, I might be tempted to go the variadic template route rather than leveraing the old C style functions that don't have type safety. Unfortunately though, much of the parsing and transforming logic would have to be recreated. If you do want to consider going this route, Andrei Alexandrescu gave a talk in which he examined this option.

Note that using a std::string format with variadic templates is of course possible.

Oh, and of course you could do a hybrid where you use a variadic template, but only to forward the arguments to vsnprintf. That would allow you to use a std::string format but you don't get the true typesafety of the variadic approach.

vnp already covered this, but let's take a second look and consider an excerpt from the standard:

  The vsnprintf function returns the number of characters that would have been written
  had n been sufficiently large, not counting the terminating null character, or a negative
  value if an encoding error occurred. Thus, the null-terminated output has been
  completely written if and only if the returned value is nonnegative and less than n.

Unfortunately, you'll have to do some pretty gross handling for this since on MS systems a negative number currently means the buffer was not large enough whereas on standard compliant systems it means some of encoding error happened.

If you include the null character in the calculation, you need to use <=. If you don't include it, you need to use <. This means that your current logic of len < initial_buf_size is wrong. It should actually be len <= initial_buf_size.

Think of it this way: len represents the length of the entire, null terminated output string (since you added 1). initial_buf_size represents the size of the entire buffer, including the required null terminator. Since both numbers include the null terminator, the case where they are equal means that the entire buffer was utilized but that it does contain the full, null terminated output string.

I wouldn't bother using initialize_buf_size. Instead, I would just hard code it into the buf1 declaration and then use sizeof(buf1). I'm all for avoiding magic numbers and pulling them into constants, but it's really only used once (and you should be using sizeof anyway -- the declaration of buf1 can change).

2 spaces is rather unusual in C++. I would expect either 4 spaces or 1 tab.

I'm not a fan of the lack of white space. Like the previous item, this is just opinion, but I (and I think most people -- though obviously I'm prone to confirmation bias on this) prefer spacing around clauses and operators. In other words:

func(param1, param2, param3)

and

if (a < b) {

Your function has way too much duplicated code. Let the va_list function be handled at the top level, and then have a second function that actually does the work. This is actually exactly what every implementation of the standard library I've ever used does with.

Basically what I'm saying is that just as the standard library has printf and vprintf, you would have string_sprintf and string_vsprintf, and string_sprintf would just call string_vsprintf under the hood.

Instead of having two cases, I would be tempted to just do an empty run to vsnprintf to figure out exactly what size you'll need.

You're using a non-standard compiler extension to use a automatic memory duration array that is actually dynamically sized (buf2).

Instead, I would use a container like a std::vector to handle the buffer, or since you're arleady using C++11, you can use std::string since it's guaranteed to be contiguous.

All in all, I might do something like this:

std::string string_vsprintf(const char* format, std::va_list args) {
    va_list tmp_args; //unfortunately you cannot consume a va_list twice
    va_copy(tmp_args, args); //so we have to copy it
    const int required_len = vsnprintf(nullptr, 0, format, tmp_args) + 1;
    va_end(tmp_args);

    std::string buf(required_len, '\0');
    if (std::vsnprintf(&buf[0], buf.size(), format, args) < 0) {
        throw std::runtime_error{"string_vsprintf encoding error"};
    }
    return buf;
}

std::string string_sprintf(const char* format, ...) __attribute__ ((format (printf, 1, 2)));

std::string string_sprintf(const char* format, ...) {
    std::va_list args;
    va_start(args, format);
    std::string str{string_vsprintf(format, args)};
    va_end(args);
    return str;
}

Note that this does not handle Windows and MS's non-compliant implementation of vsnprintf.

It would also be a good idea to wrap the __attribute__ stuff in preprocessor checks since __attribute__ is only used in GCC and clang.

Oh, and the string is unnecessarily set to all null characters and only then over written with the data we actually care about. If you super care about performance, that might be an issue, but realistically, it shouldn't matter. Anyway around it would require an extra copy anyway (since you'd have to take whatever buffer you used and copy it into a std::string).


Select array element by its weight/probability

More concise code
First, you can compute weightSum using a reduce() function instead. I am not sure if there is any particular performance benefit to this or not, but it does allow you to put everything on one line if you like that sort of thing.
const weightSum = weights.reduce((sum, weight) => sum + weight, 0);

Similarly, in newer versions of Javascript you can use weights.findIndex() instead of weights.some() to make your code more concise. However this will not work in Internet Explorer.
    const retIndex = weights.findIndex((weight) => {
        choice -= weight;
        return (choice < 0);
    });
    return retIndex;

Now, on to efficiency.
Efficiency - using input once
If you only plan to use each input once, then the algorithm you have is close to the best fit for the job. But the time to produce an output increases linearly with the size of the input (O(n)). We can improve that. (Thanks Roland Illig.)
Say that at the top, instead of simply taking the sum, we generate a new array with all the intermediate steps to get to the sum. E.g. for the input [1.5, 3.5, 2, 1.3] we create the array [1.5, 5, 7, 8.3]. This leads us to more or less the inverse of your current method; instead of subtracting weights from one side of the less-than comparison (i.e. from choice), we are adding them to the other side.
    const accumulatedWeights = weights.slice(0, 1);
    weights.slice(1).forEach((weight, i) => {
        accumulatedWeights[i] = weight + accumulatedWeights[i - 1];
    });
    weightSum = accumulatedWeights[accumulatedWeights.length - 1];

    let choice = Math.random() * weightSum; // [0 ~ weightSum]
    let retIndex;
    accumulatedWeights.some((accumulatedWeight, index) => {
        if(choice < accumulatedWeight){
            retIndex = index;
            return true;
        }
    });
    return retIndex;

Now, this is not yet an improvement on your current method. The key is that this new array accumulatedWeights has a useful property: we know it is sorted, ordered from least to most (assuming no negative weights, which would frankly break everything anyway). This means we can do a binary search on it. Instead of using .some() to go from one end of the array to the other, we can start by checking in the middle of the array, and then "zoom in" on the half that must contain the correct value, then repeat.
Think about if there are 100 values in the input, and the random number generated corresponds to the value at index 99. Without binary search, we have to go through the whole array and do 100 operations to find the correct index; with binary search we only have to do around 7. (All 100 -> top 50 -> top 25 -> top 12 or 13 -> top 6 or 7 -> top 3 or 4 -> top 1 or 2 -> definitely top 1.) This is O(log n) time efficiency, a big improvement over O(n).
Unfortunately I don't have time to write out a full binary search function, but see this StackOverflow post.
Efficiency - using input many times
But what if you wanted to use each input more than once? E.g. you want to select ten million randomized indexes in a row based on the same weighting scheme.
Well, in that case you could follow the advice of this other StackOverflow post:

First, build a big array where each number you want to select appears some number of times in proportion to its weight. E.g. for the weights [1.5, 3.5, 2, 1.3], you would generate an array with fifteen 0s, thirty-five 1s, twenty 2s, and thirteen 3s.
Then, pick a random element from the big array (i.e. compute an index via Math.floor(Math.random() * big_array.length) and return the element at that index) ten million times in a row.

You pay a certain cost up front to set up the big array, but once you have it set up, the time to find another result is constant (O(1)), no matter how long the original input was.
Whether or not this is more efficient in practice depends entirely on your use case.


Current solution
There's nothing really wrong with your current solution.  You build the tree, do the swapping and then do the inorder traversal.  Each step is implemented in a simple way and there isn't much excess code.  However, since you asked about doing it in less code, I will show you two ways to dramatically reduce your code.
You don't need to build a second tree
If you think about it, after you have read in the tree into your array called leafs, you already have a complete tree structure.  You don't need to build a second tree with nodes, left/right children, etc.  You can just use the array as your tree representation.  Therefore, all of your TreeNode code is unnecessary.
You can print the inorder traversal during the swap
Right now, you run the swap() function to swap the requested nodes, and then run the inorder() function to print the nodes in the swapped tree.  Since those are the only two operations you need to do, you can just print the traversal while swapping instead of doing two passes.
Revised solution
Here is what your code would look like after making the above two changes.  Note that I modified the array to be 1-based because the problem wanted the root to be node 1.
import java.util.Scanner;

public class Solution {
    public static final int ROOT_NODE = 1;

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        final int N = s.nextInt();
        int[][] tree = new int[N+ROOT_NODE][2];

        for (int i = ROOT_NODE; i < N+ROOT_NODE; i++) {
            for (int j = 0; j < 2; j++) {
                tree[i][j] = s.nextInt();
            }
        }

        int numDepths = s.nextInt();
        for (int i = 0; i < numDepths; i++) {
            swap(tree, ROOT_NODE, s.nextInt(), 1);
            System.out.println();
        }
    }

    public static void swap(int [][] tree, int node, int targetDepth,
            int depth) {
        if(node == -1) return;

        if(depth % targetDepth == 0) {
            int temp = tree[node][0];
            tree[node][0] = tree[node][1];
            tree[node][1] = temp;
        }
        swap(tree, tree[node][0], targetDepth, depth+1);
        System.out.print(Integer.toString(node) + " ");
        swap(tree, tree[node][1], targetDepth, depth+1);
    }
}


Unwrapping optionals for max of a 2D array in swift

Your first method does not work correctly if the first row is empty:

print(max1(array: [[], [1, 2], [-3]])) // nil

This is difficult to salvage while avoiding an optional for the current maxval.

Your second method returns nil if any row is empty:

print(max2(array: [[1, 2], [], [3, 4]])) // nil

guard is a useful language feature to avoid the “optional pyramid of doom,” or to “early exit” in exceptional cases. But in your max2() function it makes the program flow difficult to understand (and introduced an error, as we saw above). With plain old if-let-else it would look like this:

func max2(array: [[Int]]) -> Int? {
    var maxval: Int?
    for row in array {
        if let rowmax = row.max() {
            if let temp = maxval {
                if rowmax > temp { maxval = rowmax }
            } else {
                maxval = rowmax
            }
        }
    }
    return maxval
}

But actually the (explicit) handling of all the special cases of an empty array or empty rows can be avoided completely!

The Sequence.joined() can be applied to the nested array, it returns a (lazily evaluated) sequence of all concatenated rows.

This simplifies the implementation to

func max2D(array: [[Int]]) -> Int? {
    return array.joined().max()
}

Or more generic, for nested arrays of comparable elements:

func max2D<T>(array: [[T]]) -> T? where T: Comparable {
    return array.joined().max()
}

You may also consider if it is worth defining a function for that purpose, if you also can call

let myMax = my2DArray.joined.max()

directly.


Wrong is too heavy word, and I don't why it get down voted, but minor improvements are possible.

Modern::Perl is not core module and it usually means strict, warnings, and perhaps autodie are used (plus some other tweaks).
chr() is not needed, and hash slice assignment works equally well, not to mention that it is perl idiom
keys %h may generate large in memory list for bigger hashes, and while .. each handles such cases better. There is a catch with each as it uses internal hash pointer which needs to be reset with keys %h if you want to start back from hash beginning (in non LIST context keys %h doesn't generate list).

use strict;
use warnings;

my %h;
@h{ 0 .. 7 } = "A" .. "H";
my $cols = 3;
my $n = -$cols;

keys %h;
while ( my ($k,$v) = each(%h) ) {
  print "$k => $v";
  print 0 == ++$n % $cols ? "\n" : "\t\t";
}
print "\n" if $n % $cols;
print "------";


Firstly, in C, ALL_CAPS is generally used only for macros. Hence, I wouldn't use the name NODE as a typedef for your struct node, but instead something like typedef struct Node node_type;. Further, generally C is written using lowercase_with_underscores, so I'd rename it to struct node.

Using an assert in your new_leaf function on what you get back from malloc is fine in my books, as this will terminate the process if the OS can't give you back any memory, in which case you're unlikely to be able to do anything anyway.

Your function int contains(NODE *node, int value) doesn't really need an assert. If the user gives you a NULL node, then you can immediately just return 0. Giving a NULL to this function shouldn't terminate the program. A similar argument can be made for max_height.

Of course, the biggest problem is that no, your destroy function definitely does NOT clean up all the memory allocated by the program. Tools like valgrind can help to inform you if you have any memory leaks lurking around. In this case, however, it's very easy to see that the only memory that will be reclaimed is the memory for the root node (whatever you call destroy with).

Fixing this is pretty simple: it's just using a recursive algorithm that you've basically already used in insert and contains:

void destroy(node_type root)
{
    // If we have a non-NULL pointer, we need to
    // recursively free its left and right children,
    // and then free it.
    if(root) {
        destroy(root->left);
        destroy(root->right);
        free(root);
    }
}

A few other comments:

I'm not a big fan of 2 space indentation. It's not enough to (easily) visually scope blocks. I'd much rather 4 spaces.
You might want to start looking into how to user header files to split up interface and implementation as a next step (if you haven't already).
I'm not a big fan of explicitly having keeping track of what is a leaf with is_leaf. It means that any node that is down the bottom will have 2 extra dynamic allocations performed to have leaf values (see insert). Instead, I'd just set the left and right pointers to be NULL, and leave it at that. You can easily write an is_leaf function that simply checks that both pointers are NULL.
The API is a bit deficient (no deletion of a value, for example), but I'm guessing this is done as a learning exercise, so that's ok.


var ajax = new XMLHttpRequest();

ajax.open('POST', 'ajax.php?action=submit_form', true);

You can replace XHR with fetch. While XHR is widely supported, fetch is easier to work with. It uses promises instead of callbacks, which means you can readily use async/await with it. It's inspired from jQuery's $.ajax(). So if you're familiar with that, fetch will just click.

var content = '';

content = content + 'agreement=' + document.querySelector('#agreement').checked;
content = content + '&user=' + document.querySelector('#user').value;
content = content + '&password=' + document.querySelector('#password').value;
content = content + '&text=' + document.querySelector('#text').value;

Do not build query strings manually. The issue is that in query strings, certain characters must be escaped correctly for it to be valid. Otherwise, I could stick characters in there which can make the query string invalid. Use URLSearchParams() to construct the query string.

<button id="submit" onclick="submit_form()">Submit</button>

Instead of using onclick on the button, use onsubmit on the form instead. This way, you can also catch someone submitting the form by pressing enter. Also, instead of inline event properties, use element.addEventListener(). This way, you can, among other things, add more than just one handler and avoid defining a global function for your event handler.

if($_GET['action'] == 'submit_form')
{
    $agreement = $_POST['agreement'];
    $user = $_POST['user'];
    $password = $_POST['password'];
    $text = $_POST['text'];

    echo 'Data received:
';
    echo 'Agreement: '.$agreement.'
';
    echo 'User: '.$user.'
';
    echo 'Password: '.$password.'
';
    echo 'Text: '.$text.'
';
}

Not exactly sure why you'd put action in a GET parameter while everything else is in POST. Use POST all the way if you intend to POST. Also, if I recall correctly, it's up to the server to parse GET parameters in a non-GET operation. The server may choose to ignore it. This might work in PHP, but it might not work on another platform.

Also, sanitize/escape the data before printing it on the page. This looks like debugging to me, so that's fine. But never trust user input, never print arbitrary values. This can easily be used in a reflected XSS, a security issue.


You are correct when you say that the MessageHandler class violates the Single Responsibility Principle.

What you're looking for here is generics. First of all, you need to define a contract for messages and their respective handlers. This can be done with the following:

public interface IMessage
{
    // properties
}

public interface IMessageHandler<in TMessage>
    where TMessage : IMessage
{
    bool Handle(TMessage message);
}

So with the AlarmEventMessage, you can do this:

public class AlarmEventMessage : IMessage
{
    // properties
}

public class AlarmEventMessageHandler : IMessageHandler<AlarmEventMessage>
{
    public bool Handle(AlarmEventMessage message)
    {
        // stuff
    }
}

This design allows you to do some cool stuff with decorator chains, dispatching, registration by convention (if you're using an IoC container that supports it), among other things. For more information, check out the following two articles (they demonstrate how to implement the command/query pattern, but the design is identical):

Meanwhile... on the command side of my architecture
Meanwhile... on the query side of my architecture


Check Is Anagram Scala HashMap based implementation

It seems to me that groupBy() will do something very similar to your addToIndex(). The result is an immutable.Map[Char,String] instead of a mutable.HashMap[Char, Int], so the question is: which is better/easier for comparison purposes.

It turns out that the simple == evaluation is sufficiently deep to handle this.

def isAnagram(value1: String, value2: String): Boolean =
  value1.groupBy(identity) == value2.groupBy(identity)

Another, rather obvious, anagram test is simply:

value1.sorted == value2.sorted

I think, for long strings, grouping/indexing might be more efficient than sorting since each string is traversed only once. On the other hand, comparison for equality might be more complex for Maps than it would be for Strings.


Comparing hash members to other hash members

Convert the Hashes to Arrays, then use the difference operations on them.

a = { :a => 1, :b => 2, :c => 2 }
b = { :a => 1 }

p (b.to_a - a.to_a).empty?

You can do other things, like identify if two Hashes overlap in any places, by use the intersection too:

p (a.to_a & b.to_a).any?


Function for simple navigation of dataframe in console

Without changing the interface too much, your code could use the following changes. Note that I am fixing three bugs regarding corner cases:

if your data has fewer than n rows to start with (see where I used min)
if your data has a single column (see where I used drop = FALSE)
make sure that the last page will always show

I avoided duplicating the statements  where begin and end are reset, by creating an increment variable. The code computing the increment (of +n or -n) has been moved to its own function. One improvement I've made is that the function will call itself again via Recall() in case the user entered something other than the expected . or /, i.e. it will prompt the user again.

less <- function(x, n = 10) {
  begin <- 1
  end   <- n

  get_increment <- function() {
    input <- readline("Type . to scroll up, type / to scroll down: ")
    if (input == ".") -n else if (input == "/") +n else Recall()
  }

  repeat {
    print(x[begin:min(end, nrow(x)), , drop = FALSE])

    increment <- get_increment()
    begin     <- begin + increment
    end       <- end   + increment

    if(begin > nrow(x) | end < 1) break
  }
}

Now regarding your design in general, I feel it would be nice to pre-split your data.frame every n rows, and let the user know that there are for example 12 pages and that he is currently looking at page 4/12. In the prompt, also allow the user to jump to a specific page in addition to the next or previous page. Finally, make it easier to exit via a specific code like "q" rather than wait for the user to go beyond the first or last page. Here is my attempt:

less <- function(x, n = 10) {

   N <- nrow(x)
   if (N == 0) {
      message("input has no rows")
      return(NULL)
   }

   row_page_idx <- (seq_len(N) - 1) %/% n
   pages <- split(x, row_page_idx)
   num_pages <- length(pages)
   page_idx <- 1

   get_new_page_idx <- function() {
      input <- readline('Type a page number, ">" for next, "<" for previous, or "q" to quit: ')
      if (input == "q") return(0)
      if (input == ">") return(min(num_pages, page_idx + 1))
      if (input == "<") return(max(1, page_idx - 1))
      integer <- suppressWarnings(as.integer(input))
      if (!is.na(integer) & integer %in% 1:num_pages) return(integer)
      Recall() # if all fails
   }

   repeat {
      print(pages[[page_idx]])
      message("Page ", page_idx, " of ", num_pages)
      page_idx <- get_new_page_idx()
      if(page_idx == 0) break
   }
}


Classifying the user into an age bracket

A TreeMap<Integer, String> with a for loop and stop on first number greater than or equaling the number to find will solve your problem.

treemap.put(-1, "This program is for humans");
treemap.put(2, "Still in Mama's arms");
//etc...
treemap.put(Integer.MAX_VALUE, "This program is for humans");

Then, loop through entries...

for(Map.Entry<Integer, String> entry : treemap.entrySet()){
    if(entry.getKey() >= age){
        System.out.println(entry.getValue());
        break;
    }
}

The default behaviour for a TreeMap is that the contents are sorted based on the key, which explains why this works. Use Integer.MAX_VALUE for the last case - it'll be equal to or greater than any other number.

You can even use a built-in function for this:

System.out.println(treemap.ceilingEntry(age).getValue());

Making the final code...

import java.io.*;
import java.util.TreeMap;

public class Main {
    private static TreeMap<Integer, String> treemap = new TreeMap<>();

    private static void initializeAgeDescriptions() {
        treemap.put(-1, "This program is for humans");
        treemap.put(2, "Still in Mama's arms");
        treemap.put(4, "Preschool Maniac");
        treemap.put(11, "Elementary school");
        treemap.put(14, "Middle school");
        treemap.put(18, "High school");
        treemap.put(22, "College");
        treemap.put(65, "Working for the man");
        treemap.put(100, "The Golden Years");
        treemap.put(Integer.MAX_VALUE, "This program is for humans");
    }

    public static void main (String[] args) throws IOException {
        initializeAgeDescriptions();
        File file = new File(args[0]);
        BufferedReader buffer = new BufferedReader(new FileReader(file));
        String line;
        while ((line = buffer.readLine()) != null) {
            line = line.trim();

            int age = Integer.parseInt(line);
            System.out.println(treemap.ceilingEntry(age).getValue());
        }
    }
}


I would expect the standard library's mutex (which is basically pthread_mutex) to already take care of this optimization behind the scenes, the same way these days I would expect the standard library's malloc to maintain its own thread-local arenas instead of taking a lock on every call.
Have you benchmarked the difference between what you wrote above and
template<unsigned SPIN_LIMIT>
class kiss_mutex {
    std::mutex mtx_;

  public:
    void lock() {
        for (unsigned i = 0; i < SPIN_LIMIT; ++i) {
            if (mtx_.try_lock()) return;
        }
        mtx_.lock();
    }

    bool try_lock() { return mtx_.try_lock(); }
    void unlock() { return mtx_.unlock(); }
};

? I haven't, but I'd be very curious to know whether kiss_mutex<N> performed comparably to std::mutex or comparably to hybrid_lock<N> (for tuneable values of N, of course).

Your benchmark might have been thrown off by a hilarious bug in hybrid_lock::lock():
    this->mCondition.wait(guard, [this]() {
        return !this>mFlag.test_and_set(
           std::memory_order::memory_order_acquire
        );
    });

When you see it...
This is the funniest argument I've seen yet for suffixing data members with _ and never writing out this-> except where the grammar requires it. :)

Stylistically, your code seems pretty good. My nits:

I would be extremely wary of declaring template non-type parameters of type unsigned int. My advice is to stick with int, because its name is short and because it's easy to write literals of that type. The only reason I stuck with unsigned in kiss_mutex is because if I didn't, it wouldn't have been a drop-in replacement for your code.

Here's the code showing why unsigned is worse than int: if someone sees hybrid_lock<100> they're probably going to assume that 100 represents an int (or at worst a size_t), and they're going to code accordingly, and their code simply will not work if you've used some other weird type. In other words, int is widely recognized as a vocabulary type (a "ubiquitous type used throughout the internal interfaces of a program"), whereas unsigned is not generally recognized as such. Of course, unsigned might be used as a vocabulary type in your codebase; it all depends on your employer's coding style guide. But I would hope it's not, for sanity's sake (again refer back to the code in the Wandbox above).
For another set of reasons that I mostly agree with, see Laurion Burchall's "unsigned considered harmful". Since you mentioned you've used Java, you might like this similarly titled blog post elsewhere, re Java, which makes some good points re "things C and C++ screwed up in their implementation of unsigned types."

The thing you wrote is actually a mutex in C++ terms, not a lock; so it should be called hybrid_mutex. A mutex exposes imperative lock and unlock methods; a lock (for example, std::unique_lock) is a wrapper that hides lock and unlock under a protective layer of RAII. (In other words: If you're designing a drop-in replacement for std::mutex, it should almost certainly be named something_something_mutex.)

In C++11, it is inappropriate to make any special member function private. If you want a special member function to go away, declare it =delete (which you did) but leave it public; this way, you're sure to get the error messages you want, instead of weird interference from the part of the compiler that checks access controls. "This constructor was explicitly deleted" is a much better error message than "This constructor is private and by the way it's been deleted too."

The Rule of Zero: std::mutex is a non-copyable type, so merely having a member of type std::mutex suffices to implicitly delete your copy operations. It's redundant to declare them deleted; you can just rip out those lines, as I did in kiss_mutex.

On the same note, I've never seen anyone use the inline keyword as you did, on member functions that are declared in-line and are thus implicitly inline anyway. Keep the code clean by removing redundant keywords. (Personally I make an exception for virtual, but my impression is that the C++ mainstream these days doesn't even make that exception. Indeed, as of 2021, I've completely converted to the Church of override, and no longer ever write virtual redundantly.)


The biggest readability concern, in my opinion, is squashing everything on one line.  Compare:

int main () {
  for (std::size_t i = 0; i < 6; ++i) { std::cout << flatArray[i] << " "; } std::cout << std::endl;
}

to

int main()
{
    for (std::size_t i = 0; i < 6; ++i) {
        std::cout << flatArray[i] << " ";
    }
    std::cout << std::endl;
}

which can then be improved to:

int main()
{
    for (auto v : flatArray) {
        std::cout << v << ' ';
    }
    std::cout << '\n';
}

We can use some shorthand to make nested arrays easier to understand:

namespace detail {
    template <typename T, std::size_t... Dims>
    struct multi_array;

    template <typename T>
    struct multi_array<T> {
        using type = T;
    };

    template <typename T, std::size_t Dim, std::size_t... Dims>
    struct multi_array<T, Dim, Dims...> {
        using type = std::array<
            typename multi_array<T, Dims...>::type, Dim
        >;
    };
}

template <typename T, std::size_t... Dims>
using multi_array = typename detail::multi_array<T, Dims...>::type;

Now, it is more idiomatic to pass the array as an argument instead of a template argument, so that invocation uses more natural syntax and works for both runtime values and compile time values:

template <std::copy_constructible T, std::size_t N, std::size_t M>
constexpr auto flatten(const multi_array<T, N, M>& array)
    noexcept(std::is_nothrow_copy_constructible_v<T>)
{
    return /* magic */;
}

We can also easily generalize into multiple dimensions from here:

#include <array>
#include <concepts>
#include <type_traits>

namespace detail {
    template <typename T, std::size_t... Dims>
    struct multi_array;

    template <typename T>
    struct multi_array<T> {
        using type = T;
    };

    template <typename T, std::size_t Dim, std::size_t... Dims>
    struct multi_array<T, Dim, Dims...> {
        using type = std::array<
            typename multi_array<T, Dims...>::type, Dim
        >;
    };

    template <typename T>
    struct multi_array_traits {
        static constexpr std::size_t size{1};
        using type = T;
    };

    template <typename T, std::size_t N>
    struct multi_array_traits<std::array<T, N>> {
        static constexpr std::size_t size{N * multi_array_traits<T>::size};
        using type = typename multi_array_traits<T>::type;
    };

    template <std::size_t I>
    constexpr const auto& get(const auto& scalar) noexcept
    {
        static_assert(I == 0);
        return scalar;
    }

    template <std::size_t I, typename T, std::size_t N>
    constexpr const auto& get(const std::array<T, N>& array) noexcept
    {
        constexpr auto InnerSize = multi_array_traits<T>::size;

        constexpr auto Outer = I / InnerSize;
        constexpr auto Inner = I % InnerSize;

        return detail::get<Inner>(array[Outer]);
    }

    template <typename T, std::size_t... Indices>
    constexpr auto flatten(const T& array, std::index_sequence<Indices...>)
    {
        constexpr auto Size = multi_array_traits<T>::size;
        using Elem = typename multi_array_traits<T>::type;

        return std::array<Elem, Size>{Elem(detail::get<Indices>(array))...};
    }
}

template <typename T, std::size_t... Dims>
using multi_array = typename detail::multi_array<T, Dims...>::type;

template <std::copy_constructible T>
constexpr auto flatten(const T& array)
{
    constexpr auto Size = detail::multi_array_traits<T>::size;
    return detail::flatten(array, std::make_index_sequence<Size>{});
}

(live demo)


If you are doing a lot of numerical calculations in Python and want them to be fast, you should use numpy, a package specifically for this purpose.

It allows you to write your code in a vectorized way, making it easer to understand at the same time:

import numpy as np

@staticmethod
def arc_coordinates(_radius, length_of_arc, scale_factor, x0, y0):
    """
    positive curvature is a right bend, negative curvature is a left bend
    scale_factor: used to scale the values for plotting them
    x0 and y0: values are displaced such that the plot is in the center of the screen.
    """
    radius = np.array(_radius)
    delta_phi = - length_of_arc / radius
    phi = np.cumsum(delta_phi)
    dx = - radius * (np.cos(delta_phi) - 1)
    dy = - radius * np.sin(delta_phi)
    track_coordinates = np.vstack([dx, dy]).T
    track_coordinates[1:, 0] = np.cos(phi[1:]) * dx[1:] - np.sin(phi[1:]) * dy[1:]
    track_coordinates[1:, 1] = np.sin(phi[1:]) * dx[1:] + np.cos(phi[1:]) * dy[1:]
    track_coordinates = scale_factor * np.cumsum(track_coordinates, axis=0) + np.array([[y0, x0]])
    track_coordinates = np.concatenate([np.array([y0, x0]), track_coordinates.flatten()[:-2]])
    return track_coordinates

This gives the same results as your code. Note that it (just like your code) uses the weird convention that the output array is flat, alternating between x and y values, starting with a y-value.

On my machine this is not actually faster than your implementation, though:

%timeit arc_coordinates(radius, 1, 1, 0, 0)
39.4 µs ± 849 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit calculate_coordinates_from_length_of_arc_and_radius(radius, 1, 1, 0, 0)
21.5 µs ± 457 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

However, this probably has a few possibilities for improvement left (WIP).

I also renamed your function to a (hopefully) also clear but shorter name as well as the initial displacements. I also made your comment detailing the parameters a docstring.


I don't have a comment on how you parse the input. I just give a solution which runs in O(1) space and O(N) time.

Problem says that all integers are in range 0..N-2 and there's only one integer duplicated. Consider you hadn't that duplicated element, so sum of all input numbers would be (n-2)*(n-1)/2 (sum of integers from 0 to n-2). So now you can read all N integers and calculate their sum. Then if you subtract (n-2)*(n-1)/2 from this sum, the value of your duplicated element would come out.

The code would be:

int sum = 0;
int n = a.length;
for(i=0; i<n; i++)
  sum += a[i];

System.out.println(sum - (n-2)*(n-1)/2);

This method is clearly of O(n) time, but if you want to achieve O(1) space, you should avoid storing all elements in an array. Instead of that, when you parsed nextToken, you add it to sum.


Haskell Listing Directories in Working Directory

Instead of fIO f xs >>= return . ((if matches then [x] else []) ++), you can use <$>:

([x | matches] ++) <$> fIO f xs

Applicative style would allow you to compress all this yet further:

fIO f (x:xs) = (\matches -> ([x | matches] ++)) <$> f xs <*> fIO f xs

But in the end:

fIO = filterM


Return path between graph nodes using depth-first search

The algorithm you've implemented is not a depth-first search. I'm not sure what it does exactly. It uses a priority queue for some reason (a depth-first search doesn't need a priority queue). It also stores the entire path in the stack and copies every time it discovers a new vertex, which makes it time and space inefficient (your's implementation needs O(n^2) space and time even on a sparse graph (for instance, a tree), while a correct implementation is always linear in number of vertices and edges).
A standard depth-first search goes like this:

stack = [start_vertex]
parent = empty dict
seen = set(start_vertex)
while not stack.empty():
     v = stack.pop()
     for u in neighbors of v:
          if not u in seen:
              seen.add(u)
              stack.push(u)
              parent[u] = v

The code is much simpler and more efficient. To find the path itself, we can just iterate starting from the destination vertex and going to the current vertex's parent until we reach the start vertex. This way, it requires a linear amount of time and space.
The code itself is rather obscure, in my opinion. Why do we multiply something by -1 here: last.neighbors[neighbor] * -1 (probably you do it to "reverse" the order, but it's not that clear when you read it for the first time)? The fact that neightbors[v] is actually a weight of the edge is also confusing (I would expect to see something like distance or weight in the name of the variable if it stores the length of the edge). By the way, depth-first search works with unweighted graph, so I don't see the point of storing the weights, anyway.


Algorithm

Hint

You don't need to check all integers between 2 and int(math.sqrt(x))+1. You only need to check primes between 2 and int(math.sqrt(x))+1.

Stylistic

__main__

I would add a "main function" to your program. This is typically done in Python by:

def main():
    ...

if __name__ == "__main__":
    main()

See this answer for more reasons why this paradigm is followed.

sqrt

I technically have not measured the performance of sqrt, but I have more commonly seen your for loop written as:

while i * i < x:
    ...

unlike the current:

for i in range(2,int(math.sqrt(x))+1):

No need to import math then.

PEP 8

According to the PEP 8 style guide, you should add a space between the mathematical operations. So for instance, instead of:

if x%i==0:

it should be:

if x % i == 0:


Implementing Function that Maps over Stream

Since streamMap allows you to map over a stream, you can as well define a Functor instance for Stream. Actually, streams can also define an Applicative instance which zips two streams and also a Monad instance whose join computes the diagonal of a 2-dimensional stream.
Your definition of Stream is slightly inefficient as it wraps the (,) constructor in another constructor Stream. You could:

make it a newtype, or
use the UNPACK pragma, or
define just a 2-argument constructor like data Stream a = Cons a (Stream a).

Your solution deviates from the assignment that forbids any kind of divisibility testing. Function odd tests for divisibility by 2 and g implements (somewhat inefficiently) division by 2.
Without the full code it's a bit hard to test/judge correctness, but I believe your implementation is not correct. In particular, I believe for n=6 your code will yield 3, while the expected value is 1.


Why is this program for extracting IDs from a file so slow?

You said in comments that you don't know how to create a self-contained test case. But that's really easy! All that's needed is a function like this:

def test_case(filename, n):
    """Write n lines of test data to filename."""
    with open(filename, 'w') as f:
        for i in range(n):
            f.write('Mon-{0:06d} {1}\n'.format(i + 1, '  99.999' * 20))

You can use this to make a test case of about the right size:

>>> test_case('cr36275.data', 200000)
>>> import os
>>> os.stat('cr36275.data').st_size
34400000

That's about 34 MiB so close enough. Now we can see how fast your code really is, using the timeit module:

>>> from timeit import timeit
>>> timeit(lambda:pullIDs('cr36275.data'), number=1)
1.3354740142822266

Just over a second. There's nothing wrong with your code or the speed of Python.

So why does it take you many minutes? Well, you say that you're running it inside Emacs. That means that when you run

>>> pullIDs('cr36275.data')

Python prints out a list of 200,000 ids, and Emacs reads this line of output into the *Python* buffer and applies syntax highlighting rules to it as it goes. Emacs' syntax highlighting code is designed to work on lines of source code (at most a few hundred characters but mostly 80 characters or less), not on lines of output that are millions of characters long. This is what is taking all the time.

So don't do that. Read the list of ids into a variable and if you need to look at it, use slicing to look at bits of it:

>>> ids = pullIDs('cr36275.data')
>>> ids[:10]
[['Mon-000001'], ['Mon-000002'], ['Mon-000003'], ['Mon-000004'], ['Mon-000005'],
 ['Mon-000006'], ['Mon-000007'], ['Mon-000008'], ['Mon-000009'], ['Mon-000010']]


Code to take a list, convert to string and insert comma between the 'elements' - From Automate The Boring Stuff

Nice solution, these are my suggestions:

Indentation: the first line is not indented correctly, there is an extra tab or spaces before def listsmash(listu):.
Code formatting: follow PEP 8 to format the code. You can use pep8online or just use the auto-formatting feature of many IDEs.
Bug: the output should be apples, bananas, tofu, and cats but the code outputs apples,bananas,tofu,and cats. There should be a space after the comma.
Edge case: if the input list contains only apples the code outputs and apples. This is an edge case to handle, probably at the beginning of the method.
Performance: there is no much to worry about performances, as it runs linearly to the input size. However, the first if condition is executed everytime:
for x in range(len(listu)):
    if x == len(listu) -1 :
        y+= 'and '+ str(listu[x])
    else:
        y+= str(listu[x]) + ','

Limit the number of iterations to len(listy) - 1 and add the last element outside the for-loop:
def listsmash(listu):
    y = ''
    for x in range(len(listu) - 1):
        y += str(listu[x]) + ', '
    y += 'and ' + str(listu[-1])
    return y

Use str.join: str.join is a handy function in this case:
def listsmash(listu):
    y = ', '.join(str(value) for value in listu[:-1])
    return y + ', and ' + str(listu[-1])

It joins all elements of listu (except the last one) with ,  and then we can append the last element at the end. Additionally, the function .join() is faster than +=.
Naming: I am not sure what listu means, maybe you can consider a better name like items following from the problem description.

Runtime for 1 million items:
Original: 4.321 s
Improved: 0.418 s

Full code:
from random import randint
from time import perf_counter

def original(listu):
    y = ''
    for x in range(len(listu)):
        if x == len(listu) - 1:
            y += 'and ' + str(listu[x])
        else:
            y += str(listu[x]) + ', '
    return y

def improved(items):
    result = ', '.join(str(item) for item in items[:-1])
    return result + ', and ' + str(items[-1])

# Correctness
items = ['apples', 'bananas', 'tofu']
assert original(items) == improved(items)

# Benchmark
n = 1_000_000
items = [randint(0, n) for _ in range(n)]

t0 = perf_counter()
original(items)
total_time = perf_counter() - t0
print(f'Original: {round(total_time, 3)} s')

t0 = perf_counter()
improved(items)
total_time = perf_counter() - t0
print(f'Improved: {round(total_time, 3)} s')


Graphs and Kruskal's Algorithm - Python OOP

Type hints

def __init__(self, start, end, weight):

can be

def __init__(self, start: Vertex, end: Vertex, weight: float):

depending on a few things, including the order of declaration of your classes, Vertex might need to be 'Vertex' here.

For another example, this

def vertex_from_name(self, name):

can turn into

def vertex_from_name(self, name: str) -> Vertex:

Efficient lookups

To make this more efficient:

    return next((v for v in self.vertices if v.name == name), None)

Consider maintaining a string-to-Vertex dictionary to reduce this lookup from O(n) to O(1) in time.

Premature materialization

These:

    return [e for e in self.edges if (e.start == v) or (e.end == v)]

    return [e.start for e in self.edges if e.end == v] + [e.end for e in self.edges if e.start == v]

require that the entire results be stored to an in-memory list. To return the generator directly and reduce this memory requirement, the first one can be

    return (e for e in self.edges if v in {e.start, e.end})

and the second one can be

yield from (e.start for e in self.edges if e.end == v)
yield from (e.end for e in self.edges if e.start == v)

Set-membership tests

This:

""" Given a list of lists, merges e1 root list with e2 root list and returns merged list."""

is probably better-expressed as accepting a list of set, not a list of lists. That will make these two tests:

        if e1 in i:
            xroot = i
        if e2 in i:
            yroot = i

faster. This:

    self.sets = [[v] for v in self.vertices]

would then become

    self.sets = [{v} for v in self.vertices]

Strings as iterables

This

v = [Vertex(x) for x in ["A", "B", "C", "D", "E", "F"]]

can be

v = [Vertex(x) for x in 'ABCDEF']

Convenience functions

Consider making a convenience function to turn this

g.add_edge("A", "B", 9)
g.add_edge("A", "C", 12)
g.add_edge("A", "D", 9)
g.add_edge("A", "E", 11)
g.add_edge("A", "F", 8)
g.add_edge("B", "C", 10)
g.add_edge("B", "F", 15)
g.add_edge("C", "D", 8)
g.add_edge("D", "E", 14)
g.add_edge("E", "F", 12)

into

g.add_edges(
    ("A", "B", 9),
    ("A", "C", 12),
    ("A", "D", 9),
    ("A", "E", 11),
    ("A", "F", 8),
    ("B", "C", 10),
    ("B", "F", 15),
    ("C", "D", 8),
    ("D", "E", 14),
    ("E", "F", 12),
)


You can let .format() do most of the work for you:

def print_in_a_frame(*words):
    size = max(len(word) for word in words)
    print('*' * (size + 4))
    for word in words:
        print('* {:<{}} *'.format(word, size))
    print('*' * (size + 4))

>>> print_in_a_frame("Hello", "World", "in", "a", "frame")
*********
* Hello *
* World *
* in    *
* a     *
* frame *
*********

Most of the magic happens in this line:

print('* {:<{}} *'.format(word, size))

It may be easier to understand what's going on if we rewrite it as:

print('* {a:<{b}} *'.format(a=word, b=size))

This tells format to print the keyword argument a, left-aligned, on a field of total width the keyword argument b.  Note that if b was fixed, say to 10, you would write that as:

print('* {a:<10}} *'.format(a=word))

or:

print('* {:<10}} *'.format(word))


Headers.  Did you leave out the includes and function prototype at the top for simplicity or something?  If not, you need to put them here otherwise your program will not compile.
Function-returning and displaying.  The last statement in your function along with the printing of the function's return value in main() will work, but it's not a good way to write it.

Instead, move the cout <<"= "; from your function (just keep return answer;) to your std::cout statement in main().
Function arguments/parameters.  You may want to keep like-types together for clarity and so that you don't mismatch them, which would cause bugs.  Whichever order is easiest to remember.

For instance, consider these:

calculate(num1, num2, aOp);            // function call
calculate(float x, float y, char z) {} // function definition

Early return in switch.  Instead of having a local variable to update and return at the end, you could instead return from the respective case:

switch (y) {
    case '+': return x + z;
    case '-': return x - z;
    case '/': return x / z;
    case '*': return x * z;
    default: std::logic_error("invalid operator"); // from <stdexcept>
}

Notice this default statement.  If the user enters an invalid operator, but no input validation was done beforehand, and exception will be thrown.  Overall, it's best to have a useful default, and this is one example.
You should also make sure the user isn't dividing by 0.  If so, don't let the calculation take place, otherwise there will be problem.  For such a case, you can just terminate from main() early:

if (num2 == 0 && aOp == '/')
{
    std::cout << "You cannot divide by 0!  Terminating...";
    return EXIT_FAILURE;
}


SPOJ problem: Life, the Universe, and Everything

The working solution is quite good, actually. You check the return value of scanf(), and you use the while loop condition smartly to say exactly what you mean to accomplish.  The only thing wrong with it is the indentation.

Here is one reasonable way to format it.

#include <stdio.h>

int main(void)
{
    int i = 0;
    while (scanf("%d\n", &i) > 0 && i != 42)
    {
        printf("%d\n", i);
    }
    return 0;
}

The initialization of i to 0 and return 0 are actually not needed, but I don't have a problem with making them explicit.

As for your failed attempts, they fail because they attempt to store all of their input, which isn't necessary to do. When there are more than 9 inputs, the buffer overflows.


Inserting filename, reading data, inserting regex, and testing if each line matches - version 2

Pure functions

All of your functions both "do work" and print. You should separate logic and In/Out.

print('') is poor practice

If you want an extra newline just concat it to the previous message:

print('Empty regex\n')
return

Avoid noise

Maybe in a file of 1000 lines, my regex will match 5 lines, why must I watch 995 useless lines of output? Just output lines where it does match.

Prefer a dictionary or indexes to an array to a long if elif chain

if option == 1:
    filename = change_filename(filename)
elif option == 2:
    readData = read_file(filename)
elif option == 3:
    regex = change_regex(regex)
elif option == 4:
    test_data(readData, regex)
elif option == 5:
    break
else:
    print('Invalid input')
    print('Please enter a valid option')
    print('')

In all sincerity I don't know how to do this in this particular case, but iit would also give the  benefit of generating the printing message on the fly, instead of repeating the same thing twice.

Command-line?

But maybe all of that effort for the menu is counterproductive and you should allow the user to call the programme like:

python regex_script.py <regex> <filename>

by using sys.argv or argparse.

My take

This is my implementation of this program, it separates Input/Output and logic and can be used concisely from the command line:

import re
import sys

def lines_matched(regex, text):
    for line in text.splitlines():
        if re.search(regex, line):
            yield line

def main():
    if len(sys.argv) != 3:
        print("Usage: python {} <regex> <filename>".format(__file__))
        return 1
    regex, filename = sys.argv[1], sys.argv[2]
    with open(filename) as f:
        print('\n'.join(lines_matched(regex, f.read())))

if __name__ == "__main__":
    main()

argparse would make it more user friendly.


JS create array by comparing 2 dictionaries

Review

Use semicolons. Why? If you don't know why you should use them, then you should use them. Not using them can result in very hard to track down bugs that will waste hours of your valuable time.

Use const wherever and whenever possible.

The return expression Object.assign(arraya) does nothing and is not required ( Object.assign returns the first argument unchanged if there is only one argument). return arraya; will do the same.

Use for of rather than for in. When you use for in you need to ensure that the key belongs to the object which just makes the code more complex. If you dont check for own property Object.hasOwnProperty then you risk the code not working for reasons unrelated to your code.
To get the keys of an object use Object.keys eg you can then replace the for in with for (let item of Object.keys(favouriteShows)) {
As it is only the value slug you want from each item in the object favouriteShows you can further refine the for of loop to get that value for you. Use Object.values which will get the value you find with favouriteShows[item] and use destructure assignment to pull out slug thus (Note the const) you have for (const {slug} of Object.values(favouriteShows)) {

Avoid naming variables after what they are, rather name them for what they represent (Unless they represent unknowns). Eg arraya would be better as results

Don't use complicated or long names when there is no need. The arguments (graphql, favouriteShows) can be simplified to (graph, shows) without losing any meaning.

Problems
There are a number of problems with this code.

The statement that matches shows by slug  if(favouriteShows[item].slug === graphql[itemGQL].show?.slug){ will match any two shows that do not have slug defined IE slug === undefined
This is not a problem if all objects always have slug defined. However the use of show?. makes it clear that this is at least not true in part.
You can check if slug is defined in the outer loop so you don't waste time searching for undefined in the inner loop.

In your question you state  "...then add the element to an array but only one time." However if favouriteShows contains items that have the same value for slug and there is a match for that value in graphql your function will add the same entry for every occurrence in favouriteShows
To prevent this problem you can use a Set to hold the result rather than an Array, It will ensure only one copy of each item is added.

Improvement
The inner loop repeats, stepping over the same items for every item in favouriteShows. You can use a Map that indexes items via a generated hash value. This reduces the complexity of your inner loop from \$O(n)\$ to \$O(1)\$.
Thus your code ends up as with added comments
// Keep the argument names simple
const favouriteShows = (graph, shows) => {

    // Use set to ensure only a single instance of each item will be in the result
    const result = new Set();

    // Create a map of graph indexed by slug so the inner loop is not needed.
    const bySlug = new Map(Object.values(graph).map(val => [val.show?.slug, val]));

    // Extract value of slug from the item values in shows
    for (const {slug} of Object.values(shows)) {

        // Make sure slug is defined.
        // It is unclear if this value may be falsey so test against undefined
        if (slug !== undefined) {

            // Does the map bySlug have an entry that matches slug?
            if (bySlug.has(slug)) {

                // Yes then get that entry and add it to the result.
                result.add(bySlug.get(slug));
            }
        }
    }

    // To return an array convert the set to an array.
    return [...result.values()];
}

It can also be compacted a little, and making an assumption that slug will be either undefined or some truthy string we get
const favouriteShows = (graph, shows) => {
    const result = new Set();
    const bySlug = new Map(Object.values(graph).map(val => [val.show?.slug, val]));
    for (const {slug} of Object.values(shows)) {
        const show = bySlug.get(slug);
        slug && show && result.add(show);
    }
    return [...result.values()];
}

Note that bySlug.get will find the last entry in the object graph if graph contained duplicates (slug has the same value more than once). As your code uses the first instance you may want to change the second line in the function so that it reverses (via Array.reverse) the order that the map is created. If there are no duplicates then it does not matter.
const favouriteShows = (graph, shows) => {
    const result = new Set();
    const bySlug = new Map(Object.values(graph)
       .map(val => [val.show?.slug, val])
       .reverse()
    );
    for (const {slug} of Object.values(shows)) {
        const show = bySlug.get(slug);
        slug && show && result.add(show);
    }
    return [...result.values()];
}


Nitpicks

There are a few inconsistencies in your capitalization of SQL keywords. It's pretty minor. I see then and Then in some places, etc.

Naming

m1 and m2 don't make for very good aliases. Likewise e_id, e_name, e_add are not very good column names, though I realize those are probably example tables and your real schema is probably quite a bit different.

concat

Concatenation can make things confusing in SQL, in my opinion. I would encourage to see if there is a more natural way to compare data in your case statements. For example, instead of this:

case    when m1.e_id = m2.e_id and concat(m1.e_name,m1.e_add) = concat(m2.e_name,m2.e_add)

Why not try:

case    when m1.e_id = m2.e_id and m1.e_name = m2.e_name and m1.e_add = m2.e_add

This one is especially odd looking and would be easy to make a mistake:

concat(m1.e_id,',',m1.e_name,',',m1.e_add) as month1s,

CTE

I think using a common table expression instead of a subquery would make your query more elegant and easier to maintain. I also think a little more vertical space in your case statements to separate the conditions from the results helps the code read better:

with cte_cdc_codes as (
    select
    case    when m1.e_id = m2.e_id and concat(m1.e_name,m1.e_add) = concat(m2.e_name,m2.e_add)
                then  'NoChange'
            when m1.e_id = m2.e_id and  concat(m1.e_name,m1.e_add) <> concat(m2.e_name,m2.e_add)
                then  'Update'
            when m1.e_id is null
                then 'New'
            when m2.e_id is null
                then 'Deletes'
            else 'Error'
            end as cdc_codes,
        concat(m1.e_id,',',m1.e_name,',',m1.e_add) as month1s,
        concat(m2.e_id,',',m2.e_name,',',m2.e_add) as month2s
    from    month1 as m1
    full outer join
    month2 as m2
    on  m1.e_id = m2.e_id
)
select
    case    when cdc_codes ='Updates'
            Then month2s
        when cdc_codes = 'NoChange' then month1s
        when cdc_codes = 'New' then month2s
        when cdc_codes = 'Deletes' then month1s
        else 'Error' end as fin_cols
from cte_cdc_codes;


Let's look at the code first

List<string> list = new List<string> { "({[]})", "][(]}})(" };

Poor choice of variable name. You picked expression just a little below, that is a good one. Why not use the plural form of it: expressions?

foreach (var barcketsList in list)

barcketsList contains a typo, not a big deal usually. However, you should pay some more attention for an interview.
bracket-s + List you really don't want hinting this is an array/collection/list twice.

foreach (var barcketsList in list)
// <- unnecessary white line
{

Don't leave white line just anywhere within a method in your code. They should be used to divide the logical blocks, eg: declaration/initialization vs logic vs return, logic#1 vs logic#2

string expression = barcketsList;
Stack<char> stack = new Stack<char>();
char[] symbols = expression.ToCharArray();

A temporary variable expression is not necessary here. In fact, both this and barcketsList is only used once. You can substitute one by the other.
Use var when you can, it makes the variable names aligned thus making scanning easier. The variable name itself or its right-hand side assignment should give enough clue usually, plus you can always mouse-over with intellisense.

for (int start = 0; start < symbols.Count(); start++)
{
    char temp = symbols[start];

Since you are just using the index (start) to get the char, you can use a foreach-loop here

if (stack.Count == 0) //only closer no opening
{
    Console.WriteLine("NO");
    flagPrint = true;
    break;

The use of flagPrint here to escape the default final output is a bit more of a hack. For instance, since you are using stack.Any() to check for balance, you can push the closing bracket and break out of the loop to achieve the same behavior. You can also take an another approach and extract a IsBalanced out of existing code and use return.

if (!stack.Any() && !flagPrint)
{
    Console.WriteLine("YES");
}
else if (!flagPrint)
{
    Console.WriteLine("NO");
}

If we were to keep the flag, this part can be reduced to:

if (!flagPrint)
{
    Console.WriteLine(!stack.Any() ? "YES" : "NO");
}

What is not in the code

IsBalanced is not in a separated method.
Lack of argument checking/error handling

Solution

public void CheckAllExpressionsAreBalanced()
{
    var expressions = new List<string> { "({[]})", "][(]}})(" };
    foreach (var expression in expressions)
    {
        //Console.WriteLine("Expression `{0}` {1} balanced.",
        //    expression,
        //    IsBalanced(expression) ? "is" : "is not");
        Console.WriteLine(IsBalanced(expression) ? "YES" : "NO");
    }
}

// Define other methods and classes here
public bool IsBalanced(string expression)
{
    // argument validation
    if (expression == null)
        throw new ArgumentNullException(nameof(expression));

    // definition
    var brackets = new[] { "()", "{}", "[]" };
    var pairedBrackets = brackets.ToDictionary(x => x[0], x => x[1]);

    // non-bracket characters doesn't affect the result,
    // so we can filter them out to make the flow simpler
    Func<char, bool> isBracket = c => pairedBrackets.ContainsKey(c) || pairedBrackets.ContainsValue(c);

    // implementation
    var stack = new Stack<char>();
    foreach (var c in expression.Where(isBracket))
    {
        var isOpening = pairedBrackets.ContainsKey(c);
        var pair = isOpening
            ? pairedBrackets[c]
            : pairedBrackets.First(x => x.Value == c).Key;

        if (isOpening)
        {
            stack.Push(c);
        }
        else
        {
            // closing bracket with empty stack
            if (!stack.Any())
                return false;

            // closing bracket doesnt match last opening bracket
            if (stack.Peek() != pair)
                return false;

            // matched
            stack.Pop();
        }
    }

    return !stack.Any();
}

EDIT: I skipped the requirements...
EDIT2: Updated IsBalanced to accept non-bracket characters input. As @HenrikHansen points out, it doesn't make sense to throw an exception.
EDIT3: Fixed issue with trailing brackets.


Proper type checking

To start off, you shouldn't be type checking like this:

if type(x) == list:
    ...

The proper way to go is to use Python's isinstance(a, b) function, where a is a value, and b is the type you're checking against. The portion of your code that involves type checking would be re-written like this:

if isinstance(x, list):
    ...

The difference here is that isinstance allows for inheritance when checking the type of a value, rather than simply checking the type of the value itself, which can be rather useful. If you're interested, you can read more about this at this Stackoverflow question.

Nitpicks

You should have the user pass a list of values, not pass a variable amount of arguments. Your function signature should look like this:

def list_contain_sublist(search_for, collection):
    ...

Your names are rather nasty, especially for Python. In Python, variable and function names should be in snake_case, and classes should be in PascalCase. Not the other way around.

There's also no need for the Result variable. You can change this line:

Result = ListContainWSublist(searchfor, *x)

To this:

return ListContainWSublist(searchfor, *x)

This line:

Result = True

Should become:

return True

And then this line:

Result = False

Can be removed all-together.

Other than those things, it looks fine. There may be a way to do this without recursion, but I'm not sure how to. I'll leave that up to you to figure out.


There are a couple of improvements that can be made here:

a) your QUERY_STRING is magic string. Move it to a different place,
because it make your code difficult to maintain
user linked list
instead of array list. It has O(1) on insertion in worst case,
whereas array list has O(n)
do not rethrow exceptions in finally
block. You will lose all details of your original exception
every time when you concatenate strings with "+" you make too many
operations with memory, because strings are immutable. use *.format
instead


From a once over:

Your indentation in ko.extenders.selectList = function (target, params) { should be 4 spaces to make it far more readable
write could use a ternary approach:

write: function (newValue) {
  target( newValue || undefined );
}

This code could use some more/better comment
JSHint could find nothing wrong with it
I am not too excited by seeing all those options as part of the HTML, it just feels wrong. None of the tools work for you in this case ( linting, beautifying, even colored syntax ). I guess that's more a reflection on knockout than on your code.


Cloning Python standard library's function math.frexp() that extracts exponent and mantissa from a floating point number

1. Review

The ctypes module is dangerous (it's possible to crash Python if you get it wrong) and so it should be used as a last resort, when no other facilities will do the job. In this case we could use the struct module instead:

>>> # Reinterpret double-precision float as a 64-bit unsigned integer
>>> struct.unpack('Q', (struct.pack('d', 5478324268.848498)))
(4752538446597034867,)

The code in the post gets at the bits in the representation by converting to a string of 0s and 1s. It would be better to use Python's bitwise operators instead, to avoid converting to a string and back again. Let's start by declaring named constants for the shifts and masks:

# IEEE-754 double-precision floating-point format
SIGN_SHIFT = 63
EXPONENT_SHIFT = 52
EXPONENT_MASK = (1 << 11) - 1
MANTISSA_MASK = (1 << 52) - 1

and then

Q, = struct.unpack('Q', (struct.pack('d', 5478324268.848498)))
sign = Q >> SIGN_SHIFT
biased_exponent = (Q >> EXPONENT_SHIFT) & EXPONENT_MASK
mantissa = Q & MANTISSA_MASK

To assemble the result, normalize the exponent and reverse the disassembly process:

NORMAL_EXPONENT = 1023
R = (sign << SIGN_SHIFT) + (NORMAL_EXPONENT << EXPONENT_SHIFT) + mantissa
normalized, = struct.unpack('d', struct.pack('Q', R))
return normalized, biased_exponent - NORMAL_EXPONENT

(Use 1022 instead of 1023 if you want to match math.frexp exactly.)

2. Revised code

from math import isinf, isnan

# IEEE-754 double-precision floating-point format
SIGN_SHIFT = 63
EXPONENT_SHIFT = 52
EXPONENT_MASK = (1 << 11) - 1
MANTISSA_MASK = (1 << 52) - 1
NORMAL_EXPONENT = 1023

def frexp(x):
    """Return the mantissa and exponent of x, as pair (m, e).
    m is a float and e is an int, such that x = m * 2.**e.
    If x is 0, m and e are both 0.  Else 1.0 <= abs(m) < 2.0.

    """
    x = float(x)
    if x == 0.0 or isinf(x) or isnan(x):
        return x, 0
    Q, = struct.unpack('Q', struct.pack('d', x))
    sign = Q >> SIGN_SHIFT
    biased_exponent = (Q >> EXPONENT_SHIFT) & EXPONENT_MASK
    mantissa = Q & MANTISSA_MASK
    R = (sign << SIGN_SHIFT) + (NORMAL_EXPONENT << EXPONENT_SHIFT) + mantissa
    normalized, = struct.unpack('d', struct.pack('Q', R))
    return normalized, biased_exponent - NORMAL_EXPONENT

(Note that this doesn't get denormals right. I could fix it with some more work, but I think I'd rather just use math.frexp.)

3. Use cases for frexp

frexp is useful when computing mathematical functions, where we need to get the argument into a known range in order to avoid overflow, or to use a particular solution technique. Two examples:

To compute \$\log a\$ we can use frexp to find \$a = m2^e\$ with \${1\over2} \le m < 1\$ and then $$\log a = \log m2^e = \log m + e\log 2$$ and since \$m\$ is close to 1 we can use polynomial approximation (and \$\log 2\$ can be hard-coded).
The geometric mean of \$a_1, a_2, \dots, a_n\$ is \$\sqrt[n]{a_1a_2\dotsb a_n}\$ but the multiplication might overflow the floating-point range. Using frexp we can replace \$a_i\$ by \$m_i2^{e_i}\$ which gives us $$ \eqalign{ \sqrt[n]{a_1a_2\dotsb a_n} &= \sqrt[n]{m_12^{e_1}m_22^{e_2}\dotsb m_n2^{e_n}} \\ &= 2^{(e_1 + e_2 + \dotsb + e_n)/n}\sqrt[n]{m_1m_2\dotsb m_n}} $$ where \${1\over2} \le m_i < 1\$. We can now divide the multiplication into chunks of length 1023 or less, knowing that each chunk can be multiplied and remain in range. We then use frexp on the results of the chunks to extract some more powers of 2, and repeat.

(An alternative approach to computing the geometric mean while keeping the intermediate results in range would be to use logarithms and exponentiation: $$ \sqrt[n]{a_1a_2\dotsb a_n} = \exp\left({\log a_1 + \log a_2 + \dotsb + \log a_n} \over n\right) $$ but computing a logarithm is much more expensive than multiplying.)


Your question

  Does the design of the grid system is compatible with the requirement so far?

Well, maybe I don't understand how setting characters (be them Unicode if necessary, as your example shows) on each tile relates to dividing an image into squares but it seems like you would want to allow the user to upload or choose an image (perhaps from a list), which might likely be a binary file. Then you would need to do some graphical analysis of the image and divide up the area of the image (perhaps using the dimensions).

Feedback on code

Design

It appears that when a Grid object is created, it creates cells as plain objects that have an x, y and tile property. Then when the setTile() method is called, it re-assigns those cells, but the only thing that really changes is the tile, so the calculations of x and y seem unnecessary. Additionally, the tile object doesn't need to be recreated - the shape property could be simply re-assigned - perhaps via a setter method, but that property is public so it could be modified outside the class unless it is made private (though that is only experimental1.

forEach with push

The render() method of the Grid uses foreach with push:

let output = [];
this.cells.forEach(row => {
  output.push(this.renderRow(row));
});

That is essentially the map method re-implemented... Why not use that method?

const output = this.cells.map(row => this.renderRow(row));

Notice that const is used because that value is never re-assigned. This can even be used with the forEach, since calling push() doesn't re-assign the value.

The same principle applies for the renderRow() method.

render method

This method does not return any values, it merely logs output to the console. However, the method is called inside a call to console.log(), which results in undefined being output to the console. Maybe that is not a concern for you if you are the only one using the console (perhaps for debugging purposes) but be aware of this if you intend on primarily using the console for output.

undefined
=> undefined

1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Field_declarations


Here is a solution which is quick and handles all cases - negative number and negative precision. It was adapted from MDN - the main differences are

I pass positive numbers to specify decimal places where it is the opposite on MDN.
I took it out of the prototype and limited it to just the round function (removed ceil and floor)
it is significantly faster

function round(number, precision) {
  number = +number;
  precision = precision ? +precision : 0;
  if (precision == 0) {
    return Math.round(number);
  }
  var sign = 1;
  if (number < 0) {
    sign = -1;
    number = Math.abs(number);
  }

  // Shift
  number = number.toString().split('e');
  number = Math.round(+(number[0] + 'e' + (number[1] ? (+number[1] + precision) : precision)));
  // Shift back
  number = number.toString().split('e');
  return +(number[0] + 'e' + (number[1] ? (+number[1] - precision) : -precision)) * sign;
}

console.log(round(1.0e-5, 5)); // 0.00001
console.log(round(1.0e-20, 20)); // 1e-20
console.log(round(1.0e20, 2)); // 100000000000000000000
console.log(round(1.005, 2)); // 1.01
console.log(round(1234.00000254495, 10)); //1234.000002545
console.log(round(1835.665, 2)); // 1835.67))
console.log(round(-1835.665, 2)); // -1835.67))
console.log(round(1.27499, 2)); // 1.27
console.log(round(1.2345678e+2, 2)); // 123.46
console.log(round(1234.5678, -1)); // 1230
console.log(round(1234.5678, -2)); // 1200
console.log(round(1254.5678, -2)); // 1300
console.log(round(1254, 2)); // 1254
console.log(round("123.55")); // 124


By creating a base class and then inheriting from it, you end up with no duplication and with an architecture that can be easily extended.

I don't think that you should bother having valid? as protected. Calling valid? from outside is a common use case and doesn't violate encapsulation.

class Validator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    message = options.fetch(:message, I18n.t('errors.attributes.name.invalid'))
    record.errors[attribute] << message unless self.valid?(value)
  end

  def self.valid?(value)
    raise NotImplementedError
  end
end

class NameValidator < Validator
  def self.valid?(value)
    value =~ /\A[a-z][\w\p{Blank}]+\z/i
  end
end

class EmailValidator < Validator
  def self.valid?(value)
    value =~ /\A.+@.+\..+\z/i
  end
end


I think you can add functionality to Node to make the common ancestor search more ruby like.  (I can add a search by value later, if you want.)  I've added a parent member that is set automatically, and I've added each_parent and each_child_or_selfenumerators to enable easy traversal up or down the tree.

Note: Thinking about it, the search function needs a little more work in case node 2 is higher in the tree than node 1, but I am out of time right now.  Let me know what you think. Testing indicates that this is not an issue.

class Node
    attr_accessor :value, :parent
    attr_reader :left, :right

    def initialize(value = nil, left = nil, right = nil)
        @parent = nil
        @value = value
        self.left = left
        self.right = right
    end

    def left=(node)
        unless node.nil?
            @left = node
            node.parent = self
        end
        @left
    end

    def right=(node)
        unless node.nil?
            @right = node
            node.parent = self
        end
        @right
    end

    def each_parent
        return enum_for(:each_parent) unless block_given?
        p = @parent
        while not p.nil?
            yield p
            p = p.parent
        end
    end

   def each_child_or_self
       return enum_for(:each_child_or_self) unless block_given?
       stack = [self]
       while not stack.empty?
           current = stack.pop
           stack.push current.left unless current.left.nil?
           stack.push current.right unless current.right.nil?
           yield current
       end
    end
end

The new search functions:

def common_ancestor(node1, node2)
    return nil if node1.nil? || node2.nil?
    return node1 if node1 == node2.parent
    return node2 if node2 == node1.parent
    node1_parents = node1.each_parent.to_a
    node2.each_parent { |p| return p if node1_parents.include? p }
    nil
end

def common_ancestor_by_value(root, value1, value2)
    return nil if root.nil?
    nodes = root
        .each_child_or_self
        .lazy
        .select { |n| n.value == value1 || n.value == value2 }
        .first(2)
    return nil unless nodes.length == 2
    common_ancestor(nodes.first, nodes.last)
end

And a test:

n41 = Node.new("DDD")
n42 = Node.new("EEE")
n43 = Node.new("FFF")
n44 = Node.new("GGG")
n21 = Node.new("BB", n41, n42)
n22 = Node.new("CC", n43, n44)
root = Node.new("A", n21, n22)

puts common_ancestor(n44, n21).value #common ancestor of 'GGG' and 'BB' is 'A'
puts common_ancestor(n21, n44).value #order doesn't matter
puts "---"
puts common_ancestor_by_value(root, "GGG", "BB").value #same applies when searching by value
puts common_ancestor_by_value(root, "BB", "GGG").value

Update 1: Added second enumerator and search function, fixed a bug

Update 2: Added lazy enumeration and profiled code against a tree with 10K nodes.  Searching for nodes with values in the middle, the new lazy code runs about 2.5 times faster than the poster's original implementation.  Also running rubocop, there are no Cyclomatic complexity warnings


Counting the out-of-order elements of an array

Avoid static variables as much as possible.
Instead of static total, you could pass in a pointer to total and make the function modify the value it's pointing to.

The names are not great:

Instead of my_array, start would be better
Instead of endp, end would be better
Instead of chck_high, ... I don't know what would be better, because I don't really see the general logic this function represents. It counts the number of times a new local maximum is found going backwards from the end of the range, and sets the value of total. I'm wondering if this logic is really necessary in this form, or perhaps the overall logic of your program could be redesigned to simpler elements.

Instead of a comment like this:

// this function should only be called if there is at least one value in the array

It would be better to use an assertion:

assert(start < end);

Note that this requires to #include <assert.h>

This maybe a matter of taste, but I would find a for loop would be more natural for this instead of while. Using a for loop, in C99 and above, you could declare the loop variable inside the for, which would have extra benefits:

It would help you limit variables in the smallest scope necessary (inside the loop)
It would force you to use a new local variable for looping, instead of reusing the function parameter, which is a good thing

Putting it together, the function would become:

int chck_high(int *start, int *end, int *total) {
    assert(start < end);

    int maximum = *--end;

    for (int * pos = end; pos > start; --pos) {
        int a = *pos;
        if ( a > maximum ) {
            ++*total;
            maximum = a;
        }
    }

    return maximum;
}

To enable C99 mode when compiling with gcc, use the -std=c99 flag.

You can use the function like this, for example:

int main() {
    int arr[] = {1, 2, 51, 41, 4, 5};
    int total = 1;
    int maximum = chck_high(&arr[0], &arr[0] + 6, &total);
    printf("total=%d max=%d\n", total, maximum);
}


OOP implementation of in-memory file system

I'd say Root is a misnomer here, since at first glance I imagined it to represent the filesystem root (i.e. the / directory), not the root of your class tree. Moreover, instead of deriving File and Directory from a common (abstract) ancestor, I'd derive Directory from File instead, since that's what most real filesystems do anyway, i.e. they treat directories as special files.

size should not be a writable property; the File object should always calculate it based on its content. This can ensure there's no discrepancy between the stored size and the actual size of the file's content. Also, why doesn't Directory have a getSize() method? It could just call getSize() on all its children and add up the results.

You have a writable attribute on your objects, but you don't seem to be using it, e.g. in setName() you just replace the name of the object without checking if it's writable. Similarly, you have a parent argument in the constructor, but you don't use it; I'd expect the File to call addContent() on its parent automatically if the parent is specified in the constructor.

As for further features, I'd recommend making your Directory class iterable (so it can be used in for loops), as well as implementing the most common collection methods, such as forEach, has, length (i.e. the number of files in the directory), etc., instead of just exposing the array of children.