Any field change in form, disable button, and activate another

Targetting elements

$('select') is generic selector and will select all <select> elements on the page. There might be some <select> elements which are not needed to target for this functionality.

You can target only required elements using

Unique parent selector + descendant selector

In this, there will be a main container element and using this all the descendant <select> elements can be targeted.

Example:

HTML:

    <select name="list" id="list">
        <option value="">...</option>
    </select>
    <input name="refresh" />
    <input name="add" type="button" value="add" />

    <select name="list1" id="list1">
        <option value="">...</option>
    </select>
    <input name="refresh1" />
    <input name="add1" type="button" value="add1" />

    ...

JavaScript:

$('#container select').change(function() {

Using common class
Sometimes, adding all the elements under a container is not possible. In such cases, adding a common class to all the elements will allow to select elements using class selector.

$('.someCommonClass').change(function() {

Common attributes can also be added and selected using Attribute Equals Selector [name=”value”]. However, this can be slower than class selectors.

Similarly, another common + unique class should be applied to buttons.

<input name="refresh" class="anotherUnique" />
<input name="add" class="anotherUnique" />

Then, to disable/enable these buttons, they can be referenced.

HTML5 data-* attributes

HTML5's custom data-* attribute can be used to store custom data on HTML elements.

<select name="list" id="list" data-key="value">

Getting data-* attribute value

jQuery provides data(name) method to get the value of the data-name attribute value. Core JavaScript has dataset property that allows access to data attributes.

$('elemSelector').data('key')

Using prop() with value

prop() accepts second parameter which will be converted to Boolean internally and depending on the value, the action will be taken. So, the if and else statements in the question can be combined as

$('elemSelector').prop('disabled', booleanValueHere);

If second parameter is truthy, element will be disabled. If falsy then element will be enabled.

Putting it all together

// Bind change event on all select elements
// having unique class
$('select.unique').change(function () {
    // Cache this
    var $this = $(this);

    // Get the data-* attribute values
    var button1 = $this.data('button1'),
        button2 = $this.data('button2');

    // Get the value of this select box
    // Use this as second parameter to prop
    $('input[name="' + button1 + '"]').prop('disabled', this.value);
    $('input[name="' + button2 + '"]').prop('disabled', !this.value);
});
/* For Demo Purpose */
input {
  color: green;
  font-weight: bold;
}
input:disabled {
  color: gray;
  opacity: .5;
}

<select name="list" id="list" class="unique" data-button1="refresh" data-button2="add">
    <option value="">choose</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>
<input name="refresh" type="button" class="anotherUnique" value="Refresh" />
<input name="add" type="button" class="anotherUnique" value="Add" disabled />

<select name="list1" id="list1" class="unique" data-button1="refresh1" data-button2="add1">
    <option value="">choose</option>
    <option value="10">10</option>
    <option value="20">20</option>
    <option value="30">30</option>
</select>
<input name="refresh1" type="button" class="anotherUnique1" value="Refresh 1" />
<input name="add1" type="button" class="anotherUnique1" value="Add 1" disabled />

Conclusion

Now, the JavaScript code don't have to be written again for each new select element. Just adding the markup with required attributes will automatically work. The relation between HTML element-JavaScript handler is reduced from many to many to many to one.


Firstly, this is something I see a distressing amount in beginner Java programmers:

removeSpace(word).compareTo(removeSpace(reversed)) == 0

There's a method for checking if two Strings are equal. It's called equals. It'd be used like this:

removeSpace(word).equals(removeSpace(reversed))

If you wanna ignore case, you could use equalsIgnoreCase:

removeSpace(word).equalsIgnoreCase(removeSpace(reversed))

Secondly, a formatting tip: Except in method declarations or calls, always put a space before ( and a space after ). So, for example:

if(...) {

becomes

if (...) {

In your removeSpaces method:

In general, when find that you're doing it a lot, avoid using String += String. Instead, initialize a StringBuilder and append to it.
String#charAt() returns a char, which can be compared with ==; I'm not sure why you first turn it into a String, then use compareTo (which, again, should be equals, since you were comparing Strings for equality)

With those issues fixed, this is what the method looks like:

private static String removeSpace(String aword) {
     StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < aword.length(); i++)   {
         if (aword.charAt(i) != ' ')) {
             buffer.append(aword.charAt(i));
         }
     }
     return buffer.toString();
}

(Note that I changed what would have been !(... == ...) to ... != ... and that ' ' uses single quotes.)

The whole function could be replaced with word.replaceAll(" ", ""), but that's no fun, so I'm gonna keep using yours through here. Besides, it's a good way to practice to write your own methods -- just remember, when you're writing production code, to do a thorough search of the docs first. If there's a version in the standard API, a whole gaggle of people have been optimizing it to high heaven, and it might even be implemented in native code. That alone would make it a bazillion times faster than anything you could write in pure Java.

You use removeSpaces in the comparison, which somewhat obfuscates what really happens: The String is checked for palindromity (word coined?) ignoring the spaces. It's clearer to move those method calls to when you get it (plus, this removes an extra function call, which is more efficient :D):

word = removeSpaces(in.nextLine());
// ...
if(word.equals(reversed)) { // Note that I'm not using compareTo here
// etc.

Thirdly, I'd recommend pulling the code that reverses your String into another method that takes a String argument and returns a String (and applying my earlier advice about StringBuilder):

public static String reverse(String word) {
    StringBuilder reversed = new StringBuilder(word.length);
    for(int i = word.length(); i > 0; i--) {
        reversed.append(word.charAt(i - 1));
    }
}

In that snippet above, I also removed length, since it's ultimately useless. You're only using it once, so there's no point in declaring a variable, and it's actually clearer to be able to directly see what String's length we're talking about -- you don't need to go back in the code to see what it means

With all this, your main becomes a bit clearer:

public static void main(String args[]) {
    String word = "";
    String reversed = "";
    Scanner in = new Scanner(System.in);
    System.out.println("Please enter the string: ");
    word = removeSpaces(in.nextLine());
    reversed = reverse(word);
    if (word.equals(reversed)) {
        System.out.println("The string " + word + " is a palindrome");
    }
    else {
        System.out.println("The string " + word + " is not a palindrome");
    }
}

We could clean it up a little more by moving your word and reversed declarations to where the variables are first assigned, rather than their own lines (which, incidentally, don't need the = "" because they aren't used before you assign them later):

public static void main(String args[]) {
    Scanner in = new Scanner(System.in);
    System.out.println("Please enter the string: ");
    String word = removeSpace(in.nextLine());
    String reversed = reverse(word);
    if (word.equals(reversed)) {
        System.out.println("The string " + word + " is a palindrome");
    }
    else {
        System.out.println("The string " + word + " is not a palindrome");
    }
}

This means that your whole class, all together, looks something like this:

public class Reversal {
    public static String reverse(String word) {
        StringBuilder reversed = new StringBuilder(word.length);
        for (int i = word.length(); i > 0; i--) {
            reversed.append(word.charAt(i - 1));
        }
    }

    private static String removeSpace(String aword) {
         StringBuilder buffer = new StringBuilder();
            for (int i = 0; i < aword.length(); i++)   {
             if(aword.charAt(i) != ' ')) {
                 buffer.append(aword.charAt(i));
             }
         }
         return buffer.toString();
    }

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Please enter the string: ");
        String word = removeSpace(in.nextLine());
        String reversed = reverse(word);
        if (word.equals(reversed)) {
            System.out.println("The string " + word + " is a palindrome");
        }
        else {
            System.out.println("The string " + word + " is not a palindrome");
        }
    }
}

If you want to get rid of your custom method to remove spaces (which I would recommend doing if you ever had to remove spaces in production code):

public class Reversal {
    public static String reverse(String word) {
        StringBuilder reversed = new StringBuilder(word.length);
        for (int i = word.length(); i > 0; i--) {
            reversed.append(word.charAt(i - 1));
        }
    }

    private static String removeSpace(String aword) {
         StringBuilder buffer = new StringBuilder();
            for (int i = 0; i < aword.length(); i++)   {
             if(aword.charAt(i) != ' ')) {
                 buffer.append(aword.charAt(i));
             }
         }
         return buffer.toString();
    }

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Please enter the string: ");
        String word = in.nextLine().replaceAll(" ", "");
        String reversed = reverse(word);
        if (word.equals(reversed)) {
            System.out.println("The string " + word + " is a palindrome");
        }
        else {
            System.out.println("The string " + word + " is not a palindrome");
        }
    }
}

And, finally, an utterly unreadable version of your code that does the same thing, which you should never use but was annoyingly fun to write so I thought I'd provide it anyway:

public static void main(String args[]) {
    String l;
    System.out.println("The string "+(l=new Scanner(System.in).nextLine())+" is"+(l.replaceAll(" ", "").equals(new StringBuilder(l).reverse().toString().replaceAll(" ", ""))?" ":" not ")+"a palindrome");
}


Scraping the Bundesliga table and saving it to CSV

Great answers, as always.
Just a few remarks from me:

There is not enough validation in your project.
You are scraping a website that could change at any time, and your script is expecting DOM elements that may not be there. So you need to check each of them.

From the doc (emphasis is mine):

  If find_all() can’t find anything, it returns an empty list. If find()
  can’t find anything, it returns None

To avoid repetition, instead of repeatedly calling club.find (even if it's just a few times), you could have a for loop, using a list or dictionary containing the DOM elements being sought and the matching HTML attribute. Then you validate the existence of the element and extract the text value in the same pass. Thus, your code becomes more solid and easier to maintain. On the other hand, you have just 5 elements in this code. But your next project may involve retrieving a lot more.

Your HTTP request can fail too, for lots of reasons like lost connectivity. Then the rest of your code will fail. I suggest to wrap the HTTP request in its own try/catch block and stop execution if it fails. There is no point trying to parse the HTML if it was not retrieved.

It is good to have exception handling in the functions that do specific tasks, but the main function should also have its own generic exception handler. Advice: log every exception to a file. Especially if the script is going to run unattended.

One last thing: you should always test your code in less than ideal conditions: try to run it against another, arbitrary  website, or a domain name that does not even exist, and see how it behaves.


I see a number of things that could help you improve your code.

Don't #include .c files

The code has these two lines

#include "whiteSpacing.c"
#include "lineFolding.c"

Generally speaking, we divide code into .h files which define an interface and .c files which contain an implementation.  For example, a lineFolding.h file might look like this:

#ifndef LINEFOLDING_H
#define LINEFOLDING_H
#include <stdio.h>
void folding(FILE *p, FILE *q, char c);
#endif // LINEFOLDING_H

Although there are other functions within the lineFolding.c file, they are only used internally to that module and so they aren't listed in the interface.  Also note that the include of <stdio.h> is required because the interface includes two FILE * parameters.  It also incorporates the next suggestion.

Eliminate global variables where practical

Having routines dependent on global variables makes it that much more difficult to understand the logic and introduces many opportunities for error.  Eliminating global variables where practical is always a good idea, whether programming for desktop machines or for embedded systems.  In this particular case p, q and c should be passed to the other functions (if needed) and local to main.

Use better naming

Function names like getLine are good because the names suggest what they're doing.  Names like folding are not as good because the name is very generic and doesn't describe very well what the function is doing.  Names like p and q are not good at all because they don't tell the reader anything at all about what the variable means in the context of the program.  I'd rename them infile and outfile and then the program is much easier to read and understand.

Fix the bug

In the getLine function, what happens if line doesn't happen to contain a '\n' character?  The answer is that the program continues to march through memory well beyond the allocated size of the buffer.  This is an error and it must be fixed.  Fortunately, it's not that hard to do.  One way to do that is to add it as a condition for the while loop:

while(((c != EOF)) && c != '\n' && nc < MAXLINE-2)

Consider the user

If the user of this program does not supply an input filename, the program prints this unhelpful message:

  Error! Check number of arguements.

I'd suggest that something a little more instructive (and without the spelling error) might be better.  Consider instead using something like this:

printf("Usage: %s filename\n", argv[0]);

Also, instead of having a hardcoded filename temporary.txt and doing the formatting in several steps, it might be nice to allow the user to control the name and location of a sepaate output file.  For this, it would make sense to use another command line argument.  Also, while having the user type the file if the file doesn't exist might be handy, I'd suggest that doing just one thing well is a better idea.  In particular, I'd write this using only stdin and stdout so that the user could call it with redirected input and output if they care to deal with files, or without if they'd like to type directly.

Reconsider the function interfaces

Consider the whiteSpacing function.  Its basic function is to replace double spaces with a single space.  However, it's called after the file has already been adjusted to introduce line wrapping.  For this reason, I'd suggest that a better way to do this would be to pass a buffered line to the function instead.  This would allow the program to do a single pass through the file instead of requiring two.

Be careful with function sequencing

The last lines of the code include this:

remove("temporary.txt");
printf("Text in \"%s\" was formatted and overwritten.\n", argv[1]);
fclose(p);

It will probably work, but it contains a flaw in that the file p is removed and then the file is closed.  I'd suggest closing it first.

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


Expression template to compute the Euclidean distance

My concern now is that you make multiple calls to get the actual distance.
Every-time you do that then you incur the expense of the sqrt() operation.

I suppose it depends on the exact use case of your application which happens more often. But if this is for general code that could be used a lot in either capacity. I would add another two fields to indicate if it was dirty or not and cache the result so you don't have to recompute the actual value each time.

But that has the side affect of adding a conditional branch into the get which can also be expensive when looking at micro optimizations.


Simple calculator to evaluate arithmetic expressions

Thanks for sharing your code!

Pros

You actually created an instance of your class instead of using static methods
you have more than one method.

Cons

Naming

Finding good names is the hardest part in programming, so always take your time to think about the names of your identifiers.

Naming Conventions

Please read (and follow) the
Java Naming Conventions

E.g.: method names should be or start with a verb. Your method calculator() should better be named calculate().

Care for correct spelling

You named a variable problm. What is that? I suspect you misspelled problem, but it could something completely different.

Declare variables as late as possible

Your method calculator() has two variables immediately declared at the beginning of the method. you first variable is result but it is the last one referenced. It is not needed untill the start of the for loop. Therefore it should be declared there.

The reason is that "late declaration" simplifies the use of your IDEs automated refactorings. One of them is extract method.
You can use it to put the for loop into a separate method.
If you do it on your code as it is you would get this:

public void calculator() {
    double result=0;
    String problm = "";
    System.out.println("Use: \n\"/\" to divide \n\"x\" to multiply \n\"+\" for addition \n\"-\" to substract \n\n>");

    problm = input.nextLine();

    result = calculateResult(problm, result);

    System.out.println("Answer is: " + result);
}

private double calculateResult(String problm, double result){
    for (int i=0; i<problm.length();i++) {
       // calculate the actual result...
    }
    return result;
}

You new method got an useless parameter.

If you had declared the variable result before the loop you could hav included it in the extracted patr and your code would be like this:

public void calculator() {
    System.out.println("Use: \n\"/\" to divide \n\"x\" to multiply \n\"+\" for addition \n\"-\" to substract \n\n>");

    String problm = input.nextLine();

    double result = calculateResult(problm);

    System.out.println("Answer is: " + result);
}

private double calculateResult(String problm){
    double result=0;
    for (int i=0; i<problm.length();i++) {
       // calculate the actual result...
    }
    return result;
}


Python Converting numbers to words, using Recursive

What is your desired output? Your function has no return statements (other the one commented out), and the only print statement is in the number <= 0 block. Have you run this function? Unless I'm missing something, it won't do anything if you input 0. And when you strip out the last digit, you don't actually store it anywhere, so it's just gone.

You seem to be doing double tabs for your indents, which makes it hard to read once you get several levels deep. Also, you can save yourself an indent level after the number <= 0 block; since you have nothing but an else block after this, you can put a return at the end of the if block. Then you won't ever get to the else block unless the if condition is false, making the else redundant. So you can get rid of that and move everything in an indent level.

You don't show what face_value is, so it's hard to evaluate your code when it comes to that part.

Also, unless I'm misunderstanding, the if number <= 0 block should be something like this:

if face_value_count == 0:
     result = "Zero"
     print (result)
     return(result)
return('negative '+rec_ntw(-number, face_value_count))

You could replace the if else blocks after the number <= 0 block with a case statement.

Using recursion in this case is rather odd. The basic structure of your function is:

def f(x):
  #do action 1
  #do action 2
  #do action 3

But you're implementing it as:

def f(x,instruction_address):
   if instruction_address == 1:
       # do action 1
   if instruction_address == 2:
       # do action 2
   if instruction_address == 3:
       # do action 3
   f(x, instruction_address+1)

That's just ... really weird.

Consider the following code:

def numbers_to_words(number):
    numbers = ['zero','one','two','three','four','five','six','seven','eight','nine',
              'ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen',
              'seventeen','eighteen','nineteen']
    tens_places = ['twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety']
    if number <20:
        return(numbers[number])
    #print(number)
    if number%10 == 0:
        return(tens_places[number//10-2])
    return(tens_places[int(str(number)[0])-2]+'-'+numbers[int(str(number)[1])])

This turns any number from 0 to 99 to words, no recursion. It can easily be extended to -999 to 999, and a little more work would get it to, say, -10^33 to 10^33.


It is always better to follow component approach in angularjs. Even if your using angularjs prior to version 1.5.x you can use directives to emulate this approach thus making each directive completely isolated manageable code chunk. it is always better to avoid usage of $scope. it leads to creation of scope soup. To avoid this use controllerAs namespace. and rather than broadcasting events which might lead to uncertain behavious use services to enable communication between directives. This will make your code more manageable and readable and in the future you could easily port to angular2 if you want.


Looks cool, nice job!

One this I would say is that the plugin makes too many assumptions about the client's DOM structure. Having fixed selectors like $('.front') and $('.back') within your plugin script is dangerous -- what if I'm working in a page that has a 'front' class on the body?

It's best to let the client pass in exactly what DOM elements they want to manipulate. You could, for example, do something like this:

The html:

I'm in front!

I'm in back!

The initialization:

$('#flipper').jFlip();

In your plugin script, you now know exactly which elements the client wants to work with:

...
return this.each(function() {
 ...
 $flipper = $(this);
 $front = $flipper.find('[data-face=front]:first');
 $back = $flipper.find('[data-face=back]:first');
 ...
});

Now you don't have to deal with any pesky DOM tree traversal, which carries a risk of finding the wrong element.

A couple other notes:

When you're specifying css attrs with jquery, height:
someNumberVariable works just fine. You don't need to wrap it with
'' + someNumberVar + 'px'
Why not set the duration as an optional param?
It would be nice to have a $('#myEl').jsFlip('flip') method. Adding methods like this will add some complexity to your code, but the good news is there are some good plugin patterns out there that you can work off of. IMO, this is the prettiest one I've seen.
Once you've figured out how to add methods to your plugin, it's fairly simple (and best practice) to add a 'destroy' method, that would unbind all of your event handlers. To do this, you need to namespace your events.

For example:

to bind: $flipBtn.on('click.jFlip', function() { ... })

to destroy: $flipBtn.off('.jFlip');   // unbind all events in .jFlip namespace

One other thing: this plugin replicates the functionality of existing CSS3 animations, which will always be faster. This plugin is still useful as a fallback for browsers that are not up to speed on CSS3, but it would be best to check for that capability first, and implement with CSS3 if available.

I hope this is helpful. Keep on rocking the plugins!


A complex number class is very useful! This is pretty straightforward and easy to understand, too.
The Class
First, I should mention that if you haven't already seen it, there is a complex class in the standard template library. It's great to make your own so that you can learn how it works, but just wanted to mention it in case you missed it.
I think having 2 ways of using the data (real and imaginary parts vs. magnitude and angle) is a great idea. However, I would keep only one pair around and have functions to calculate the others. For example, you might keep the real and imaginary parts and calculate the magnitude and angle only when needed. (Or the reverse if you find that it's more common to use the magnitude and angle.) The reason is that one set of the data can get out of sync with the other. The constructor that takes arguments sets the real and imaginary parts, and then calculates the magnitude and angle. The set_* methods also have to recalculate both parts. If you ever expand the class, you'll have to ensure that every method always does the calculations 2 ways - once for real/imaginary parts, and again for magnitude and angle. This is likely to be slow. If you kept only one representation, you could simply do the conversion to the other representation only when asked for data in that format.
The Functions
I'm guessing from the names that the 2 functions calculate the sum and product of 2 Complex numbers? You ask:

Is it possible to change them in order to make them accept also doubles as input?

There are 2 ways you could approach that. You could simply make an overloaded version:
double somma(double a, double b) {
    double c;
    c = a + b;
    return c;
}

Or you could use templates. To do that, you need to have an operator+() for your Complex class. Then you can write somma() as:
template <typename T>
T somma(T a, T b) {
    T c;
    c = a + b;
    return c;
}

The compiler will then change out T for whatever type the arguments are when you call it. If you call it like this:
Complex x(2, 5);
Complex y(3, 6);
Complex z = somma(x, y);

it will do what your function currently does. If x, y, and z are float or double, then it will use float for the type and return the expected result.

Is it correct to say that my functions haven't got side effects?

Yes, it is. They don't set any state that a caller can't see. They don't cause anything to be output other than the return value of the function.

Would it be better to put the functions in the class as data members?

That depends on how you're going to use them. In general, for a class that represents a type of number having operator+() and operator*() (and related ones like operator+=() etc.) is probably a good idea.


API using NodeJS to recive data from client and send it to a server

the code has plenty of room for improvement, and yes it violates the solid principals like the  Single responsibility principle "your functions are way too big and the module in itself has too many responsibilities ",  to clarify there are no rules on how API should be written in NodeJS there are code practices and design patterns that help us developers write more maintainable code, so don't try to follow every single rule you will get stuck in optimizing and it really depends on your project needs.
Now for the improvement here are some suggestions you can work on :

separate your endpoints in different files, take a look at my answer here, you can use the express router
move your constant variables like "loginValidationURL " in a different file like config.js then import and use it
don't overuse URL params use post request to get objects to your server
Build the application with a framework independent mindset
Make your functions lighter separate them by  roles like this take this example on your "/api/auth endpoint" it will explain many things

// Your implimation

api.post("/api/auth", (req, res) => {
  const clientAuth = {
    username: req.body.username,
    password: req.body.password
  };

  const loginValidationURL = `http://${process.env.HOST}/api/users/${clientAuth.username}/${clientAuth.password}/valid`;

  axios
    .get(loginValidationURL, { headers: { Authorization: process.env.AUTH } })
    .then(response => {
      let token = response.data.result.identity.userId;
      response.data.result.result == 0
        ? res.json({ status: "Authenticated", result: 1, token: hash })
        : res.json({ status: "Wrong Username or Password", result: 0 });
    })
    .catch(error => {
      console.log("error " + error);
      res.json({
        status: `Couldn't reach Arena Gaming Server. Try again later`,
        result: 404
      });
    });
});

/* Api Handler
 * file path : routes/api/client.js
 * in this file i only write the client api endpoints /client/auth /client/logout /client/:id the basic crud
 * i have seperate the main job in a controller module like that the api is mucj cleanter
 */
const express = require("express");
const router = express.Router();
const { authClient } = require("../controller/clientcontroller");

router.post("/client/auth", (req, res) => {
  authClient(req, res)
});

/* controller
 * file path : routes/controller/clientcontroller.js
 * in this file i only write the client controllers for each api call
 */

const { extractClientAuth } = require("./api/client/reqHandler"); // this module will be responsible for extracting and validation req objects
const { loginValidationUrlBuilder } = require("../../config"); // this module is responsible for all your static and config objects like axios custom headers
const { apiClient } = require("./services/externalJobs"); // this for exrtenal jobs and api calls
const { responseBuilder } = require("./api/tools"); // this module for creating response objects

function authClient(req, res) {
  const clientAuth = extractClientAuth(req);
  const loginValidationURL = loginValidationUrlBuilder(clientAuth);
  apiClient
    .login(loginValidationURL)
    .then(response => res.json(responseBuilder.authSuccess(response)))
    .catch(error => {
      res.json(responseBuilder.authFailed(error));
    });
}

this is by no mean the best way it's just a way to structures your project take from it what you like another this I can recommend this video on youtube channel Dev Mastry he does an excellent job of explaining how to create a scalable node application using express and MongoDB https://www.youtube.com/watch?v=fy6-LSE_zjI


First just a small cosmetic improvement: I'd call the method MergeSimilarIps or something like this (you know better what name would make more sense). Aggregate suggests you would get a sigle result.

    foreach (var cidrA in parsedCidrs)
    {
        foreach (var cidrB in parsedCidrs)
        {
            if (cidrA != cidrB)
            {

I thnink you can speed the merge a little bit by using for loops and starting the second one at i + 1 of the first loop. This way you check x == y only once because y == x is the same an you already checked it so there is no need that you do it again plus the + 1 will skip x == x.

Compare these two loops. The first one works like in your solution:

var nums = new [] { 1, 2, 3 };

foreach (var x in nums)
{
    foreach (var y in nums)
    {
        Console.WriteLine($"({x}, {y})");
    }
}

its result is:

(1, 1)
(1, 2)
(1, 3)
(2, 1)
(2, 2)
(2, 3)
(3, 1)
(3, 2)
(3, 3)

The second one works without repetitions.

for (var x = 0; x < nums.Length; x++)
{
    for (var y = x + 1; y < nums.Length; y++)
    {
        Console.WriteLine($"({nums[x]}, {nums[y]})");
    }
}

It produces only 1/3 of this list above:

(1, 2)
(1, 3)
(2, 3)

This means you get only unique combinations without repetitions.


JavaScript modular framework for a large web-site

Very readable code, some minor comments:

Some folks dislike the lacking curly braces for one liners, I dont mind it here myself
JsHint will complain about you creating a function in a for loop, I think you should indeed refactor that
Using this[name] to register modules would be to fickle for me (shenanigans with bind, apply, and call come to mind), I would prefer a self executing function with a var statement.
You only have 1 line of comment, for a very straightforward piece of code, I would have commented the moduleExports[exportFnName] = (function (exportFn) { line
I would split this out in to 2 different error messages:  if (!name || !module.init)
        throw new Error('Could not load a module ' + name);
Actually, in your code I see that init is a bit contrived, I would not make that mandatory personally

Now, when I take a step back, I think you might be suffering from Second System Syndrome. Consider that in effect you are replacing

$("button").click(function() {
    $('input').attr('data-color'));
});

with

kibfw.register('decorator', {
  init: function () {
    this.$decorateItems = this.$('input');
  },
  context: {
    $decorateItems: undefined
  },
  exports: {
    setColor: function (color) {
      this.$decorateItems.css('color', color);
    }
  }
});

// Usage:
$("button").click(function() {
    kibfw.decorator.setColor($(this).attr('data-color'));
});

I like window.kibfw, it is pretty beautiful. But I would hate to have to write a website with it.


Call center dispatch using object-oriented Python

Segragated the responsilibites of call center into call center and employee
from abc import ABCMeta, abstractmethod
from random import random

class CallCenter(metaclass=ABCMeta):
    """
    A call center class that will be inherited from by the director

    Attributes:
        name: Name of the employee
        number: Mobile phone number of the employee
        level: Define level of the employee - respondent, manager or director
    """

    @classmethod
    def dispatchCall(self, cls):
        return cls.answerCall()

class Employee(metaclass=ABCMeta):

    def __init__(self, name, number, level):
        self.name = name
        self.number = number
        self.level = level

    def canEmployeeHandle(self):
        canHandle = random()
        if canHandle > 0.5:
            return True
        else:
            return False

    def isEmployeeBusy(self):
        busy = True if random() <= 0.5 else False
        return busy

    @abstractmethod
    def answerCall(self):
        """Print a string indicating that this employee is currently
        answering the call or propogate up the chain"""
        pass

class Director(Employee):
    """
    A class definition for the director who will be the third in chain
    to answer the call
    """

    def answerCall(self):
        print("The director is now on call with you")

class Manager(Director):
    """
    A class definition for the manager who will be the second in chain to
    answer the call
    """

    def answerCall(self):
        if not self.isEmployeeBusy() and self.canEmployeeHandle():
            print("The manager is answering your call")
        else:
            print("Manager is busy, escalating the call to the Director")
            super(Manager, self).answerCall()

class Respondent(Manager):
    canHandle = random()  # class variable to check if respondent can handle call
    """
    A class definition for the respondent who will be the first in chain
    to answer the call
    """

    def answerCall(self):
        if not self.isEmployeeBusy() and self.canEmployeeHandle():
            print("The respondent is answering your call")
        else:
            print("Employee is busy, escalating the call to the Manager")
            super(Respondent, self).answerCall()

if __name__ == "__main__":
    director = Director("Alex", "+17654736791", "director")
    manager = Manager("Unai", "+331577285782", "manager")
    respondent = Respondent("Mark", "+16574872817", "respondent")
    CallCenter.dispatchCall(respondent)
    enter code here


Command-line search for web-scraped TV Guide listings

Refactoring #1

The first thing I noticed is the repetition in user_input. You're using the case statement as flow control--it's no different than a series of if/else statements. Instead, use the case statement to set your info variable and move the other statements out:

info = case input
       when "football"           then SportsToday::Schedule.football
       when "baseball"           then SportsToday::Schedule.baseball
       when "college basketball" then SportsToday::Schedule.college_basketball
       when "nba basketball"     then SportsToday::Schedule.nba_basketball
       end

show_info(info)
post_search_options

Refactoring #2

After the first refactoring, it becomes clear that the case statement is simply translating a String to a method name (which gets translated back to a String in the method itself). This is inefficient. It might be tempting to generate the method name:

SportsToday::Schedule.call(input.tr(" ","_"))

but all that does is mask the underlying problem: you have a method for every possible search string.

Instead, consider changing the interface of the class. Instead of one method per search string, use one for all:

#SportsToday::Schedule

def self.sport(sportname)
  select_by(sportname)
end

Not only does this simplify your SportsToday::Schedule class, it simplifies your CLI:

info = SportsToday::Schedule.sport(input)
show_info(info)
post_search_options

Note that I "cheated" a little on this refactoring, as the interface changes slightly. The user needs to enter the case of the sport name differently. However, it's not much different than before, as an exact match was required in your original code too. If the intent is to make it accommodate user input, you can adjust for user input sloppiness in your Schedule class. I wouldn't do it in the CLI, because it requires knowledge of the Schedule's underlying data format and that should be kept encapsulated in your Schedule class.

[I don't have time to add more refactorings right now, I'll try to come back to this and add more.]


Calculate and displays the sum of all numbers from 1 to 20

Bug?
Do you want to display a cumulative sum every time the loop executes? That's what you do now. If not - if you want to only display the final sum - you need to de-indent your print.
Sum
You can do the whole sum using the actual sum function, like this:
total = sum(range(1, n + 1))

Note that you should not call a variable sum, because that shadows the built-in sum function.
Calculating the sum
This doesn't actually need a loop or a call to sum at all. Math will tell you that the entire sum will evaluate to \$n(n + 1)/2\$; an example of equivalence:
$$
\begin{align}
1 + 2 &= 3\\
\frac{2 * 3}{2} &= 3
\end{align}
$$


Reduce the calls to database for validations in rails

You can memorize result using ||=

def referred_by_id
    @reffered ||= User.where(referral_code: referer_referral_code).first.id
end

def validates_presence_of_referer_referral_code
    u = referred_by_id
    if u.nil?
        errors.add :referer_referral_code, "Not a valid Referral Code"
    else
        if @user.referral_code == referer_referral_code
            errors.add :referer_referral_code, "Can't use your own referral code"
        end
    end
end

You shouldn't name your method with get_ prefix.

EDITED:

It is ruby naming convention to not use prefixes like get_ nor set_ (according to Rubocop and Ruby style guide). I think it is because, every method is a getter by default (always returns last line).
When you call referred_by_id method, it will query a db just once and then it will memorize result. So it will improve performance if this method is called more then once in this class.


Compare files, returning first differing line

Perfect code does not exist, it's all a matter of opinion, but I would write the handling of the program arguments differently.
The first argument is the name of the program so you dont expect 3 arguments, but just 2 from the user's perspective.
Also, I would change the *++argv x2 into argv[1] and argv[2] to make more clear what you mean with the program arguments.

And I would explicitly check the retrun value of strcmp to make it more clear that you are checking for inequality.

So not if (strcmp()) but if (strcmp() != 0)

    if (argc != 3)
    {
        fprintf(stderr, "Incorrrect usage: got %d arguments, expected TWO", argc);
        exit(1);
    }
    /*attempt to open files*/
    if (!( (fp1 = fopen(argv[1], "r")) && (fp2 = fopen(argv[2], "r")) ))
    {
        fprintf(stderr, "%s: can't open %s\n", prog, argv[1] || argv[2]);
        exit(2);
    }
    /*read line from each file*/
    for (i = 0; fgets(line1, MAXLINE, fp1) && fgets(line2, MAXLINE, fp2); i++)
    {
        if (strcmp(line1, line2) != 0)
        {
            /* print line # and line that differed */
            fprintf(stdout, "Line %d\n%s: %s\n%s: %s", i, argv[1], line1, argv[2], line2);
            break;
        }
    }


First, I would clean up the indices in the inner loop. I think the +2 and -2 are a bit confusing at the first glance.

def sieve(n):
    array = []
    for i in range(0, n + 1):
        array.append(True)
    for i in range(2, n + 1):
        for j in range(2*i, n+1, i):
            if array[j] != False:
                if j % (i) == 0:
                    array[j] = False
    final = []
    for i in range(0, n+1):
        if array[i] == True:
            final.append(i)
    return final

This way, array indices directly correspond to their number, no conversion needed. This wastes array space for 0 and 1, but I think it is a lot easier to understand.

The primary optimization that is possible adjusts the ranges of the loops. Each non-prime
<= n
has a divisor <= sqrt(n) and thus we can limit the outer loop to range(2, math.sqrt(100) + 1)

Additionally we don't actually need to run the inner loop for numbers which are non-prime (since each non-prime has prime divisors) and we can add an if array[i] == True: to reduce the number of inner loops further.

The range of the inner loop can also be reduced. It actually can start at i^2 instead of 2*i since the argument made earlier also applies here. All non-primes smaller than i^2 must have an divisor < i and thus were already set to false in an earlier iteration of the outer loop.

If we apply these changes, we get the following code:

def faster_sieve(n):
    array = []
    for i in range(0, n + 1):
        array.append(True)

    for i in range(2, int(math.sqrt(n)) + 1):
        if array[i] == True:
            for j in range(i*i, n + 1, i):
                if array[j] != False:
                    if j % i == 0:
                        array[j] = False
    final = []
    for i in range(2, n + 1):
        if array[i] == True:
            final.append(i)
    return final

For comparison we can run

faster_sieve(int(math.pow(10, 7)))

and

sieve(int(math.pow(10, 7)))

On my machine:

~ time python faster_sieve.py
python faster_sieve.py  5.44s user 0.04s system 99% cpu 5.477 total

~ time python sieve.py
python sieve.py  32.97s user 0.03s system 99% cpu 33.003 total

Which is a lot faster!

Now we could to some python microoptimizations, but I don't know anything about python. A first step could be to replace the append-loop with something faster like array = [True] * (n + 1), which saves another second on my machine

~ time python faster_sieve.py
python faster_sieve.py  4.46s user 0.02s system 99% cpu 4.475 total

So, yes indeed, your code could be further optimized.

/e
I might add that there are already good reviews of python code for the sieve on this site. For example this which applies a lot of python optimization.

/e2

Looking at the code again and looking at Wikipedia, the checks inside the inner loop are actually not needed since j is per loop definition a multiple of i and we can simplify it to

for j in range(i*i, n + 1, i):
    array[j] = False

which optimizes the program further:

~ time python faster_sieve.py
python faster_sieve.py  2.61s user 0.01s system 99% cpu 2.617 total

/e3 After reading jerry's response and finding two bugs in his implementation, I think there is another easy optimization that can be added to his approach. Since i is always odd in his inner loop, so is i * i. Thus we can increase the increment step of the inner loop from i to i * 2 (i * i + i would be even). This result in the following results:

Simon: 3.5496606826782227
Jerry (broken): 1.7031567096710205
Josay: 2.2623558044433594
Krypton: 5.4344189167022705
Krypton2: 2.5819575786590576
Jerry2: 1.396036148071289

Krypton2 and Jerry2 being:

def krypton2(n):
    array = [True] * (n + 1)

    for i in range(2, int(math.sqrt(n)) + 1):
        if array[i] == True:
            for j in range(i*i, n + 1, i):
                array[j] = False
    final = []
    for i in range(2, n + 1):
        if array[i] == True:
            final.append(i)
    return final

def jerry2(n):
    array = [True] * n

    result = []

    result.append(2)
    for i in range(4, n, 2):
        array[i] = False;

    for i in range(3, int(math.sqrt(n) + 1), 2):
        if array[i]:
            for j in range (i*i, n, i * 2):
                array[j] = False;

    for i in range(3, n, 2):
        if array[i]:
            result.append(i)
    return result


Calling synchronous code in asynchronous method

If it's really just removing an item from a dictionary (and not e.g. doing synchronous file IO), then Alternative 1 is the best.

When you're using async for scalability (e.g. in ASP.NET), using Task.Run() like this won't help you (since the number of threads used stays the same), it will only hurt you a bit (since Task.Run() has some overhead).

When you're using async for responsiveness (e.g. in GUI applications), using Task.Run() like this can make sense, but only for long-running operations (MS recommendation is operations that can take more than 50 ms). Since dictionary operations shouldn't take long you shouldn't use Task.Run() here either.


Producing every string of a given length using some range of characters

There is not much to understand about "brute forcing" something. "Brute force" does not mean a particular algorithm.

"Brute force" simply means that instead of using a clever algorithm to simplify a problem (simplify here means reducing the running time) you just test every single possible input to see which one produces the right result.

For example in password cracking, "brute force" means calculating every single possible password and testing them one by one. A smart algorithm would try passwords that are based on names and such first, because we know those are used way too often.

So, first of all, you need to clarify the problem that you are trying to solve through brute force.


This is not idiomatic writing style in Go, because the value variable is misleading:

if _, value := keys[entry]; !value {

The first returned value is the value in the map, the second value indicates success or failure of the lookup.
So rename it to ok or found.

If the slice is very large,
then list = append(list, entry) may lead to repeated allocations.
In that case, you can optimize by preallocating list to the maximum possible capacity (len(strSlice)), and assign elements by index rather than using append.
But if you have no reason for this optimization then don't do it,
that would be premature optimization,
the current solution is fine.


Passing file identifiers to all subroutines of fortran code

If you want to share access to one or more files that are known beforehand, a possible way is to make each file into a singleton and to pack all of them in a  module. I illustrate the principle below, after rewriting your code in modern fortran. The example incorporates many feature that should be considered for a production code. Of course, the implementation should be adapted to your real code.
module mod_output
  use, intrinsic :: iso_fortran_env, only : ERROR_UNIT
  implicit none
  private

  character(len=*), parameter :: MSG_NEW = 'Neue Datei ist geoeffnet'
  character(len=*), parameter :: MSG_DEL = 'Alte Dateil ist geloest '

  integer, public , parameter :: DIR_ID  = 1
  integer, public , parameter :: FILE_ID = 2

  !.. Singleton
  type, private :: class_output
     character(len=:), allocatable :: Directory
     character(len=:), allocatable :: FileName
     integer                       :: unitID      = 0
     logical                       :: opened      =.FALSE.
   contains
     procedure, public :: set     => class_output_set
     procedure, public :: getUnit => class_output_getUnit
     procedure, public :: open    => class_output_open
     procedure, public :: isSet   => class_output_isSet
     procedure, public :: close   => class_output_close
  end type class_output
  !*** some examples:
  type(class_output), public :: output_1
  type(class_output), public :: output_2
  integer, parameter, public :: SIZE_OUTPUT_LIST=10
  type(class_output), public :: outputList(SIZE_OUTPUT_LIST)

contains

  subroutine class_output_set(self,fieldID,strn)
    implicit none
    class(class_output), intent(inout) :: self
    integer            , intent(in)    :: fieldID
    character(len=*)   , intent(in)    :: strn
    select case ( fieldID )
    case ( DIR_ID  )
       self%Directory = trim(adjustl(strn))
    case ( FILE_ID )
       self%FileName  = trim(adjustl(strn))
    end select
  end subroutine class_output_set

  logical function class_output_isSet(self) result( isSet )
    implicit none
    class(class_output), intent(in) :: self
    isSet = allocated( self%Directory ) .and. allocated( self%FileName )
  end function class_output_isSet

  subroutine class_output_open(self)
    implicit none
    class(class_output), intent(inout) :: self
    character(len=:), allocatable :: path, msg
    character(len=100)            :: iomsg
    logical                       :: exists
    integer                       :: uid, iostat
    if( .not. self%IsSet() )then
       write(ERROR_UNIT) " output file not set"
       error stop
    end if
    call execute_command_line("mkdir -p "//trim(self%Directory))
    path = trim(self%Directory) // trim(self%FileName)
    inquire( file = path, exist = exists )
    if(exists)then
       msg = MSG_DEL
    else
       msg = MSG_NEW
    endif
    open(newunit = uid   , &
         file    = path  , &
         action  ="write", &
         iostat  = iostat, &
         iomsg   = iomsg )
    if( iostat /= 0 )then
       write(ERROR_UNIT,"(a)") iomsg
       error stop
    endif
    write(uid,"(a,x,i0)") msg, uid
    self%unitID = uid
    self%opened = .TRUE.
  end subroutine class_output_open

  subroutine class_output_close(self)
    implicit none
    class(class_output), intent(inout) :: self
    character(len=100) :: iomsg
    integer            :: iostat
    close(self%unitID  , &
         iostat= iostat, &
         iomsg = iomsg )
    if( iostat /= 0 )then
       write(ERROR_UNIT,"(a)") iomsg
       error stop
    endif
  end subroutine class_output_close

  integer function class_output_getUnit(self) result( uid )
    implicit none
    class(class_output), intent(inout) :: self
    if(.not.self%Opened)then
       write(ERROR_UNIT,"(a)") "Attempt to access unit of closed file"
       error stop
    endif
    uid = self%unitID
  end function class_output_getUnit

end module mod_output

Then your main program would look like this
program main
  !.. the other outputs can be initialized and used as well.
  !   If the different files have constant directory and filename
  !   they may be specified in mod_output and initialized collectively
  !   by an init routine at the beginning of the main program
  use mod_output
  implicit none
  integer, parameter :: int_vector(3) = [1,2,3]
  call output_1%Set(  DIR_ID, "sediment/"   )
  call output_1%Set( FILE_ID, "advect1.dat" )
  call output_1%Open()
  CALL bdexch( int_vector, size(int_vector) )
  call output_1%Close()
end program main

subroutine bdexch( ivec, n )
  use mod_output, only : output_1
  implicit none
  integer, intent(in) :: ivec(n), n
  integer :: uid
  uid = output_1%getUnit()
  write(uid,"(a,*(x,i0))") 'bdexch schreibt', ivec + 10
end subroutine bdexch

For an introduction to the simple syntax of modern Fortran, I suggest the following quick modern Fortran tutorial.


Addition plus division taking up all my CPU - Kinect depth denoising

@Jesse has already addressed the parallelization fun the way I would have addressed it. This answer merely adds a couple of coding style observations.

private readonly KinectSensor _KinectSensor;
private List<DepthImagePixel[]> _LastFrames;
private FilteredDepthPixel[] _FilteredDepths;
private bool _ResolutionFilteredDepthsInitialized;

These private fields don't follow the camelCase convention that's in order for private fields. Should be like this:

private readonly KinectSensor _kinectSensor;
private List<DepthImagePixel[]> _lastFrames;
private FilteredDepthPixel[] _filteredDepths;
private bool _resolutionFilteredDepthsInitialized;

Actually the last one, named like this, could be a delegate of some kind. I prefer using is or has as a prefix, it makes it easier to find the Boolean flags in the autocomplete dropdown:

private bool _isResolutionFilteredDepthsInitialized;

You're over-qualifying your member variables:

this._lastFrames.Add(currentPixels);
this.ReduceNoiseAndInvokeIfRequired(currentPixels, depthFrame.PixelDataLength, depthFrame.MaxDepth, depthFrame.MinDepth);

The this qualifier is redundant here, and is adding noise that's not needed. Ironic when you consider that the method invoked is called ReduceNoise ;)

_lastFrames.Add(currentPixels);
ReduceNoiseAndInvokeIfRequired(currentPixels, depthFrame.PixelDataLength, depthFrame.MaxDepth, depthFrame.MinDepth);

In terms of readability, I find it particularly rewarding with cases like this:

if (!this._ResolutionFilteredDepthsInitialized)

That turn into this:

if (!_isResolutionFilteredDepthsInitialized)

But then again, your usage of this is consistent all across, so this is basically a matter of personal preference - I prefer only qualifying with this when it's needed.

One thing though, is that if you're going to keep all the this qualifiers, then the _ underscore prefix should be dropped on the private fields.

Your event here:

public event EventHandler<DenoisedDepthReadyEventArgs> DenoisedDepthReady;

Appears to be raised by this method call:

RaiseOnDenoisedDepthEvent(this._FilteredDepths, maxDepth, minDepth);

Convention would be to raise the event in a method like this:

public void OnDenoisedDepthReady(DenoisedDepthReadyEventArgs args)
{
    if (DenoisedDepthReady == null) return;

    DenoisedDepthReady(this, args);
}

Or (and?):

public void OnDenoisedDepthReady(FilteredDepthPixel[] depths, int minDepth, int maxDepth)
{
    if (DenoisedDepthReady == null) return;

    var args = new DenoisedDepthReadyEventArgs(depths, minDepth, maxDepth); // assuming constructor
    DenoisedDepthReady(this, args); // or pass args to above overload
}


jQuery toggle sort order and save to variable

Mostly I'ma java developer, but I think that there are a couple of things that you can do to tidy the code up.

If you do not want to store state in the DOM then you can remove the jQuery data statements and store in the global scope. If I were a jQuery developer I would probably wrap this functionality into a plugin (sortable?) and then to call it on a table with the sortabletable calss use $('.sortableTable').sortable(). It would be more reusable, more encapsulated, and less likely to cause you weird behavior if you have two tables in your page!

However here's my quick take on the above code:

var column;

$('thead th').click(function () {

    // Get the current column clicked
    var thisColumn = $(this);

    if (thisColumn.is(column)) {
        var sort = column.data("sort");
        var newSort = toggle(sort);
        column.data("sort", newSort);
    } else {
        column = thisColumn;
        column.data("sort", false);
    }
    // Replace text in DIV
    $("div").text("column=[" + column.text() + "], order=[" + column.data("sort") + "]");

});

function toggle(current) {
    return !current;
}

You could skip over setting an initial state and have toggle (and you Ajax code) work with undefined values properly (returning false).


Improving performance when sorting array of structs by multiple fields

If your analysis is correct and the slowdown is really cased by the copying, then you could avoid that by using Array.Sort(), which directly sorts the array you have.

Though Array.Sort() isn't as convenient as OrderBy() combined with ThenBy(), you will have to create an IComparer or Comparison for each of the possible sort orders. It could look something like this:

Comparison<eCubeType> yFirstComparison = (c1, c2) =>
{
    int result = c1.Y.CompareTo(c2.Y);
    if (result != 0)
        return result;

    // ...

    return c1.Z.CompareTo(c2.Z);
}

If you don't like to do this manually you can use NList (the project site seems to be down at the moment):

IComparer<eCubeType> yFirstComparer = KeyComparer<eCubeType>.OrderBy(c => c.Y)
    .ThenBy(c => c.CubeType).ThenBy(c => c.LightLevel).ThenBy(c => c.X).ThenBy(c => c.Z);


Read a number with commas and decimal dots not using "builtin" support

Was intended as a joke, but should actually work for very large numbers because it only looks at the digits one by one. It uses some knowledge about digit character code points (48..58) O:)

int carry = 0;
boolean dot = false;
for (int i = 0; i < text.length(); i++) {
  char c = text.charAt(i);
  if (c >= '0' && c <= '9') {
    System.out.print((char) (c / 2 + 24 + carry))
    carry = (c & 1) * 5;
  } else {
    System.out.print(c);
    dot |= c == '.';
  }
}
if (carry != 0) {
  System.out.print(dot ? "5" : ".5");
}

More reasonable (one could do the division inline here, too) -- and no library calls at all (except for printing the result).

double result = 0;
double decimal = 0;
for (int i = 0; i < text.length(); i++) {
  char c = text.charAt(i);
  if (c >= '0' && c <= '9') {
    if (decimal != 0) {
      result += (c - '0') * decimal;
      decimal /= 10;
    } else {
      result = result * 10 + (c - '0');
    }
  } else if (c == '.') {
    decimal = 0.1;
  }
}
System.out.println(result / 2);


Check out PostgreSQL's tips on adding a lot of data into a table. In particular, are you sure that you need that index before INSERTing all that data? It might speed things up if you create the index after all the data has been added to the table.


Change random methods without losing too much performance

First of all, you should shuffle the array instead of sorting it on a random number. There can be duplicates in the random numbers, which means that lower numbers would end up earlier in the array slightly more often. This is naturally a small difference as the random numbers are large, but as you want to avoid any predictable pattern, it is still important.

Look at the Fisher-Yates algorithm for shuffling the values in an array.

To use the crypto random generator, you need a way to transform the bytes that it returns into a number in a specific range. You can use a method like the following to get a number in a range with the same probability for all numbers in the range (limited only by the randomness of the generator). It calculates the largest range of numbers that can be used to create a number in the desired range, then loops until it has picked a number in that range.

public static int GetInt(RNGCryptoServiceProvider rnd, int max) {
  byte[] r = new byte[4];
  int value;
  do {
    rnd.GetBytes(r);
    value = BitConverter.ToInt32(r, 0) & Int32.MaxValue;
  } while (value >= max * (Int32.MaxValue / max));
  return value % max;
}

This is based on the example on documentation page for the GetBytes method, but adapted for larger numbers.

On my computer the function will generate a million random numbers in 450 ms. The Random class does it in 20 ms, so it's slower, but not very slow. Shuffling on the other hand is faster than sorting, so you will get some performance back there.


Overriding default animation parameters with custom values

Object.assign(_defaultOptions, optionsArg )

But this will have side effects as it changes _defaultOptions object itself.


Combinations of size k from a list in OCaml

Your tails is very beatiful, your is_empty useless, and combnk a mess.

In combnk, your indentation obfuscates the actual structure of the code. Here is a better indentation:

let rec combnk k lst =
  if k = 0 then
    [[]]
  else
    let f = function
      | []      -> []
      | x :: xs -> List.map (fun z -> x :: z) (combnk (k - 1) xs)
    in
      if is_empty lst then
        []
      else
        List.concat (List.map f (tails lst))

Now there are some interesting observations to be made here: The branch if is_empty lst then [] does not access f, so we could move this test outside of the let:

let rec combnk k lst =
  if k = 0 then
    [[]]
  else if is_empty lst then
    []
  else
    let f = function
      | []      -> []
      | x :: xs -> List.map (fun z -> x :: z) (combnk (k - 1) xs)
    in
      List.concat (List.map f (tails lst))

But is the is_empty test actually necessary? tails [] produces an empty list, List.map f [] produces an empty list for any function f, and List.concat [] also produces an empty list. We now have:

let rec combnk k lst =
  if k = 0 then
    [[]]
  else
    let f = function
      | []      -> []
      | x :: xs -> List.map (fun z -> x :: z) (combnk (k - 1) xs)
    in
      List.concat (List.map f (tails lst))

How can this be improved? We can move the tails definitions inside the else-branch let so that it's restricted to the only scope where it is used:

let rec combnk k lst =
  if k = 0 then
    [[]]
  else
    let rec tails = function
      | []          -> []
      | _ :: t as l -> l :: tails t
    and f = function
      | []      -> []
      | x :: xs -> List.map (fun z -> x :: z) (combnk (k - 1) xs)
    in
      List.concat (List.map f (tails lst))

Regarding the question whether the case [] -> [] in f is necessary except for the type system: The answer is no, as the list produced by tails cannot contain another empty list – l :: [] is l again. This would change when you swap [] -> [] in tails for [] -> [[]], which would be arguably more correct.

Now that f and tails are so close together you may notice some similarities.  Indeed, we can combine the two directly, thus getting rid of one map:

let rec combnk k lst =
  if k = 0 then
    [[]]
  else
    let rec inner = function
      | []      -> []
      | x :: xs -> (List.map (fun z -> x :: z) (combnk (k - 1) xs)) :: inner xs
    in
      List.concat (inner lst)

Of course, inner could be made partially tail recursive (but this reverses the order of combinations):

let rec combnk k lst =
  if k = 0 then
    [[]]
  else
    let rec inner acc = function
      | []      -> acc
      | x :: xs ->
        let this_length = List.map (fun z -> x :: z) (combnk (k - 1) xs)
        in
          inner (this_length :: acc) xs
    in
      List.concat (inner [] lst)

There is still an indirect recursion through combnk, more obvious if we rewrite it like this:

let rec combnk k lst =
  let rec inner acc k lst =
    match k with
    | 0 -> [[]]
    | _ ->
      match lst with
      | []      -> List.flatten acc
      | x :: xs ->
        let this_length = List.map (fun z -> x :: z) (inner [] (k - 1) xs)
        in
          inner (this_length :: acc) k xs
  in
    inner [] k lst

Now all that is left to do is to write a map that takes an external accumulator, thus also removing the need for flatten or concat:

let rec combnk k lst =
  let rec inner acc k lst =
    match k with
    | 0 -> [[]]
    | _ ->
      match lst with
      | []      -> acc
      | x :: xs ->
        let rec accmap acc f = function
          | []      -> acc
          | x :: xs -> accmap ((f x) :: acc) f xs
        in
          let newacc = accmap acc (fun z -> x :: z) (inner [] (k - 1) xs)
          in
            inner newacc k xs
    in
      inner [] k lst


Sort, & find out duplicates and missing elements in an array

On the small 13 element array your implementation appears to be fairly performant, but since you request a "faster" implementation I took a stab at one myself.

Implementation

In this implementation I wanted to remove the multiple loops and use a data structure that lent itself to faster lookups, so I used plain javascript objects as maps. I also defined each array function callback outside where it'd be used to only instantiate a single copy.

function findDupsMiss2(arr) {
  const processedNumbers = {};
  const duplicates = {};
  const noDuplicates = {};

  const checkDupOrNot = (el, i) => {
    if (processedNumbers[el]) {
      duplicates[el] = el;
      delete noDuplicates[el];
    } else {
      noDuplicates[el] = el;
    }
    processedNumbers[el] = el;
  };

  arr.forEach(checkDupOrNot);

  const missedReduceFn = (missed, el, i, arr) =>
    el + 1 !== arr[i + 1] ? el : missed;
  const missed = [
    ...Array(
      processedNumbers[Object.values(processedNumbers).length - 1]
    ).keys()
  ].reduce(missedReduceFn, null);

  return [missed, Object.values(duplicates)];
}

Testing

This is the function I defined to measure how performant a function is:

const measurePerf = (fn, data, runs = 1000000) =>
  [...Array(runs).keys()]
    .map(() => {
      const start = performance.now();
      fn(data);
      const end = performance.now();
      return end - start;
    })
    .reduce((total, current) => total + current) / runs;

This takes a function and measures how long it takes to execute, sums the total time then divides by the # of runs to get an average execution time.

Used as such

measurePerf(findDupsMiss, data); // uses default 1 million iterations
measurePerf(findDupsMiss, data, 1000);

Initial Results

Using the default 1-million iteration performance measure

findDupsMiss1
[7, Array[4]]
0: 7
1: Array[4]
0: 2
1: 3
2: 5
3: 9
0.0021040050006413367

findDupsMiss2
[7, Array[4]]
0: 7
1: Array[4]
0: 2
1: 3
2: 5
3: 9
0.0023690749967063313

At first this may seem like your code is already faster (or my implementation is slower), but this isn't the entire story.

If we analyze the Big-O complexity of your implementation we find it is O(n^2). Of the outer loops (3x O(n) forEach loops and 2x O(nLog_n) sorts) each of the forEach loops has an additional O(n) search loop to find either an index or if an element is already included, bumping the Big-O to O(n^2).

The other implementation has also 4x loops (1x forEach, 1x array spread, 1x array reduce, 1x object.values), but has no inner loops, each loop uses an O(1) lookup in a map, so has an O(n) complexity.

  But where is the sort?

When using an object as a map with number-like keys, they are inserted in numerical order, so we get "sorting" for free. (in reality there is probably some minimal search though).

Further Results & Extended Examination

  What does this Big-O O(n^2) vs O(n) mean?

This has to do with how much work there is to do based upon input size. When an algorithm's Big-O complexity is O(n) then when the input size doubles the output should roughly double, i.e. something like 2n (hand wavey), whereas when an algorithm's Big-O complexity is O(n^2) then the output size something more like 4n.

Here's a rough table of output. Because of performance I had to drop the test performance iterations to 100 (versus10^6), but figured 100 runs is still enough to gather enough data for decent comparisons.

TBH the average is less relevant here as this table is more to illustrate the ratio between the two algorithms, with a secondary comparison in parenthesis to highlight the ratio of output from the previous iteration

const measurePerf = (fn, data, runs = 1000000) =>
  [...Array(runs).keys()]
    .map(() => {
      const start = performance.now();
      fn(data);
      const end = performance.now();
      return end - start;
    })
    .reduce((total, current) => total + current) /runs;

function findDupsMiss1(arr) {
  // your code here
  var noDuplicates = [];
  var missedNum;
  var duplicates = [];
  var sortedDuplicates = [];

  arr.forEach((el, i) => {
    if (noDuplicates.includes(el) == false) {
      noDuplicates.push(el);
    }
  });
  var sortedArr = noDuplicates.sort((a, b) => a - b);
  for (var i = 0; i < sortedArr.length - 1; i++) {
    if (sortedArr[i] + 1 !== sortedArr[i + 1]) {
      missedNum = sortedArr[i] + 1;
    }
  }
  arr.forEach(el => {
    if (arr.indexOf(el) != arr.lastIndexOf(el)) {
      duplicates.push(el);
    }
  });
  duplicates.forEach(el => {
    if (sortedDuplicates.includes(el) == false) {
      sortedDuplicates.push(el);
    }
  });

  var lastdup = sortedDuplicates.sort((a, b) => a - b);

  return [missedNum, lastdup];
}

function findDupsMiss2(arr) {
  const processedNumbers = {};
  const duplicates = {};
  const noDuplicates = {};

  const checkDupOrNot = (el, i) => {
    if (processedNumbers[el]) {
      duplicates[el] = el;
      delete noDuplicates[el];
    } else {
      noDuplicates[el] = el;
    }
    processedNumbers[el] = el;
  };

  arr.forEach(checkDupOrNot);

  const missedReduceFn = (missed, el, i, arr) =>
    el + 1 !== arr[i + 1] ? el : missed;
  const missed = [
    ...Array(
      processedNumbers[Object.values(processedNumbers).length - 1]
    ).keys()
  ].reduce(missedReduceFn, null);

  return [missed, Object.values(duplicates)];
}

const data = [10, 9, 8, 9, 6, 1, 2, 4, 3, 2, 5, 5, 3];

const perf1 = measurePerf(findDupsMiss1, data);
console.log(findDupsMiss1(data), perf1);

const perf2 = measurePerf(findDupsMiss2, data);
console.log(findDupsMiss2(data), perf2);

const processIterations = async () => {
  const results = [];

  // # elements 1, 2, 4, 8, 16, 32, 64, ..., 262144, 524288
  for (let i = 0; i < 20; i++) {
    const dataLength = 1 << i;
    const randData = [...Array(dataLength).keys()].map(() =>
      Math.floor(Math.random)
    );

    const [t1, t2] = await Promise.all([
      // For your sanity, start skipping findDupsMiss1 here at 11.
      // Maybe don't go more than 15 unless you like creating space heaters.
      i < 11 ? measurePerf(findDupsMiss1, randData, 100) : "skipped",
      measurePerf(findDupsMiss2, randData, 100)
    ]);

    results.push({
      iteration: i,
      dataLength,
      t1: Number.isFinite(t1) ? Number(t1).toFixed(3) : t1,
      t2: Number.isFinite(t2) ? Number(t2).toFixed(3) : t2
    });
  }

  return results;
};

processIterations().then(results => {
  console.log(`\t# Elements\tt1\tt2\tt2:t1 ratio`);
  results.forEach(({ iteration, dataLength, t1, t2 }, i, arr) => {
    const prev = arr[i - 1] || {};
    const t2t1Ratio = Number(t2 / t1).toFixed(2);
    const t1Ratio = Number(t1 / prev.t1).toFixed(1);
    const t2Ratio = Number(t2 / prev.t2).toFixed(1);

    console.log(
      `${iteration}\t${dataLength}\t${t1}(${t1Ratio})\t${t2}(${t2Ratio})\t${t2t1Ratio}`
    );
  });
});

    # Elements  t1 avg          t2 avg          t2:t1 ratio
0   1           0.002(NaN)      0.003(NaN)      1.50
1   2           0.002(1.0)      0.004(1.3)      2.00
2   4           0.003(1.5)      0.005(1.3)      1.67
3   8           0.006(2.0)      0.006(1.2)      1.00
4   16          0.005(0.8)      0.012(2.0)      2.40
5   32          0.011(2.2)      0.016(1.3)      1.45
6   64          0.031(2.8)      0.029(1.8)      0.94
7   128         0.084(2.7)      0.048(1.7)      0.57
8   256         0.270(3.2)      0.094(2.0)      0.35
9   512         1.032(3.8)      0.186(2.0)      0.18
10  1024        4.696(4.6)      0.372(2.0)      0.08
11  2048        16.303(3.5)     0.749(2.0)      0.05
12  4096        67.092(4.1)     1.492(2.0)      0.02
13  8192        266.986(4.0)    3.018(2.0)      0.01
14  16384       1081.774(4.1)   6.785(2.2)      0.01
15  32768       skipped(NaN)    12.298(1.8)     NaN
16  65536       skipped(NaN)    25.941(2.1)     NaN
17  131072      skipped(NaN)    49.775(1.9)     NaN
18  262144      skipped(NaN)    99.556(2.0)     NaN
19  524288      skipped(NaN)    195.841(2.0)    NaN

Notes:

Average time is in milliseconds
Item in () is the ratio to the previous time (i.e. line above)
Each iteration 100 runs for performance measuring
Stopped measuring algorithm 1 after 15 iterations, it's just too slow

Conclusion

As can be seen, the table confirms your algorithm, after a certain point, appears to settle into roughly a 4x output size based upon 2x input, where the other algorithm appears to settle around 2x, as expected. Also, a tipping point appears to consistently be around iteration #6 / 64 elements when algorithm #2 overtakes algorithm #1 and is more performant.


Assign value based on 100s of switch statement

If state.dimensionType is always an exact key match for a value in state.dimensions, and assuming that the default means the key doesn't exist, then you can do a lookup, for example:

if (!state.dimensions.hasOwnProperty(state.dimensionType)) {
  throw new Error('No dimension type specified');
}

state.dimensionQty = state.dimensions[state.dimensionType];


Part 1
For not_in_preamble, I'd use a for-else instead of your found variable, and not re-use the same set (I don't think it's worth it):
def not_in_preamble(nums, preamble):
    for i in range(preamble, len(nums)):
        current = nums[i]
        diff = set()
        for j in range(i - preamble, i):
            if nums[j] in diff:
                break
            diff.add(current - nums[j])
        else:
            return current

Since your "Any other feedback or alternative solutions are welcome" also allows less efficient solutions, here's how I actually solved it myself :-)
from itertools import combinations

def not_in_preamble(nums, preamble):
    for i in range(preamble, len(nums)):
        if nums[i] not in map(sum, combinations(nums[i-preamble : i], 2)):
            return nums[i]

Preamble size 25 and nums size 1000 are easily small enough for that to run quickly.
Part 2
Your sub_array_with_sum is great, although it does rely on the input being non-negative numbers, which isn't guaranteed in the problem statement (but is the case for the fixed input file).
I'd just go with PEP 8 and change nums[i: j + 1] to nums[i : j + 1] or nums[i : j+1]. And perhaps I'd go with while True:, relying on the existence of an answer.
Your algorithm almost only takes O(1) space. The only reason it takes more is copying out the sub-array (or rather sub-list, as this is Python and the problem never says "array", so there's really no need to call it array). Could be done in O(1) space to make the algorithm not just time-optimal (O(n)) but also space-optimal. Though that would require more code, not worth it (unless you have an interviewer who insists).
Input
I'd change [int(l) for l in f.read().splitlines()] to list(map(int, f)), or at least [int(line) for line in f].
Output
I'd change
print(f'PT 1 result: {pt1_result}') to
print('PT 1 result:', pt1_result). Bit shorter, and it works in older versions of Python. And at least in IDLE, the f-string is styled only as string, the whole thing green, including the variable. I don't like that.


Finding which items have at least one common value with other items

For set-based operations like this it's better to use HashSet<T>.

  The HashSet<T> class provides high-performance set operations.

The items can easily be converted to ones containing HashSets. Then, the Overlaps method does the comparison:

var hashed = items
    .Select(i => new { Name = i.Name, Values = i.Values.ToHashSet() })
    .ToList();
var overlaps = hashed.Select(h1 => new
{
    h1.Name,
    Overlaps = hashed
        .Where(h2 => h2.Name != h1.Name && h2.Values.Overlaps(h1.Values))
        .Select(h => h.Name)
});

Result:

A => B
B => A,D
C
D => B

Of course, if possible, it would be better to create items with HashSets at the outset.

EDIT

Triggered by your comment I did some benchmarking. I blew up your array a 1000 times, keeping unique names and then just measured both methods, using Linqpad:

var items = Enumerable.Range(1,1000).SelectMany(e =>  new[]
{
    new { Name = "A" + e, Values = new [] { 20, 4, 5, 9, 3, 22 } },
    new { Name = "B" + e, Values = new [] { 10, 7, 9, 8, 42 } },
    new { Name = "C" + e, Values = new [] { 11, 103, 0 } },
    new { Name = "D" + e, Values = new [] { 7, 35, 42 } }
});

var sw = Stopwatch.StartNew();
var hashed = items.Select(i => new { Name = i.Name, Values = i.Values.ToHashSet() }).ToList();

sw.Elapsed.Dump();

var overlaps = hashed.Select(h1 => new
{
    h1.Name,
    Overlaps = hashed
        .Where(h2 => h2.Name != h1.Name && h2.Values.Overlaps(h1.Values))
        .Select(h => h.Name).ToList()
}).ToList();
sw.Stop();
sw.Elapsed.Dump();

sw.Restart();
var tuples = items
    .SelectMany(x => x.Values, (x, y) => new { x.Name, Value = y })
    .ToList();

sw.Elapsed.Dump();
var result = tuples.Join(tuples,
           x => x.Value,
           x => x.Value,
           (x, y) => new { NameA = x.Name, NameB = y.Name })
    .Where(x => x.NameA != x.NameB)
    .Distinct()
    .GroupBy(x => x.NameA, x => x.NameB)
    .ToList();
sw.Stop();
sw.Elapsed.Dump();

The results:

00:00:00.0035664
00:00:02.0326684
00:00:00.0029370
00:00:06.3872002

As you see, the preparatory actions for both methods are done in 'no time', but the hashset-based method is considerably faster. Interestingly, if I blow up the arry 2000 times, the hashset-based method takes 7.7s and your method throws an OutOfMemoryException on my box.

Side note: if I don't make the names unique both methods are comparable. (On which I based my previous comment).


You are using the __call for a completly wrong purpose. Instead of defining the functions/methods in the class itself, you are in fact defining them in a __call function.

Everytime you call a method on your current class the compiler does this:

doest the method exist? does the scope have privileges to call the method? -> call the method.

No method found? doest the object have a __call method? does the scope have privileges to call the method? -> call the method.

Now you are in the __call method. It now does a lot of string comparisons (could be 'optmized' using switch statements if a lot of calls are made).

Not really optimal, not to mention that the compiler and or other developers now have no clue at all or it/they are passing enough arguments to a method. hell

But, what is the point of the __call method then you may ask. Some argue this should never have been implemented in the first place, some love it. But that is a different argument.

Some neat examples:

http://www.garfieldtech.com/blog/magical-php-call
Laravel facades (click here for the code)


Why do you submit the current user id in the form? I assume the user is logged in by the statement current_user.id in the form. If you're placing the current user id into the form, you allow the user to change the value (assuming you use the submitted user id in your handler). I know the field is hidden, but everything that an client submits can be manipulated. The only thing to do is open up the developer tools and alter the HTML source. Instead of submitting the id through the form I recommend simply using current_user in the handler and don't submit the user id at all.

You mention you're looking into Action Cable at the moment. However Action Cable is based on the web-socket technology. This could be used, but the main reason they where invented is to keep the connection between the server and client open so the server can send data to the client without the client making a request first. This is mostly done when something changed on the server that has impact on the current view of the client. The term for this would be push notifications or messages.

Since the view doesn't have to change when something changed on the server there is no need to make things more complicated. Instead you want to update the responses when user selects an answer (user initiated). The solution is to update the user response on change (using JavaScript). Rails has a build in system that does this documented in the Ruby on Rails Guides - Working with JavaScript in Rails: 3.2 Customize remote elements.

Let me provide you with an (untested) example:

First we ensure that the correct routes are present so we can update the response in a reasonable fashion.

# config/routes.rb
# ...
resources :questions, only: [] do
  member do
    post 'answer', to: 'responses#answer'
  end
end
# ...

This should create the route /questions/:id/answer that will be handled in ResponsesController#answer. This route should create a helper named answer_question that accepts an question or question id as its first argument.

The controller might look something like this:

# app/controllers/responses_controller.rb
# ...
def answer
  question = Question.find(params[:id])
  answer   = question.answers.find(params[:answer_id])
  response = question.responses.find_or_initialize_by(user: current_user)

  if response.update(answer: answer)
    head :ok
  else
    render 'answer_error'
    # renders /app/views/responses/answer_error.js.erb
    # Here you can write some JS to update the DOM and sets an error
    # message somewhere.
  end
end
# ...

And now for the final part of the puzzle we need the view.

<% # I don't know which view this is, but it replaces the one that OP provided. %>

<%= @question.prompt %>

<% @question.answers.each do |question| %>
  <%= form_for @response, url: answer_question_path(@question), method: :post, remote: true do |f| %>
    <%= f.hidden_field :answer_id, value: answer.id %>
    <%= f.submit a.answer.titleize, class: 'btn btn-block btn-lg btn-primary' %>
  <% end %>
<% end %>

By having an nested route you eliminate the need to submit the question id. And the user id can be left out for reasons mentioned before.

From the tone in your post I assume you also want to drop those forms. This is possible by using the "Customize remote elements" that I linked above. This would leave you with a view that might look something like this.

<%= @question.prompt %>

<% @question.answers.each do |answer| %>
  <%= radio_button_tag "question_#{question.id}_answer", answer.id, false, data: {
    remote: true,
    method: :post,
    url:    answer_question_path(@question),
    params: { answer_id: answer.id }
  } %>
<% end %>

The above would simply generate radio buttons (using radio_button_tag) that are linked to each other (per question). On change a request will be send to the specified URL. This eliminates the need for a form altogether. Keep in mind that no labels are currently present for the radio buttons, you'll have to add them yourself.

Of course you could also use other input HTML input elements to achieve the same result. If you want to stick to the button approach I recommend taking a look at button_tag in combination with the technique shown above. Or button_to which is an helper that generates the wrapping form for you.

As I said, this is an untested example. Might any errors come up let me know in the comments.


Overall I would have to say that this is the neatest and most clear implementation of a Merge Sort that I have seen. There is nothing wrong with variables i, j and k. They are standard names for looped array indexes. There is a single empty line in your code which is inconsistent with the rest of the method. That is the only nitpick I can find in terms of the style and neatness. It is a tiny, inconsequential thing.

The only recommendations I can make, are things that will improve performance, or will introduce some other common practices that may impact readability, though they are still more standard than what you have.

First, some common practice things

Consider doing post-increments inside the array-reference. This code:

while (i < leftSize && j < rightSize) {
    if (left[i] <= right[j]) {
        arr[k] = left[i];
        i++;
        k++;
    } else {
        arr[k] = right[j];
        k++;
        j++;
    }
}
while (i < leftSize) {
    arr[k] = left[i];
    k++;
    i++;
}
while (j < leftSize) {
    arr[k] = right[j];
    k++;
    j++;
}

would commonly be written as:

while (i < leftSize && j < rightSize) {
    if (left[i] <= right[j]) {
        arr[k++] = left[i++];
    } else {
        arr[k++] = right[j++];
    }
}
while (i < leftSize) {
    arr[k++] = left[i++];
}
while (j < leftSize) {
    arr[k++] = right[j++];
}

There is no change to the logic, the code is just a bit more compressed. The impact to readability is debatable, you get more code on a screen, but you have to look for the increments.
You copy the array contents using a regular loop:

int[] left = new int[leftSize];
int[] right = new int[rightSize];
for (int i = 0; i < mid; i++) {
    left[i] = inputArray[i];

}
for (int i = mid; i < size; i++) {
    right[i - mid] = inputArray[i];
}

The above would typically be done (for performance reasons), as one of two ways, either:

int[] left = new int[leftSize];
int[] right = new int[rightSize];
System.arraycopy(inputArray, 0, left, 0, leftSize);
System.arraycopy(inputArray, leftSize, right, 0, rightSize);

In Java6 and above, the Arrays utility class can be used too:

int[] left = Arrays.copyOfRange(inputArray, 0, leftSize);
int[] right = Arrays.copyOfRange(inputArray, leftSize, inputArray.length);

I would go with the Arrays.copyOfRange(...) call.

The above changes do not change the logic of your program at all, just the techniques used at the various points.

Your implementation would still be 'textbook'.

In terms of performance, though, your limit is the number of times you create, copy, and discard arrays of data.

There is a variant of the Merge Sort that uses just two arrays, the input array, and a 'temp' array that is the same size. The algorithm repeatedly merges small chunks of data from one array, to the other, then swaps them, and merges the now larger chunks back to the first, and keeps doing that until the data is sorted.

Using that algorithm means there is no additional array copying, etc. It is much faster, but the implementation would look very different to yours. Still I would recommend you try it. There are examples on Wikipedia


Replace each element in ArrayList with pair of Ints which sum to existing element

You don't need the if statement that is calculating left.  You can just make it the value that completes right into value:

int left = value - right;

Also, it is bad practice to modify a collection while you are iterating over it.  Make a new list and populate it, and just assign the reference at the end of the method.


Blocking queue implementation with std::unique_ptr

So if one producer and one consumer thread are using the queue, the producing queue gets prioritized.

I don't see anything in your code that corresponds to this sentence in your explanation. I think you have no "prioritization" going on here. The only thing determining which threads get to run when is the OS thread scheduler. And there's nothing at the algorithm level that could be described as "priorities"; this isn't like a rwlock where one side can "starve" the other. Contrariwise — each side here is "feeding" the other!

std::unique_ptr<struct Resource> res1{new struct Resource};

Two or three things about this line:

Don't use raw new and delete; use std::make_unique here instead.
Don't Repeat Yourself: use auto to avoid repetition here.
In C++, writing struct (or class or union) in a type-name is not idiomatic.

Thus this line should become:

auto res1 = std::make_unique<Resource>();

and your main routine in total becomes:

int main() {
    BQueue<std::unique_ptr<Resource>> q{40};
    q.push(std::make_unique<Resource>(42));
    q.push(std::make_unique<Resource>());
    for (int i = 0; i < 30; ++i) {
        q.push(std::make_unique<Resource>(i));
    }
    for (int i = 0; i < 15; ++i) {
        std::unique_ptr<Resource> res1;
        q.pop(res1);
    }
}

Writing return 0; at the end of main is unnecessary and unidiomatic (unless you want to be explicit because you return a non-zero value by some other codepath).

About unique_ptr inside the container versus outside: Instinctively prefer abstractions that are composable. So, if your options are:

create BQueue<T> that deals internally in std::unique_ptr<T>, or
create BQueue<T> that deals internally in T,

you should obviously prefer the latter. As a bonus, this means that your code will be useful ("reusable") even for people who are still stuck on boost::unique_ptr — they won't have to switch all their code from boost to std just to use your queue class.

while (_queue.size() >= _size) {
  _condition_full.wait(lock, [&]() { return (_queue.size() < _size); });
}

This loop is extremely confusing. You're looping with one condition outside and a different condition in the inner lambda. I strongly recommend removing one or the other of these loops. Specifically, I would remove the inner loop.

while (_queue.size() >= _size) {
  _condition_full.wait(lock);
}

The nice thing about removing the inner loop (as above) is that it's easily readable by a non-expert (say, someone coming from Java, C#, or Python). But if your target audience is C++ experts, this would also be okay:

_condition_full.wait(lock, [&]() { return (_queue.size() < _size); });

Your condition variables have mildly confusing names, IMO. Is _condition_full the thing I should wait on when the queue is full? Or is it the thing that gets notified when the queue is full? A little thought shows that it must be the former; but I don't like thinking, even a little bit. :)

Notice that this line —

_queue.push(std::move(item));

— runs under the mutex lock. If the item's move-constructor does something sketchy, this could be dangerous.

If you generalize your BQueue far enough that the user-programmer is allowed to customize the underlying container (e.g. change std::queue<T> to std::queue<T, std::list<T, A>>), then be aware that the user-defined memory allocator will also be running under the mutex lock. This probably isn't a problem at your current level of caring-about-metaprogrammy-bits, but it's something to consider.

if (!_condition_empty.wait_for(lock, std::chrono::seconds(1),
                               [&]() { return !_queue.empty(); })) {
  // waited too long for input.
  return false;
}

This (a function that blocks, but only for 1 second) is weird and dangerous. Don't do this.

If you want a pop function, write one. If you want a try_pop function (that can fail if the queue is empty), write one. If you want a try_pop_for function (that can fail by timing out), write one. But what you did was

write a try_pop_for_1s function (?!)
misname it pop (?!)

/* THIS FOLLOWING CODE MAY BE NEEDED;
 * KEEP IT IN CASE
 * _condition_empty.notify_one();

I believe this code is not needed. Consider:

The queue is empty. Thread C1 enters pop and blocks on _condition_empty.
Thread C2 enters pop and blocks on _condition_empty.
Thread P enters push, adds an item to the queue, and notifies-one on _condition_empty.
Thread P enters push again, adds a second item, and notifies-one on _condition_empty.

At this point, if either thread C1 or C2 is still waiting, it's a bug in the standard library. They should both be awake and waiting their turns to grab the mutex lock and process one item each off of the queue.

Similarly, the _condition_full.notify_one() at the end of push should not be needed, because if you've got two threads waiting on _condition_full, you might as well wait for the second pop before you unblock the second producer thread.

So:

template <class T>
void BQueue<T>::push(T item) {
  std::unique_lock<std::mutex> lock(_mutex);
  _condition_full.wait(lock, [&]() { return (_queue.size() < _size); });
  _queue.push(std::move(item));  // DANGER: running user code under a lock
  _condition_empty.notify_one();  // the queue is no longer empty
}

template <class T>
bool BQueue<T>::pop(T &item) {
  std::unique_lock<std::mutex> lock(_mutex);
  if (_condition_empty.wait_for(lock, std::chrono::seconds(1),
                                 [&]() { return !_queue.empty(); })) {
    item = std::move(_queue.front());  // DANGER: running user code under a lock
    _queue.pop();  // DANGER: running user code under a lock
    _condition_full.notify_one();  // the queue is no longer full
    return true;
  }
  // waited too long for input; the queue is still empty
  return false;
}


Node.js Nested Callbacks, multiple requests

Use Step.js or async.js to make this look cleaner.  Step.js is simpler, but async.js gives you more flexibility.

Also, your function single needs to have a callback, and cannot return values since the functions it's invoking are not returning values.

Additionally, generally the data retrieval methods should be separate from the rendering methods.

With Step.js, this could look like:

 var Parse = require('parse-api').Parse,
    Step = require('step');
    var parse = new Parse();
exports.getAndRenderData = function(res, params1, params2, params3){
   getData(params1, params2, params3, function(err, data){
      if(err)
        throw err:
      else {
        res.render('viewname', data);
      }
   });
}

var getData = function(params1, params2, params3, callack) {
    var data = {};
    Step()(
        function getClass1(){
            parse.find('Class_1',params1, this);
        },
        function getClass2(err, class1data){
           if (err) throw err;
           data.class1 = class1data;
           parse.find('Class_2',params2, this);
        },
        function getClass3(err, class2data){
           if (err) throw err;
           data.class2 = class2data;
           parse.find('Class_3',params3, this);
        },
        function callbackWithAll(err, class3data){
           if (err) callback(err);
           else {
             data.class3 = class3data;
             callback(null, data);
           }
        }
    );
}


Firstly, your encryption is useless. Just run this one line of python code:

print reduce(fractions.gcd, map(eval, encoded))

And it will tell you what your user key is (with a pretty high probability).

Your algorithm is really obfuscation, not encrytion. Encryption is designed so that even if you know the algorithm, but not the key, you can't decryt the message. But your algorithm is basically designed to make it less obvious what the parts mean, not make it hard to decrypt without the key. As demonstrated, retrieving the key is trivial anyways.

def encode(string, giveUserKey = False, doubleEncode = True):

Python convention is lowercase_with_underscores for local names

    encoded = [] #Numbers representing encoded characters
    keys = [] #Key numbers to unlonk code
    fakes = [] #Which items in "encoded" are fake
    #All of these are stored in a file

    if giveUserKey:
        userkey = random.randrange(2 ** 10,  2 ** 16)
        # Key given to the user, entered during decryption for confirmation
        # Could change range for greater security

Why isn't the key a parameter?

    else:
        userkey = 1

    for char in string:
        ordChar = ord(char)
        key = random.randrange(sys.maxsize)
        encoded.append(hex((ordChar + key) * userkey))
        keys.append(hex(key))

These just aren't keys. Don't call them that.

        if random.randrange(fakeRate) == 0:
            fake = hex(random.randrange(sys.maxsize) * userkey)
            encoded.append(fake)
            fakes.append(fake)

    if doubleEncode:
        encoded = [string.encode() for string in encoded]
        keys = [string.encode() for string in keys]
        fakes = [string.encode() for string in fakes]

Since these are all hex strings, why in the world are you encoding them?

    hashValue = hex(hash("".join([str(obj) for obj in encoded + keys + fakes]))).encode()

    return encoded, keys, hashValue, fakes, userkey

def decode(encoded, keys, hashValue, fakes, userkey = 1):
    if hash("".join([str(obj) for obj in encoded + keys + fakes])) != eval(hashValue):
        #File has been tampered with, possibly attempted reverse-engineering
        return "ERROR"

Do not report errors by return value, use exceptions.

    for fake in fakes:
        encoded.remove(fake)

What if coincidentally one of the fakes looks just like one of the data segments?

    decoded = ""

    for i in range(len(keys)):

Use zip to iterate over lists in parallel

        j = eval(encoded[i]) / userkey

Using eval is considered a bad idea. It'll execute any python code passed to it and that could be dangerous.

        decoded += chr(int(j - eval(keys[i])))

It's better to append strings into a list and join them.

    return decoded