Transforming from spherical coordinates to Cartesian coordinates using Eigen

There's not really much to review here. While I have some experience with Eigen, I have no idea what SSPL is. I'm going to assume SSPL:MatrixX is basically Eigen::Matrix3Xf.

const int size = 1000;

This should probably use constexpr rather than const.

for(int i=0; i<direction.size();i++)

It's been a while since I've used Eigen, but I believe you have a bug in this for prologue. If I recall, the return type of size() for Array types is not int. I think it is actually std::ptrdiff_t (or possibly std::size_t), but it's user-customizable. If it is std::ptrdiff_t (for example), and std::ptrdiff_t is larger than int (as it is on some platforms, I think including 64-bit Windows), then you will get UB if the values get cut off.

The way to fix this is to use decltype:

for (decltype(direction.size()) i = 0; i < direction.size(); ++i)

Now the first loop is just generating test data, so let's skip down to the next loop.

const T1 azimuthAngle = direction(i).first*M_PI/180;    //converting to radians

What's infinitely better than:

auto y = /* expression with x */; // convert x to foo

is:

auto y = convert_to_foo(x);

In other words, since you're converting to radians, you should have:

constexpr auto to_radians(float v) noexcept
{
    return (v * pi<float>) / 180.0f;
}

Now, in addition, M_PI is not actually portable. If you don't care, fine, but if you care about portability, you can define a π constant either as:

constexpr auto pi = 3.14159265358979f;

or, better, as:

template <typename T>
constexpr auto pi = T(3.14159265358979L); // add as many digits of precision as you please

in which case you can even make the conversion function a template:

template <typename T>
// possibly constrain T
constexpr auto to_radians(T const& v) noexcept((v * pi<T>) / T(180))
{
    return (v * pi<T>) / T(180);
}

Any way you do it, you should end up with:

const T1 azimuthAngle = to_radians(direction(i).first);
const T1 elevationAngle = to_radians(direction(i).second);

Now in the next few lines you need the sin and cos of the azimuth and elevation. You might as well precalculate them - especially since you reuse some of them:

auto const cos_azimuth = std::cos(azimuthAngle);
auto const sin_azimuth = std::sin(azimuthAngle);
auto const cos_elevation = std::cos(elevationAngle);
auto const sin_elevation = std::sin(elevationAngle);

transformedMatrix(0,i) = cos_azimuth * cos_elevation;
transformedMatrix(1,i) = sin_azimuth * cos_elevation;
transformedMatrix(2,i) = sin_elevation;

But transforming coordinate systems seems both like something you can reuse and - more importantly - something you can test in isolation. So this should be a function:

template <typename Pair>
auto spherical_to_cartesian(Pair const& spherical)
{
    const auto azimuthAngle = to_radians(std::get<0>(spherical));
    const auto elevationAngle = to_radians(std::get<1>(spherical));

    auto const cos_azimuth = std::cos(azimuthAngle);
    auto const sin_azimuth = std::sin(azimuthAngle);
    auto const cos_elevation = std::cos(elevationAngle);
    auto const sin_elevation = std::sin(elevationAngle);

    return std::tuple{cos_azimuth * cos_elevation, sin_azimuth * cos_elevation, sin_elevation};
}

Which makes your loop:

for (decltype(transformedMatrix.cols()) i = 0; i < transformedMatrix.cols(); ++i)
{
    std::tie(
            transformedMatrix(0, i),
            transformedMatrix(1, i),
            transformedMatrix(2, i))
        = spherical_to_cartesian(direction(i));
}

Now, if you're asking about how to do geometric transforms with Eigen, that seems more like a Stack Overflow question. As for vectorization, that depends on what SSPL::MatrixX is. But the loop above can be very easily parallelized, because each transform is independent. As for how, the standard way would require that Eigen::Array and SSPL::MatrixX could be used with standard algorithms, in which case the answer would simply be:

// Hypothetical code.
std::transform(std::par_unseq, begin(direction), end(direction), begin(transformedMatrix), spherical_to_cartesian);

Or you could look into OpenMP and parallel for.


Wrap array operation result string inside another string

Use JavaScript's array methods to your advantage and solve you problem the functional way:

const generate_list_data_attribute = (attribute_name, from_array) => {
  const string = from_array.map(element => `"${element}"`).join(",")
  return `data-${attribute_name}="[${string}]"`
}


Implementing faster StringBuilder that only works with ASCII strings

This is very, very buggy. This is the most reliable way I could find to reproduce the bug.

static void Main(string[] args)
{
    var sb = new FastStringBuilder();
    var chars = new[] { 'a', 'b', 'e', 'd' };
    sb.Append(new string(chars));
    Console.WriteLine(sb.ToString());
}

Note how args is not used. Now run the program with different arguments:

$ ./Test
dfhj
$ ./Test abc
OZ?'
$ ./Test abcdef
"-~s


An Angular service to provide window and document objects

Assuming you want a SOLID code and keep the single responsibility principle, you would need to inject window and document separately.
A clean way is to provide each of them using the useValue property of your provider:

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [
   { provide: "windowObject", useValue: window}
  ]
})

as already answered on SO:
same stuff for the document provider.


Static utility functions to turn arrays into SQL statements

It's not so much about the state than it is about coupling. When you test a method, you want to control its dependencies; when the method under test calls a static method, you can't control that dependency and thus, the method under test is coupled with the implementation of that static method, so you might as well consider that static method inlined into the method under test, as far as testing goes.

So, you've called this class Utility. Like the Helpers and Managers of this world, a class called Utility is pretty much an incentive to become a dumping ground for just about anything that's, well, a "utility". Name things after what they're responsible for, and thank yourself later: in this case, a SqlStatementBuilderUtility would make it much clearer what the intent is, and then the class would be much less prone to grow some bubbleSort or sendMail "utility" members in the future.

Side note, the indentation is off; it's like the class-level scope doesn't exist, the class and its members are all at the same indentation level, and that doesn't look right.

I don't think static is the main concern here - indeed, these methods look like good candidates for being static. The problem is what they're being used for. It looks like it's building SQL statements out of whatever values are thrown at it, which obfuscates the actual queries your application is sending to the database server, and raises a flag about sql-injection.


Recursively displaying json data on website

Your code is a pain to read, please add early returns.
To go with the point above, please follow PSR-12.
iterative tables side by side. Your code creates another table within a , so it's no exactly side by side.

Here is how I refactored your code:

I completed step 1 and 2.
I have broken everything up into methods:

<?php

namespace App;

class DisplayArrayTable
{
    protected $result = '';

    /**
     * @param mixed $value
     */
    protected function setupMeaningFullName1(string $key, $data): void
    {
        $this->result .= "
{$key}: 	";

        if (!is_array($data)) {
            $this->result .= "{$data}
";

            return;
        }

        $this->result .= "
";

        foreach ($data as $key => $value) {
            $this->setupMeaningFullName2($key, $value);
        }

        $this->result .= "
";
    }

    /**
     * @param mixed $value
     */
    protected function setupMeaningFullName2(string $key, $data): void
    {
        $this->result .= "
{$key}: 	";

        if (!is_array($data)) {
            $this->result .= "{$data}
";

            return;
        }

        $this->result .= "
";

        foreach ($data as $key => $value) {
            $this->setupMeaningFullName2($key, $value);
        }

        $this->result .= "
";
    }

    /**
     * @param mixed $value
     */
    protected function setupMeaningFullName3(string $key, $data): void
    {
        $this->result .= "
{$key}: 	";

        if (!is_array($data)) {
            $this->result .= "{$data}
";

            return;
        }

        $this->result .= "
";
    }

    public function handle(array $data): string
    {
        foreach ($data as $key => $value) {
            $this->setupMeaningFullName1($key, $value);
        }

        return "
{$this->result}
";
    }
}

I have identified the pattern and further refactored your code

<?php

namespace App;

class DisplayArrayTable
{
    const MAX_ITERATIONS = 3;
    protected $currentIteration = 1;
    protected $result = '';

    /**
     * @param mixed $value
     */
    protected function iteration(string $key, $data): void
    {
        $this->result .= "
{$key}: 	";

        if (!is_array($data)) {
            $this->result .= "{$data}
";

            return;
        }

        if ($this->currentIteration === static::MAX_ITERATIONS) {
            $this->result .= '
';

            return;
        }

        $this->result .= '
';

        foreach ($data as $key => $value) {
            $this->currentIteration++;

            $this->setupMeaningFullName2($key, $value);
        }

        $this->result .= '
';
    }

    public function handle(array $data): string
    {
        foreach ($data as $key => $value) {
            $this->iteration($key, $value);
        }

        return "
{$this->result}
";
    }
}

Performed further refactoring to improve iteration method

<?php

namespace App;

class DisplayArrayTable
{
    const MAX_ITERATIONS = 3;
    protected $currentIteration = 1;
    protected $result = '';

    public function handle(array $data): string
    {
        foreach ($data as $key => $value) {
            $this->iteration($key, $value);
        }

        return "
{$this->result}
";
    }

    /**
     * @param mixed $value
     */
    protected function iteration(string $key, $data): void
    {
        $this->result .= "

            {$key}:
            ";

        if (!is_array($data)) {
            $this->result .= "{$data}
";

            return;
        }

        if ($this->currentIteration === static::MAX_ITERATIONS) {
            $this->result .= '
';

            return;
        }

        $this->setupNewTable($data);
    }

    protected function setupNewTable(array $data): void
    {
        $this->result .= '
';

        foreach ($data as $key => $value) {
            $this->currentIteration++;

            $this->iteration($key, $value);
        }

        $this->result .= '
';
    }
}

So, all you need to do now is call this call and pass in a valid array
use App\DisplayArrayTable;

...

$dataArray = json_decode($data, true);

if ($dataArray && is_array($dataArray)) {
   $html = (new DisplayArrayTable)->handle($dataArray);
}


Pass canvas content from client to admin using web socket

The biggest bottleneck here is the fact that your read and emit are hooked to a mouseMove. Even the slightest movement will cause a lot of reads, as well as flood your server. The next problem would be canvas size. The larger the canvas, the longer reading operations will take and the bigger the transfer will be. And of course, you have network latency which you really can't avoid.

You can debounce. If you happen to use Lodash, there's a debounce function you can use to execute only until a certain period has elapsed since last call. That way, you won't be flooding operations. The side effect is that it's not "live" as it will only transmit if the client pauses. But half a second isn't that bad of a pause though.


