Is this form submission validator professional?

A few things:

Variables in JavaScript should be camelCased. PascalCase is traditionally left for types.
CSS classes are generally lower-case and hyphenated. Instead of #Name, consider #name (and the corresponding HTML attribute, id='name')
Use $ instead of jQuery. $ is syntactic sugar that essentially resolves the same thing, but it's one character instead of 6, and it's more conventionally used (see below)
Consider using the jquery.validate library. This will make your validation significantly less painful. If you're using ASP MVC you can use jquery.validate.unobtrusive to automatically map your validation on your view model from C# to JavaScript.
Keep your semi-colon conventions consistent. Use them at the end of every statement, or don't use them at all.
If you're going to use $('#element') calls a lot, consider calling that $('#element') once and storing it inside of a variable inside the scope you are using that element.

With regards to validation, you should always perform validation on the server side. I cannot overstate that point. You must do it. Client-side validation is a bonus that should be performed in addition to server-side validation, but should not be relied upon and you should not make it core functionality to your site (users can easily disable JavaScript, and some browsers like Tor have JavaScript disabled by default).

Remember that the golden rule in programming is that end-users are stupid. The weakest point to any application is the point that the end-user is allowed to provide input. You should treat the data received from the form as such, even if you already have client-side validation.

Your approach will work with 10+ input elements, but you will be repeating a lot of code. As suggested above it's advisable for you to check out jquery.validate which will allow you to maintain validation rules a lot easier (and DRY up your validation)

I don't think you should be concerned whether or not your code is professional but rather that it signals it's intent to other developers clearly and it is maintainable. Your code is certainly clear in what it tries to do it but strikes me as scaling very badly in terms of maintainability, and I think you should address that.

Example of jQuery Validate

Well, I've only really used jquery.validate.unobtrusive, but here's a link to the library. I'm sorry I can't provide much more info on that, as most of it was done automatically for me behind the scenes by ASP MVC 4.

jQuery in WordPress

  Wordpress automatically no-conflicts jQuery as a matter of courtesy. If you're only using jQuery, you can override this and just put in a $ = jQuery; somewhere. Better yet, you can use jQuery(function($) { ... to alias $ to jQuery inside your ready handler. – Schism

Or, as pointed out by @Pinoniq in his answer, you can wrap it in an IIFE (aka self-executing functions).


Looks OK to me. jQueryUI will take care of most of the low-level stuff like not letting you open several dialogs and such (by simply not letting you click "behind" the modal).

The code could be cleaned up though:

Store $(item) in a variable (same with the modal element)
No need to quote those option names
Most of the options you're setting are already the default options
Extract repeated code into functions
Don't use plain attributes to store "jobid" and certainly not "value" (since that's a real attribute for some elements). It's invalid markup. Use data-* attributes instead.
Don't use the onclick attribute either. You have jQuery: Use it.
Consider using a more semantically appropriate element for the close-job button. Like <a> or <button>. A div is semantically void; it doesn't mean anything. An a or a button, meanwhile, implies that it's clickable and will perform some sort of a action.

JavaScript

$('.close-job').on('click', function (event) {
  var button = $(this),
      job = button.data('job'),
      uri = button.data('uri'),
      modal = $('#closeWarningModal');

  function closeJob() {
    // ...
  }

  function dismissModal() {
    modal.dialog('close');
  }

  if(modal.length) {
    modal.dialog({
      modal: true,
      title: 'Close Job',
      buttons: {
        Cancel: dismissModal,
        Close: function () {
          closeJob();
          dismissModal();
        } // <-- there was an extra comma here; some versions of IE will choke on that
      }
    });
  } else {
    closeJob();
  }
});

HTML

<button class="close-job" data-uri="closeurl" data-job="jobid">Close</button>


I know that the following might seem crazy at first but humour me for a minute.  The main improvement is so that variables are not reused (which confuses their meaning) and the subtle .appendTo("#maintable") is at the end (which means the document is altered once).

There is not functional need to store the objects into variables as they aren't re-used. I often try to write in this pattern as it looks more like the way you'd write html.

if (!$("#maintable"))
    setupIndex();

$("<tr/>", {"class":"panels"})
    .append(
        $("<td/>")
            .text(desc)
            .prepend(
                $("<h3/>")
                    .append($("<a/>", { text : name, href : name + "/index.html"})))
            )
    )
    .append(
        $("<td/>")
            .append($("<a/>", {href: name + "/index.html"}))
            .append($("<img/>", { css : {width : "200px", height : "auto"}, src : name + "/thumbnail.png"}))
    )
    .appendTo("#maintable");


Stack implementation with shared_ptr C++11

Use containers

Instead of char* name use std::string name, it's safer with the cost of very little overhead, and prevents basic errors like assigning a char string to a pointer, like you do in your constructors, for example:

template <typename T>
inline Stack<T>::Stack(const char* name) :size(0), top(std::make_shared<Node>()), name(name)

You assign a pointer to a pointer, without any control over the lifetime of memory for name, and you'd get undefined behavior when you try to use it.

Always use brackets

Instead of

if (isEmpty()) top = std::move(add);
else {
    add->prev = std::move(top);
    top = std::move(add);
}

You should write

if (isEmpty()) {
    top = std::move(add);
}
else {
    add->prev = std::move(top);
    top = std::move(add);
}

It makes the code more readable and would prevent mistakes that are too easy to miss. There're several places like this in the code.

Your copy constructor is bad

You're not doing a deep copy, but a shallow copy. q gets shared ownership of s stack, you should make a deep copy of it. For example, when you call clear on s, the internal stack gets destroyed, however, q is now in inconsistent state. Here's an example of your stack deep copy

template <typename T>
Stack<T>& Stack<T>::operator=(const Stack<T>& s) {
    if (this != &s) {
        //Creating a new stack
        top = std::make_shared<Node>();

        //Copying the top value
        top->value = s.top->value;
        std::shared_ptr<Node> s_stack = s.top;
        top->prev = std::make_shared<Node>();
        std::shared_ptr<Node> this_prev = top;

        //Copying next values
        while (s_stack->prev) {
            this_prev = this_prev->prev;
            s_stack = s_stack->prev;
            this_prev->value = s_stack->value;
            this_prev->prev = std::make_shared<Node>();
        }

        this_prev->prev = nullptr;
        size = s.size;
    }
    return *this;
}

Note that further improvements can be made if your Node class would be more intelligent and provide a constructor that would initialize the value, but set the prev pointer to nullptr.

Clear function is bad

After clear the expected behavior is that s is reset to the initial state, that is, top is a shared_ptr to Node object with value = 0, however, after clear method top is a shared_ptr to nullptr. This should be a better implementation that wouldn't mess with other shared owners of internal stack.

template <typename T>
inline void Stack<T>::clear() {
    top = std::make_shared<Node>();
    top->prev = nullptr;
    top->value = 0;
    size = 0;
}

However, it requires a correct implementation of copy constructor, since now q memory wouldn't be destroyed, that's what shared_ptr expresses.

PS. You could also gain more insight if you would add a destructor to Node which would output something when a corresponding Node object is destroyed, something like this, but for learning purposes only, it's not a production code in any way.

~Node() {
    std::cout << "destroyed\n";
}


Represent json file with a set of different data members to a C++ class

Correctness

I'm not sure what exactly you mean by 'correct'. Personally, I regard this code as poorly written, so I would reject it during peer review at my work. It's using C++ as if it were C, and violating several OOA/D heuristics.

Class Message knows it has subclasses

Class Message shouldn't have that 'type' member - a base class should not know anything about its subclasses, not even that any subclasses exist. At the moment, class Message knows that it has <= 2^(sizeof(int)*8 - 1) subclasses (else that int would need to be a 'uint128_t' or something). And if you changed that 'int' to be an 'enum message_type', which is what it really is, then Message would know of the existence of each of its subclasses, which would be even worse: addition of a subclass would require modifying the base class.

It seems to me you can simply delete that 'type' member, and the lines that set its value, without any loss of functionality.

The take-away point is: C++ objects (instances of some class) already 'know' the class of which they are an instance. You don't need to store this information a second time using class data members.

Encapsulation (Google for this term)

Classes shouldn't have public data - where you're setting public members directly, you should either be passing arguments to constructors, or (less preferably) calling setters after instance construction.

Performance

Do you really care about performance of this code? Think very hard about why this code is performance-critical. Chances are, it's not.

If this code really is performance-critical, for example it's executed thousands of times per second on a small embedded processor in a real-time system on which lives depend, then consider instead using an optimised binary format instead of JSON, using superior algorithms elsewhere in your code, offloading work to other parts of the system that are less time-critical or have more resources, or simply reducing the scope of the project to something easier to accomplish.

Pros and cons of using inheritance (instead of a variant member)

Pros of inheritance: Uses C++ in the way its designers intended and in the way later readers will expect. Allows for polymorphism (Google for this term). Promotes future code re-use and eases modification, by making it easier to add additional subclasses later on, or modify the superclass behaviour/implementation.

Cons of inheritance: I can't think of any. You'd be mimicking inheritance by use of containment, which may be sadly necessary in some circumstances but seems worthless to you in this circumstance.

Strange JSON

The JSON is redundant, which means it's possible for it to be inconsistent. What does it mean for the JSON to contain a 'type' attribute with the value 0, meaning email, but then inside its 'typeProperties' sub-object, it contains all of the the attributes appropriate to an SMS and none of the attributes appropriate to an email?

If this isn't possible, then why does the JSON design permit it? Why not just treat it as an SMS if it has SMS members, or an email if it has email members, and dispense with the 'type' attribute?

If this is possible, then how are you intending to handle it?


What you've got is not a framework. It is a library.

I can see you are basically creating a jQuery-like wrapper for selecting DOM nodes and event handling. Nothing terribly wrong with the main idea.

Why have a function called Framework which has a function inside of it? Every call to Framework(...) causes myFramework to be recreated. Instead, just use a regular prototype-based "class" in JavaScript:

function Framework(sel) {
    if (!(this instanceof Framework)) {
        // return a new Framework object if called without the "new" keyword
        return new Framework(sel);
    }

    this.sel = sel;

    if (this.sel) {
        if (typeof this.sel !== 'string') {
            this.selArray = new Array(this.sel);
        } else {
            this.what = this.sel.charAt(0);

            if (this.what == ".") {
                this.selArray = document.querySelectorAll(this.sel);
            } else if (this.what == "[") {
                this.selArray = document.querySelectorAll(this.sel);
            } else if (this.what == "#") {
                this.sel = this.sel.substr(1);
                this.selArray = new Array(document.getElementById(this.sel));
            }
        }
    }
}