I choose to focus on the Single Responsibility Principle in this answer.
To move closer to the Single Responsibility Principle, I think some of the functionality needs to be moved around. I have decomposed the class and removed all state that is shared on the class (rhetorical question: is the class responsible for state or functionality? If it is "both", then surely that violates SRP?!). Shared state like this can get tough to reason about and lead to an ever-larger class as the functionality evolves over time.
How about a scraper object, with one method run that accepts a URL and returns the result for a URL (and its sub-URLs)?
Usage:
import scraper from './scraper.js'

const { emails: { valid, dangerous }, links: { internal } } = await scraper.run('http://www.example.com')

We configure a result object which we then pass around to populate, before it is returned:
const scraper = {
    async run(url) {
        const result = {
            emails: { valid: [], dangerous: [] },
            links: { internal: [] }
        }
        return scrape(url, result)
    }
}

We define a scrape function, responsible for coordinating the scraping of a URL:
async function scrape(url, result, visited=new Set()) {
    if (visited.has(url)) {
        return result
    }

    visited.add(url)
    const dom = await fetchDom(url)
    const internalLinks = findInternalLinks(dom)
    const { valid, dangerous } = validateEmails(findEmails(dom))

    for (let link of internalLinks) {
        await scrape(link, result, visited)
    }

    result.links.internal.push(...internalLinks)
    result.emails.valid.push(...valid)
    result.emails.dangerous.push(...dangerous)

    return result
}

Function fetchDOM is responsible for retrieving the DOM from the network for a URL:
async function fetchDOM(url) {
    try {
        const { status, data } = await axios(url)
        switch (status) {
            case 200:
                return new JSDOM(await data)
            case 404:
                console.log('this page doesnt exists')
                return process.exit(1)
        }
    } catch (error) {
        console.log(error)
        return process.exit(1)
    }
}

findInternalLinks is responsible for returning an array of internal links, found within the supplied DOM:
function findInternalLinks({ window: { document: body } }) {
    let links = body.querySelectorAll('a[href^="/"]')
    return Array.from(links).map(link=>link.getAttribute('href'))
}

findEmails is responsible for returning the an array of emails, found within the supplied DOM:
const EMAIL_REGEX = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi

function findEmails({ window: { document: { body: { innerHTML: html } } }) {
    return html.toString().match(EMAIL_REGEX)
}

validateEmails splits an array of emails into two sets: valid and dangerous:
const DANGEROUS_DOMAINS = ['loan', 'work', 'biz', 'racing', 'ooo', 'life', 'ltd', 'png']

function validateEmails(emails) {
    const dangerous = []
    const valid = Array.from(emails).filter(email=>{
        let domainName = email.split('@')[1].split('.')[1]
        if (DANGEROUS_DOMAINS.includes(domainName)) {
            dangerous.add(email)
            return false
        } else
            return true
        })
    return { valid, dangerous }
}

The writing of a file is a wholly separate responsibility. Perhaps create an emailFileWriter object to encapsulate it:
const emailFileWriter = {
    write(emails) {
        return new Promise((resolve,reject)=>{
            fs.writeFile('./emails.txt', emails, err=>{
                if (err) {
                    reject('Could not write file')
                }
                resolve('success')
            })
        })
    }
}

I would put each of these functions and objects in a separate file. Each has its own responsibility after all.


Selecting filter checkboxes using Selenium

The method appears to have some pointless operations.

You loop over a List<WebElement>, to build a Map<String, WebElement>, where the key of the map is the text in a WebElement in the list.
But you use only one key in the map, the String filter parameter received by the method. As such, you don't need a map at all.

This implementation is (almost) equivalent:

public void selectFilter(String filter) {
    List<WebElement> filters = driver.findElements(selector.someWebElement());
    WebElement value = null;
    for (int i = 0; i < filters.size(); i++) {
        String key = filters.get(i).getText();
        if (key.equals(filter)) {
            value = filters.get(i).findElement(By.cssSelector("a"));
        }
    }
    if (value != null) {
        value.click();
    }
}

I say almost equivalent, because I added a missed null-check.

To further improve the performance, it would be better to refine this call:

    List<WebElement> filters = driver.findElements(selector.someWebElement());

As apparently it fetches many elements that don't match the String filter parameter of the method.


Most of your variable names seem good, however xy explains nothing.

You should normally have two space's around operators.
b = b + result[x] is more readable than b=b+result[x],
which looks at a glance like a variable.

Why do you need to import numpy to do a simple mod?
Python comes with mod, %.

You use the word result,
which I would use to imply that that will be the result of a function.

You shouldn't import things anywhere apart from the beginning of the file.
I nor anyone else wants to traverse you entire program to find that you import numpy's mod.
We want to know at the begging you use it.
Also this can lead to bugs where you think you have imported numpy, but you haven't.

Your programs overall ability to be read with ease is quite low.

I would recommend splitting the function into two.
A 'feeder' and a 'consumer'.

First I love generators, and you can write one that reduces the complexity of this program.

The algorithm that I use is to find the start and stops of the split.
Then I replace start with stop and add a random amount to the stop.
It really is that simple. To do the majority of your program.

def get_numbers(length):
    start, stop = 0, 0
    while stop < length:
        start, stop = stop, stop + random.randint(1, length)
        yield start, stop

This is simple, it will count until it gets to or past the length, and will return them.
You can think of it like building an array that looks like [(start, stop), (start, stop), ...].

This is a near drop in replacement for the entire program until for i in points:.
However I use a lazy approach for that for loop.
Where yours is a one dimensional list of index.

If you wanted it to build an array instead then it would look like the following block.
However it's not advised, as it will lead to bad memory usage, and it will take slightly longer.

def get_numbers(length):
    list_ = []
    start, stop = 0, 0
    while stop < length:
        start, stop = stop, stop + random_int(length)
        list_.append((start, stop))
    return list_

Then you can now split the string.
To do this I will loop through the above generator and yield split strings.

def random_multisplitter(word):
    for start, stop in get_numbers(len(word)):
        yield word[start:stop]

I use Python's amazing split operation just like you did.
However as you want random_multisplitter to return a list, not a generator.
You will change it.
But a generator is a better choice for the 100k words input.
This is as then you will have a smaller memory consumption.

def random_multisplitter(word):
    return [word[start:stop] for start, stop in get_numbers(len(word))]

If not faster, it will at least be smaller and nicer to look at.

I thought that the program would be larger, and so, a small one function version would be:

from random import randint

def random_multisplitter(word):
    length = len(word)
    start, stop = 0, 0
    while stop < length:
        start, stop = stop, stop + randint(1, length)
        yield word[start:stop]

# Generator
random_multisplitter('runtime')
# List
list(random_multisplitter('runtime'))

Some people may dislike that I allow the slice to go above the maximum length of the list. Just to avoid any potential confusion about that, it's safe to use, but can seem weird.

>>> 'abcde'[0:20]
'abcde'
>>> 'abcde'[20]
IndexError: string index out of range

Due to this you may wish to change the assignment of stop to the following:

start, stop = stop, randint(stop + 1, length)

Or when you are returing the values change it to:

yield start, min(stop, length)

The former will have a higher amount of splits to the end of the string. Where as the unmodified version and latter version will prominently have two or three main splits on small strings.

As this is tagged performance, It's probably best if we have a speed test.
The code I use to test the speed is:

word = ' ' * 100000

def time_it(fn, name):
    n = 100
    t0 = time.time()
    for _ in range(n):
        fn(word)
    t1 = time.time()
    print name, '=', t1-t0

This uses time and so just take the results with a bit of salt.

Also, I can't test your original code.
random_int is not defined in the example.

And finally I used start, stop = stop, stop + random.randint(1, 2) On the 'Slow' ones, and start, stop = stop, stop + random.randint(1, length) on the 'Fast' ones.

Other Answer = 75.2860000134
Slow Generator = 12.1919999123
Slow List = 13.236000061
Fast Generator = 0.00200009346008
Fast List = 0.0019998550415

Keep in mind that Generators perform better when they aren't converted to a list straight off the bat.


How to separate data from logic when serializing types - grid tile map example

I have been experimenting and found this solution to be the best:

[Serializable]
public class Tile
{
    [field: NonSerialized]
    public event EventHandler<TileTypeChangedEventArgs> TileTypeChanged;

    [NonSerialized]
    public const TileType defaultType = TileType.Empty;

    public TileType type
    {
        get { return _type; }
        set
        {
            if (Enum.IsDefined(typeof(TileType), value) == false)
                throw new InvalidOperationException("Trying to set undefined tile type.");

            if (value != _type)
            {
                _type = value;
                var args = new TileTypeChangedEventArgs(_type);
                OnTileTypeChanged(args);
            }
        }
    }

    public int x { get; private set; }
    public int z { get; private set; }

    TileType _type;

    public Tile() { }

    public Tile(int x, int z, TileType type = Tile.defaultType)
    {
        this.x = x;
        this.z = z;
        this.type = type;
    }

    public Tile(Tile original)
    {
        this.x = original.x;
        this.z = original.z;
        this.type = original.type;
    }

    public override string ToString()
    {
        return string.Format("Tile: {0}|{1} = {2}", x, z, type);
    }

    protected virtual void OnTileTypeChanged(TileTypeChangedEventArgs e)
    {
        var handler = TileTypeChanged;
        if (handler != null)
            handler.Invoke(this, e);
    }
}

public class TileTypeChangedEventArgs : EventArgs
{
    public TileType type { get; private set; }

    public TileTypeChangedEventArgs(TileType type)
    {
        this.type = type;
    }
}

public enum TileType
{
    Empty,
    Grass,
    Water,
    Dirt
}

The problematic point was the accidental serialization of the event. I didn't know about the [field: NonSerialized] attribute for properties, but this works very well for the BinaryFormatter, XmlSerializer and Json.Net. I also had to add a little bit of ContractResolver logic for the later to deserialize private properties, but I found it much cleaner than having to supply more attributes in my data classes.

Another thing to note is the use of a copy constructor in the Tile class as well as in the Map which holds an array of tiles. When writing data to disk I copy everything before saving to avoid problems when I save on another thread while my users change the current map instance.

I'd still be happy to read any suggestions about how to improve my class design.


C++ smart pointers and the Service Locator (anti-?)pattern

Note that the "old" version should store the logger in a std::unique_ptr in main, rather than explicitly calling new and delete.

The simplest possible thing would be something like this:

struct Services // previously `Engine`
{
    Logger logger;
};

int main()
{
    {
        Services services;
        services.logger.log("yep");
    }

    //services.logger.log("nope"); // obviously doesn't compile
}

To use the logger "somewhere else" we can pass it into an object constructor by reference, (or pass the entire Services object by reference):

struct Object
{
    explicit Object(Logger& logger):
        logger(&logger) { }

private:

    Logger* logger;
};

If necessary, the object can store the logger (or Services) by reference (which has the side-effect of preventing us defining assignment operators for Object as we can't re-assign a reference), or by pointer (which allows us to define assignment operators, but can also be reassigned to a nullptr (for better or worse)).

Either way, we still depend on the lifetime of the Logger being longer than the lifetime of the Object. With C++, this is usually enforced simply by the implicit order of destruction of stack objects (and any child objects they contain), e.g.:

{
    Services services;
    Object object(services.logger);

} // destruction in reverse order: first object, then services.

It might seem like we can use std::shared_ptr and std::weak_ptr to enforce the above constraint (longer service lifetime), but it adds overhead and complexity, and can lead to more serious issues. When we promote a weak_ptr to a shared_ptr, the new shared_ptr also "owns" the service. So the lifetime is no longer defined by Services, but by the service user as well.

If we enforce the Object lifetime constraint properly ourselves, we don't need this. If we don't enforce that constraint, then the exact moment of a service being destroyed becomes very difficult to determine, which leads to similar problems as with Singleton objects.

This article has some more arguments against using std::shared_ptr, and points out that what we actually need is some sort of checked pointer or borrowed reference for debugging. Unfortunately, this doesn't exist in the C++ standard library.

Note that if it's actually necessary to swap out, or destroy a service part-way through use, we can't store any pointer or reference to the service. It must be fetched from Services every time it's accessed. This is probably quite difficult to enforce though.

In short:

Avoid using this pattern if possible.
Pass dependencies by reference in constructors (or other functions).
Ensure that lifetimes are well-defined and easy to understand (i.e. avoid std::shared_ptr).
Ensure that the lifetime of the Engine / Services exceeds the lifetime of anything that uses them.
Don't move or copy the individual services, or the Services class.

And to answer your questions:

Yes.
Allowing direct access to the service member, returning a raw pointer from an accessor function, or returning a reference from an accessor function are all reasonable options. The first is simplest unless you have some other constraints (enforcing access through an interface, or enforcing const correctness).
I'd argue not (see above).


Finding the common iterator category in C++

If you have a typelist of iterator tag types, then std::common_type will find the common base type.

using InTag = std::istream_iterator<int>::iterator_category;
using BdTag = std::list<int>::iterator::iterator_category;
using RaTag = std::vector<int>::iterator::iterator_category;

static_assert(std::is_same_v<std::common_type_t<InTag, BdTag>, std::input_iterator_tag>);
static_assert(std::is_same_v<std::common_type_t<InTag, RaTag>, std::input_iterator_tag>);
static_assert(std::is_same_v<std::common_type_t<BdTag, RaTag>, std::bidirectional_iterator_tag>);

If you are unwrapping the tag type at the call site, just have the trait do it.

template <class... Iterators>
struct common_iterator_tag
: std::common_type<typename std::iterator_traits<Iterators>::iterator_category...>
{
};

template <class... Iterators>
using common_iterator_tag_t = typename common_iterator_tag<Iterators...>::type;

using RaIter = std::vector<int>::iterator;
using InIter = std::istream_iterator<int>::iterator;

static_assert(std::is_same_v<std::input_iterator_tag, common_iterator_tag_t<RaIter, InIter>>);

using BackIter = std::back_insert_iterator<std::vector<int>>;
using InsertIter = std::insert_iterator<std::list<int>>;

static_assert(std::is_same_v<std::output_iterator_tag, common_iterator_tag_t<BackIter, InsertIter>>);


Convert a numeric string to number but without python's built in function

Doctstrings

The docstring:

"""
Convert numeric string to number withoutusing python's built in functions.
"""

Should be at the top of the inside of the function.

(Also withoutusing should be without using.)

Global Variables

Global variables are typically a bad design practice. Move these:

dec_places = {6:100000, 5:10000, 4:1000, 3:100, 2:10, 1:1}
char_digit = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5,  '6':6, '7':7, '8':8,  '9':9}

Inside the function.

Function naming

str2int should be renamed to str_to_int.

Better algorithm

dec_places is unneeded and limits your algorithm significantly.

I would enumerate over the reversed of your string:

for ind, char in enumerate(reversed(num_str)):
    number += char_digit[char] * 10**(ind + 1)

enumerate takes an iterable and creates tuples of (0, el1), (1, el2) ....

We reverse the string and then multiply each character by the appropriate power of 10. This allows you to go beyond the 6th power.

Alternatively, you can keep an iter value that counts up from 1. I'll leave this as an exercise. It might be faster than using reversed. You should not need a dictionary though.


Two java classes with different annotation values only

You can parameterize the @path annotation with regular expressions to specify one class/method that accepts multiple paths

@Path("/{firstpath: first|second}/{param}") // will match /first/{param} and /second/{param}
public class First {

    @GET
    @Path("/{data}{p:/?}{difference:(\w*)}") // {p:/?} makes "/" optional, {difference:(\w*)} allows for optional text
    public Response doStuff(
            @Context HttpServletRequest request,
            @Context UriInfo uri,
            @Context HttpHeaders httpHeaders,
            @PathParam("param") String param,
            @PathParam("data") String data
    ) {

        // whatever
        return new Response();

    }

}


Optimizations/improvements:

Namings

write is too generic name for specific function. The one of better names is write_points
_2d. Even if a variable is marked as "protected" _..., starting its name with a digit is a bad naming pattern. As it's a boolean flag a meaningful name would be is_2dim (is 2-dimensional space)

Since mesh argument is only used to access its inner property points it's better to pass the target points data structure directly (It's called Replace Query with Parameter technique)