Framework.prototype = {
    constructor: Framework,

    ready: function(func) {
        // ...
    },

    click: function(func) {
        // ...
    }
};

The code that inspects the selector and calls querySelectorAll or getElementById is completely redundant and unneeded. If this.sel is a string, just blindly pass it to document.querySelectorAll. You've gained nothing by inspecting the selector. The speed difference between getElementById("foo") and querySelectorAll("#foo") will be negligible at worst, so why complicate your code?

if (this.sel) {
    this.selArray = typeof this.sel === "string"
        ? document.querySelectorAll(this.sel)
        : [this.sel];
}

Optimizing The Attaching Of Events

In your code, you loop over the array of elements, and on each iteration you test for attachEvent or addEventListener. Browsers won't magically change their native DOM API, so testing for these methods repeatedly when the result will be the same is extra work for the browser. Instead, create a method that does the event binding, which we will call bind.

Instead of testing for the "attachEvent" method on each iteration of the loop in click, test it once:

Framework.prototype = {
    constructor: Framework,

    ready: function(func) {
        // ...
    },

    click: function(func) {
        for (var i = 0; i < this.selArray.length; i++) {
            this.bind(this.selArray[i], "click", func);
        }

        return this;
    },

    bind: !!document.addEventListener
        ? function(element, event, func) {
            element.addEventListener(event, func, false);
            return this;
        }
        : function(element, event, func) {
            element.attachEvent(event, "on" + func);
            return this;
        }
};

The bind method is set on the prototype and makes use of a ternary operator to assign a function to the bind property that supports the current browser's native API instead of checking for support.

       // The Test: Does the browser have a document.addEventListener method?
    bind: !!document.addEventListener

     // Yes: The browser does. Use this function to bind events using standard API
        ? function(element, event, func) {
            element.addEventListener(event, func, false);
            return this;
        }

     // No: The browse does not. Use Internet Explorer's API
        : function(element, event, func) {
            element.attachEvent(event, "on" + func);
            return this;
        }

The decision to use attachEvent or addEventListener is made once at page load. The Framework.prototype.bind method will directly use the supported API for each browser rather than test for it.

More information on ternary operators: Conditional (ternary) Operator

Implicitly Declared Global Variables

Don't forget that variable assignments without var before the variable name create implicitly declared global variables. The for loop in the click method does this with the i variable, and your original Framework method mysteriously declares a global variable newTask.


Can anyone improve my multidimensional array more distinctive?

Shortest solution I can come up with:

function array_unique_recursive ($array) {

    // First loop the array and call self on any sub arrays
    // Note that $value is referenced
    foreach ($array as &$value) {
        if (is_array($value)) {
            $value = array_unique_recursive($value);
        }
    }

    // Now unique this level
    return array_unique($array, SORT_REGULAR);

}

print_r(array_unique_recursive($echo));

See it working


Best way to structure PHP AJAX handlers?

Lots of if's tend to signal the need for some classes. What are you using for the main routing that's being done by your app? In other words, when you point to domain.com/blog, how does your app know where to go?

One way to do routing is to use a front controller. It parses the request and makes the appropriate calls. From there, you can create classes for each individual controller your app needs. For example, perhaps you have a blog part of your site. Your front controller routes all requests that start with /blog to the BlogController.php class. This class has several methods: show, create, delete, recent, etc. And depending on the url request, the appropriate method is called.

At this point, adding ajax is easy & organized. Say you have implemented comments in PHP, so you have an addComment method on your Blog controller. To turn it into ajax, simply make your ajax request to /blog/comment/add (or whatever route you're currently using to get here). The front controller will point it to the appropriate method in your Blog controller, and now all you need to do is check if the request was ajax (look at the $_SERVER['HTTP_X_REQUESTED_WITH'] variable). If it was, return just the data you need (some success info).

To add new, ajax-only functionality, you can simply add more methods to your controller, and point your ajax request to the appropriate url. Essentially, you'll be using url's to handle your routing, instead of your if-else structure. And why not? That's what a web app is designed to do in the first place.

For more on this type of architecture, check out this really great article from Symfony2's documentation: http://symfony.com/doc/current/book/from_flat_php_to_symfony2.html.


Using Node.js, Express, and Express Router to implement a very simple REST API

After I examine the codes you have written, I could see some things that are not rightly done. Below are the few things I highlighted:

The structuring of the codebase is not okay hence it can be maintainable and scalable if the codebase grows.
The RESTful API naming convention is not an acceptable one. Endpoints of any REST API should contain only resources (nouns) and use HTTP methods (verbs) for actions. You named your endpoint as /qanda instead of /qandas. I recommend you read this RESTful API Designing guidelines by Mahesh Haldar posted at Hackernoon. It's a great resource for developers.
Thirdly, you did not separate your server from express; they are both coupled together. It's not best practice to do so.
When API is being consumed by other applications, upgrading the APIs with some changes would also lead to breaking the existing services contract - this has been noticed by a lot of applications that provide API services. It is a best practice to always prefix all your URLs with /api/v1/users . If there is any major breaking update, we can name the new set of APIs as v2, v3, or v1.X.X. respectively.

From my experience, this is how I would approach it:

Firstly, I will create a directory called, qanda-api, inside it, I'll create other directories called src and two files app.js and server.js that reside inside the root directory with src
Secondly, inside src I will create two sub-directories called routes and controllers
Thirdly, I will initialize an npm registry in the root of the project directory that keeps track of all npm installed packages by typing the command below via the terminal:

npm init

After that, I will install the three dependencies that I will be using via the same terminal, but this time you must have internet access:

npm install express dotenv morgan

If the above process executes successfully, you will see the installed packages inside a file called package.json

Now let's do the coding by getting our hands dirty

Let's first create a file named controllers/qandaController.js in other to write our qanda logic that will be exported to its route file.

exports.getAllQandas = (req, res) => {
    res.status(200).json({
        status: 'success',
        message: 'Documments retrieved successfully',
        data: 'The data goes here from the data!'
    });
};

exports.getQanda = (req, res) => {
    res.status(200).json({
        status: 'success',
        message: 'Doc retrieved successfully',
        data: 'The data goes here from the data!'
    });
};

exports.createQanda = (req, res) => {
    res.status(201).json({
        status: 'success',
        message: 'Qanda created successfully',
        data: 'Return the created data here!'
    });
};

exports.updateQanda = (req, res) => {
    res.status(200).json({
        status: 'success',
        message: 'Doc updated successfully',
        data: 'The updated data goes here!'
    });
};

exports.deleteQanda = (req, res) => {
    res.status(200).json({
        status: 'success',
        message: 'Doc deleted!',
        data: 'Return the Deleted data'
    });
};

Now, it's time for us to create our qanda route in routes/qandaRoutes.js. We will then import the controller logic in its route handler below.

const express = require('express');
/**
 * import the qanda controller
 */
const qandaController = require('./../controllers/qandaController');

const router = express.Router();

router
    .route('/')
    .get(qandaController.getAllQandas)
    .post(qandaController.createQanda);

router
    .route('/:id')
    .get(qandaController.getQanda)
    .patch(qandaController.updateQanda)
    .delete(qandaController.deleteQanda);

module.exports = router;

Let's open the file we created earlier on called app.js in other to make use of the express we had installed. The content of this file is only for express which is then exported to its server:

const express = require('express');
const morgan = require('morgan');

const qandaRouter = require('./routes/qandaRoutes');

const app = express();

if (process.env.NODE_ENV === 'development') app.use(morgan('dev'));

// ROUTES
app.use('/api/v1/qandas', qandaRouter);

/*
 ** HANDLING UNHANDLED ROUTES
 */
app.all('*', (req, res, next) => {
    res.status(404).json({
        status: 'fail',
            message: `Can't find ${req.originalUrl} on this Server!`
    });
});

module.exports = app;

Let's create our server which becomes our entry point to the application. This where the actual execution happens whereby the exported app.js get used by inserting it as an argument in the createServer() function.

require('dotenv').config({ path: '.env' });
const http = require('http');

const app = require('./app');

const port = process.env.PORT || 5000;

const server = http.createServer(app);

server.listen(port, () => console.log(`App running on port ${port}`));

Conclusion
It's highly recommended to always have separation of concerns while writing codes and to aptly have a clean codebase that is maintainable and scalable over time. There's more to code organization when it comes to API design, one of it is the DRY principle (Don't Repeat Yourself). If you want to learn more about API design in Node.JS I recommend you take this course by Jonas. He demystifies the abstract concepts and taught best practices to the core. I've wrapped this answer with API design projects in Github: API and Tourism API. Feel free to clone or modify as you need.


Java code to convert between hex & binary strings

There are several things that hinder the performance of your code:

You are using a map to convert from hex digits to binary strings. However map lookups are slow, compared to simple array indexing or a switch statement . What you need to do, instead of using a map, just use a switch statement, when converting from hex to bin:

    switch (s.charAt(i))
    {
      case '0':
        binaryString.append("0000");
        break;
      ...
      case 'F':
        binaryString.append("1111");
        break;
    }

However, this approach probably will not be as efficent when converting from bin to hex.

Because it is easy to calculate the length of a bin string from the length of a hex string, you can easily preallocate StringBuilder's with the calculated size. This will save you time, because the will be no memory reallocations.
If you code is not multithreaded, you could preallocate the StringBuilder's themselves and store them in some private fields of your class. This way you'd avoid spending time for unnecessary creation of the object, that would almost immediately be destroyed.


Print an integer and its digits reversed

This problem is more about numbers than strings, so I felt the need to post a non-string-based solution. I've got my original Scheme version, and a Common Lisp adaptation of same.

Scheme version:

(define (reverse-digits n)
  (let loop ((n n) (r 0))
    (if (zero? n) r
        (loop (quotient n 10) (+ (* r 10) (remainder n 10))))))

Common Lisp translation of the Scheme version:

(defun reverse-digits (n)
  (labels ((next (n v)
             (if (zerop n) v
                 (multiple-value-bind (q r)
                     (truncate n 10)
                   (next q (+ (* v 10) r))))))
    (next n 0)))


Your general idea is correct - looping over columns to find out if one of them is active, and then only looping over the rows to find out which button was pressed will be somewhat faster (as in: more responsive) than checking each possible button separately.

If I were to suggest any improvements in the method - you could look into using pin change interrupts instead of busy looping. This would provide you with hardware support to detect when a pin goes LOW.
This would also allow you to put your arduino to sleep to save power while waiting for a button to be pressed.

You might also need to debounce the keypress since you can get momentary false readings from a switch. This would basically require a small delay (usually less than 100ms) after you detect a keypress, and then rechecking after the delay if that switch is still active.

the comments below are going beyond your question but I decided to add them for some perspective on coding style

As far as your code goes I would suggest putting the entire key-checking logic in a single function that uses local variables for your column and row counters. This primarily helps with reasoning about the code but also has a small positive effect on memory usage overall (memory on the stack will be reclaimed after a return from the function).

Instead of using magic numbers throughout your code you should use constants/macros. This has the benefit of giving the value a name, and having a single place that would require changing instead of multiple values that are not easily ctrl+f'able. Calculating array length can be automated. This eases adding changes further on, and helps enforce correctness by the compiler.

You should also declare your pin arrays as const if possible. This will make optimizing your code easier for the compiler.

A sample of how this would look together:

//define rows and columns
const byte row[] = {9,8,7,6};
const byte rowCount = sizeof(row) / sizeof(row[0]); //old C trick for calculating static array length
const byte col[] = {5,4,3,2};
const byte colCount = sizeof(col) / sizeof(col[0]);

const byte keys [ rowCount ] [ colCount ] =
{
    {0x1,0x2,0x3,0xA},
    {0x4,0x5,0x6,0xB},
    {0x7,0x8,0x9,0xC},
    {0xE,0x0,0xF,0xD}
};


Finding the lowest perfect square that can be added to a number to make another perfect square

I can see a few changes you can do in your code.
First one, save the calculated square and use it in the next iteration:
def solve2(n)
  # Start with an initial zero value
  pow = 0
  (1..n).each do |i|
    # This is the same as i**2, but using the square previously calculated.
    # Google squares and pascal triangle to more insight about this, but
    # in terms of cpu usage, this is faster.
    pow = pow + (i - 1) * 2 + 1
    r = pow + n
    return r -= n if (Math.sqrt(r) % 1).zero?
  end
  -1
end

And yes, it's not a big improvement, but it works. Trying in a worst case scenario, where no value is found so it must check every different iteration:
irb(main):250:0> require 'benchmark'
=> false
irb(main):251:0>
irb(main):252:0> Benchmark.bm do |x|
irb(main):253:1*   x.report { solve 50_000_002 }
irb(main):254:1>   x.report { solve2 50_000_002 }
irb(main):255:1> end
       user     system      total        real
   9.072362   0.029596   9.101958 (  9.783397)
   8.491063   0.030566   8.521629 (  9.159671) # ~600ms faster than the previous one, yay!

Next thing, instead of iterating between 1 and n, you need to iterate only integer values between Math.sqrt(1**2 + n) and Math.sqrt(n**2 + n). For example, using the current code with the same 50_000_002 value of the benchmark:
irb(main):358:0> Math.sqrt(1**2 + 50_000_002)
=> 7071.068023997506 # 1st iteration, for sure this will fail with ( % 1).zero?
irb(main):359:0> Math.sqrt(2**2 + 50_000_002)
=> 7071.068236129531 # 2nd one still with decimals
irb(main):360:0> Math.sqrt(3**2 + 50_000_002)
=> 7071.068589682892 # and so on...
irb(main):361:0> Math.sqrt(4**2 + 50_000_002)
=> 7071.069084657567
irb(main):362:0> Math.sqrt(5**2 + 50_000_002)
=> 7071.069721053526

as you can see, for the first values of the iteration, you're getting pretty much the same integer value with only decimals of difference. Eventually you'll be close to get an integer value much further in the 114th iteration:
irb(main):392:0> Math.sqrt(114**2 + 50_000_002)
=> 7071.986849535285
irb(main):393:0> Math.sqrt(115**2 + 50_000_002)
=> 7072.003040157718 # that was close, but not enough to get a integer. Keep trying...

So checking all those 114 values were useless, because their results weren't even integers. After a while, reaching the last values, you still don't get a single integer value:
irb(main):394:0> Math.sqrt(50_000_000**2 + 50_000_002)
=> 50000000.500000015
irb(main):395:0> Math.sqrt(50_000_001**2 + 50_000_002)
=> 50000001.50000001
irb(main):396:0> Math.sqrt(50_000_002**2 + 50_000_002)
=> 50000002.5

Then, the problem was to check float values when we need to check only when values have no decimals. In other words, instead of iterate between 1 and 50_000_002, you must iterate between 7072 (ceiling value for result of Math.sqrt(1**2 + 50_000_002), taken from your first previous iteration) and 50_000_002 (floor result of Math.sqrt(50_000_002**2 + 50_000_002), your last iteration, which at the end is the same value as n).
Why using this new perspective? mostly because Math.sqrt is an expensive operation compared with +, - or * (or even ** if the solve2 improvement hasn't been applied). I'll try to explain as much as I can in the code:
def solve3(n)
  # Lowest square root result. This will be the starting point
  lowest_sqrt = Math.sqrt(1 + n).ceil
  # then getting first i value to compare. This is the last time using
  # Math.sqrt
  i = Math.sqrt(lowest_sqrt**2 - n).to_i
  # Keeping a flag, which will be the value to return later
  flag = i
  # Initial values for perfect square, where will be used the base value from
  # previous iteration (that's why i - 1) to make the power replacement as in
  # solve2
  pow = (i - 1)**2
  # and result after adding the n value.
  res = sq(pow, i) + n
  loop do
    pow = sq(pow, i)
    # When square and result are the same, that's our lowest perfect square
    return flag**2 if res == pow

    # In case result is lower, result must be recalculated with new square
    # value.
    if res < pow
      flag = i
      res = pow + n
    end

    i += 1
    break if i > n
  end
  -1
end

# pascal triangle trick
def sq(pow, i)
  pow + (i - 1) * 2 + 1
end

This is a significant improvement compared with previous implementations:
irb(main):908:0> Benchmark.bm do |x|
irb(main):909:1*   x.report { solve 50_000_002 }
irb(main):910:1>   x.report { solve2 50_000_002 }
irb(main):911:1>   x.report { solve3 50_000_002 }
irb(main):912:1> end
       user     system      total        real
   9.077371   0.036185   9.113556 ( 10.015861)
   8.486830   0.026608   8.513438 (  9.090664)
   4.709684   0.012402   4.722086 (  4.925373)

And I think there's still space to improve the code. I have the feeling there are some useless comparisons in the loop that can be avoided, but I've spent a while explaining all this, so I'll leave that to you :)


Soccer winning probabilies from ELO strength indicator

With the possibility of first_at_home and second_at_home both being True, there really is not too much to improve on here.

The only things I see are:

Instead of doing first = first + 100, you can do first += 100.
Instead of doing -((first - second)/ 400.0) you can do (second - first)/ 400.0.
There is also no need to specify your operands as floats (400.0 vs 400) because Python does float division with the basic / operator.

Here are my improvements:

def winning_prob(first, second, first_at_home=False, second_at_home=False):
    """ Return winning probability, given ELO ratings of two soccer teams

    Args:
        first: ELO rating of first team
        second: ELO rating of second team
        first_at_home: is first team playing at home?
        second_at_home: is second team playing at home?

    Returns:
        Winning probability of first team against second team
    """
    if first_at_home:
        first += 100
    if second_at_home:
        second += 100

    return 1 / (10**((second - first)/400) + 1)


Coupon code generator using the strategy pattern in PHP

It's correct. But if you want to restrict return types to something specific (and I would, because db) you could write interface functions like this:

function generateCoupon(): string;
function generateDiscount(): int;

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

http://php.net/manual/en/functions.returning-values.php


Need some advice and feedback on my C code calling Bash functions

Comments

Because your question is marked clean-code and I see that you have commented your declaration of the variable command with the comment command, let me make a note about comments. There are good comments, and bad comments; in my experience, a very high numbers of comments written by many developers are bad. For a thoughtful exposition of comments, see Bob Martin's chapter on them in Clean Code (an invaluable book). In short, if you are going to insert a comment, make sure it actually adds something. Then, make sure you can't add that information into the code itself, by renaming variables, etc. Then, if you can't, carefully craft your comment.

Functions

Because you are asking about the general cleanliness of your code, let me advice that you use smaller functions. There are many benefits to small functions, which I will not get into here; many of the best software books discuss this, including Martin's book, mentioned above.

Magic Numbers

Replace numbers like -1 and 10 in your code with a constant that has an explicit name explaining these numbers. This increases the readability and maintainability of your code.

Stdout and Stderr

In Unix, C and C-based languages, you have three streams attached to your process by default: standard in, standard out, and standard error. Don't write error messages to standard out—write them to standard error.

Calling Bash from C

Consider that calling Bash...

...makes your code much, much less portable, by tying it down to a system with Unix utilities—and more specifically than that, one that has Bash—and more than that, one that has a version of Bash which supports all the features you decide to use.
...makes your code harder to test

by creating external dependencies. If you are not familiar with the problem of dependencies, try reading up on it. Roy Osherove, in The Art of Unit Testing, and Michael Feathers, in Working Effectively with Legacy Code, both have much discussion of it.
Bash scripts do not have the debugging tools for than that C has (Valgrind, GDB, IDEs, etc).

...makes your code harder to read:

by lessening its homogeneity
by making the user move around move between various source files
by lessening your IDE's ability to aid you in traversing the code, since some of the calls are embedded in strings as calls to an external
because Bash is often even harder to read than C

...makes your code harder to maintain, because of being harder to test and read.
...is unnecessary, because under the covers Bash is just calling the Unix C API anyway.
...is artistically distasteful— it smells like a kludge.
...adds a failure point to your code. Just look how many possible error messages you output, and then abort!
...presumably, this will also be a performance hit because of the overhead of running Bash.

I would strongly advise you not to use sys calls unless you are calling a very complex external application that would be difficult to reproduce in your C code in reasonable time and doesn't have a C API (and serious applications are not generally written in Bash) or you are performing an extremely low-level function that there is no C API for. Work for homogeneity—it's much cleaner.


Reverse the character order of the words in a string

I like the effort that you put into naming your variables.  You may have gone a bit overboard, though.  For example, instead of candidateReversedWordsString, how about result?

A few mechanical issues:

This could be a static method, since it relies on no instance state.
It's pretty funny that you defined a final String[] of length 1 to store one String with the ability to change its only element.  Why not just use a regular String variable?
You have…

 int stringCharacterIndex = 0;
 …
 while (stringCharacterIndex < string.length()) {
     …
     stringCharacterIndex++;
 }

That pattern would be easier to understand if written as

for (int i; i < string.length(); i++) {
    …
}

Here, I would opt for a short variable name i, which has the connotation of being a loop counter that is an index.  string[i] is easy enough to understand.

This statement summarizes your strategic error:

candidateReversedWordsString[0] = new StringBuilder().
        append(candidateReversedWordsString[0].substring(0, wordStartIndex)).
        append(reverseWordStringBuilder.reverse().toString()).
        append(candidateReversedWordsString[0].substring(stringCharacterIndex)).toString();

Basically, you are rebuilding the entire tentative result string every time you want to reverse a word.  That's bad for performance, and also complicates your code.

I think that you would be better off without using any StringBuilder, and just using a char[] instead, especially since you know that the result will be exactly the same length as the input.

Consider this solution instead:

public static String reverseWords(String string) {
    char[] c = string.toCharArray();
    int wordStartIndex = -1;
    for (int i = 0; i < c.length; i++) {
        if (c[i] == ' ') {
            // Ignore spaces
            continue;
        }
        if (wordStartIndex < 0) {
            // Mark start of word
            wordStartIndex = i;
        }
        if (i + 1 == c.length || c[i + 1] == ' ') {
            // Word ends here; reverse it
            for (int a = wordStartIndex, b = i; a < b; a++, b--) {
                char swap = c[a];
                c[a] = c[b];
                c[b] = swap;
            }
            wordStartIndex = -1;
        }
    }
    return new String(c);
}


Given an arbitrarily large file containing integers, return the largest N numbers, highest first

Consider remembering the n largest numbers:

def top_n(filename, n = 100)
    require 'set'

    topn = SortedSet.new()

    File.foreach(filename) do |line|
        num = line.to_i
        if topn.length < n
            topn.add(num)
        elsif num > topn.first
            topn.delete(topn.first)
            topn.add(num)
        end
    end
    return topn.to_a
end


Check if the user is 18 years old (upto days)

There's a potential bug in your method if the user is born just the day after the age requirement. Your method will return true when it should in fact return false. For example the following code prints true:

public static void main(String[] args) {
    DateTime test = new DateTime().minusYears(1).plusDays(1);
    System.out.println(isUser18Older(test, 1));
}

public static boolean isUser18Older (DateTime userDob, int minimumAge){
    DateTime minAge = new DateTime();
    Days days = Days.daysBetween(userDob, minAge.minusYears(minimumAge));

    return days.getDays()>=0 ;
}

although the user was born the day after the requirement. This is because you're not taking the time into account.

The name of the method is misleading with regard to what it does. It is named isUser18Older, which implies that the method checks whether a user has at least 18 years-old. However, the method takes a minimumAge parameter, which is actually the minimum age requirement. Therefore, I suggest renaming that method hasAgeRequirement.

The code itself could be written more simpler and to-the-point. Instead of getting the number of days between the two dates, just retrieve the number of years between the date of birth and today and compare it with the age requirement:

public static boolean hasAgeRequirement(DateTime userDob, int minimumAge) {
    DateTime now = new DateTime();
    Years age = Years.yearsBetween(userDob, now);
    return age.getYears() >= minimumAge;
}

This is easier to read since it directly codes the intent of the method.


UPenn CIS 194 Homework 1: Validating credit card numbers

You're on the right track, I think.  If I had to pick one general criticism, it would be to watch out for redundant special cases.

In my opinion, the exercise guides you towards making an unnecessary complication in toDigits and doubleEveryOther.  Actually, the list of digits from right to left, as produced by toDigitsRev, is the more natural representation to work with.  If you work with the list in left-to-right order, then doubleEveryOther needs to look ahead to see whether the list has an odd or even digit count, which is awkward.  Therefore, if given free reign, I'd define a doubleEveryOther' that expects right-to-left input instead.

toDigitsRev does not need special cases for 0 and for n < 10.  Instead of calling div and mod, use the divMod function to capture both pieces of information from the same calculation.

toDigitsRev :: Integer -> [Integer]
toDigitsRev n
  | n <= 0    = []
  | otherwise = m : toDigitsRev d
  where
    (d, m) = n `divMod` 10

As mentioned above, we can simplify doubleEveryOther by working right-to-left:

-- Doubles the second, fourth, sixth… numbers in the list
doubleEveryOther' :: [Integer] -> [Integer]
doubleEveryOther' (x:y:zs) = x : 2 * y : doubleEveryOther' zs
doubleEveryOther' (x:[])   = [x]
doubleEveryOther' []       = []

You don't need a case for sumDigits (x:[]) — it's already covered by sumDigits (x:xs), where xs is the empty list.  The way you wrote it is fine, but personally I'd prefer to write it as sum . map sumDigits' so that you can see at a glance that it's performing a sum of some transformed values.

sumDigits :: [Integer] -> Integer
sumDigits = sum . map sumDigits'
  where
    sumDigits' n
      | n < 10    = n
      | otherwise = sumDigits $ toDigitsRev n

The validate function does not need a special case for 0.  It's also more idiomatic to set up a "pipeline" of function calls using $ than to use nested parentheses.

validate :: Integer -> Bool
validate n = 0 == (sumDigits $ doubleEveryOther' $ toDigitsRev n) `mod` 10


Some notes:

Without knowing the internals of the app, the use of some hardcoded values like dropoff_slits=-1 or doorman_type="none" look a bit suspicious.
Keep the maximum line length to 80 (100 at most) chars.
Write parens in method signature: def self.latest_pickup_date(current_zone, doorman).
latest_timeslot.nil? ? Date.current : latest_timeslot.slot_date. Use  Object#try instead: latest_timeslot.try(:slot_date) || Date.current.

There are many valid ways of DRYing this method. That's what I'd write:

def self.latest_pickup_date(current_zone, doorman)
  base_timeslots = Timeslot.where(dropoff_slots: '-1', zone_id: current_zone)
  timeslots = doorman ? base_timeslots : base_timeslots.where(doorman_type: "none")
  timeslots.order(:slot_date).last.try(:slot_date) || Date.current
end


While it's clear that you're new to python, it's still pretty good that you got it to run first time. Good job!

Input Validation

Currently, you have a list of forbidden characters. While that can work, by default python allows unicode input. That means there's literally thousands of letters someone can input. I suggest instead using a whitelist of valid inputs. Like this:

VALID_LETTERS = "abcdefghijklmnopqrstuvwxyz"  # This won't ever change, and typically this sort
# of things  is a module-level variable.

def valid_word(word):
    for letter in word:
        if letter not in VALID_LETTERS:
            print(f"Letter {letter} is not a valid letter. Please use just a-z.")
            return
    if len(word) > 8:  # This was 12 in your script. Little mistake? And you might want a
        # module-level constant for this as well.
        print("\n\nError: Word is too long. Use a word with eight characters or less.")
        return False
    return True

main() and game()

Generally, in python we never execute code at the moment the module is loaded. Read here for details, and how we guard against it. I'll come back to this later. For now, it means we should put as much as possible into functions - lets call them main() and game().

main() will be the main menu function. Since we don't have a true menu, this will basically start a game, and perhaps ask if the player wants to play again.

game() will be a function that lets us play a single game. Most of this will be a loop that gets player input and calculates the game state. Basically everything in your script that isn't another function should be in the game() function.

I'll cut some variables we don't need later on. I'll explain them when we get to where we use them.

Like this:

def game():
    # Variable naming is important. This is an example of a good name.
    guessed_letters = []

    # ill_chars = [...]  We already have this variable before here!

    # Lets assign the parts directly. We can index them as in "3rd part".
    # And for ourselves, we comment the meaning to make sure we still know what it means a year
    # from now.
    hangman_parts = [
        "    O",  # Head
        "   /",  # Left Arm
        "|" ,  # Torse
        "\\",  # Right Arm
        "/",  # Left Leg
        " \\"  # Right Leg
    ]
    hangman_progress = ["",
                        "|",
                      "\n|",
                      "\n|"]

    hangman_final = ["|~~~~|\n"]

    # Check if word is valid

    # Naming: should be word_is_valid, to be consistent with your other variables.
    word_is_valid = False
    while not word_is_valid:
        word = input("\n\n\nChoose any word\n\n\n").lower()
        word_is_valid = valid_word(word)
    # With this loop condition, it'll keep asking until valid_word returns True. So we can just
    # assign that value to word_is_valid directly.

    # Since this is the word we're trying to guess, lets just push it upwards in
    # the console a lot, so we won't see it all the time:
    print("\n" * 100)  # Prints 100 newlines.

    # We don't need word_list, just word will do. We don't need spaces either.
    while True:  # Main game loop. We don't need to check for anything, we'll just use break or
        # return to get out.

Now we're going to use a list comprehension. It's almost the same as a generator expression, but it gives us a true list, so we can ask python how long it is:

        # Calculate how many bad letters we have with a list comprehension:
        bad_letter = len([letter for letter in guessed_letters if letter not in word])
        draw_hangman(bad_letter)
        if bad_letter > 5:
            print("\n\n\n\nYOU GOT HUNG")
            return
        print("\n\n\n\n")

You used to draw your hangman at two different places, while it's more practical to do it in one place. It also ensures that if you want to change something, you'll only have to change it once.

I've also changed how to draw it. It's much more useful to have a function for this drawing operation, and have it calculate how to draw from the number of bad letters so far. This makes the drawing independent of the current game state. Here's the version I came up with, based on your modifications of hangman_final:

def draw_hangman(bad_letter):
    print(hangman_final, end="")
    if bad_letter > 0:  # Head
        print(hangman_progress[1] + hangman_parts[0], end="")
    if bad_letter == 2:  # Torso and arms
        print(hangman_progress[2] + "    " + hangman_parts[2], end="")
    elif bad_letter == 3:
        print(hangman_progress[2] + "".join(hangman_parts[1:3]), end="")
    elif bad_letter > 3:
        print(hangman_progress[2] + "".join(hangman_parts[1:4]), end="")
    if bad_letter > 4:  # Legs
        print(hangman_progress[3] + "   " + hangman_parts[4], end="")
    if bad_letter > 5:
        print(hangman_parts[5], end="")

Here we need to print the letters we guessed, and underscores otherwise. We can calculate and print it in one line:

        print(" ".join(letter for letter in word if letter in guessed_letters else "_"))

For every letter, this will print it if it's contained in guessed_letters, and otherwise print an underscore. This is a generator expression. This one is almost equal to the function:

def make_word(word, guessed_letters):
    result = []
    for letter in word:
        if letter in guessed_letters:
            result.append(letter)
        else:
            result.append("_")
    return result

I say almost, because it's not exactly a list that comes out of it, even if it acts the same if you use it in a for loop or feed it to a function that does, like "".join(). It also acts more like a loop than a function, but that's not really important right now.

We feed the result to the join. And note that we feed it to " ".join(), with a space in between, which will put a space between every letter like you did before.

        print(f"\n\nThe word has: {len(word)} letters.")  # f-strings are shorter, and easy to use.
        print(f"\nYou've tried the following letters:\n\n{''.join(guessed_letters) }\n\n")
        # For a string literal inside an f-string, use the other type of quotes

        # This is another generator expression - this one returns a not-quite-list of booleans, and
        # the all() builtin function returns True if and only if all results of the generator
        # expression are True.
        if all(letter in guessed_letters for letter in word):
            print(f"You WIN!\nThe word was: {word}")
            return

        input_valid = False
        while not input_valid:
            new_letter = input("\n\nPlease choose a letter: \n\n\n\n").lower()
            # VERY GOOD that you lowercase it! Prevents tons of weird behaviour.
            if len(new_letter) > 1:
                print("Please enter a single letter only.")
            elif new_letter not in VALID_LETTERS:
                print(f"{new_letter} is not a valid letter. Please enter a letter a-z")
            elif not new_letter:  # Empty strings evaluate to False
                print("Please enter a letter before pressing enter.")
            elif new_letter in guessed_letters:
                print("You already guessed {new_letter} before!")
            else:
                guessed_letters.append(new_letter):
                input_valid = True

This is pretty close to your input. But I put it in a loop, so if we have an invalid input, we don't have to traverse the entire game loop again. I use a pretty simple signalling boolean to keep it going, but perhaps there's more elegant ways to do this. Never wrong to keep it simple, though.

Right now, to play the game, all you have to do is call the game() function. But perhaps we want to play multiple games in series? Lets make our main() function:

def main():
    game()
    while "y" in input("Play again? [Y/n]").lower():
        game()

Why is this in a separate function? Again, for the sake of extensiblility. Perhaps, we want to import our game from another module. If so, we don't want it to run when we import, but when we call a function. So we end the script with this guard:

if __name__ == "__main__":
    main()

If we execute this file directly, this will run our main() function and let us play the game. But if we import it, it won't, so we can call the function when we want it.


Your solution looks correct, though it is a bit long.

One way to shorten it is to remove the elses:

def goto(level, button)
  inputs_types_are_accepted = (level.is_a? Integer) && (button.is_a? String)
  if inputs_types_are_accepted
    current_floor, desired_floor = level.to_i, button.to_i
    if current_floor.between?(0, 3) && desired_floor.between?(0, 3)
      floor_change = desired_floor - current_floor
      return floor_change
    end
  end
  # Don't move elevator if the input is wrong in any way
  0
end

You don't need to do level.to_i when you have already ascertained that level is an Integer. You can also eliminate the variables inputs_types_are_accepted and floor_change.

(current_floor && desired_floor) won't work.  In English, you can ask whether "the current floor and desired floor are both between 0 and 3", but you can't translate that literally into Ruby.  Since you want to perform two tests, you have to write it as two tests.  The way the && operator works is that it will return the left operand (current_floor) if it is considered true — and in Ruby, every integer is considered to be true.

One thing that I like about your solution and that I dislike about the "top-voted" solution is that the latter does not extend well to handle more than 10 floors.  Although the problem states that there are just 4 levels, but still, using ('0'..'3').include?(button) to validate the floor in the string domain rather than the integer domain feels like a hack to me.

Obviously, there are many possible formulations.  It's a new moon today, so I feel like writing it this way:

def goto(level, button)
  floors = (0..3)

  # Validation: don't move elevator on invalid input
  return 0 unless button.kind_of?(String) && floors === (dest = button.to_i)
  return 0 unless floors === level

  dest - level
end

The way you wrote your solution tends to lead to deeper nesting.  As a rule of thumb, it is preferable to return early on failure, since there are usually many ways to fail, but only one way to succeed.


I am thinking that you would want to keep that default route in there in the case that something happens to the other routes, then there is something to route to if your custom routes get hosed up for some reason.

Defaults are there for a reason, don't get rid of them


Count non-transparent pixels in a canvas

What about this?!

data = context.getImageData(0, 0, canvas.width, canvas.height).data
count = 0
count++ for x, i in data when (i+1) % 4 is 0 and x > 0


Rosalind problem "Consensus and Profile"

I am going to ignore all the file reading code, which is extraneous to the problem, and focus just on simplifying the code to find the consensus.  It can be done in essentially a single a line, the one beginning consensus = ....  Everything else is just setting up the sample data.

transpose gets us the columns, and max_by ... count get us the most frequently occurring nucleotide:

matrix = <<EOS
A T C C A G C T
G G G C A A C T
A T G G A T C T
A A G C A A C C
T T G G A A C T
A T G C C A T T
A T G G C A C T
EOS
.split("\n").map{|x| x.split(' ')}

nucleotides = %w(A C G T)

consensus = matrix.transpose.map {|x| nucleotides.max_by {|n| x.count(n)}}

p consensus #=> ["A", "T", "G", "C", "A", "A", "C", "T"]


Post line-oriented timings from a profiling run, please. Where does it actually spend its time?
Curly braces {} are good for you, even when your for or if statement is a one-liner. Someone will be maintaining this code later, and it might not be you.
Please rename to radixSort(), from the Latin word for root.
Recursion overhead is simply not an issue here.
I imagine you're testing with random integers, so stability or reversing would not affect that. But think about timsort https://en.wikipedia.org/wiki/Timsort which is stable. If there are runs of non-descending input values, you would really like to preserve them. That would let you verify and terminate early.
Arrays.sort() runs in \$O(n \log{n})\$ time. Your radix sort is "efficient" in the sense that it runs in \$O(n)\$ time, but the notation can hide impressively large constants, like bits per Integer in your case. A linear read scan tries to blow out memory bandwidth, and L2 (last level) cache won't help you. You're not even working on cache-size subproblems with a subsequent merge. Yes, I agree that switching to an \$n\log{n}\$ sort for limited size subproblems would be helpful.
You mentioned decimal digits, and I see no reason to go there. But consider sorting into 4 buckets during a pass, or 8, or 16....


As far as I can tell, it checks if you provide too many options, but it doesn't check if you provide too few. This should be done before trying to do anything with SRC and DST. set -o errexit -o nounset as the first line would be prudent.

set stuff is not inherited by subshells. So to make a failure in the dd command propagate you should start with set -o errexit -o pipefail. A simpler way to achieve the same effect would be to add -o pipefail to set, create a function with the dd | xxd commands, and use this directly instead of assigning to variables.

What happens if dd fails, for whatever reason? For example, dd() { echo foo; } will override the command. Use command dd [sic] if you want to make sure it doesn't use shell builtins, aliases or functions.
There's no == operator in POSIX [ - AFAIK this only works by accident on some systems. You can either use Bash' [[ or a single =.
|| true can hide issues with the preceding command. Either check first if the command should be run before trying (and not ignoring the error), or run the command and check if the exit code matches the one you expect.
Use More Quotes™

I can't comment on the safety of the KEYn generation or setkey use.


Creating a styled component inside a component function

You generally should not to nest your components. Though when the component is small enough, like a one-liner, it's fine to do so.

In your specific case, you can make use of withComponent method to change the tag name of an existing component:

const Heading = styled.h2`
    margin: 0;
    ...lots of css...
`;

const Title = (props) => {
    const StyledHeading = Heading.withComponent(props.headingLevel || "h2");
    ...
};

You'd still be defining the StyledHeader inside another component, but most of the code would live outside.

Additionally...

I noticed these long lines:

font-weight: ${styleData['typography_settings']['title'][props.typographySize]['weight']};

Looks like this styleData is some sort of theme. I suggest you look into  built-in theming support of styled components before rolling your own.
The variable hasSupplementaryTitle can be eliminated. It's conventional to perform an existence check by just:

if (props.supplementaryTitle) {


TamperMonkey script to add a button to Jira

The code is well commented. The indentation in most places seems to be four spaces but the last few lines have indentation of two spaces so that could be made more consistent. The last comment is a bit humorous...

It seems that if the button isn't found by the id attribute, it just bails. There could be alternative ways to find that button. For example, my company recently upgraded to version 7.11.2 and it appears that the create button still has an id attribute of create_link but the list item above it also has an id attribute of create-menu so that element could be found instead. And the unordered list also has a class name of aui-nav so if the create button can't be found the list could be found instead.  I also see in the latest online version 1001.0.0 (e.g. *.atlassian.net) that the navigation menu has been moved to the left side of the screen and no longer uses list items so if your Jira gets updated you'll need to update your approach to finding that element.

I know you are familiar with const given your answers like this one so why not use it for things like projectCode, idat?

Also, a list item element is created and then the innerHTML contains another list item element:

var node = document.createElement("LI");
node.innerHTML = '

Log activity

';

This yields HTML like below:

Log activity

MDN's documentation for
 claims "It must be contained in a parent element: an ordered list (
), an unordered list (
), or a menu (<menu>)"1 and that the permitted content is Flow Content, which does not include list item elements.  But obviously our browsers render it as expected. Ideally that list item would not contain a child list item...

You could consider using the fetch API instead of classical XHR requests unless browser compatibilty is an issue.

And since you are using ecmascript-2015 features like let, you could consider using more arrow functions...

1https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li


For one thing, it is very inadvisable to use the += operator with strings, because it's slow and it requires the string to be relocated in the memory. This isn't much of a problem with higher-level languages like Python, but with C and also Java, it's not a good idea, and it's not good practice. Since you know that there are 26 letters in the alphabet, you can make a length 26 array to store the key instead. Otherwise, the rest of the code looks good! :)


Determining if a sentence is a palindrome

The implementation given by @janos is a good one, but it is possible to improve it further. Specifically, most of the inefficiency arises from the single line:
char[] chars = string.replaceAll(" ", "").toLowerCase().toCharArray();

The replaceAll() method creates another copy of the string. Then, toLowerCase() creates another copy of the string. Finally, toCharArray() creates yet another copy in a character array of the resulting string. Of course, with the exception of the final result, the rest will get garbage collected. But each of the copies in an additional O(n) time.
Here is a suggestion:
private static boolean isPalindrome(String s) {
    int i = 0;
    int j = s.length() - 1;

    while (i < j) {
        if (Character.isWhitespace(s.charAt(i))) {
            i++;
            continue;
        }

        if (Character.isWhitespace(s.charAt(j))) {
            j--;
            continue;
        }

        if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) {
            return false;
        } else {
            i++;
            j--;
        }
    }
    return true;
}

I used the following test code to compare the performances of the two methods:
public class Main {

public static void main(String[] args) {

    String palindrome = "a b c de f g h x x xa b   a xxx     hg f e d c b  a";
    String nonPalindrome = "abcd e f g h  xxxabcxxx hgfe  d c ba";

    long start = System.currentTimeMillis();

    for (int i = 0; i < 1000000; i++) {
        Main.checkPalindrome(palindrome);
        Main.checkPalindrome(nonPalindrome);
    }

    long elapsed = System.currentTimeMillis() - start;

    System.out.println("checkPalindrome: time elapsed: " + elapsed + " milliseconds.");

    start = System.currentTimeMillis();

    for (int i = 0; i < 1000000; i++) {
        Main.isPalindrome(palindrome);
        Main.isPalindrome(nonPalindrome);
    }

    elapsed = System.currentTimeMillis() - start;

    System.out.println("isPalindrome: time elapsed: " + elapsed + " milliseconds.");

}

private static boolean isPalindrome(String s) {
    int i = 0;
    int j = s.length() - 1;

    while (i < j) {
        if (Character.isWhitespace(s.charAt(i))) {
            i++;
            continue;
        }

        if (Character.isWhitespace(s.charAt(j))) {
            j--;
            continue;
        }

        if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) {
            return false;
        } else {
            i++;
            j--;
        }

    }

    return true;
}

private static boolean checkPalindrome(String string) {
    char[] chars = string.replaceAll(" ", "").toLowerCase().toCharArray();
    for (int i = 0; i < chars.length / 2; ++i) {
        if (chars[i] != chars[chars.length - 1 - i]) {
            return false;
        }
    }
    return true;
}

}

Running on my computer produced the following result:

checkPalindrome: time elapsed: 7373 milliseconds.
isPalindrome: time elapsed: 421 milliseconds.


Fast affine transformations of many 3D points by one 3×4 matrix

Small differences due to precision are expected and can usually be ignored.

12 shuffles like that are a bit much, though not necessarily avoidable, depending on whether there is AVX support. With AVX, it is better to literally broadcast from memory, rather than emulate broadcasting with a load and shuffles. Even though this means there will be more loads, the shuffles are a bigger problem: loads (even broadcasting loads) typically have a throughput of 2/cycle while the shuffles typically have a throughput of 1/cycle. This means that _mm_set1_ps(float) is actually the better option, as long as you compile with AVX support. That wouldn't use the wider width yet though.

Also annoying is that MSVC apparently likes to reload those pointers inputs_.xs etc continuously. There is really no spare load-throughput for that, despite the presence of 9 FP additions (which are also bad though, since they're 1/cycle pre-Skylake), there are 21 loads there, limiting the throughput of the loop to once every 10.5 cycles (which is more than 9, if barely). Fortunately it can very easily be convinced to stop doing that, simply by copying them into local variables before the loop.

Next, I don't know what MSVC is up to there with its refusal to contract addition and multiplication into FMA, for processors that support it it should definitely be used. Using the corresponding intrinsic does the trick of course, but that makes it harder to compile for pre-FMA targets (Ivy Bridge and older). Anyway if I write the high level code like this:

Vector4 *   xs = inputs_.xs;
Vector4 *   ys = inputs_.ys;
Vector4 *   zs = inputs_.zs;
Vector4 *   outxs = outputs_.xs;
Vector4 *   outys = outputs_.ys;
Vector4 *   outzs = outputs_.zs;

for( int i = 0; i < number_of_packets_; i++ )
{
    outxs[i] = _mm_fmadd_ps(m02, zs[i],
               _mm_fmadd_ps(m01, ys[i],
               _mm_fmadd_ps(m00, xs[i], m03)));

    outys[i] = _mm_fmadd_ps(m12, zs[i],
               _mm_fmadd_ps(m11, ys[i],
               _mm_fmadd_ps(m10, xs[i], m13)));

    outzs[i] = _mm_fmadd_ps(m22, zs[i],
               _mm_fmadd_ps(m21, ys[i],
               _mm_fmadd_ps(m20, xs[i], m23)));
}

The actual code looks pretty good, apart from the fact that it uses short vectors:

$LL4@transform_:
    lea      rcx, QWORD PTR [rdx+rax]
    lea      rax, QWORD PTR [rax+16]
    vmovups xmm0, xmm7
    vfmadd231ps xmm0, xmm4, XMMWORD PTR [rax-16]
    vfmadd231ps xmm0, xmm5, XMMWORD PTR [r10+rax-16]
    vfmadd231ps xmm0, xmm6, XMMWORD PTR [r11+rax-16]
    vmovups XMMWORD PTR [rcx+rbx], xmm0
    vmovups xmm0, xmm3
    vfmadd231ps xmm0, xmm8, XMMWORD PTR [rax-16]
    vfmadd231ps xmm0, xmm9, XMMWORD PTR [r10+rax-16]
    vfmadd231ps xmm0, xmm10, XMMWORD PTR [r11+rax-16]
    vmovups XMMWORD PTR [rcx], xmm0
    vmovups xmm0, xmm1
    vfmadd231ps xmm0, xmm11, XMMWORD PTR [rax-16]
    vfmadd231ps xmm0, xmm12, XMMWORD PTR [r10+rax-16]
    vfmadd231ps xmm0, xmm13, XMMWORD PTR [r11+rax-16]
    vmovups XMMWORD PTR [r9+rax-16], xmm0
    sub      r8, 1
    jne      SHORT $LL4@transform_

That doesn't really address the SSE2 side of the store directly, but you can do the same thing but with separate add/mul. Proper use of AVX would use the wider vectors. For this code that's a fairly trivial change, just make almost everything wider (except the matrix). If AVX is available, you should use it in this case - it doesn't help for everything, but for this type of code (almost purely vertical SIMD, apart from some broadcasts) it's great. FMA is also a free performance win here (especially on Haswell and Broadwell), well worth using even if it means writing two versions and doing runtime dispatch to also support the Bridges (which are perhaps not old enough yet to completely disregard).

Supporting 32bit machines is annoying. They don't even have enough registers to load all of that matrix, so everything gets bogged down by the extra loads that are suddenly required. I don't see good fixes. Rearranging the multiplication so that the matrix can be held in 4 registers does work, but then a horizontal addition appears which is bad, and the multiplication wastes a lane on padding. I expect it would be worse than the extra loads, on the other hand if we're talking about old hardware like Core2 (which had x64 support, but at the time installing a 64bit OS was a rarity) then extra loads are extra bad since the load throughput used to be only 1/cycle. On the other hand, horizontal addition also used to be much worse than it is now. It just seems like all options are terrible. It depends on your audience of course, but frankly I don't think it's worth expending much energy on.


Integer square root in x86 assembly (NASM)

The first thing which strikes me as odd is how you calculate your initial estimation. If you only take every 2nd bit into account that means a value like 0b10101010101010 would yield a 0 as your initial estimation (or 1 after the  or ecx, 1 adjustment) - not very good. Also it's not clear to me why you skip the first 3 bits, that makes even your best estimates off by a factor of 2.

But I can see what you try to do: just take the "half" of the bits of the initial value. I think you can fix that by first or-ing the even with the uneven bits together and then apply the shifting and roring:

        mov     eax, [esp+4]
        test    eax, eax,
        jnz     positive
        ret              ; Return immediately when input is 0
positive:
        mov     ecx, eax
        shl     ecx
        or      eax, ecx
        bsr     ecx, eax ; Get highest bit for later adjustment
        xor     edx, edx
loop:
        shr     eax, 2
        rcr     dx
        jnz     loop
        shr     cl       ; Adjust for skipped bits
        inc     cl
        rol     dx, cl
        mov     ecx, edx ; Use ecx to store estimation

Note that shr modifies the zero flag, but rcr doesn't so you can jump out of the loop as soon as eax turns out to be 0.

Furthermore note that 1 is an implied parameter for shifting operations if none is given. So you can safe a byte each time you leave it out (and possibly a cycle).

The other thing which is strange is that you only do one iteration. You should repeat it till your estimated value varies only by 0 or 1 between iterations, otherwise it's hard to see how your sqrti function will be useful.

And I don't think you need the or ecx, 1 statement. Just make sure to return immediately if [esp+4] turns out to be 0. And if its positive your ecx register should never become 0 if you get the initial estimation right.


Reading data from multiple different resource bundle property files in Java

I don't see the need to implement sub classes in your code example above. You need inheritance only if you add specific implementation on the sub class. All you need is to create an interface to encapsulate the resolver (IResourceBundle) for abstraction, then create a factory for them.
public interface IResourceBundle {
    String getMessage(final String key);
    String getMessage(final String key, final Locale locale);
}

public enum ResourceBundles {
    EXCEPTION_MESSAGE("exceptionmessages"),
    LABEL("resourcelabels");
    private String bundleName;
    private ResourceBundles(String name) {
        bundleName = name;
    }
    public String toString() {
        return bundleName;
    }
}

public final class ResourceResolverFactory {
    private Map<ResourceBundles, IResourceBundle> resolvers;
    private ResourceResolverFactory() {
        resolvers = new HashMap<ResourceBundles, IResourceBundle>();
    }
    public IResourceBundle getBundle(final ResourceBundles resourceBundle) {
        IResourceBundle resolver = resolvers.get(resourceBundle);
        if(resolver != null) {
            return resolver;
        }
        resolver = new ResourceBundleReader(resourceBundle.toString());
        resolvers.put(resourceBundle, resolver);
        return resolver;
    }
    private static final ResourceResolverFactory instance = new ResourceResolverFactory();
    public static ResourceResolverFactory getInstance() {
        return instance;
    }
}

public class ResourceBundleReader implements IResourceBundle {
    private String resourceBundle = null;
    public ResourceBundleReader(final String resourceBundle) {
        Objects.requireNonNull(resourceBundle);
        this.resourceBundle = resourceBundle;
    }
    public String getMessage(final String key) {
        return getMessage(key, Locale.getDefault());
    }
    public String getMessage(final String key, final Locale locale) {
        final ResourceBundle mybundle = ResourceBundle.getBundle(resourceBundle, locale);
        return mybundle.getString(key);
    }
}

public class Main {
    public static void main(String[] args) {
        ResourceResolverFactory factory = ResourceResolverFactory.getInstance();
        IResourceBundle exceptionMessageResolver = factory.getBundle(ResourceBundles.EXCEPTION_MESSAGES_RESOURCE);
        // do something with exceptionMessageResolver
        IResourceBundle labelResolver = factory.getBundle(ResourceBundles.EXCEPTION_MESSAGES_RESOURCE);
        // do something with labelResolver
    }
}

In this case, adding more resource bundle means adding new enum in ResourceBundles not introducing new sub-class.


The greatest hindrance to understanding is the naming:

What is npn?  Some type of transistor?  next_perfect_number would be a much better name for the function!
What is spd?  An abbreviation for "speed"?  sum_factors would be an improvement… but see below.
You prompt for "n", but assign the result to a variable named x.  That's confusing.

The next biggest problem is that the npn() function tries to do too much.  It would be much clearer if the while loop were moved into a separate is_perfect_number(n) function.

A function that performs a complex calculation should not also perform I/O, as such mixing will prevent code reuse (for unit testing or for a future GUI, for example).  That is, npn() should return its result rather than printing it.

Idiomatic Python would use more elegant ways to perform the loops.  The n += 1 loop could be done using itertools.count().  The loop to calculate spd would be much more succinctly expressed using sum() with a generator expression.  It would certainly be easier to read the intent behind the code that way, but you would also have to introduce a Python-specific language feature.  It's hard to say which approach a beginner would find easier to understand.

It would be good practice to reduce the amount of free-floating code.  I suggest packaging the prompting and printing code in a main() function.

from itertools import count

def next_perfect_number(n):
    """Find the next perfect number after integer n"""
    for i in count(n + 1):
        if is_perfect_number(i):
            return i

def is_perfect_number(n):
    """Test whether n is a perfect number"""
    # Simple but inefficient algorithm
    return n == sum(i for i in range(1, n) if n % i == 0)

def main():
    print("Find the next perfect number after n.")
    while True:
        try:
            n = int(input("Enter your n: "))
            if 1 <= n < 8128:
                break
            print("Choose a number between 1 and 8128, please.")
        except ValueError:
            print("n should be a positive integer!")
    print(
        "The next perfect number after {0} is {1}.".format(
            n,
            next_perfect_number(n)
        )
    )

if __name__ == '__main__':
    main()


First, you have multiple functions with the same name.  That's not valid.

Assuming these sections are divs, to hide all of them except one, take a look at the not function:

function reveal1() {
    $("div").not("#section1").hide("slow");
    $("#section1").show();
}

Or more generically:

function revealThisElement(elementId) {
    $("div").not("#" + elementId).hide("slow");
    $("#" + elementId).show();
}

$(".icn_1").click(function() { revealThisElement("section1"); });
$(".icn_2").click(function() { revealThisElement("section2"); });
$(".icn_3").click(function() { revealThisElement("section3"); });

Or better yet, why not try something like this:

$(".revealable").click(function() {
   revealMe(this);
});

function revealMe(element) {
    $("div.revealable").not("#" + element.id).hide("slow");
    $(element).show();
}


Debugging based on a debug level without performance impact?

It's going to take some time for Python to run the test dbglvl >= lvl. You can estimate the amount of time using the timeit module. For example, on my computer,

>>> from timeit import timeit
>>> def f1():
...     pass
...
>>> def f2():
...     if x > 0:
...         pass
...
>>> x = 0
>>> timeit(f1)
0.14283514022827148
>>> timeit(f2)
0.18653011322021484

So the if x > 0: test costs about 40 ns. If this is going to be a problem for you, then Python is probably not a suitable language for your application.
You can avoid the test altogether by having a separate name for the logging function at each debug level and then assigning a no-op function to the levels that don't apply.

def debug_message_write(format, *args):
    debug_output.write(format.format(*args))

def debug_message_ignore(format, *args):
    pass

debug_message_1 = debug_message_write if debug_level >= 1 else debug_message_ignore
debug_message_2 = debug_message_write if debug_level >= 2 else debug_message_ignore
# etc.

(You could avoid the repetition here by writing to the globals() dictionary in a loop.)

And then in the code you would call

debug_message_3("Opening {}", filename)

or whatever. But this is more complicated than your original approach and I doubt that the minuscule saving in time is worth it.
Your code would be easier to read if you wrote debug_message instead of dbgmsg and debug_level instead of dbglvl. There is no need for you to save on vowels: there is no danger of running out.


Preventing invalid entity state that contains two related collections

I would give these the same signature

public void IncludeList(Guid id)

public bool RemoveFromIncludes(Guid id)

And rename

public bool AddToIncludes(Guid id)
{
    ...
    return _includedLists.Add(id);
}

Another approach is

Dictionary<GUID, bool>

and just one list


Macro to convert an indented hierarchy to a database format

Thanks very much to JNevill for his solution - it is indeed significantly faster than my original code. I had to make some changes to accommodate more than one # column, as well as headers to the left of the indented hierarchy column i.e.:

Region        Base Level        Account 1     Account 2

 USA         Level 1               500           800
 USA             Level 2a          300           400
 USA             Level 2b          200           400

Here is my new code based on JNevill's framework:

Sub HierarchyConvert()

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Dim WS                      As Worksheet
Dim SR                      As Range
Dim LastRow                 As Long
Dim rngReadCell             As Range
Dim rngWriteRow             As Range
Dim Indent                  As Integer
Dim LastIndent              As Integer
Dim MaxIndent               As Integer
Dim ValueArray(0 To 19)     As Variant

Set WS = ActiveWorkbook.ActiveSheet
Set SR = WS.Range(StartCell())
LastRow = SR.End(xlDown).Row
MaxIndent = 5

Set rngWriteRow = WS.Rows(SR.Row)

For x = 0 To 4
    SR.Offset(0, 1).EntireColumn.Insert
    SR.Offset(-1, 1) = "Level " & 7 - x
Next x

SR.Offset(-1, 0) = "Level 2"
SR.Offset(-1, 5) = "PC"

For Each rngReadCell In WS.Range(SR.Address & ":B" & LastRow)
    Indent = rngReadCell.IndentLevel
    If Indent <= LastIndent And LastIndent <> 0 Then
        Set rngWriteRow = rngWriteRow.Offset(1)
        For i = 1 To Indent
            rngWriteRow.Cells(1, i + 1).Value = rngWriteRow.Cells(1, i + 1).Offset(-1).Value
        Next i
    End If
    rngWriteRow.Cells(Indent + 2).Value = Trim(rngReadCell.Value)
    If Indent = MaxIndent Then
        'Copies leftmost header from base-level row to top left of write-row
        rngWriteRow.Cells(1) = rngReadCell.Offset(, -1).Value
        'Copies data to right of base-level row to the write-row
        For Z = 0 To 19
            ValueArray(Z) = rngReadCell.Offset(, Z + 6).Value
        Next Z
        For M = 0 To 19
            rngWriteRow.Cells(Indent + M + 3).Value = ValueArray(M)
        Next M
    End If
    LastIndent = Indent
Next rngReadCell

Range("A" & SR.Offset(0, 1).End(xlDown).Row + 1 & ":Z" & LastRow + 1).ClearContents
WS.UsedRange.IndentLevel = 0

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub


Some suggestions:

Use var when declaring variables, unless you really want to make global variables (which you probably don't)
Combine var statements using ,

var a = 1, b = 2, c = 3;

Combine classes in toggleClass

$(this).toggleClass('minus expand')

Cache selectors that are used often (like $('#main'))
You don't need to use $li2 inside the click handler, you can just use $(this)
Turn repeated code into a function

$(function(){
    var $main = ('#main'),
    slide = function(ele, find){
        return $(ele).toggleClass('minus expand').find(find).delay(200).slideToggle(400);
    },
    $li = $('> li.expand', $main).click(function(){
        var $ul = slide(this, 'ul.sub-level');
        $('> li > ul', $main).not($ul).slideUp('slow');
        $('> li.minus', $main).not(this).toggleClass('minus expand')
    }),
    $li2 = $('.sub-level > li.expand').click(function(){
       slide(this, 'ul.sub-level2');
    });
});


K&R Exercise 1-19. Reverse program input one line at a time

Minor:

getline()

When size is pathologically small (sz <= 1), if (c == '\n') { tests the uninitialized c leading to  undefined behavior.

With sz <= 0, s[i] = '\0'; is not valid either.

I'd recommend to note the condition that sz > 1 is expected.

Further, I'd use size_t rather than int for the buffer size and re-code to handle those edge cases.

size_t getline(char s[], size_t sz) {
    int c = 0;
    size_t i;

    for (i=0; i + 1 < sz && (c=getchar())!='\n' && c!=EOF; ++i) {
        s[i] = c;
    }
    if (c == '\n') {
        s[i] = c;
        ++i;
    }
    if (i < sz) {
      s[i] = '\0';
    }
    return i;
}


I personally would not rely on using magic strings.

  Magic strings are where you have taken something like a class/method/variable name and written it within a string, which is then used to identify the appropriate class/method/variable

This makes it hard to refactor later on if you change a class name, it is too easy to miss instances etc. Furthermore, the code that you currently have is case-sensitive. This might be by design, however, consider the following:

var actuallyABananaTree = oTreeType.GetTree("Coconut");

Even though the developer is specifying a coconut tree, he actually gets a banana tree. If the construction logic was changed to:

if (tree.Equals("coconut", StringComparison.OrdinalIgnoreCase))

You would then get the right tree type back. See StringComparison Enum for the comparison options.

In that same construction logic, you are also not checking to see whether or not the parameter tree is a null reference. This might be something that you wish to consider adding, especially if you use the approach suggested above.

Use of Enums

A better approach would be to use enums instead of magic strings. For example:

enum MyTreeTypes {
      Coconut,
      Banana
}

Then in your construction logic, you can have:

public ITree GetTree(MyTreeTypes tree)
{
    switch (tree)
    {
        case MyTreeTypes.Coconut:
            return new CoconutTree();
        default:
            return new BananaTree();
    }
}

Using this approach ensures type safety and prevents problems of magic strings when refactoring etc. Also, you will compile time errors if you spell the tree type incorrectly


If you want to keep the two lists (otherwise check Hackworth's answer), the best solution would be to use LINQ extensions

public IEnumerable<Page> AllPages
{
    get
    {
        return HeaderPages.Concat(SurveyPages);
    }
}

This way you do not create any unnecessary collections. It forces you to use IEnumerable<Page> though, but in my opinion it is a good thing.


There's no need for the 2nd argument in substr. So you could just do:

origin.substr(target.length * -1) === target

or

origin.slice(target.length * -1) === target

Same deal.

Edit: Whoops. Actually it's not quite the same deal. As Sumurai8 commented on Simon's answer, MDN says that JScript does not handle negative offsets for substr. However, slice has no such caveat. So long story short: Use slice, not substr.

Instead of * -1, you could also use a unary minus:

origin.slice(-target.length) === target

One thing you might want, though, is to check target before you try accessing its length property. If target == undefined you'll get an error. Something simple like this should do:

if(!target) return false;

One gotcha though: It'll return false if target is an empty string, since empty strings are false'y. However, it doesn't really make much sense to check if string ends with an empty string, so perhaps that's fine? Otherwise, do a typeof check (like the one below) on target.

And you might want to check origin too. However, here you just want to check that it's a string - not if it's just false'y. You'll be calling slice on it, so it must be a string or you'll get an error, whereas the worst that can happen if target isn't a string (but is truth'y) is that target.length is undefined.

So to check origin do:

if(typeof origin !== 'string') return false;

By the way, without the target-is-false'y check, if target is a string but also empty, you'll get some tricky results:

Origin        Target         Result
==========================================
"foo"         ""             false
""            "foo"          false
""            ""             true

Results #2 makes sense, but results #1 and #3 are perhaps a little strange, because, again, what does it mean to have an string end with an empty string? The results are due to slice(-0) being the same as slice(0), i.e. returning the whole string. So in effect you're checking:

"foo".slice(0) == "" // => "foo" == "" (false)
"".slice(0) == ""    // => "" == "" (true)

Kinda confusing.

If you want an empty target string to always return true, you could do:

if(typeof origin !== 'string') return false;
if(typeof target !== 'string') return false;
if(!target) return true;

  I'm aware my code has a lot of white-space for JavaScript standards. I like to think it keeps code readable. The naming can probably be improved.

Whitespace seems just fine to me! Don't know what JS you're used to, but I see absolutely no reason to change anything about whitespace usage.

I would drop the outer parentheses though, like Simon suggested.

As for naming, I'd call it endsWith, or stringEndsWith.

You could also extend the String prototype with an endsWith method, but generally it's better to leave native prototypes alone. However, this is fairly harmless, so I'd be tempted to say:

if(!String.prototype.endsWith) {
  String.prototype.endsWith = function (ending) {
    if(typeof ending !== 'string') return false;
    if(!ending) return true;
    return this.slice(-ending.length) === ending;
  };
}

Here we can skip checking origin, because we're adding the method to String itself. So if it's called, it's called on a string.


Find the best pairs of elements based on match weight

A couple improvements:

Pop from array and iterate over remaining items in nested loop

I tried to modify the nested for statements used to add to $possiblePairs and use a functional approach like with array_reduce() but instead found the example in this answer. Consider shifting (i.e. popping from the beginning) from the array to yield an array with the remaining elements with which to generate pairs.

while ($item = array_shift($elements)) {
    foreach($elements as $element) {
        //generate pair with $item and $element

With this approach, there is no need to keep track of counter variables (e.g. $i, $j), use those to index into the array, nor increment those until certain conditions change. It also makes the following line superfluous (so it can be removed):

$elementCount = count($elements);

Store pair as key, and score as value

This way the sorting can be simplified - using asort() with SORT_NUMERIC as $sort_flag. Then reverse the array for descending order using array_reverse().

while ($item = array_shift($elements)) {
    foreach($elements as $element) {
        $possiblePairs[$item.'_'.$element] =  rand(1, 100);
    }
}
asort($possiblePairs, SORT_NUMERIC);
$possiblePairs = array_reverse($possiblePairs, true);

Output from keys

Because of the changes above, the keys are the pairs so use list() and explode() to unpack the pairs.

$used = [];
    foreach($possiblePairs as $pair => $score) {
        list($element1, $element2) = explode('_', $pair);
        if($score !== 0 &&
            !in_array($element1, $used) &&
            !in_array($element2, $used))
        {
            // save the pair to the output array
            $output[] = [$element1, $element2];
            // store the elements that have already been used
            array_push($used, $element1, $element2);
        }
    }
    return $output;

Another optimization

In order to only go through the  (last) foreach loop as few times as necessary, the following conditional could be added after pushing values into $used:

if (count($used) == count($elements)) {
     break;
}

That should prevent excess loop iterations. While the difference may be negligible for small lists, it may be very helpful to reduce the execution time for larger lists.

Demonstration

Check out this playground example for a demonstration. And compare the time output at the end with the original.

| Run | Original             | Updated               |
|-----|----------------------|-----------------------|
|  1  | 0.0002138614654541s  | 0.00012707710266113s  |
|  2  | 0.00021195411682129s | 0.00017905235290527s  |
|  3  | 0.00021100044250488s | 0.00017690658569336s  |
| Avg | 0.0002122720083s     | 0.0001610120138s      |

Here is the updated code:

function stuff($elements = []) {
    $output = [];

    // build an array with every unique possible pair
    while ($item = array_shift($elements)) {
        foreach($elements as $element) {
            $possiblePairs[$item.'_'.$element] =  rand(1, 100); // this would be replaced by a function calculating how closely the current elements match
        }
    }
    //use asort to sort on values and
    asort($possiblePairs, SORT_NUMERIC);
    $possiblePairs = array_reverse($possiblePairs, true);

    $used = [];
    foreach($possiblePairs as $pair => $score) {
        list($element1, $element2) = explode('_', $pair);
        if($score !== 0 &&
            !in_array($element1, $used) &&
            !in_array($element2, $used))
        {
            // save the pair to the output array
            $output[] = [$element1, $element2];
            // store the elements that have already been used
            array_push($used, $element1, $element2);
            if (count($elements) == count($used)) {
               break;
            }
        }
    }
    return $output;
}


How can I optimize my code that uses nested for loops?

It is normally good to break code into several methods.
Everything that is inside your

if(!hit.equals(p) && !me.equals(p))

should be moved to a separate method taking as input those 3 points a,b and c

When coding problems of a mathematical flavor it is often very useful to support your code with some kind of theory.

In this case you might want to look up the mathematical terms "dot product" and "cross product". Once you understand those it becomes easy to implement your function.

And remember to make several functions (dotProduct() and crossProduct()) so you can reuse code later.

When it comes to performance you need to look at your algorithm.
There is no need to test all pairs of points (hit, p).
Maybe you should make a small method that computes the angle of a vector from me to p? If angle is the same they hit, otherwise they miss.

So the question becomes given a list of angles for points in hits and a list of angles in reachable, do they contain a common angle?


TOP 1

When selecting values that correspond to Unique fields referenced by constants (OwnerUserId), you're only really selecting one field, meaning this is redundant.

UVN

Unexplained Variable Names

Don't use names like Q and A, they're confusing at best and unreadable at worst.

DECLARE @Q
DECLARE @A

DECLARE @Questions
DECLARE @Answers

Yo dawg, heard you like SELECTs

SELECT --...
FROM (
  SELECT TOP 1
    (
      SELECT UpVotes
      From Users
      WHERE Id = @UID
    ) as Upvotes,

SQL is not intended to be used like that.

You don't need to create pseudo tables to select from to store your data.

You can use a base table, and then specify certain fields calling other tables from that.

SELECT
  UpVotes + DownVotes as [Total Votes],
  (SELECT COUNT(*) FROM Posts WHERE OwnerUserId = Users.Id) as [Post Count]
FROM Users

Formatting

This formatting is a bit weird:

SELECT Score = Upvotes   * @Up +
          Downvotes * @Down +
          Questions * @Q +
          Answers   * @A +
          Comments  * @Comment,

You might want to break these up a little more.

Naming

These aren't the actual values, they're type weights, so I'd add the word weight to the end of the variable names:

DECLARE @Up      int = 1
DECLARE @Down    int = 2
DECLARE @Q       int = 10
DECLARE @A       int = 5
DECLARE @Comment int = 1

Into:

DECLARE @UpVotesWeight     int = 1
DECLARE @DownVotesWeight   int = 2
DECLARE @QuestionsWeight   int = 10
DECLARE @AnswersWeight     int = 5
DECLARE @CommentsWeight    int = 1


isn't it better to write input as a macro ?

No. At best it might work as a generic function.

  how can i write to_binary as pure function ?

It already is a pure function, it doesn't mutate or depend on external state

  wouldn't be better to return binary type from to_binary instead i32

You should return a String. Converting to i32 is pretty weird. The numbers inside i32 are already in binary. The point of a to_binary function is pretty much always because you for some reason want a textual representation in binary.

As a quick side note, Rust already has the ability to convert values to binary:

format!("{:b}", value);

Your to_binary function would be a bit simpler if build a Vec or Vec  and then converted that instead of building a String.


The docstring is not quite right: "Find first non-repeated char in a string" — and then what? It should say explicitly that it returns the character.
The function returns False if all characters are repeated. This is a bad idea: it would be easy for the caller to forget to check. It's better to raise an exception in exceptional cases.
myDict is an uninformative choice of variable name. This dictionary contains counts of characters, so it should have name like counts or character_counts.
c in myDict.keys() can be simplified to c in myDict.
Building a dictionary of counts can more easily done using the built-in collections.Counter. It's not clear why you would want to avoid using this. Trivial functions should be trivial.
There's no point in testing if 1 in myDict.values(). Dictionaries have efficient lookup by key, but not by value, so the in operator here has to look through all the values. Since you're going to look through all the values anyway, this doesn't save you anything.
The runtime is \$Θ(n^2)\$ because s.index(k) has to search through the string for the character k. But there is a \$Θ(n)\$ algorithm:

from collections import Counter

def unique_char(s):
    """Return the first non-repeated character in the string s, or raise
    ValueError if all characters are repeated.

    """
    counts = Counter(s)
    for c in s:
        if counts[c] == 1:
            return c
    raise ValueError("all characters are repeated")


There are already links on this page to reasons why singletons should not be used. I will not repeat those.
is it a good way to provide a singleton object from 3rd party library?
No. Your singleton has an undocumented internal state which affects the processing of the input parameters. On the first invocation, the getInstance(String connectionString) methods returns a connection to the database requested by the caller. On subsequent invocations it returns a connection to the database requested by the first caller, regardless of what connection string is provided to it. You could document it but it doesn't fix the issue of this being a very error prone solution: your method does something unexpected if something that cannot be verified during run time happened before it was called.


You have two long if blocks:

if (isset($_POST['submit'])) {
    if (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token']) {
    ...
    }
}

Why not combine them?

if (isset($_POST['submit']) && (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token'])) {
    ...
}

also the way you've structured this, you don't need $error, to see if there are errors you can simply check empty($errors) (true => ok, false => not ok).

Other than that, your code looks fine.