In current approach, when reaching the condition if not _2d: the expression np.unique(points[:, 2]).size will be calculated repeatedly, instead:
since points array is expected to be 2d array with either 2 or 3 columns we can collect unique counts across all columns at once (instead of declaring imax, jmax):

col_counts = [np.unique(row).size for row in points.T]

The whole conditional:

_2d = False
if points.shape[1] == 2:
    _2d = True
elif np.unique(points[:, 2]).size == 1:
    _2d = True

is now replaced with a single statement:

is_2dim = points.shape[1] == 2 or col_counts[2] == 1

Calling print function at each iteration to write the data into file:

for value in points.flatten(order="F"):
    print(value, file=p3dfile)

is definitely less efficient and performant than calling writelines() on generator expression at once.

The final optimized function:

def write_points(filename, points):
    """
    Write the mesh points to filename in PLOT3D format.
    filename: is the name of the output file.
    mesh: is a numpy array of size (N,2) or (N, 3) where N is the number of points. mesh[i] is a numpy array coordinates of the i'th point.

    """
    col_counts = [np.unique(row).size for row in points.T]
    is_2dim = points.shape[1] == 2 or col_counts[2] == 1

    with open(filename, "w") as p3dfile:
        pd3file.write(' '.join(map(str, col_counts)))
        pd3file.writelines(f'{num}\n' for num in points.flatten(order="F"))


Avoid single letter variable names. Spell out the words they stand for to make your code easier to read.

Your comments are useless. You are just restating the code in less detail. The only comment you should have is explaining about the '=' like you did in your post.

Don't double-space your code.

Pickle isn't safe. You can construct a pickle that does arbitrary things like delete files or what-not. So you should pretty much never be sending them over a socket.


Matrix OOP implementation using C++11 and C++14

Lets start from the usage:

It is not possible to write range loops with the current version
no rowcount() and columncount() (or anything similar). So it is not possible to actually traverse matrix
operator[]() won't work on const objects, since there is no operator[](std::size_t index) const.

Clarity and cleanliness:

nuke pimpl. I'm serious, it doesn't add much benefit here. In fact, the compilation might be increased by pimpl, since matrix is very lightweight anyway.
#include <iostream> header is not needed, should be removed.
double indirection. _impl should actually be MatrixRow. But if pimpl is gonna get nuked, it will be embedded into matrix itself.
std::vector<> would be much better fit here.

Nitpicks:
destructor is generated for you automatically. defaulting it is redundant.

Some general guidelines:

OOP is usually mixed with some functional programming in C++. For example, templates.
C++ code usually tries to provide some default behavior that is correct and safe, and some access to underlying implementation that when accessed lets programmer to take all of the control to himself (literally everything).

Recommendation for next iteration:

I think that std::vector<T> will be the best fit here. Calculating the index to jump at should be pretty easy (it is what compiler does for us anyway). I think it will be okay to return T* from operator[](), because users know they shouldn't mess with it, but making some small struct would good as well. Something like std::array_view<T> would be nice (though it seems like it is not in the standard yet, even in C++17). Also, you get iterators for free with vector approach.

Just write:

auto begin()
{
    return storage.begin();
}

auto end()
{
    return storage.end();
}

As a result, you get range loop for free as well.


Merge two sorted linked lists without recursion

You're duplicating the code to copy and merge nodes four times - that can't be good. You could move that into a separate function, but that might become messy because of all the state that has to be changed.

An alternative is to rethink your loop a bit. This idea is to loop while either A or B still have elements to avoid the two other whiles in your code. The internal logic can then be simplified to something like:

while ((currentA != nullptr) || (currentB != nullptr)) {
  int next_item;
  if (currentA == nullptr) {
    // A is empty, pick from B
    next_item = currentB->item;
    currentB = currentB->next;
  } else if (currentB == nullptr) {
    // B is empty, pick from A
    next_item = currentA->item;
    currentA = currentA->next;
  } else if (currentA->item < currentB->item) {
    next_item = currentA->item;
    currentA = currentA->next;
  } else {
    next_item = currentB->item;
    currentB = currentB->next;
  }
  // append to list C
}

Still some duplication, but at least it's just two-line blocks without any logic (and no memory allocations).

Also this should be simplified:

Node* node = new Node();
node->item = currentB->item;
node->next = NULL;

Provide a constructor for your node class:

explicit Node(int item) : item{item}, next{nullptr} {} // >= C++11
explicit Node(int item) : item(item), next(NULL) {}    // old C++

(Add a destructor while you're at it, or use smart pointers to avoid leaks.)

Then you can write:

Node* node = new Node(next_item);
if (headC == nullptr) { // or if (!head) { ... }
    headC = node;
} else {
    currentC->next = node;
}
currentC = node;

Last point: make sure you actually need to duplicate the elements. You could avoid all the allocations by re-using the nodes, if the input lists can be trashed (which is usually the case for a merge sort).


Showing/hiding a box containing a Facebook profile

From a once over,

You have far more than a few words that are copy pasted, you could extract all the common statements into a common function:

function transitionDataDone( data ){
    $("div#facebook div.wrapper > img:first-child").attr("src", "http://graph.facebook.com/"+data.id+"/picture?type=normal");
    $("div#facebook h3").html("Facebook account of "+data.name+"");
    $("div#facebook div#heading a").attr("href", "http://www.facebook.com/"+data.username);
    $("div#facebook tr:first-child td:first-child b").text(data.id);
    $("div#facebook tr:first-child+tr td:first-child b").text(data.first_name);
    $("div#facebook tr:first-child+tr+tr td:first-child b").text(data.last_name);
    $("div#facebook tr:first-child td:first-child+td b").text(data.gender.charAt(0).toUpperCase() + data.gender.slice(1));
    $("div#facebook tr:first-child+tr td:first-child+td b").text(data.locale);
    $("div#facebook tr:first-child+tr+tr td:first-child+td b").text(data.username);
}

Once you have done that, you will notice that you are not repeating too many jQuery selectors. The only one that stands out to me is $("div#facebook div#notice"); If you cache this selector and apply the previous code, you get something like this (not tested, but you should get the gist):

function transitionData(data) {
    var $divNotice = $("div#facebook div#notice");
    if($divNotice.is(":visible")) {
        $("div#facebook div#heading *").fadeOut();
        $divNotice.animate({"opacity":"0"}, function() {
            transitionDataDone( data )
            $divNotice.slideUp();
            $("div#facebook div.wrapper").slideDown();
            $("div#facebook div#heading *").fadeIn();
        });
    } else {
        $("div#facebook div#heading *, div#facebook div.wrapper").fadeOut(function() {
            transitionDataDone( data );
            $("div#facebook div#heading *, div#facebook div.wrapper").fadeIn();
        });
    }
}

function transitionDataDone( data ){
    $("div#facebook div.wrapper > img:first-child").attr("src", "http://graph.facebook.com/"+data.id+"/picture?type=normal");
    $("div#facebook h3").html("Facebook account of "+data.name+"");
    $("div#facebook div#heading a").attr("href", "http://www.facebook.com/"+data.username);
    $("div#facebook tr:first-child td:first-child b").text(data.id);
    $("div#facebook tr:first-child+tr td:first-child b").text(data.first_name);
    $("div#facebook tr:first-child+tr+tr td:first-child b").text(data.last_name);
    $("div#facebook tr:first-child td:first-child+td b").text(data.gender.charAt(0).toUpperCase() + data.gender.slice(1));
    $("div#facebook tr:first-child+tr td:first-child+td b").text(data.locale);
    $("div#facebook tr:first-child+tr+tr td:first-child+td b").text(data.username);
}

Finally, I must say, your approach is terrible. Your elements should have unique id's ( first_name, username etc. etc. ), the way you select elements now is a maintenance nightmare. Re-ordering the elements means re-writing the JavaScript code!


If you are driven to get the absolute best performance, there are a number of things I would change. These changes will not necessarily improve the readability, but the performance will be best.

First up, creating a new Random() each time is going to slow you down. This may well be about half of your time, in fact. I recommend a static version if you can be sure you won't have threading issues, or alternatively I would recommend a ThreadLocal. In general a ThreadLocal is the better option because even though Random is thread-safe, you don't want contention when it locks one thread against another.

The second thing is "Why use a List?". Seriously, it's overkill. Use a primitive array, and preferably use char.....

String concatenation is slow, so the number += digits.get(randomDigit); is essentially the same as:

StringBuilder sb = new StringBuilder(number);
sb.append(String.valueOf(digits.get(randomDigit));
number = sb.toString();

If you insist on using String concatenation then you would be better off using:

StringBuilder sb = new StringBuilder(10);
for (...) {
    ...
    sb.append(digits.get(randomDigit));
    ...
}
return sb.toString();

Finally, when there is just one member left in the array there is no need to do the random lookup (it will always return 0), so you can just use 1 as the limit of your loop and simply append the last remaining Integer from your List.

Taking the above things in to consideration, I would recommend the following (which has a couple of other differences that I 'like'):

private static final ThreadLocal<Random> RANDOM = new ThreadLocal<Random>() {
    public Random initialValue() {
        return new Random();
    }
}

public static final String randomize() {
    final char[] digits = "0123456789".toCharArray();
    final Random rand = RANDOM.get();
    int index = digits.length;
    // Fisher-Yates.
    while (index > 1) {
        final int pos = rand.nextInt(index--);
        final char tmp = digits[pos];
        digits[pos] = digits[index];
        digits[index] = tmp;
    }
    return new String(digits);
}

EDIT

I just realized another tweak could squeeze a little more performance out too.... consider this implementation which does not even need to create an array on each invocation, and who cares what order the digits are when you are just going to reshuffle them anyway. Thus, this saves creating a char[] array each time as well. The only new instance is the returned String:

private static final class Generator {
    private final Random rand = new Random();
    private final char[] digits = "0123456789".toCharArray();

    public final String generate() {
        int index = digits.length;
        // Fisher-Yates.
        while (index > 1) {
            final int pos = rand.nextInt(index--);
            final char tmp = digits[pos];
            digits[pos] = digits[index];
            digits[index] = tmp;
        }
        return new String(digits);
    }
}

private static final ThreadLocal<Generator> GENERATOR = new ThreadLocal<Generator>() {
    public Generator initialValue() {
        return new Generator();
    }
};

public static final String randomize() {
    return GENERATOR.get().generate();
}


Of course, the most efficient solution would be to let python parse the binary string as integer ;)

binaryToDecimal = lambda x: int(x,2)

But you already know that, so what about simplifying your code like this:

binaryToDecimal = lambda binary: sum(1<<(len(binary)-index-1) for index, char in enumerate(binary) if char=='1')

removing the creation of the inner list comprehension just to pick one value
not using power but bitshift (integer computation, faster, more accurate)
don't create a list to pass to sum, pass a generator comprehension (it's faster, saves memory)
in your condition, don't convert your number to integer, just test against the char value (it's faster)

Keep in mind that your parsing has no error checking!


Adding Length dimension to a Crate Object

I see no problem, given your comment, to have a 'stretchy' crate, but in my example code below you can control whether the crate can be stretched or not.

class Crate
{
    private $length, $width, $height;
    private $resizable = true;

    function __construct(float $length, float $width, float $height)
    {
        list($this->length, $this->width, $this->height) = [$length, $width, $height];
    }

    function getDimensions(): array
    {
        return [$this->length, $this->width, $this->height];
    }

    function isResizable()
    {
        return $this->resizable;
    }

    function fixateSize()
    {
        $this->resizable = false;
    }

    function addLength(float $extraLength): float
    {
        return $this->length += $this->isResizable() ? $extraLength : 0;
    }
}

I've added three methods; getDimensions(), isResizable() and fixateSize(). Note that there's no function to undo the fixateSize(). That is intentional: What would be the point of fixating the size if you can undo it?

I've made the dimension and resize fields private. Only the Crate class should be responsible for manipulating these. Child classes should use the methods of Crate to change them, hence the getDimensions() method.

Note how addLength() now returns the new length, and how it doesn't add the $extraLength when the crate size is fixated. Instead of returning the new length you could return a boolean, indicating whether the extra length is accepted. Another reason for not accepting the extra length could be that the crate would become too long.

I wouldn't use the CrateService class, that just overly complicated, and the addLength() method that returns a new object is just weird. The name of the method doesn't suggest this at all. A better name would have been cloneAndStretch().


Finding the intersection of elements in two sets

Is there another better way to implement those two methods in 1 and 2?

Of course there is.

My advice is to think about the problem as though you were solving the problem without a computer.

Here, I'm going to give you a list of a thousand unsorted integers between 0 and 999999.

Now I'm going to ask you one thousand times whether a particular number I've chosen at random is on the list.

Would you really try to answer every question by reading down the list from top to bottom every time?

Give some thought as to how you might solve that problem before you read on.

.

.

.

.

.

No, really, think about it.

.

.

.

You probably thought something like

the first time I go down the list, I could make ten smaller lists:  numbers I've seen from 0-99999, numbers I've seen from 100000-199999, from 200000-299999, and so on.  That will take a thousand steps to make ten buckets of roughly 100 items each.
Then the second time I'm asked the question, I can first figure out what bucket the number might be in. Then I can search that bucket, and I know I will only have around 100 things to check instead of 1000.
And hey, while I'm doing that, I might as well divide that bucket up into ten buckets of roughly ten items each!

Every time you do a search that makes ten more buckets, you make subsequent searches that hit that bucket ten times faster.

All right, that should get you started; can you implement something like this bucketing algorithm in code?

Now, think the same way about intersection. Can you use the same bucketing trick to make intersection vastly faster? Or something similar?  Again, think about how you would solve the problem if I asked you to do it by hand.


Formatting
This may be a copy and paste error, but generally int main() will start in the first column like the #include does. Other the rest of the indentation needs to be based on that. This was correctly done in your earlier question.

#include <stdio.h>

int main()
{
    int T;
    scanf("%d", &T);

    ...

}

Functions
You may not have run into difficult problems yet, but as the programs get more complex the best way to solve them will be to break it up into smaller pieces where each particular task is easy to solve. In this case the outer for loop would make a good function. Perhaps the inner loop would make a second good function.

Variable Names
Variable names should be meaningful to make the code more readable, easier to understand and maintainable.

The problem statement gives you the variable names T, N, M and K which are currently being used in the code, however, it also gives you what the variables are used for. It might be better to use names such as testCount for T, maxPrice for N, minPrice for M and itemCount for K.

The variable name halfPrice could be misleading be it won't always be half of the maximum price.

Mixing Types in Comparisons
There is the possibility of Floating Point Error in the code because of this comparison:

            halfPrice = (halfPrice < M) ? M : halfPrice;

While the minimum price is input as an integer it might be better to convert it to a float and use that in the comparison. This conversion should only be done once per test case.

In many cases banks work around this by keeping amounts in 2 integer values, one for dollars and one for cents (units are USA, units may differ based on location).


Updating 3 columns conditionally on a database table

I haven't tested this but you should be able to use CASE statements to conditionally update column values, with fallback values of the existing column values:

UPDATE dbo.Roles SET
    DisplayName = CASE WHEN DisplayName LIKE `` THEN Name ELSE DisplayName END,
    Name = CASE WHEN Name NOT LIKE ('%' + Convert(varchar(200), Tenant) + '%') THEN CONCAT(Tenant, '_', DisplayName) ELSE Name END,
    NormalizedName = CASE WHEN DisplayName LIKE '' THEN CONCAT(Tenant, '_', UPPER(DisplayName)) ELSE DisplayName END
WHERE DisplayName LIKE ''
    OR Name NOT LIKE ('%' + Convert(varchar(200), Tenant) + '%')
    OR NormalizedName NOT LIKE ('%' + Convert(varchar(200), Tenant) + '%');

Note that this may be slightly more challenging to read and there may be more updates per column because it would update any row that needs any column updated, but it would be two fewer UPDATE statements.

Your mileage may vary- especially depending on how many rows exist in the table. It would be wise to compare not only the execution times but also the execution plans.


De-serializing and serializing objects to be sent over the network

IMHO you are doing to much inside of the constructor (Sub New()). The constructor should be used to construct the object. It should be avoided that exceptions are thrown from inside of a constructor.

A better approach would be to add a Shared method which takes care of the deserializing and make the constructor private. This shared method would then return the fully constructed data object.

The exception handling in the constructor is senseless in its current state. You don't gain any advantage of using a Try..Catch because you are throwing the exception anyway. You can simply omit it.

Instead of calling ms.ToArray() in the ToByte() method you sould call ms.GetBuffer() which returns the content of the stream without creating a new byte array.

There is no need to set the Position property of the newly created MemoryStream. It is automatically set to the beginning. So skip _ms.Position = 0.

While we are at _ms, one shouldn't use underscore prefix unless it is a class level variable where it is accteptable.

  public name as string
  public cmd as Commands
  public  message  as String

These fields shouldn't be public avaible. For encapsulation you should use properties.

Comments should be used to explain why something is done in the way it is done. Let the code speak for itself about what is done by using meaningful and descriptive names for classes, methods and variables.
Comments like ' create new BinaryFormatter only add noise to the code which should be removed for readability.

In the ToByte() method the setting of bf = Nothing is not needed and therefor you should declare the BinaryFormatter as near to its usage as possible (inside the using).

The Catch ex As SerializationException would need a comment why you handle the exception like you do.

This 'Converts the Data structure into an array of bytes should be put inside a XML documentation block.

Dim oData as data

Please don't use hungarian notation like you are using it. By having intellisense you can easily hoover over the variable and see it is a class. There is no need to prefix it with o for object.

Naming a class data does not add any value. One should name a class in a way that it is obvious what purpose the class serves.

You also should be consistent at your naming style. Sometimese you are using an underscore prefix (like already stated) and sometimes you don't. If you have choosen a style you should stick to it.


Counting pairs of numbers that differ by a given amount

Your solution is \$O(X^2)\$ which is too slow for \$X\approx 10^5\$.

Instead of checking differences with two nested loops, you should just loop over the first element a and perform binary search to find the number of elements of the form a+Y. This will reduce the complexity to \$O(X \log X)\$ which will be fast enough.


Easier ways to make an RPG dice roller code?

Mystery inputs
It's clear that there's an implied structure to this input:
message = input('>')
reader = message.split(' ')

requiring between four and five tokens. I have no idea what those are, and neither does your user. Replace '>' with an actual description of what's expected here.
Unpacking
times = reader[0]
sides = reader[2]

can be
times, _, sides = reader[:3]

though the discarded second item is suspicious. You do need to show what this is, and it probably shouldn't be there.
Looping and overwrites
This:
for output in range(int(times)):
    output_with_modifier = [(int(x) + int(modifier)) for x in result]

does not make sense. If you ask for 100 times, output_with_modifier will be calculated 100 times and thrown away 99 of them. Only the last value will be kept. You probably want to de-indent that last assignment so that it happens outside of the loop.
More looping
end = False
while end == False:
    dice_reader()
    end_message = input('Again? ')
    if end_message.lower() == 'no':
        end = True
else:
    pass

First, delete that else; pass - it isn't doing anything. Also, end == False should be not end; but you shouldn't be using a termination variable at all. If you find a no, simply break.
Suggested code
Some of this may challenge a beginner, but I like to think that CodeReview is for "aspiring advanced programmers". I've tried to comment it extensively, but feel free to ask questions in the comments.
import re
from random import randint
from re import Pattern
from typing import ClassVar, Iterable

class Dice:
    """
    One specification for dice rolls in Dungeons & Dragons-like format.
    """

    def __init__(self, times: int, sides: int, modifier: int = 0):
        if times < 1:
            raise ValueError(f'times={times} is not a positive integer')
        if sides < 1:
            raise ValueError(f'sides={sides} is not a positive integer')

        self.times, self.sides, self.modifier = times, sides, modifier

    # This is a class variable (basically a "static") that only has one copy
    # for the entire class type, rather than a copy for every class instance
    # It is a regular expression pattern that will allow us to parse user
    # input.
    INPUT_PAT: ClassVar[Pattern] = re.compile(
        # From the start, maybe some whitespace, then a group named "times"
        # that contains one or more digits
        r'^\s*(?P<times>\d+)'

        # Maybe some whitespace, then the letter "d"
        r'\s*d'

        # Maybe some whitespace, then a group named "sides" that contains one
        # or more digits
        r'\s*(?P<sides>\d+)'

        # The beginning of a group that we do not store.
        r'(?:'

            # Maybe some whitespace, then a "+" character
            r'\s*\+'

            # Maybe some whitespace, then a group named "modifier" that
            # contains one or more digits
            r'\s*(?P<modifier>\d+)'

        # End of the group that we do not store; mark it optional
        r')?'

        # Maybe some whitespace, then the end.
        r'\s*$',

        # We might use "d" or "D"
        re.IGNORECASE
    )

    # This can only be called on the class type, not a class instance. It
    # returns a new class instance, so it acts as a secondary constructor.
    @classmethod
    def parse(cls, message: str) -> 'Rolls':
        match = cls.INPUT_PAT.match(message)
        if match is None:
            raise ValueError(f'Invalid dice specification string "{message}"')

        # Make a new instance of this class based on the matched regular
        # expression.
        return cls(
            int(match['times']),
            int(match['sides']),
            # If there was no modifier specified, pass 0.
            0 if match['modifier'] is None else int(match['modifier']),
        )

    @classmethod
    def from_stdin(cls) -> 'Rolls':
        """
        Parse and return a new Rolls instance from stdin.
        """

        while True:
            try:
                message = input(
                    'Enter your dice specification, of the form\n'
                    '<times>d<sides> [+ modifier], e.g. 3d6 or 4d12 + 1:\n'
                )
                return cls.parse(message)
            except ValueError as v:
                print(v)
                print('Please try again.')

    def roll(self, with_modifier: bool = False) -> Iterable[int]:
        """
        Return a generator of rolls. This is "lazy" and will only execute the
        rolls that are consumed by the caller, because it returns a generator
        (not a list or a tuple).
        """
        mod = self.modifier if with_modifier else 0
        return (
            randint(1, self.sides) + mod
            for _ in range(self.times)
        )

    def print_roll(self):
        print(
            'Dice rolls:',
            ', '.join(str(x) for x in self.roll()),
        )

        if self.modifier != 0:
            print(
                'With modifier:',
                ', '.join(str(x) for x in self.roll(with_modifier=True)),
            )

def test():
    """
    This is an automated test method that does some sanity checks on the Dice
    implementation.
    """

    d = Dice.parse('3 d 6')
    assert d.times == 3
    assert d.sides == 6
    assert d.modifier == 0

    d = Dice.parse('3D6 + 2')
    assert d.times == 3
    assert d.sides == 6
    assert d.modifier == 2

    try:
        Dice.parse('nonsense')
        raise AssertionError()
    except ValueError as v:
        assert str(v) == 'Invalid dice specification string "nonsense"'

    try:
        Dice.parse('-2d5')
        raise AssertionError()
    except ValueError as v:
        assert str(v) == 'Invalid dice specification string "-2d5"'

    try:
        Dice.parse('0d6')
        raise AssertionError()
    except ValueError as v:
        assert str(v) == "times=0 is not a positive integer"

    d = Dice.parse('100 d 12+3')
    n = 0
    for x in d.roll(True):
        assert 4 <= x <= 15
        n += 1
    assert n == 100

def main():
    test()

    dice = Dice.from_stdin()
    dice.print_roll()

if __name__ == '__main__':
    main()


The :space: portion of the regex makes no sense, and probably does not do what you intend.

> x <- "abc:def."
> gsub("[^a-zA-Z0-9,-:space:]", " ", x, perl = TRUE)
[1] "abc:def."

Notice that the colon and period are still present after the substitution.

In fact, inside the character class, ,-: means "all characters with ASCII codes from 44 (the comma) up to 58 (the colon)".

A literal hyphen must be the first or the last character in a character class; otherwise, it is treated as a range (like A-Z).

If you want a character class for whitespace, use "\\s" or [:space:].

So, if you wanted to convert all consecutive strings of junk to a single space, preserving only letters, digits, commas, slashes, hyphens, and whitespace, you could write:

gsub("[^-,/a-zA-Z0-9[:space:]]+", " ", x, perl = TRUE)

or

gsub("[^-,/a-zA-Z0-9\\s]+", " ", x, perl = TRUE)


setjmp and longjmp implementation in mmix

Looks like your setjmp takes the jmp_buf parameter as $0 - but how is jmp_buf defined - how much space does it need for example?
Also longjmp takes 2 parameters - the same jmp_buf and an int - I don't see $1 being used for the second input parameter in your longjmp
You can find commandline tools to run MMIX programs at https://mmix.cs.hm.edu/exe to try out your implementation - there's a Windows GUI debugger too - could you show sample MMIX code that calls your setjmp and longjmp?


Robustness

The randomNumber field of GuessMyNumber should not be public.
For example a bad user could do this:

GuessMyNumber guessMyNumber = new GuessMyNumber();
guessMyNumber.generateNumber(1, 75);
guessMyNumber.randomNumber = 25;
guessMyNumber.validateInput(25);  // -> yeay, I win!

That would be devastating. Internal implementation details like this should be hidden, make them private. The same goes for numberFound.

It would be better to remove the generateNumber method,
and initialize the number once and for all in the constructor.
That is, randomNumber can be final, which will make your class more robust,
less prone to errors.
If you want to play multiple games,
you can create a new instance of GuessMyNumber.

Finally, the response variable really doesn't need to be an instance variable,
it should be a local variable in the validateInput method.
In fact, you don't even need to store the message in a local variable,
you can simply return directly.

Simplify

The conditions in validateInput have many duplicated elements.
It would be better to cache the difference of the guess and the target number in a variable and reuse it.

Also some of the conditions are mutually exclusive,
so you should chain them using else if statements.

Unit testing

To make sure that the validation logic works well and correctly handles all corner cases (too high, too low, close, perfect match),
it would be good to unit test it.

Coding style

The convention in Java is to put opening braces on the same line as the statement,
so instead of writing like this:

public String validateInput(int guessedNumber)
{

I recommend to adopt this writing style:

public String validateInput(int guessedNumber) {

Suggested implementation

Putting the above suggestions together (and then some more):

import org.junit.Test;
import java.util.Random;
import static org.junit.Assert.assertEquals;

class GuessMyNumber {

    public static final int CLOSE_LIMIT = 5;
    public static final String MSG_TOO_HIGH = "You're too high!";
    public static final String MSG_TOO_LOW = "You're too low!";
    public static final String MSG_CLOSE = "You're close!";
    public static final String MSG_WIN = "Congratulations! You guessed my number!";

    private final int randomNumber;
    private boolean numberFound = false;

    public GuessMyNumber(int min, int max) {
        Random random = new Random();
        this.randomNumber = random.nextInt((max - min) + 1) + min;
    }

    public String validateInput(int guessedNumber) {
        int diff = guessedNumber - randomNumber;
        if (diff == 0) {
            this.numberFound = true;
            return MSG_WIN;
        }
        int absoluteDiff = Math.abs(diff);
        if (absoluteDiff <= 5) {
            return MSG_CLOSE;
        }
        if (diff < 0) {
            return MSG_TOO_LOW;
        }
        return MSG_TOO_HIGH;
    }
}

public class GuessMyNumberTest {
    private static final int NUMBER = 55;

    private final GuessMyNumber game = new GuessMyNumber(NUMBER, NUMBER);

    @Test
    public void testTooHigh() {
        assertEquals(GuessMyNumber.MSG_TOO_HIGH, game.validateInput(NUMBER + GuessMyNumber.CLOSE_LIMIT + 1));
    }

    @Test
    public void testTooLow() {
        assertEquals(GuessMyNumber.MSG_TOO_LOW, game.validateInput(NUMBER - GuessMyNumber.CLOSE_LIMIT - 1));
    }

    @Test
    public void testCloseHigh() {
        assertEquals(GuessMyNumber.MSG_CLOSE, game.validateInput(NUMBER + GuessMyNumber.CLOSE_LIMIT));
    }

    @Test
    public void testCloseLow() {
        assertEquals(GuessMyNumber.MSG_CLOSE, game.validateInput(NUMBER - GuessMyNumber.CLOSE_LIMIT));
    }

    @Test
    public void testWin() {
        assertEquals(GuessMyNumber.MSG_WIN, game.validateInput(NUMBER));
    }
}


Scraping with asyncio/aiohttp and retrying the request on error

with back-connect proxies, is you do not always get a proxy that works.

There are several possibilities here. The origin webserver could be responsive, slow (slower than your timeout), or dead, and the proxy could be responsive, slow, or dead. Call those "health" details. It doesn't look like you are tracking health details of either one, so you don't adapt to such details. For faster processing, use adaptive timeouts and don't re-submit requests to dead hosts (don't contact known-dead proxies, and don't contact known-dead webservers).

EDIT: An example of an adaptive timeout would be triple the observed median response time of a host, which attempts to capture a large fraction of the pdf (probability distribution function) of its observed response times, conditioned on actually getting a response.

class Proxy:
    def __init__(self, headers, proxy):

I'm not crazy about that last identifier. Call it proxy_url, please. It clearly isn't an instance of the Proxy class.


Lockless Queue Multiple-Reader Singler-Writer in C++

This line seems really strange to me:

static_assert(N!=0x80000000,"N is too large.");

Technically, it is rather odd to just compare for equality with one big number where there could be numbers even bigger. Didn't you mean:

static_assert(N >= 0x80000000, "N is too large.");

const uint32_t MASK = 2*N-1;

Since all the values in this line are known at compile time and MASK is apparently not meant to be changed, you should consider making it both static and constexpr:

static constexpr uin32_t MASK = 2*N-1;

That's kind of trivial, but you can also use curly braces instead of parenthesis in your constructor initialization list:

RnW1FifoFixed():
    m_array{new T[N]},
    m_read{0},
    m_write{0}
{
    // ...
}


Limitations

Being able to sort in \$O(n)\$, counting sort can be very efficient,
but with the right kind of data.
Just keep in mind that it won't work well when the variation in values is very large.

Optimizations and extensions

The implementation checks the maximum value,
so the array of counts will use that much space.
You could reduce the amount of space used by finding the minimum too.
That way the size of the array of counts could be max - min instead of max.
That will of course require to use the min as an offset both when building the array of counts,
and when writing the output.

Related to that, the current implementation doesn't support negative values in the input.
But it could, by using the minimum value as an offset.
In fact,
by applying the optimization above,
negative numbers will be automatically supported.

Unnecessary storage and mutations

There's no need for the temporary output array,
and for modifying the content of count to contain positions.
Once you have the array of counts,
you can directly overwrite the target array,
reducing the amount of code and simplifying the implementation.

for (int countIndex = 0, outIndex = 0; countIndex < count.Length; ++countIndex)
{
    for (int i = 0; i < count[countIndex]; ++i)
    {
        arr[outIndex++] = countIndex;
    }
}

Unnecessary array initialization

int[] arrays are initialized with zeros,
no need to manually set the content to zeros.

Style tips

It's recommended to always use braces with loops and conditionals.

Testing

It's better to use a proper unit testing framework that gives you simple pass-or-fail results,
rather than reading the output and verifying manually that it's actually correct.


Don't do too much in one loop

            for(int i = 0; i < word.length(); i ++) {
                if (guess.equals(Character.toString(word.charAt(i)))) {
                    if(!iterated)
                        temp += Character.toString(word.charAt(i));
                    else {
                        holder = Character.toString(temp.charAt(i)).replace("-", guess);
                        temp = temp.substring(0, i) + holder + temp.substring( i + 1, temp.length());
                    }
                } else {
                    if(!iterated) {
                        temp += "-";
                    }
                }
            }

In this, you handle two entirely different purposes.  You change the existing string to display any occurrence of the character.  And on the first iteration, you fill in the string with dummy characters.  This may be slightly more efficient on that first iteration, but it is less efficient on every other iteration.  Consider how this code looks without the !iterated checks.

            for (int i = 0; i < word.length(); i ++) {
                if (guess.equals(Character.toString(word.charAt(i)))) {
                    holder = Character.toString(temp.charAt(i)).replace("-", guess);
                    temp = temp.substring(0, i) + holder + temp.substring( i + 1, temp.length());
                }
            }

How much harder is it to do the initial fill?  StackOverflow suggests something like

    String temp;
    if (word.length() > 0) {
        char[] array = new char[word.length()];
        Arrays.fill(array, '-');
        temp = new String(array);
    } else {
        temp = "";
    }

Or you could make a method like they do:

    String temp = getStringWithLengthAndFilledWithCharacter(word.length(), '-');

Or any other variants there.

Which code would you rather read?  Those two simple blocks or one large one?

StringBuilder to build a string

You use repeated calls to substring and string concatenation to build your replacement string.  Behind the scenes, Java probably converts this into a StringBuilder.  Why not embrace that and do it yourself?

            if (guess.length() != 1) {
                System.out.println("Guesses must each be a single letter.");
                continue;
            }

            char c = guess.charAt(0);
            for (int i = word.indexOf(c); i >= 0; i = word.indexOf(c, i + 1)) {
                temp.setCharAt(i, c);
            }

This reduces the two line solution to one even simpler line in the loop.

It also eliminates the need to test that the current index is equal to the guessed character.  This reverses the logic, searching for the guess in the string.

I also added an explanatory message for why multicharacter or empty guesses don't work.  The original just silently goes to the next guess in that instance.

Iterate with for loops

Your do/while loop skips the first check at the expense of a more complicated loop.  If you change to a for loop, it's easier to read at the expense of one extra comparison.

Summary

        StringBuilder temp;
        if (word.length() > 0) {
            char[] array = new char[word.length()];
            Arrays.fill(array, '-');
            temp = new StringBuilder(new String(array));
        } else {
            temp = new StringBuilder();
        }

        for (int turn = 0; turn < 10; turn++) {
            System.out.println("Enter your letter guess");
            String guess = keyboard.nextLine();

            if (guess.length() != 1) {
                System.out.println("Guesses must each be a single letter.");
                continue;
            }

            char c = guess.charAt(0);
            for (int i = word.indexOf(c); i >= 0; i = word.indexOf(c, i + 1)) {
                temp.setCharAt(i, c);
            }

            System.out.println(temp.toString());
            if (word.equals(temp.toString())) {
                System.out.println("You guessed correctly!");
                break;
            }
        }

It would be more elegant to break this into more methods, but it will work like this.


Fraction class implemented in Objective-C

@property
You declare properties in the header file, but you don't actually use them as anything more than instance variables, which suggests you may not quite understand their full power.
An Objective-C property is three things.

An instance variable
A setter
A getter

When you write @property int numerator;, you have created all three of these things.
Whether or not you write anything else, the class now has a private instance variable known as _numerator, a getter method in the form of - (int)numerator; and a setter method in the form of - (void)setNumerator:(int)numerator;
So given a fraction variable called myFrac, all of the following is instantly valid:
myFrac.numerator = 3;
NSLog(@"%i", myFrac.numerator);
[myFrac setNumerator: 4];
NSLog(@"%i", [myFrac numerator]);

The square bracket notation is perfectly valid, though when dealing with properties in Objective-C, we tend to prefer just using the dot notation.
What's more is that this fact makes these methods superfluous:
-(void) setNumerator: (int) n
{
    numerator = n;
}

-(void) setDenominator: (int) d
{
    denominator = d;
}

Except... not completely.  The first one is definitely unnecessary.  The second, however... it needs some logic.  Zero is not a valid denominator.  We need to prevent the case of the user setting the denominator to zero.  I think this is one of the rare cases where throwing an exception in Objective-C might be okay.  And in fact, why don't we just throw the exact exception that'd be thrown if we did actually divide by zero?
- (void)setDenominator:(int)denominator {
    if (denominator == 0) {
        // no reason to build a NSException object, just:
        __unused int divisionByZero = numerator/denominator;
    }
    _denominator = denominator;
}

I mean, I see that in converting it to a double, you deal with this, but what about when you print?  You really shouldn't let the object exist in an invalid state.
And you might have noticed I used a mysterious _denominator there.  As of Xcode 4 (I think, maybe even older), properties are autosynthesized in the .m file to their name prefixed with an underscore.  The @synthesize directive is no longer needed, and all Objective-C developers I know have abandoned it in favor of using the autosynthesized version.  The underscored name also is a huge clue that this is a direct access instance variable and not anything else.

-(void) setTo: (int) n over: (int) d
{
    numerator = n;
    denominator = d;
}

You follow this pattern of using short names for the arguments, and I think it's probably simply to avoid the name class with your synthesized property names.  And now you've just discovered another reason why the auto-synthesized underscore prefixed property names are great!  Although, truthfully, we should be going through the setters, so this method should look like this:
- (void)setTo:(int)numerator over:(int)denominator {
    self.numerator = numerator;
    self.denominator = denominator;
}

And if you put an NSLog statement in setDenominator:, you'll see that this method will now go through that method to set the value.
By the way, notice how I keep moving your opening braces to the correct line?

-(void) print
{
    NSLog(@"%i/%i", numerator, denominator);
}

As far as I know, methods like this, across the board, are a no-no in OOP.  Instead, classes should have an instant method which returns a string to be printed by whoever is using the class if they want to print the class.  In most languages, the method is called toString(), in Objective-C, we call it description.  Your description method should look like this:
- (NSString *)description {
    return [NSString stringWithFormat:@"%i/%i",numerator,denominator];
}

One thing to note is the behavior of NSLog.  NSLog doesn't just work for NSString objects.  It works any object.  As all Objective-C objects have a description method (which at a minimum is inherited from their super class), NSLog prints the value returned by the object's description method.  As such, by implementing description, see what happens if you call:
NSLog(@"%@", myFrac);

-(double) convertToNum
{
    if (denominator) return (double) numerator / denominator;
    else return NAN;
}

This method is actually problematic for me.  There's no telling what type of variable someone might need out of your fraction.  Whose to say they don't need a float?  Or an int?  Or an NSInteger?  There are a lot of possible types of number data types that one might need...
So, for starters, I'll point you to other Objective-C classes with method names like doubleValue, intValue, integerValue, etc.  As such, a method that returns the double representation of an object should probably be called doubleValue.
But perhaps what may be even more important that writing a method for all the different numeric data types... why don't we make use of Objective-C class categories and the NSNumber class?
In the .h file for this class, add the following:
@interface NSNumber (Fraction)

+ (NSNumber *)numberWithFraction:(Fraction *)fraction;

@end

And now in the .m file, assuming you've properly changed over to a method called doubleValue, add the following:
@implementation NSNumber (Fraction)

+ (NSNumber *)numberWithFraction:(Fraction *)fraction {
    return [NSNumber numberWithDouble:[fraction doubleValue]];
}

@end

Now anyone who has imported this file has also imported the ability to seemlessly create NSNumber objects with a single method call, and it will feel just like creating a NSNumber object with any other data type.


Finding which users have the most questions with unaccepted answers

This is essentially a good, clear and effective query. The only feedback I can offer is minor and somewhat subjective.

In the first CTE, unanswered, I personally would use distinct rather than grouping by posts.id. I group by when I am using an aggregate function; since there's no aggregate, distinct expresses the intention clearer to me.
I'm not intimately familiar with SEDE but I think you can inner join between users and posts in the percentages CTE. This is likely to be more performant, and again it expresses the intention clearer.  The left outer join to unanswered still makes sense because you want to include the count of answered as well as unanswered posts. (Personally, I write left join rather than left outer join - less typing, totally equivalent).
I'm not a huge fan of your layout and indentation style. Wholly subjective (and I don't know if I'm in the minority or you are) but I usually start each new query clause (select, from, joins, where, etc) on a new line, and leave a blank line between each clause.
I recommend aliasing all tables/rowsets for clarity, e.g. ...from users as U..., and referring to the alias e.g. select U.Id....  So long as you choose sensible aliases (never just A, B, C etc) this is clear and more compact.
Your final ordering, by UnansweredPct, doesn't guarantee the same order between re-runs (as two users could and do have the same value in that column). I'd order by more columns to ensure consistent ordering - it isn't the end of the world in this particular query, but in some cases consistency can be really important, so it's a good habit to have.
I am not a fan of using top in any "long term" SQL queries (in the context of my day job, any query which will be used in production rather than just ad-hoc code). Whether you consider your query to be the former or the latter is up to you ;-) My "production" approach would be to add a Row_Number() function, ordering by UnansweredPct (and other columns, see above), then restrict where RowNo <= ##MaxRowsToSelect:int?100## instead of the top.  This also means you can just order by RowNo.


Conversion to typescript from javascript

Use explicit type annotation only when necessary In the vast majority of cases, TypeScript can infer the type of an expression automatically, without you having to note it manually. It's probably better and easier to let TS take care of it - it makes for less code to read and write. If you're ever not sure what sort of type an expression is, use an IDE which can tell you (like VSCode, which works really well with TypeScript - just hover over an expression and it'll tell you what type TypeScript has inferred for it).
For example:
const fileURL: string = URL.createObjectURL(file);
const link: HTMLAnchorElement = document.createElement('a');

can be
const fileURL = URL.createObjectURL(file);
const link = document.createElement('a');

IMO, TypeScript shines most when it looks almost identical to JavaScript, with the added bonus of warning you when you're doing something that's type-unsafe.

I think the only code I can't figure out how to convert over is the blob type.

Its type is a Blob, which you can see in VSCode (or any other good TS-aware IDE):

But, as said, better to let TS infer it automatically; no need for const file: Blob =.
Prefer generics over type assertion Generics are the most elegant way to denote the type of a particular expression, when the type isn't set in stone by the function signature. The as keyword, in contrast, is less type-safe: as tells TypeScript "I know exactly what I'm doing, ignore whatever type this value was determined to be previously and assume that it's of THIS type instead".
For example, the following code does not throw a TS error, despite the as clearly being nonsensical:
const foo = {
    bar: 'bar'
} as {
    fn?: () => Promise<Array<string>>
};

as isn't as bad as any, but they both should be avoided when possible.
In your case, getElementById is not generic, unfortunately, but querySelector is. You can change:
const spinner: HTMLElement = document.getElementById('spinner') as HTMLImageElement

to
const spinner = document.querySelector<HTMLElement>('#spinner')!;
// you could also use <HTMLImageElement> if you needed image element specific types

Generics are essentially type arguments that come in <> brackets, before the expression arguments inside the parentheses of the function call. Above, <HTMLImageElement> tells querySelector: "This selector, if it matches, will match an HTMLImageElement." This is preferable to as because only the types that extend Element can be passed to querySelector.
Function name Functions should describe actions, or what they do. webApiUrl might be more precisely named getApiUrl. (Or, just export the URL string alone: export const apiUrl = '...';, there doesn't seem to be any need for the function)
Error handling If the fetch fails, no indication is given to the user or to other parts of the program. Whenever you have a Promise, you should almost always make sure that possible errors inside it get handled. TSLint rule: no-floating-promises.
While you could add a .catch onto the fetch Promise chain:
    spinner.style.display = 'none'
})
.catch((error) => {
    // handle errors
});

It might be better to let the caller handle errors as needed. Change:
fetch(`${apiUrl}/api/...

to
return fetch(`${apiUrl}/api/...

so that each caller can do downloadPdf(id, fileName).catch(handleErrors) individually.
Semicolons Some of your lines are missing semicolons. This is stylistically inconsistent and can lead to odd bugs if you forget a semicolon where it's required. Add the missing semicolons, and consider using a linter which warns you when they're missing. (The rationale behind using a linter is similar to the rationale behind using TypeScript - turn annoying, hard-to-encounter, sometimes-hard-to-debug runtime errors into trivially fixable compile-time errors.)


Is this the right way to implement a hashmap?

No, this is not the correct way to implement a hash map in Java, and especially not to implement the java.util.Map interface.

You aren't even explicitly implementing the Map interface.
What is (Map[]) Array.newInstance(Map.class, capacity) supposed to be? I'd think a simple new Map[capacity] would be sufficient.
You calculate your hashes yourself. However, every Object has a hashCode() method – use that instead.
Because you shouldn't calculate the hash code yourself, you shouldn't do any special handling of String and Character or Integer.
In your get method, what happens when the key is not one of your special classes? Not only will you be doing a linear search through your bins which breaks my expectations about the algorithmic complexity of a hash map, you'll also start at index -1, which will greet you with an ArrayIndexOutOfBoundsException.
Should you be implementing java.util.Map, the get method should throw an explicit NullPointerException rather than an optional assertion error as you do not want to allow null keys.
For some reason, the hash method is public. Furthermore, hash and doHash are not static although they don't access any object state.
Many criticisms about get also apply to put.
Your remove method sports this code: arr[i].k.equals(key). That risks a null pointer exception when arr[i] is null. Instead: arr[i] != null && key.equals(arr[i].k)
remove also has a loop that will only execute once or nonce:

while (arr[i]!= null && arr[i].k.equals(key)){
    pairs.add(arr[i]);
    arr[i] = null;
    size--;
}

Note that you never modify i.
In remove, it would be much simpler to look up the bin for that key, and then empty that bin rather. Consider putting your main get logic into a private int getBin(Object key), which you could use both in get:

int i = getBin(key);
... // assert i in range
if (arr[i] != null) {
    return arr[i].v;
}

and remove:

int i = getBin(key);
... // assert i in range
if (arr[i] != null) {
    V value = arr[i].v;
    arr[i] = null;
    size--;
    return value;
}

The Map class would usually be named Entry. Note that the java.util.Map interface contains a nested interface java.util.Map.Entry which you'd also have to implement for compatibility.
containsKey could be implemented using a getBin helper as

int i = getBin(key);
... // assert i in range
return arr[i] != null;

Your hash map can only contain 100 elements. If it grows larger, you should reallocate the storage array. You are furthermore resolving hash collisions via “open addressing” (using the next free bucket). Alternatively, you could use linked lists in each bucket, which also simplifies growing the hash table.

Then, there are many style problems in your code.

Consider changing a few whiles to easier to read for loops.
i = i + 1 could be abbreviated to i += 1, but is most often written i++.
Always use braces around the blocks of an if:

if (key instanceof Integer) {
    i = hash(Integer.parseInt(key.toString())) % capacity;
}

Many of your casts could be prevented with the use of generics. In remove, you have

Object temp = arr[i].v;
...
return (V) temp;

Instead:

V temp = arr[i].v;
...
return temp;

Regarding the question: “do I need to follow all OOP concepts(because I am using Java)?” – the answer is yes, but not because you are using Java. Instead, you'll want to write solid OOP code simply because your are writing object-oriented code, the language does not matter. Applying best practices is vastly preferable to producing shoddy, almost-working, bug-ridden code.

What now?

Your hash map implementation does not hold up to a code review. But that's not a problem.

First, learn more about the topic: there is the Wikipedia article on hash tables, there is also the source code for java.util.HashMap (e.g. here). Compare what you've learned with your code, and try to understand your errors.
Along the way, you'll probably also get better at actual Java programming.
Then, try again. Start with a clean slate, and write another HashMap implementation. I'm sure you'll have improved by leaps and bounds. And please come back to have your new code reviewed :)


No it's not possible writing

Variable3 = Var1 Variable Var2

With the Variable as an operator, i decided to use call_user_func to call the BC Math functions http://php.net/manual/en/ref.bc.php

I removed the $mathinput since you were not using it anyway.

  Result

<?php
$input1    = $_GET["num1"];
$input2    = $_GET["num2"];
$operator  = $_GET["symbol"];

$operators = [
    '+' => 'bcadd',
    '-' => 'bcsub',
    '*' => 'bcmul',
    '/' => 'bcdiv',
    '%' => 'bcmod',
];

$result = array_key_exists($operator, $operators)
        && is_numeric($input1)
        && is_numeric($input2)
        ? call_user_func($operators[$operator], $input1, $input2)
        : null;
?>

<?php if (!$result) : ?>

Error: Invalid input or arithmetic operator.

<?php else: ?>

Result: <?= $result; ?>

<?php endif; ?>

  EDIT

The array_key_exists function checks if a given key exists in the array.
http://php.net/manual/en/function.array-key-exists.php

The following is a shorthand if / ternary logic

$var = array_key_exists($operator, $operators)
&& is_numeric($input1)
&& is_numeric($input2)
? 'all true' : 'conditions not met';

Simply checks if all the conditions are true, if so the above example would set $var to a string with a value of 'all true', if one of the conditions would return false, the $var would be set to 'conditions not met'

You could write the above snippet using regular if / else statements like this:

if(array_key_exists($operator, $operators) && is_numeric($input1) && is_numeric($input2)) {
    $var = 'all true';
}
else {
    $var = 'conditions not met';
}

Using ternary logic could have some of the following advantages when used properly.

Makes coding simple if/else logic quicker
Makes code shorter
Makes maintaining code quicker, easier


Given N and M find all stepping numbers in range N to M

Code review

Avoid unnecessary indentation whenever possible. An early exit block should always be on top. What I mean by that is this:

for(...)
{
    // this saves your 1-level of indentation
    if (amount < 2)
    {
        // update result
        continue;
    }

    // rest of code here
}

Use intermediary variables if the code gets too long and loses its meaning

int current = (int)Char.GetNumericValue(num[j]), next = (int)Char.GetNumericValue(num[j+1]);
if(current > next)
{
    ascending=false;
}
if(ascending)
    less = next - current;
else
    less = current - next;

BTW, this can be simplfied to remove ascending variable:

if(current > next)
{
    less = current - next;
}
else
{
    less = next - current;
}

Or, even better: Math.Abs(current - next)
Put spaces around operators and control structures like for, if, while.
You can also compare the char directly, as "the value of a char object is a 16-bit numeric (ordinal) value": '2' - '1' == 1
Don't work on numbers as a string and convert it back. It is highly inefficient.
Divide your code. The block inside the first for-loop can be extracted into a bool IsStepNumber(int).

The Task

  The stepping number:

  A number is called as a stepping number if the adjacent digits have a difference of 1. e.g 123 is stepping number, but 358 is not a stepping number.

Basically, we need to (1)extract the digits, and (2)check if the adjacent digits have a difference of 1.

If you understand the positional notation, the extraction is pretty straightforward :

public static IEnumerable<int> GetDigitsReverse(int value)
{
    while(value > 0)
    {
        yield return value % 10;
        value /= 10;
    }
}

Due to the nature of this algorithm, the digits are in reserve order (right to left). Although it is really simple to re-reverse it (by chaining .Reverse()), it doesn't matter in which direction we are check the adjacent digits.
To compare adjacent items in a sequence, we can pair up a sequence with itself offset-ed by 1:

public static bool IsSteppingNumber(int value)
{
    var digits = GetDigitsReverse(value).ToList();
    return digits
        .Zip(digits.Skip(1), Tuple.Create)
        .All(x => Math.Abs(x.Item1 - x.Item2) == 1);
}

To enumerate all step numbers in a defined range, we can use the following method:

public static IEnumerable<int> ListSteppingNumbersBetween(int a, int b)
{
    return Enumerable.Range(a, b - a + 1)
        .Where(IsSteppingNumber);
}


Ok, this might come across as blunt and hurtful, but it's meant to be helpful (code-review IMO should be harsh, here's why):

"I have been writing PHP programs in the MVC pattern for quite some time"
No, you haven't. Really. M-V-C stands for, as you well know: Model-View-Controller. The code you pasted just strings all three together in one single script. That's spaghetti-code (at best), not framework-like MVC code. Not even close.

"I have this PHP file that prints a result in XML, and I put this file in 'model'"
Again: any file that generates output belongs in the view. As the name suggests, anything that is sent to the client (ie the client gets to "see"), is part of the clients view of your application. You really should read up on MVC, to find out what belongs where. (there's a link at bottom of my answer)

At the top, you set your header, then you process the request (without checking if there has been a POST request). Setting the headers as soon as possible (before anything has been sent to the client) is understandable. But in the context of the MVC pattern, it shouldn't really matter. In fact, it's one of the great things about the real MVC pattern: inside your controller and model layer, you're absolutely sure the headers haven't been sent yet, because the view is only generated (and sent to the client) at the very end of the request.
So, as your app sets about processing the request, and you hit a point where the client should be redirected, you can do so, almost blindly. Safe in the knowledge that the headers aren't sent yet. That's why MVC is so successful, and why redirects are mostly found in the controller. To clarify, look at this very simple graph (from cakePHP site, but it applies to MVC in general):

(source: cakephp.org)

Here you see the flow of an MVC webapp:

The client interacts with the view, and a request is sent to the server.
The dispatcher receives teh request and does some initial processing. Based on this request, the dispatcher deceides which controller needs to be constructed, and which method needs to be called to set things in motion
The controller can do some more checks, to make sure the request is valid. If this is not the case the Model layer is left alone, and the client is redirected. Back over to the dispatcher, (2). This step should be uncommon (as it only occurs when something isn't quite right.
Normally, the inital processing on the request data consists mainly of pouring the data into objects, and deciding what the Model layer needs to do with them.
The model layer receives data from the controller and takes over. Here's where you'll find the actual logic. DB connections, computation, ... it's all contained here (which is why this is also referred to as the business layer). The data provided by the controller can be broken down more (checked/processed), used in queries etc... The result is returned to the controller. Note that the model layer does not communicate with the view in any way!
The controller checks what the Model-layer returned. This can either be data, needed to build a new view, or an object/string saying the data turned out to be invalid/insufficient or nothing at all. Whatever it is, the controller can decide to redirect (back to step 1), call the model again (back to 3) or moving on: build the view, passing the data it received from the Model-layer.
Finally, we can start building the view. The controller passes the data it received from the model layer and the View takes over. It isn't untill we've reached this step that the headers are set. During steps 1 through 4, the headers are nowhere near being set, but at this point, it's too late to go back.
That's why the view is a simple script, containing markup and simple PHP (some loops, some if's and the occasional switch). A view contains no logic at all!.
Finally, the resulting page (view) is sent to the client. Job done.

I hope this makes a few things clear, but now
Moving on:

$connection->arrayToObject($_POST,$property_overloading = true);

$property_overloading = true? why not pass true? now you have a global variable that is just sitting there. $connection, as I gather from the query at the bottom of your code, is a DB class. What is it doing processing your POST parameters? That's not it's job. That's a gross violation of the Single Responsability Principle. Don't. Just Don't!
SRP states that an object/class should have one and only one task (reason to change): processing POST params and connecting to the DB are 2 distinct tasks.

Following that, you check a series of parameters that may or may not be set, and sanitize them one by one. I mean: really! you're using an object, clearly that object should take care of sanitizing the data, and, using getters, you could just do something like this

$post->get('hide', false);
//with getter in Post class:
public function get($param, $defaultValue = null)
{
    if (!isset($this->data[$param]))
    {//not set, return default
        return $defaultValue;
    }
    return $this->data[$param];
}

The same applies to setters, only the setter sanitizes the data.
Though at this point, you have bigger fish to fry: don't do things like

if (preg_match("/\n/", $post->description))
{
    $post->description = preg_replace("/\n/is", " ", $post->description);
}

In the if experession, you're using a regular expression, only to then use another regex to remove the unwanted chars. Either do:

public function setDescription($desc)
{//in object, of course
    $this->description = preg_replace('/\n/',' ',$desc);
    return $this;
}
//or:
$this->description = implode(' ', explode(PHP_EOL, $desc));

If the string doesn't contain any new-lines, it's not going to be changed! Why bother checking?

Next, you're echo-ing all over the place, to which I can only say: don't. as Dave Jarvis says use an API like simplexml.

Stringing a query at the end and executing it, depending on what $error hold (is it a global??) is just terrible By the time you're generating output, you should have all your data ready set, good to go. Building the response/view should be a formality. That's why a view should not contain any logic. All data has been fetched and structured accordingly.

To answer your question (on which part should go where):

processing the request is usually done in the Routing objects, and the processed request is then used to create/and pass to the (front)controller. The controller passes the bits and pieces of the request to the model-LAYER (services, helpers, data-models), which is where all the logic is kept. The controller then receives the results from the model-layer, and passes it on to the view, which (through a series of loops and if's) generates the output.

If any of this is still a bit merky, refer to the MVC wiki or ask for more details.