I don't think you should worry about calling new like that, but you can avoid it by embracing objects and Ruby, it's not perl, you're not stuck with hashes! Make your data into objects and if you need a hash representation of it then write a method that converts the object into a hash.

If you want to be able to keep track of objects that's when I'd use a hash, by putting it into a class variable, or even better, a class instance variable.

Additional:

Since you've mentioned JSON in the comments, or perhaps you'd be passed the hash, then I'd still use objects, just add a way to coerce a hash into an object. A library I've forked called Grackle communicates with Twitter and can receive either JSON or XML. It does this by loading handlers, which means the same data object class can receive many differing types of input and still produce an object with a standard interface.

module Handlers
  module JSONHandler
    require 'json'

    def from_json json
      hash = JSON.parse(json)
      recursive hash
    end

    # You might want to add an extra check to stop an infinite loop
    # Beware the data!
    def recursive hash
      return nil if hash.nil?
      return hash unless hash.respond_to? :fetch
      Item.new id: hash["id"], parent: recursive(hash["parent"])
    end
  end
end

class Item
  extend Handlers::JSONHandler

  def self.items
    @items ||= {}
  end

  def initialize(id:, parent:nil)
    @parent = parent
    @id = id
    self.class.items[@id] = self
  end

  attr_reader :parent, :id

  def to_h
    h = {id: @id, parent: (@parent && parent.id) }
    h.reject{|k,v| v.nil? }
  end

  alias_method :to_hash,:to_h
end
# => Item
parent = Item.new id: 3
# => #<Item:0x007fa94a4010c8 @parent=nil, @id=3>
child = Item.new id: 7, parent: parent
# => #<Item:0x007fa94a9abe38 @parent=#<Item:0x007fa94a4010c8 @parent=nil, @id=3>, @id=7>
Item.items
# => {3=>#<Item:0x007fa94a4010c8 @parent=nil, @id=3>, 7=>#<Item:0x007fa94a9abe38 @parent=#<Item:0x007fa94a4010c8 @parent=nil, @id=3>, @id=7>}
Item.items[3]
# => #<Item:0x007fa94a4010c8 @parent=nil, @id=3>
Item.items[7]
# => #<Item:0x007fa94a9abe38 @parent=#<Item:0x007fa94a4010c8 @parent=nil, @id=3>, @id=7>
Item.items[7].parent
# => #<Item:0x007fa94a4010c8 @parent=nil, @id=3>
parent.to_h
# => {:id=>3}
child.to_hash
# => {:id=>7, :parent=>3}
json_parent = parent.to_h.to_json
# => "{\"id\":3}"
json_child = child.to_h.to_json
# => "{\"id\":7,\"parent\":3}"
parent2 = Item.from_json json_parent
# => #<Item:0x007fb543e26940 @parent=nil, @id=3>
child2 = Item.from_json json_child
# => #<Item:0x007fb5431d7270 @parent=3, @id=7>

and to make calling it easy:

def self.Item(*args, **keywords)
  case args.first
  when String # it's JSON
    Item.from_json args.first
  when Hash
    # you might want to nick the recursive bit from the handler
    # or write an Hash handler etc
    Item.new id: args.first["id"], parent: args.first["parent"]
  when Item
    args.first
  else
    Item.new id: keywords[:id], parent: keywords[:parent]
  end
end

Item(parent)
# => #<Item:0x007fb9b2765160 @parent=nil, @id=3>
Item(child)
# => #<Item:0x007fb9b272f330 @parent=3, @id=7>
Item(json_parent)
# => #<Item:0x007fb9b26fdd30 @parent=nil, @id=3>
Item(json_child)
# => #<Item:0x007fb9b26c7dc0 @parent=3, @id=7>
Item(parent.to_h)
# => #<Item:0x007fb9b26965b8 @parent=nil, @id=3>
Item(child.to_h)
# => #<Item:0x007fb9b2664928 @parent=3, @id=7>
Item(id: 3)
# => #<Item:0x007fb9b262ed50 @parent=nil, @id=3>
Item(id: 7, parent: parent)
# => #<Item:0x007fb9b25fc990 @parent=#<Item:0x007fb9b23bd7b0 @parent=nil, @id=3>, @id=7>


JavaScript function that toggles element visibility according checked radio input

I'd use data attributes on the radio buttons to point to the IDs of the text inputs. Then you don't have to worry about constructing the ID strings in code. For IE8, use getAttribute()

I'd also use external CSS to default all the text fields to hidden -- to avoid that first nested loop in your JavaScript.

I'd then use a CSS class to toggle the visibility of the text fields (if the class is present, the field is visible, if the class is not present, the field is hidden). This makes it easier to locate the currently visible input (document.getElementsByClass), instead of having to iterate through all the text fields every time a radio button is clicked.

If you use data attributes and CSS classes, the event handler becomes pretty generic. You could use "event delegation" and attach the handler once to the parent element (avoiding that forEach loop -- which is not supported natively in IE8).

FYI, the <label> tag is significantly less usable without it either encompassing both the radio button and label text, or having its for attributed defined.


How can I make a shorter binary rule in haskell?

I'm a little out of practice with haskell, but I'm quite fond of it. I want to address your "extra" question first.

wich one of the 2 version is more readable for an haskell programmer, and why ? [sic]

Haskell programmers aren't a special magic kind of people. They tend to take the benefits of brevity more seriously than folks in love with python, but I think they'll still agree that golfed code is not readable/smarter/better. The basic rule of good (code) writing applies: Write what you mean.

create a list starting with [0]
each step, concatenate all the current elements in the list, put the next number at the beginning and add at the end.

Neither of your proposed solutions is obviously doing that, although it only takes a minute to see that your first solution is doing that.
Noughtmare's suggestion is based on a different construction of the OEIS sequence, although the OEIS presents this as an invariant, not a construction, so the reader still needs to think the matter through (a little).
Give-or-take efficiency, write code that obviously does what you're saying it does. Unfortunately, the OEIS entry doesn't describe the sequence in terms that translate directly to a lazy infinite list declaration, so you need to provide some documentation of your own.
-- https://oeis.org/A007814
rulerSequence :: [Integer]
rulerSequence = concat halfs
  where seed = [0, 1]
        -- The sequence is built by concatenating with itself
        -- and incrementing the last index. `nextHalf` builds
        -- the right-hand-side of each such concatenation.
        nextHalf priorHalfs = let priors = concat priorHalfs
                              in (init priors) ++ [(last priors) + 1]
        halfs = seed:[nextHalf (take iteration halfs) | iteration <- [1..]]


Before worrying about performance, you should worry about security. You are vulnerable to SQL injection. Never put any variables directly into queries, use prepared statements instead.

Other than that:

mysql_ is deprecated for quite a while, and it will be removed in future PHP versions. You really shouldn't write code using it, use PDO or mysqli_ instead (and as said, with prepared statements).
upper-case all SQL keywords in your queries to improve readability.
your indentation is inconsistent.
your query seems a bit off. Do you really need union? Shouldn't something like WHERE (sender_id = '$sender_id' AND receive_id = '$receive_id') OR (sender_id = '$receive_id' AND receive_id = '$sender_id') work?
I would change the date and time columns to a datetime column, it should speed up your query a bit.
receive should be receiver to fit in with sender.


A more elegant implementation of the gcd function:

int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}

To ensure that the arguments are positive, it's easiest to use the abs(...) function.

Please also indent your code nicely to make it more readable.

And put spaces around operators. For example, instead of this:

for(int i=1;i<=first_number&&i<=second_number;i++){

Write like this:

for (int i = 1; i <= first_number &&i <= second_number; i++) {

Putting it together, the implementation of the entire program can become short and sweet:

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}

int main() {
    int num1, num2;

    cout << "Enter first number: ";
    cin >> num1;
    cout << "Enter second number: ";
    cin >> num2;

    cout << "Greatest Common Divisor: " << gcd(abs(num1), abs(num2)) << endl;
}

You can play with this on ideone.


Security: XSS

You are open to reflected XSS via this payload:

p=foo","","");alert(1)//

Note that the injection takes place into a JavaScript context, which is worse than injections into HTML context because browser filters have a hard time catching it (if you try the payload with eg chrome, it will execute, while "</script><script>alert(1)</script> would not).

Standard HTML-encoding would solve your problem, but OWASP recommends escaping to prevent XSS in a JS context.

Misc

p isn't a great variable name. If it stands for page, just use $page instead (also for the GET index).
As your other variable and function names are in english, navegacion should be as well.


MySQL query in nested loop to get scores and averages for students

You can replace:

  $learningoutcomeid = (int)$row4['learningoutcomeid'];
  $coursename = $row4['coursename'];
  $studentid = $row4['studentsisid'];
  $learningoutcomename = $row4['learningoutcomename'];
  $learningoutcomeid = (int)$row4['learningoutcomeid'];
  $assessmentcount = (int)$row4['assessmentcount'];
  $scoreavg = number_format($row4['scoreavg'], 1);
  $over3 = $row4['over3'];

by:

extract($row4);
$scoreavg  = number_format($scoreavg,1);

Note that there are several weird things in your code: 2x 'learningoutcomeid' and 'studentsisid'. Sloppy coding?

Your code here is also incomplete and not working. Sorry, that means no answer to your question.

What is also a serious problem is that the code is undocumented. There are NO comments to explain what's being done. Suppose you hand over this project to someone else, how is this next person to make sense of it? I looked at it for a while, and I cannot make sense of it. There seems to be just one table you use: 'studentscores', but it's structure eludes me.


FizzBuzz implementation in Java without modulus operator

I think this implementation is really too confusion for the problem at hand, although I think it is quite an interesting solution.

As you said it yourself, integer division loses the fractional part (rounds down towards 0). You can actually use this for your solution! Because if a number is not evenly divisible, multiplying with the division result will not give you back the original number, it will be smaller!

So a way to do this would be:

public static String fizzBuzz(final int number) {
    if (number / 15 * 15 == number) {
        return "FizzBuzz";
    } else if (number / 5 * 5 == number) {
        return "Buzz";
    } else if (number / 3 * 3 == number) {
        return "Fizz";
    }
    return Integer.toString(i);
}

Note that a number divisible by 3 and 5 is also divisible by 15.


Oke I'm going to have with this review the point of javadoc, namings and methods.

First :

You make comment, what is actually good but try to make javadoc in stead of commenting everything.

// comparator for sorting only
class NodeComparator implements Comparator<Node> {
    @Override
    public int compare(Node n0, Node n1) {
        return n0.getNDescendants() - n1.getNDescendants();
    }
}

should be :

/**
* Comparator for sorting on descendants
*/
class NodeComparatorNDescendants implements Comparator<Node> {
    @Override
    public int compare(Node n0, Node n1) {
        return n0.getNDescendants() - n1.getNDescendants();
    }
}

Why :
This cause you no more effort than commenting, but you can generate a complete javadoc what other persons can look into.
Also see that I added the on what you are sorting there.
At last I changed also the class name. Now you will already see without the javadoc on what you will compare.
Note : Effective class name helps you later also, take this code after a year not seen and you will need to see the implementation of the comparator if you want to know on what it compares.

Second :

Like I already said in the first point, naming is everything.
Node n => why just not Node node.
Other example : NodeComparator cmp => NodeComparator nodeComparator
This will not take more memory from your program if you have fear for that :), and if you use autocomplete this will not lose time to program.

Thirth :

Small effective methods are better than big ones that do a lot.
How less code in a method => the sooner you find the bug because your method complexity is lower.

Example :

// turns the tree into a full binary tree by removing as few nodes as possible
public void makeFullBinary() {
    // first, recursively make all the children into full binary trees
    for (Node n : children) {
        n.makeFullBinary();
    }
    // sort the children from least to most number of descendants
    Collections.sort(children, cmp);
    // remove descendants as needed to end up with 0 or 2
    while ((children.size() != 0) && (children.size() != 2)) {
        children.remove(0);
    }
    // recompute the number of descendants
    nDescendants = 0;
    for (Node c : children) {
        nDescendants += 1 + c.getNDescendants();
    }
}

should be :

// turns the tree into a full binary tree by removing as few nodes as possible
public void makeFullBinary() {

    createBinaryTree();
    Collections.sort(children, cmp);
    adjustBinaryTree();
    recalculateDescendants();
}

private void createBinaryTree () {
    for (Node n : children) {
        n.makeFullBinary();
    }
}

private void adjustBinaryTree () {
    while ((children.size() != 0) && (children.size() != 2)) {
        children.remove(0);
    }
}

private void recalculateDescendants () {
    nDescendants = 0;
    for (Node c : children) {
        nDescendants += 1 + c.getNDescendants();
    }
}

Why :
Each method is shorter then the whole method.
It's easier to read and to comprehent the actual doing of the method.
Now there is just one thing what bothers me, but it is an discussion amoung programmers, that's the reason I didn't changed it but still going to say
nDescendants is a calculated field.
For more rightness you should remove the int and set the recalculateDescendants code in the getNDescendants().
Yes you lose performance and you gain an always correctness of the getter.
Now you see directly why there are always discussions about that.

Hope this helps you already to improve yourself.


Iterative uniform recombination of integer lists in python with numba

No significant performance improvement but cleaner code.
Because temp_list is overwritten element-wise you can create it once and then leave it. At the end of each iteration you can then copy the entire list into int_list for the next iteration.
Similarly you can simplify creating the random ints a and b a bit. There are a lot of ways that get close to this in numpy but nothing I can find that beats the naive sampling directly works with numba and numba beats any overall solution I can think of without it.
Unfortunately (or maybe fortunately depending on your view), the numba compiler is compiling it down to the best solution I can think of for both your original version and this. Only difference is readabilitiy:
@nb.njit()
def comb(int_list, l, iterations):
    n = len(int_list)

    temp_list = int_list

    for _ in range(iterations):
        for i in range(n):
            a, b = 0, 0
            while a == b:
                a = random.randint(0, n - 1)
                b = random.randint(0, n - 1)

            temp_list[i] = a ^ ((a ^ b) & random.randint(0, l))

        int_list = temp_list

    return int_list

print(timeit(lambda: comb(list(range(1000)), (1 << 10) - 1, 100000), number=10))


Setting up a development environment - 2

These conditions are mutually exclusive, so they should be chained using elif:

if [ $# -eq 0 ]
then
    a="client"
fi

if [ $# -eq 1 ]
then
    a="$1"
fi

if [ $# -gt 1 ]
then
    a="$1"
    echo "Git-tooo many arguments"
fi

Like this:

if [ $# -eq 0 ]
then
    a="client"
elif [ $# -eq 1 ]
then
    a="$1"
else
    a="$1"
    echo "Git-tooo many arguments"
fi

This avoids unnecessary evaluations. That is, when $# is 0, only the first condition will be evaluated, the others won't be. In your original code, all conditions will be evaluated always.

As mentioned in the previous review, changing directory inside a script is not recommended. In config_grunt you have this as the last statement of the function:

cd ~/root

It seems pointless, and as it doesn't seem to have anything to do with configuring grunt, it probably shouldn't be in this function.


An entire file size retriever using a recursive os function in python

If there's no reason to make it a class, don't make it a class.  (A good clue is that your class doesn't have any instance variables, and that both of its methods could be static without changing the way they work.)
Both of your functions return the same information (formatted differently), but one calls it file_size and the other calls it directory_size even though it's the same number.  In addition, neither has a type annotation for the return value.  This all adds up to make it hard to figure out what each function does.  Maybe it'd be better to just have one function that gets the size and a seperate one that formats it as a string?
The totalsize parameter does not seem to serve any purpose as a parameter, and should be removed.
There's no reason to convert os.listdir into a tuple; you can iterate over it as-is.
current_directory is not necessarily a directory, so this name is confusing.
Your size formatting logic has an obvious gap in its if...elif chain.  Adding an else case fixes that.
This is a style thing, but I think f-strings are nicer looking than explicitly converting to str and using concatenation.
Your GB/MB/KB definitions are both copy+pasted and wrong.  Maybe this whole if...elif construction could be done more cleanly by turning the unit definitions into a table (where each unit size is defined exactly once) and iterating over the table?
Your recursive function would actually be simpler if it accepted any arbitrary path.  That way you wouldn't have to do as much logic inside the body of your iteration over the os.listdir results, and could actually just do it as a simple sum of recursive calls.
It's easier to test your code if you write a __main__ block that accepts a command line parameter!

Here's my massaged version of your code (does basically the same thing, but it uses the units as I've defined them rather than your hybrid 1024 * 10^N units -- having them defined the way I did it here makes it very easy to change if you'd rather make them 2^10, 2^20, etc).

import os
import sys

def recursive_get_size(path: str) -> int:
    """Gets size in bytes of the given path, recursing into directories."""
    if os.path.isfile(path):
        return os.path.getsize(path)
    if not os.path.isdir(path):
        return 0
    return sum(
        recursive_get_size(os.path.join(path, name))
        for name in os.listdir(path)
    )

def format_size(num_bytes: int) -> str:
    """Formats a size (given in bytes) into a human-readable string."""
    for unit_name, unit_size in [
        ("GB", 10**9),
        ("MB", 10**6),
        ("KB", 10**3),
    ]:
        if num_bytes > unit_size:
            return f"Size in {unit_name}: {round(num_bytes / unit_size, 3)}"
    else:
        return f"Size in bytes: {num_bytes}"

if __name__ == '__main__':
    print(format_size(recursive_get_size(
        sys.argv[1] if len(sys.argv) > 1 else r"E:\Utilities_and_Apps\Python"
    )))


Your code looks good, but there are some things which can be simplified.
Additionally, the method can be improved to return a array of the
actual managed object subclass type instead of AnyObject.

Simplifications and small improvements

var request: NSFetchRequest<NSFetchRequestResult>

request is assigned exactly once, therefore it should be a constant:

let request: NSFetchRequest<NSFetchRequestResult>

let entityClassName = NSStringFromClass(entityClass)
let entityName = entityClassName.components(separatedBy: ".").last ?? entityClassName

can be simplified to

let entityName = String(describing: entityClass)

which returns the unqualified class name of the given class
(in contrast to String(reflecting:) which returns the fully qualified
class name including the module name).

if let predicate = predicate {
    request.predicate = predicate
}
if let sortBy = sortBy {
    request.sortDescriptors = sortBy
}

The predicate and sortDescriptors of NSFetchRequest are optionals, so there is no need to conditionally unwrap
the given parameters. You can assign them directly:

request.predicate = predicate
request.sortDescriptors = sortBy

fetchedResult = try self.fetch(request) as? [T]

We know that the fetch request returns an array of T objects,
the cast cannot fail. Therefore the second half of the method
can be reduced to

do {
    let fetchedResult = try self.fetch(request) as! [T]
    return fetchedResult
} catch let error {
    print(error.localizedDescription)
    throw error
}

making the fetchRequestError variable obsolete. And if you don't
need to print the error locally then no do/catch is needed at all:

let fetchedResult = try self.fetch(request) as! [T]
return fetchedResult

A possible error will be re-thrown to the caller of the method.

Putting it all together, the method now looks like this:

extension NSManagedObjectContext{
    func fetchObjects <T: NSManagedObject>(_ entityClass:T.Type,
                       sortBy: [NSSortDescriptor]? = nil,
                       predicate: NSPredicate? = nil) throws -> [AnyObject] {

        let request: NSFetchRequest<NSFetchRequestResult>
        if #available(iOS 10.0, *) {
            request = entityClass.fetchRequest()
        } else {
            let entityName = String(describing: entityClass)
            request = NSFetchRequest(entityName: entityName)
        }

        request.returnsObjectsAsFaults = false
        request.predicate = predicate
        request.sortDescriptors = sortBy

        let fetchedResult = try self.fetch(request) as! [T]
        return fetchedResult
    }
}

Returning a "correctly" typed array

The return type is [AnyObject], which means that the return value has to be cast to the actual managed object subclass type

let objects = try context.fetchObjects(YourEntity.self) as! [YourEntity]

This can be improved by changing the return type to [T] and using
a typed fetched request NSFetchRequest<T>:

extension NSManagedObjectContext{
    func fetchObjects <T: NSManagedObject>(_ entityClass:T.Type,
                       sortBy: [NSSortDescriptor]? = nil,
                       predicate: NSPredicate? = nil) throws -> [T] {

        let request: NSFetchRequest<T>
        if #available(iOS 10.0, *) {
            request = entityClass.fetchRequest() as! NSFetchRequest<T>
        } else {
            let entityName = String(describing: entityClass)
            request = NSFetchRequest(entityName: entityName)
        }

        request.returnsObjectsAsFaults = false
        request.predicate = predicate
        request.sortDescriptors = sortBy

        let fetchedResult = try self.fetch(request)
        return fetchedResult
    }
}

This is now called as

let objects = try context.fetchObjects(YourEntity.self)

and objects is an array of YourEntity without additional cast.


Fast execution of function which resembles matrix multiplication

I think you can rearrange your equation from

\$
AB_{ija} = \frac{1}{2}(A_{ia} + B_{ja})
\$

\$
\begin{align}
C_{ij} = \sum_a & A_{ia}\cdot \log\left(\frac{A_{ia}}{AB_{ija}}\right) + B_{ja}\cdot \log\left(\frac{B_{ja}}{AB_{ija}}\right) + \\
&+ (1-A_{ia})\cdot \log\left(\frac{1-A_{ia}}{1-AB_{ija}}\right) + (1-B_{ja})\cdot \log\left(\frac{1-B_{ja}}{1-AB_{ija}}\right)
\end{align}
\$

to

\$
\begin{align}
C_{ij} = \sum_a & A_{ia} \cdot \log A_{ia} + B_{ja}\cdot \log B_{ja} - 2AB_{ija}\cdot \log AB_{ija}\\
&+ (1-A_{ia}) \cdot \log (1-A_{ia}) + (1-B_{ja})\cdot \log (1-B_{ja}) - 2(1-AB_{ija})\cdot \log (1-AB_{ija})\\
= \sum_a & A_{ia}\cdot \log A_{ia} + \sum_a B_{ja}\cdot \log B_{ja} - 2\sum_a AB_{ija}\cdot \log AB_{ija} + \dots
\end{align}
\$

This will at least save you some divisions, which can be a bit slower. But the crucial part is to see that you can compute the sums separately. The sums with only \$A\$ or \$B\$ are a lot less computation, which you would otherwise repeat, and only the combined terms are (computationally) hard.

It also means that there is probably a  numpy way to eliminate at least some of your for loops, which might give you a bit of a speedup, although numba will negate some of that (by already having sped up the for loops). The hard part is then to use the numpy broadcasting correctly to achieve this, which is left as an exercise for now :).


Webpack loader for Phaser.io asset files

Your current implementation doesn't work!

Look at this snippet, where I extracted the standalone function:

function exports(source) {
  var s = source;
  var re = /"url":\s*\".*,/g;
  var m;
  do {
    m = re.exec(source);
    if (!!m) {
      var path = m[0].split(':')[1].trim().slice(0, -1);
      s = s.replace(path, 'require(' + path + ')');
   }
  } while (m);
  return s;
}
var source = {
      "level1": [{
            "type": "image",
            "key": "starwars",
            "url": "assets/pics/unknown-the_starwars_pic.png",
            "overwrite": false
        },{
            "type": "image",
            "key": "spaceship",
            "url": "assets/pics/spaceship.png",
            "overwrite": false
        }
    ],
    "level2": [{
            "type": "image",
            "key": "spaceship",
            "url": "assets/pics/spaceship.png",
            "overwrite": false
        }
    ]
};
document.write(exports(JSON.stringify(source)).replace(/overwrite/g, '$&'));

The result is that the overwrite key following the url one is part of the require(...).
It comes from the way you expressed the regexp:

/"url":\s*\".*,/

Since the regexp is greedy the ending .*, consumes almost the whole string, up to the very last ,. Then when you apply split(':') on it, you keep the overwrite attached at the end of your path.

To fix this issue, you'd better to use this regexp:

/"url":\s*\"[^"]*",/

Here is the same snippet, now with this new regexp:

function exports(source) {
  var s = source;
  var re = /"url":\s*"[^"]*",/g;
  var m;
  do {
    m = re.exec(source);
    if (!!m) {
      var path = m[0].split(':')[1].trim().slice(0, -1);
      s = s.replace(path, 'require(' + path + ')');
   }
  } while (m);
  return s;
}
var source = {
      "level1": [{
            "type": "image",
            "key": "starwars",
            "url": "assets/pics/unknown-the_starwars_pic.png",
            "overwrite": false
        },{
            "type": "image",
            "key": "spaceship",
            "url": "assets/pics/spaceship.png",
            "overwrite": false
        }
    ],
    "level2": [{
            "type": "image",
            "key": "spaceship",
            "url": "assets/pics/spaceship.png",
            "overwrite": false
        }
    ]
};
document.write(exports(JSON.stringify(source)).replace(/overwrite/g, '$&'));

Well, as expected the overwrite is not included in the require(...).
But... now the require(...) itself is duplicated on the 2nd url occurrence, and omitted on the 3d one!

I din't try to look deeper on this second issue, because with the newly expressed regexp we clearly can do the job much more simply, like this:

function exports(source) {
  return source.replace(/"url"\s*:\s*"([^"]*)"/g, function(match, path) {
    return '"url":require("' + path + '")';
  });
}

Here is this version working:

function exports(source) {
  return source.replace(/"url"\s*:\s*"([^"]*)"/g, function(match, path) {
    return '"url":require("' + path + '")';
  });
}
var source = {
      "level1": [{
            "type": "image",
            "key": "starwars",
            "url": "assets/pics/unknown-the_starwars_pic.png",
            "overwrite": false
        },{
            "type": "image",
            "key": "spaceship",
            "url": "assets/pics/spaceship.png",
            "overwrite": false
        }
    ],
    "level2": [{
            "type": "image",
            "key": "spaceship",
            "url": "assets/pics/spaceship.png",
            "overwrite": false
        }
    ]
};
document.write(exports(JSON.stringify(source)).replace(/overwrite/g, '$&'));


Only small/minor issues:

Since code it to be portable to C with minor mods, suggest demarcating that which is sort code from test code.  Its appears the sort code is only these 3.  Do not mix test code with the application code.  Better in separate files.

void quickSort( int a[], int first, int last )
int pivot(int a[], int first, int last)
void swap(int& a, int& b)

pivot(), swap() should be static functions.  No need for them outside this file.
Minor: int vs. size_t.  An int index may lack sufficient range to index an array.  Use size_t as that is Goldilocks type neither to narrow nor wide a type to handle all array sizes - it is just right.  As size_t is some unsigned type, watch out for attempting to create negative values.  I did not notice any issue for your code concerning that.

// int N = sizeof(test)/sizeof(int);
size_t N = sizeof(test)/sizeof(int);

// void quickSort( int a[], int first, int last )
void quickSort( int a[], size_t first, size_t last )

// int pivot(int a[], int first, int last)
size_t pivot(int a[], size_t first, size_t last)

The sort would works well with other types beside int.   Perhaps code that way.

typedef int sort_type;
void quickSort(sort_type a[], size_t first, size_t last )

Function signature: Rather than oblige the calling code to supply 0, n-1, create a top level call:

void quickSortTop(sort_type a[], size_t size) {
  if (size) quickSort(a, 0, size-1);
}

Minor: Keep local variables as local as able.  pivotElement could be declared and initialized in 1 step local to the if() block as it is not used outside the block.  This borders on style issues, but as a rule, limiting variable scope is easier to see its use and impact.

int pivotElement;  // here
if(first < last) {
    int pivotElement = pivot(a, first, last); // or here
    quickSort(a, first, pivotElement-1);
    quickSort(a, pivotElement+1, last);
}

Minor: Correct comment?  I would think to reverse the order a >= would be needed.  If this is not so, then I would expect < to work slightly faster than <=.

/* If you want to sort the list in the other order, change "<=" to ">" */
/* If you want to sort the list in the other order, change "<=" to ">=" */

Minor: Dead code swapNoTemp().  No explanation for its existance here.


How can I simplify these if/else clauses?

This should be more simplified and more clear, now we make the query to the devices context first, then we get the result, instead of repeating the same thing three times. Remember, always use using when dealing with objects that inherits IDisposable:

using (SampleEntities sampleEntities = new SampleEntities())
{
    string searchname = parameters[1];

    var devices = (from dev in sampleEntities.NetworkDevices
        select dev);

    if (parameters[0].ToUpper() == "STARTSWITH"
        && parameters[1] != null)
    {
        ViewBag.MyMessage = "Displaying device names beginning with \"" + searchname + "\"";
        devices = (from dev in devices
            where dev.Name.StartsWith(searchname));
    }
    else if (parameters[0].ToUpper() == "CONTAINS"
        && parameters[1] != null)
    {
        ViewBag.MyMessage = "Displaying device names containing \"" + searchname + "\"";
        devices = (from dev in devices
            where dev.Name.Contains(searchname));
    }
    else
    {
        ViewBag.MyMessage = "Diplaying device names equal to \"" + name + "\"";
        devices = (from dev in devices
            where dev.Name == name);
    }

    var Model = (from dev in devices
                 from inter in sampleEntities.DeviceInterfaces
                 where inter.NetworkDevice.Id == dev.Id
                 select new DeviceInterfaceModel
                 {
                     DeviceName = dev.Name,
                     InterfaceName = inter.Name,
                     IPv4Address = inter.IPv4Address,
                     IPv4SubnetMask = inter.IPv4SubnetMask,
                     CIDR = inter.CIDR,
                     Subnet = inter.Subnet
                 })
    .ToList();

    return View(Model);
}


There, well, really isn't much to review here, so I have just a couple of points on this.

Add a docstring to the class Temporary. Describe what this class does in detail, and flesh it out with useful information about arguments as well.
You're missing some whitespace in between parameters in your __exit__ declaration. It should look like this def __exit__(self, _, __, ___).
You should add a method like write_to_file so that the user can change the contents of the file during runtime, before it's deleted.
As mentioned by @GarethRees, there's already a Python module built for this kind of use, tempfile.

I hope this helps! If there's anything else that you want me to cover on this, mention it in the comments, and I'll see if I can cover it.


List creation, manipulation, user interaction, loops, and just winging some fun stuff for a game

As a beginner Pythonista, one of the easiest ways to get tips on writing Python is to run your script(s) through pep8. That said, here are some non-PEP8-related tips:

Avoid pre-processing constant data on every run. After deleting what I assume are non-applicable spells simply replace the original array with the output of print(spells).
Reusing variables like you use spells and need is a code smell - it's hard to read the code and understand immediately what the type is at any given point. Instead you can either use a separate variable to avoid confusion or (in the need case) reverse the random/int check:

if need == 'r':
    […]
else:
    try:
        spell_number = int(need)
    except ValueError:
        print("Arr or a number, dammit!")

randint "[returns] a random integer N such that a <= N <= b." So you should print(spells[randint(0, len(spells)-1)]).
Your code is screaming for a class like Spellbook to reuse within other code.
Ditto for a main function with some argparse magic to enable scripting.
An IDE like PyCharm will do spell checking for you (snarky slang not included in the last community edition).


Calculating distance with Euclidean, Manhattan, and Chebyshev in C#

Let's start with some housekeeping. You're not using these using so they should be removed:

using System.Collections.Generic;
using System.Linq;
using System.Text;

Your namespace is far too generic - it's much better than ConsoleApplication1 but you should use something like <Company>.<Product>.<Feature> in your real app.

Your method names should be verb phrases ManhattanDistance should be CalculateManhattanDistance (and likewise for the others).

Why does your ChebyshevDistance take different parameters to the others? That seems unfriendly in the API design.

You should add documentation comments rather than simple comments to explain what a method does.

e.g.

/// <summary>
/// Calculates the Manhattan distance between the two points.
/// </summary>
/// <param name="x1">The first x coordinate.</param>
/// <param name="x2">The second x coordinate.</param>
/// <param name="y1">The first y coordinate.</param>
/// <param name="y2">The second y coordinate.</param>
/// <returns>The Manhattan distance between (x1, y1) and (x2, y2)</returns>
public static int CalculateManhattanDistance(int x1, int x2, int y1, int y2)
{
    return Math.Abs(x1 - x2) + Math.Abs(y1 - y2);
}

I'd also consider swapping the order of the parameters so you specify x1, y1, x2, y2 or using Point and PointF instead.

Now that's out of the way... ManhattanDistance looks correct.

EuclideanDistance is missing the final square root. The article you've linked to explains why that's bad:

  I’ve seen several A* web pages recommend that you avoid the expensive square root in the Euclidean distance by just using distance-squared
  [snipped pseudocode]
  Do not do this! This definitely runs into the scale problem. The scale of g and h need to match, because you’re adding them together to form f. When A* computes f(n) = g(n) + h(n), the square of distance will be much higher than the cost g and you will end up with an overestimating heuristic. For longer distances, this will approach the extreme of g(n) not contributing to f(n), and A* will degrade into Greedy Best-First-Search.

According to the Chebyshev distance Wikipedia article, in the Cartesian plane it's simply:

max(|x2 - x1|, |y2 - y1|)

Making it:

public static int CalculateChebyshevDistance(int x1, int x2, int y1, int y2)
{
    return Math.Max(Math.Abs(x2 - x1), Math.Abs(y2 - y1));
}

Although, following the article you linked your result should be:

public static int CalculateChebyshevDistance(int x1, int x2, int y1, int y2)
{
    var dx = Math.Abs(x2 - x1);
    var dy = Math.Abs(y2 - y1);
    return (dx + dy) - Math.Min(dx, dy);
}

I can't see how to prove that they're equivalent... If anyone can, I'd be interested to see it!

They are obviously equivalent... If you add the dx and dy together and then subtract the smaller of the two you are obviously left with just the bigger value i.e. the max of dx and dy.


squaring a number using bitwise multiplication or using *

Negative input causes undefined behavior
If input1 is negative, your code reaches the end of function without returning a value.  Either you should return something such as 0 in that case, or you should make the input type be unsigned.
Simplification using math
Your expression (2*(input1+1)+1) evaluates to 2*input1+3.  So to minimize the work done, you could do:
if (input1 > 0) {
    input1 += input1 + 3;
    return input1 * input1;
}

This has two adds, one multiply, and zero shifts.  This is one less shift than the code in "code1" and one less multiply than the code in "code2", so it should be faster than either of them.


I think Peilonrayz's answer is misleading (and might also timeout if you implement it): yes, you should exploit the limits, and yes, you can use the Sieve of Eratosthenes to speed things up, but not in the way he suggested.

Let's examine the time/space complexities of a bunch of algorithms and see how they compare. Below, we'll use \$N\$ to denote the maximum of \$m\$ and \$n\$, \$D\$ to denote the maximum difference between \$m\$ and \$n\$, and \$T\$ to denote the number of test cases. For the problem at hand, \$N = 10^9\$, \$D=10^5\$, and \$T=10\$.

OP's algorithm. Here for every input pair \$(m, n)\$, we loop over all numbers \$x\$ in this range, and check whether it is prime by checking whether it is divisible by any number between \$1\$ and \$x\$ inclusive. In the worst case, this requires time \$O(TDN)\$ and space \$O(1)\$.
Sieve the entire range (Peilonrayz/Billal). Here we use the trick of precomputing the set of primes in the entire allowed interval of length \$N\$, which allows us to answer each input query in time \$O(D)\$. If we use a fast sieving algorithm to do this precomputation [f1] this will take time around \$O(N)\$ (suppressing small logarithmic factors). This gives us an algorithm with time \$O(N + TD)\$ and space \$O(N)\$.

This is already a good deal faster than the original algorithm (at the cost of a lot more space). However, you can already do about as well in terms of time (and much better in terms of space) by just making some simple optimizations to OP's algorithm:

OP's algorithm with faster primality checking. One very simple improvement to make to the original algorithm is to remove a lot of the redundant work in checking whether a number is prime. A nice "folklore" result about primality checking is that to check whether a number \$x\$ is prime, you only need to check whether it is divisible by anything less than or equal to \$\sqrt{x}\$ (if it is composite, at least one factor will be less than this). This means you can check whether each number is prime in time \$O(\sqrt{N})\$ [f2] instead of \$O(N)\$ as in the original code. This improved algorithm requires worst-case time \$O(TD\sqrt{N})\$ and space \$O(1)\$. In practice, this runs pretty fast [f3], so it will probably outperform method 2 and might be sufficient for solving this problem.
Sieving only the relevant interval. Sieving methods like the Sieve of Eratosthenes are great, but it is important to understand why rather than apply them blindly. One reason why they are so great is that they let you eliminate many composite numbers at once very cheaply; for example, once you notice \$2\$ is prime, you can very efficiently loop over all larger even numbers and mark them as composite.

It would be nice to do this for the interval \$[m, n]\$ without having to do it for the entire interval \$[1, N\$]. By using our earlier observation that every composite number in this range is divisible by a prime less than \$\sqrt{N}\$, we can use the following strategy:

Precompute all the primes less than \$\sqrt{N}\$ by using the Sieve of Eratosthenes. This takes time approximately \$O(\sqrt{N})\$ and space approximately \$O(\sqrt{N})\$.
Make an empty boolean array of length \$n-m+1\$ with all values initialized to true, corresponding to the numbers between \$m\$ and \$n\$ inclusive.
For each prime in the list from 1., mark all multiples of that prime as false in the array from 2. For a prime \$p\$, this takes time \$O(D/p)\$.
The remaining values in the array set to true are the primes. Iterate over the array and print them out.

The tricky part of analyzing this is figuring out how long step 3 should take. The runtime of this step is roughly \$O(D\sum_{p < \sqrt{N}}\frac{1}{p})\$, where the sum is over all primes less than \$\sqrt{N}\$. Simple bounds from harmonic series show this is at most \$O(D\log N)\$; more careful bounds from analyzing sums of reciprocals of primes show that this is actually \$O(D\log\log N)\$. (Incidentally, this is also where the \$\log\log N\$ comes from in the Sieve of Eratosthenes).

Overall, this algorithm takes time \$O(\sqrt{N} + TD\log\log N)\$ and space \$O(\sqrt{N} + D\$), and is a clear winner for the constraints set in the problem.

In terms of coding style advice, I think Coal_ covered a lot of the relevant points. One thing which is sometimes important for algorithmic problems in Python 2.7 is to use xrange instead of range; the main difference being that range actually stores the list in memory and can lead to increased space complexity (for example, even though your original algorithm should use space \$O(1)\$, it actually uses space \$O(N)\$ because of your use of range).

[f1] It doesn't really matter whether we use Sieve of Eratosthenes or Sieve of Atkin; the only theoretical difference is small logarithmic terms in the complexities, and in practice it shouldn't make much of a difference for numbers of this size.

[f2] In fact, there are very efficient primality tests which run in time and space polynomial in the logarithm of $N$. Using one of these would give you an algorithm that runs in time \$O(TD\log^{k}N)\$ and space \$O(\log^{k}N)\$ (here \$k\$ is some small integer, like 4). Theoretically this is better than the above methods (especially for large \$N\$), but the overheads from these primality tests make it not as fast as sieving for numbers this small.

[f3] One reason for this is that not every primality check takes time \$\sqrt{N}\$; for example, the primality check catches that all even numbers > 2 are not prime in the first step. You end up saving about a $\log N\$ factor over the naive time bound.


Rails 6: Attaching Devise current_user.id to form submissions

Why do we need user_id in params at all? Probably, there is a need to add some context to a current scope. And yes, you're trying to write straightforward logic in a different way.

Here is some suggested refactoring:

class ListsController < ApplicationController
  def new
    build_resource
  end

  def create
    build_resource

    respond_to do |format|
      if update_resource
        # ...
      else
        # ...
      end
    end
  end

  def update
    update_resource
    # ...
  end

  def destroy
    destroy_resource
  end

  private

  def permitted_params
    params.require(:list).permit(:title, :active)
  end

  def resource
    @resource ||= current_user.lists.find(params[:id])
  end

  def build_resource
    @resource = current_user.lists.new
  end

  def update_resource
    resource.update(permitted_params)
  end

  def destroy_resource
    resource.destroy
  end
end

For those pure-CRUD controllers common logic can be easily moved into concern. We've created a gem some time ago https://github.com/cimon-io/unobtrusive_resources


First of all, if this function is not in a class you must remove the self parameter, there's no need of that. Then you should insert a check if the parameters are correct, that is the rows number and the columns number must be at least equals to maxLength:

if len(matrix) < maxLen and len(matrix[0]) < maxLen:
        return -1 # return error code

In this cases, when you have to move across a matrix, I suggest you to use a sort of direction tuples, which are tuples of the form (1,0), (0,1), (1,1), (-1,0) etc..; so for each element of the matrix you add to the indexes of that element one of this tuples multiplied for a number. Maybe it's more complicate to speak about it than show it:

def maxPathProduct(matrix, maxLen):
    if len(matrix) < maxLen and len(matrix[0]) < maxLen:
        return -1
    maxProduct = -1
    maxList = []
    directions = [(1, 0), (0, 1), (1, 1)]
    for i in range(len(matrix)):
        for j in range(len(matrix[0])):
            for dir in directions:
                tempProduct = 1
                tempList = []
                inc = 0
                indexOutOfBound = False
                while len(tempList) < maxLen and not indexOutOfBound:
                    row = i + dir[0] * inc
                    col = j + dir[1] * inc
                    if row < len(matrix) and col < len(matrix[0]):
                        tempProduct *= matrix[row][col]
                        tempList.append(matrix[row][col])
                        inc += 1
                    else:
                        indexOutOfBound = True
                if tempProduct > maxProduct:
                    maxProduct = tempProduct
                    maxList = tempList
    return maxProduct, maxList

In this case you have only to move from left-to-right ((0,1)), up-to-down ((1,0)) and diagonally-up-to-down ((1,1)). With those direction tuples you can avoid that terrible long list of if-elif-else. I've tried this solution a bit, I'm not completely sure that it works, but I hope that you understand the trick.


Check smsc type of batch and submits it to the proper queue

I assume you have (or can easily extract) an interface JMSQueue for this answer.
That's not really an unreasonable assumption I'd say, if you need help with that just drop me a note.

You're using the wrong tool here. What you have is a "mapping" between a string and a certain JMS-Queue.
Let's put that into code:

private Map<String, JMSQueue> queues = new HashMap<>();

// [...]
for (Batch batch : input.getBatches()) {
    JMSQueue responsibleQueue = queues.get(batch.getSmsc());
    if (responsibleQueue == null) {
        // queue not found. Log or whatever and then do the next batch
        continue;
    }
    responsibleQueue.sendJMSMessage(batch.getList(), priority);
}

Note that I've done some small changes on your code:

Respect indentation and whitespace around operators. Your IDE can help you with that.
Avoid unnecessary variables. They only make it harder to understand the code. Don't have everything inlined, but exercise care when creating variables.
Respect the naming conventions (talking about getlist)


Move array element to the first position

function update(e) {

    // find index
    var i = arr.findIndex(o => o.v === e.v);

    // if already at start, nothing to do
    if (i === 0) return;

    // remove old occurrency, if existing
    if (i > 0) {
        arr.splice( i, 1 );
    }

    // add e to the start
    arr.unshift( e );

    // keep array at the correct size
    arr.length = Math.min( arr.length, 4 );
}

Somewhat less code. I don't know about the performance.


Prefer using \n over std::endl

Other than that, it looks like your code is rather clean and up-to-date style-wise.  I might suggest that the get_instance_by_id return the actual type, not the Base in case it gets used in a context where a specific one is known at compile time (or within other template code).


Trying to outsmart the challenge defeats the purpose
While there is value in learning how to do the bare minimum needed (as you try to detect the number as soon as it is inputted instead of performing a search), there is only so much you can learn by trying to outsmart the challenge and not practice the knowledge this challenge is supposed to help you practice (which in this case is binary search).
Input reading
You can read the input faster using BufferedReader, see this answer's "Reading Data" section for example. You can read a whole line at once and then perform a search.
Binary search
Binary search is a very fast way to find an item in a sorted array where by looking at any element you know if what you're looking for is on the left or right of the current position.
You can perform the search on the string, converting the string to an array of numbers is unnecessary and therefore a waste of time.


Number of occurrences of each different word in a line of text

The easiest way would be to use a LinkedHashMap<String,AtomicInteger>, adding the words in order.

LinkedHashMap is a Map, so duplicate keys can easily be detected. AtomicInteger will allow incrementing the value without having to replace the value in the Map. Yet AtomicInteger isn't exactly intended to be used as a dumb counter, making your own Counter class is also a good option, as long as it has an increment() and a get() method, it'll make your interaction with the Map a lot smoother.

You can use String.split() to break up the input String in words.

Quick pseudo code:

split input String into words
loop the words
   if word not in map
      add word as key, with new counter
   get counter for word and increment
loop map entries
   print word and number of occurrences

Edit

Given the scope of your knowledge, I'll make a suggestion that only uses what you should know already. The idea is to replace the Map by an ArrayList of words and a matching array of int to hold the counts.

split input String into words
initialize an int[] array with the size equal to the number of words // max needed capacity
initialize an ArrayList of Strings
loop the words
   determine index of the word in ArrayList.
   if word not in ArrayList
      add word to ArrayList
   increment int in array at matching index as the word in the ArrayList
loop ArrayList
   print word and number of occurrences (from same index in array)


Take an Integer and print it in a Different Base Recursively (c++)

1. Names/Magic numbers
What is the magic number 55 in your base converter function?
I suggest giving it a name.
2. Bounds / Magic numbers / validation
Also, what are the upper and lower bounds on which bases are allowed? Only 2-9 since you are comparing with 9? That should also be specified and checked when reading the input.
3. Code formatting / style
Your code has a lot of space (empty lines and unnecessarily many newlines).
Unless your school requires you to follow that particular style, I suggest reformatting it into a more readable style. You can for example paste it into this formatter to get a more concise and readable code.
https://codebeautify.org/cpp-formatter-beautifier
For example, this is the output of reformatting part of your code.
void BaseConverter(int num, int base) {
  if (num == 0) {
    cout << "";
  }

  if (num >= base) {
    BaseConverter(num / base, base);

    if (num % base > 9) {
      cout << char(num % base + 55);
    } else {
      cout << num % base;
    }
  } else {
    cout << num % base;
  }
}

4. cout multiple inputs
You can chain inputs to cout so you don't need to do this
cout << endl;
cout << endl;

But rather
cout << endl << endl;
5. File reading
It doesn't seem that the requirements for the assignment are to read from a file. If that is correct, I think you should skip the file reading and read from cin or a similar terminal input instead.


Regex

The regex used is /(https:\/\/clyp.it\/)([\w]{8})/.
Since, here you're checking if the string is URL and not using to extract data from string, capturing groups can be removed.

[\w]: Match word character(alphanumeric character and underscore). This can be written as \w by removing character class.

I'll also suggest to use word boundary and use of i-case-insensitive flag to match both uppercase and/or lowercase alphabets.

/\bhttps:\/\/clyp.it\/\w{8}\b/

match vs test

String#match is used to extract data from string. To check if string follows particular pattern, use RegExp#test. test is faster than match.

See regex.test V.S. string.match to know if a string matches a regular expression

$('a[href^="https://clyp.it/"]').filter(function() {
    return /https:\/\/clyp.it\/\w{8}/i.test(this.innerHTML);
});

Variable Naming

Variable names should be self-descriptive. I'll recommend to read https://github.com/ryanmcdermott/clean-code-javascript#variables.

clyplinks can be just links or clypLinks(camelCase)
x can be renamed to flag and used as boolean(true/false)
e should be el if you like short names or element. As it is jQuery wrapped element, it is common to use $ as prefix in variable name- $element.

Event binding

For single link, this will work. If there are multiple links on the page to bind events on dynamic elements event delegation can be used. When using event delegation, the code should be moved outside of each so that event is not bound multiple times.

The syntax is

$(parentElementSelector).on(event, childElements, callbackFunction)

In this case, as there is no common parent element which contain all the links, we can use document

$(document).on('click', '.embed', function(event) {

Using data-*

Instead of using a flag to store the status of link, HTML5 custom data-* can be used. So, on click of link, first check if variable value is set and depending on the value perform action. To read the value of data-* attribute use data().

// Inside click handler
if ($(this).data('state') === 'embedded') {
    // Already embedded
    // Remove
} else {
    // Not embedded
    // Add
}

// Change the value
$(this).data('state', function(i, value) {
    // switch the value
    return value === 'embedded' ? 'not embedded' : 'embedded';
});

After doing these changes, previous code will not work. Inside the handler $(e).html( is used to change the link text. Note that html() will set the innerHTML of the element and not replace it. If you inspect the Embed link by clicking on it, you'll notice that link is nested. To solve this, just use $(this).html('[remove]'). Also, note that $(this) inside event handler refer to the element on which the event has occurred.

jQuery Wrapping & Method Chaining

clyplinks is already jQuery collection of element. There is no need of wrapping it in jQuery again.

jQuery allows to chain most of the methods.

var clyplinks = $('a[href^="https://clyp.it/"]').filter(function() {
    return this.innerHTML.match(/(https:\/\/clyp.it\/)([\w]{8})/);
});
$(clyplinks).each(function(index) {

can be written as

$(someSelector).filter(function() {
    return ...;
}).each(function(index) {

This also eliminates clyplinks variable.

Below things are also important

Code Formatting: You may install plugin/package in editor/IDE
Missing Semi-colons: Use jslint/jshint


index is a singular noun that doesn't represent of group of things, therefor it isn't a good name for an array.

Your method is named anagram_indices and returns an array, I like to call the returned array results, so it's clear that the array are the anagram indices.

Using i and x is very confusing, so much that it made me question my own knowledge of the enumerate function. I expected i to be the index and x to be the letter, while it's the opposite. You should rename those with better variable names. Actually, using single letter variable names is almost never a good idea, there are some edge cases. I expect a variable named i to represent an index, for example.

Your algorithm itself is fine, but the naming is very confusing, which is kind of a problem.


A Brushfire algorithm to generate a distance map in a grid

I would suggest to implement a HeatMapGridPoints class and inside this class, create two separate methods for GetUnexploredPoints and GetOpenPoints which will return list of GridPoint. This way, you can expand and also reuse the HeatMap. Also, it would be more readable than just gathering them into one method.

Example :

public class HeatMapGridPoints
{

    public IList<GridPoint> GetUnexploredPoints(IGrid grid)
    {
        var points = new List<GridPoint>();

        for (int i = 0; i < grid.Width; i++)
        {
            for (int j = 0; j < grid.Height; j++)
            {
                points.Add(new GridPoint(i, j));
            }
        }

        return points;

    }

    public IList<GridPoint> GetOpenPoints(IGrid grid, GridPoint goal)
    {
        // rest of the code
    }

}

you can also do something like this :

public class HeatMapGridPoints
{
    private readonly IGrid _grid;

    private readonly GridPoint _gridPoint;

    public IList<GridPoint> OpenPoints { get; private set; }

    public IList<GridPoint> UnexploredPoints { get; private set; }

    public HeatMap(IGrid grid, GridPoint goal)
    {
        _grid = grid;

        _gridPoint = goal;

        OpenPoints = GetOpenPoints();

        UnexploredPoints = GetUnexploredPoints();
    }

    private IList<GridPoint> GetUnexploredPoints()
    {
        ...
    }

    private IList<GridPoint> GetOpenPoints()
    {
        ...
    }

}

usage :

var heatMap = new HeatMapGridPoints(grid, goal);

foreach(var point in heatMap.OpenPoints)
{
    ....
}

this would make it much easier to maintain and also more readable.


There's not really much code here to review, and for what it is, all I really have are some subjective stylistic concerns (I'm not a fan of omitted braces or multiple declarations per line). Instead of reviewing it as a stand alone snippet, I'm going to review it as what I would expect a fully idiomatic and generic sorting function to be in C++.

The biggest issue I see with this is that it's not quite up to snuff with regards to C++ idioms. It's very rare to write a method that actually takes a container (and isn't just a convenience method for the iterator version). Instead, it's customary to take two iterators since that allows you to operate on any container. In certain situations, you can even make decisions based on the iterator type. For example, you could have your sort fall back to std::sort if the iterator is a random access iterator.

Anyway, what I'd expect to see is this:

template<typename FwdIterator>
void sort_selection(FwdIterator beg, FwdIterator end)
{
    ...
}

Some people prefer just Iter or something similar, but I like to specify the lowest iterator requirement necessary to use the function. In this case, you just require a forward iterator.

Speaking of iterator types, you should use != over < when dealing with iterator loops if all you care about is whether or not the second iterator has been reached by the first.

operator< might not be present on iterators in situations where operator!= is. This is a perfect example actually. Forward iterators are not required to define operator< and in fact usually won't. Other than the std::vector hard coding, the beg < end is the only thing stopping you from generalizing to a forward iterator.

As Ben Voigt noted, it would also be expected to generalize the comparator:

template<typename FwdIterator, typename Comparator>
void sort_selection(FwdIterator beg, FwdIterator end, Comparator cmp)

You would then either have the comparator default to std::less or you would have two functions: one that takes a comparator and one that just calls the comparator taking version with a std::less instance.

All in all, without going completely overboard, I would expect a sorting method to look something like this:

template<typename FwdIterator, typename Comparator>
void sort_selection(FwdIterator beg, FwdIterator end, Comparator cmp)
{
    for (; beg != end; ++beg)
    {
        FwdIterator min = std::min_element(beg, end, cmp); // auto if >= C++11
        if (cmp(*min, *beg))
            std::iter_swap(min, beg);
    }
}

template<typename FwdIterator>
void sort_selection(FwdIterator beg, FwdIterator end) {
    // using instead of typedef if >= C++11
    typedef typename std::iterator_traits<FwdIterator>::value_type value_type;
    sort_selection(beg, end, std::less<value_type>());
}

It might be worth noting that you don't actually need two methods. I just think it's a little cleaner than this:

template<typename FwdIterator, typename Comparator = std::less<typename std::iterator_traits<FwdIterator>::value_type>>
void sort_selection(FwdIterator beg, FwdIterator end, Comparator cmp = Comparator())


It depends on how much /* Code */ there is. If it's just a few lines, that's one thing. If it gets too large though, the reader will lose sight of the fact that you're creating an anonymous listener. I would say that if the anonymous listener is more than 5, or maybe 10 lines then you should use an inner class instead.

There comes a point where even an inner class is really too large though.

In general, questions about "When is  too big?" are highly subjective, but failing to ask them, and failing to act on the answers leads to hard to read, difficult to maintain code.

Also, as biovamp pointed out, if you want to reuse the code, then you need to create a regular class.


Function to grab stdin, stdout, stderr of a child process

There might be good use cases for goto,
but this is not one of them.

It's best when code reads from top to bottom.
The goto statements break that readable flow.
Since the jump-to labels are quite far,
I'm forced to scroll to the end to see what they do.
After I scrolled, I find some code using variables defined at the beginning,
which I haven't memorized earlier,
so now I have to go back to top.
Effectively I'm making several jumps back and forth to understand how this works,
and then a few more jumps to verify carefully that it should work well.

This is a nightmare, and it doesn't have to be.
If you replace the goto statements with the code at their jump-to labels,
the code becomes:

if (pipe(in)) {
    return -1;
}
if (pipe(out)) {
    close(in[0]);
    close(in[1]);
    return -1;
}
if (pipe(err)) {
    close(out[0]);
    close(out[1]);
    close(in[0]);
    close(in[1]);
    return -1;
}

This is a lot more readable:
everything I need to understand these guard statements are right there above.

You probably don't like the duplication when closing in,
and again later in the code if fork failed,
closing in and out.
It's true that code duplication is not good,
but I think it's the lesser of evils here,
and it's outweighed by the improvement in readability.

If you still disagree, and consider avoiding the duplication more important,
then you can improve this technique with goto by using more descriptive labels,
for example:

  close_err_and_out_and_in_and_return_with_failure:
    close(err[0]);
    close(err[1]);
  close_out_and_in_and_return_with_failure:
    close(out[0]);
    close(out[1]);
  close_in_and_return_with_failure:
    close(in[0]);
    close(in[1]);
  return_with_failure:
    return -1;

Avoid comments when possible.
Instead of a comment,
try to code in a way to make the comment unnecessary.
For example:

/* This section is never be reached without a goto */

This comment could be replaced with this statement:

return pid;

Not only this is short and sweet,
it has the great benefit that since it's code,
it is enforced: the lines below it will not be reached,
no matter what changes in the code above the return statement.

And we're kind of back to the pesky goto statements.
Without the goto statements,
this concern here about the comment and the logic wouldn't exist in the first place.


Linked lists of templated classes vs function ptr

The second is simpler, neater and avoids virtual functions. Prefer std::function over boost::function unless the latter gives you something extra, which it doesn't here


int fd, readcount;
// ...
readcount=mmap(0,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);

If this is the code you're using, it probably gave you a warning which you ignored.  mmap returns void *.  You should change the declaration of readcount to int *.  Also, the size of the mapping should be a multiple of the page size.  I'd be sure to re-read the manual for mmap, carefully read any compiler warnings, and make sure your code checks for errors.

At any rate, if int *readcount; refers to shared memory, the following will not work:

++*readcount;

The problem is this line is conceptually broken into a few steps:

Fetch *readcount into register
Increment register
Store back into *readcount.

If multiple processes perform steps 1/2/3 in lockstep, and the initial value is 0, they will both store 1 back.

You could use a GCC extension for compare and swap to make an increment safe:

int fetch;
do
{
   fetch = *readcount;
} while (!__sync_bool_compare_and_swap(readcount, fetch, fetch+1));

However I'm not sure if this will work right if you do it on memory mapped from a file by mmap.  Keeping this kind of atomicity in a page fault handler seems complex and I'm not sure if the standard guarantees that it should work.


Stack implementation using a linked list

Time complexity

The time complexity of push and pop operations should be \$O(1)\$, and so it is in your case too. It doesn't matter how many elements you have, these operations should take constant time. (UPDATE: you've edited your original post, and made pop wipe out the entire stack. That's not normal! Normally, the pop operation on a stack should return the most recently added value. That's \$O(1)\$ time.)

Avoid printing to stdout

Instead of the display* methods that print to stdout, it would be better to override toString. That way your implementation would be more testable.

Generalize

Why limit the stack, linked list, node elements to int type? It would be trivially easy to rewrite to make it work with any type T.

The question is tagged "beginner", so I understand you might not be familiar with generics just yet. In that case, see this official tutorial. Or perhaps you can also learn from my example implementation further down.

Add an isEmpty method for the stack

Your linked list has an isEmpty method but the stack doesn't. It would be good to have such method for the stack too.

Reinventing the wheel

When reinventing the wheel (here, linked list), it's good to mimic what exists. For example, java.util.LinkedList uses the method names addFirst and removeFirst, instead of insertFirst and deleteFirst. It's good to follow the example.

Access modifiers and encapsulation

As @rolfl pointed out, Node should not be exposed to the outside. Users of the stack should not have to know its inner workings.

Also, the members of Node should be private, and the data and next fields can be final. Similarly in the stack, the linked list member should be private.

Naming

You use poor names in many places.

Instead of n for the new node when replacing the first item of a linked list, newFirst would be more intuitive
Instead of temp for the old first item removed from a linked list, oldFirst would be more intuitive
Instead of li for the linked list in the stack, linkedList would be more intuitive

Suggested implementation

class LinkList<T> {

    private static class Node<T> {

        private final T data;
        private final Node<T> next;

        public Node(T data) {
            this.data = data;
        }

        @Override
        public String toString() {
            return data.toString();
        }
    }

    private Node<T> first = null;

    public void addFirst(T data) {
        Node<T> newFirst = new Node<T>(data);
        newFirst.next = first;
        first = newFirst;
    }

    public T removeFirst() {
        Node<T> oldFirst = first;
        first = first.next;
        return oldFirst.data;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        Node current = first;
        while (current != null) {
            builder.append(current).append(" ");
            current = current.next;
        }
        return builder.toString();
    }

    public boolean isEmpty() {
        return first == null;
    }

}

class LinkListStack<T> {

    private final LinkList<T> linkedList = new LinkList<>();

    public void push(T data) {
        linkedList.addFirst(data);
    }

    public T pop() {
        return linkedList.removeFirst();
    }

    public boolean isEmpty() {
        return linkedList.isEmpty();
    }

    @Override
    public String toString() {
        return linkedList.toString();
    }
}

Unit tests

@Test
public void testPushAndPop() {
    LinkListStack<Integer> st = new LinkListStack<>();
    st.push(50);
    st.push(70);
    st.push(190);
    assertEquals("190 70 50", st.toString());
    assertEquals(190, (int) st.pop());
    assertEquals("70 50", st.toString());
}

@Test
public void testPopUntilEmpty() {
    List<Integer> values = Arrays.asList(50, 70, 190, 20);
    LinkListStack<Integer> st = new LinkListStack<>();
    assertTrue(st.isEmpty());
    for (Integer value : values) {
        st.push(value);
    }
    assertFalse(st.isEmpty());
    for (int i = values.size(); i > 0; --i) {
        assertEquals(values.get(i - 1), st.pop());
    }
    assertTrue(st.isEmpty());
}


Prefer Clear Naming over using namespace std

Before I go into why

using namespace std;

is to be avoided, in the case of this program it is not needed since there is no use of any functions that derive from the std namespace in this code.

According to the MSDN website:

  Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

A collision is when 2 different functions have the same name, the same arguement types and a similar functionallity (this is why they have the same name). Someone developing software may want to override a function such as std::cout, std::cin or they may want to override the functionallity of a class such as std::vector or std::stack. Namespaces allow these constructs to be overriden.

The use of the programming statement:

using namespace std;

hides the fact that cin, cout, vector and stack are coming from the namespace std where cin, cout,
vector and stack are used in the code. This can cause confusion of where the code is actually
coming from.

As the software becomes more complex and uses more libraries this becomes a bigger problem.

For a more detailed discussion of why it is a bad idea to use using namespace std; see this stackoverflow question and stackoverflow question.

Use Standard Libraries When Possible

Instead of writing a binary search it might be better to use the one provided by the standard template library. It saves time when writing code, and every effort has been made to make the standard library functions as efficient as possible, which means you won't generally have to optimize it.

To use the standard library binary search you would need to include the  algorithm header

#include <algorithm>

Reduce Complexity, Follow SRP

The Single Responsibility Principle states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

  Robert C. Martin expresses the principle as follows:
          A class should have only one reason to change.

While this is primarily targeted at classes in object oriented languages it applies to functions and subroutines well.

The void exploreCave(int N) function could be broken up into at least two functions. This code specifically seems to be a good candidate for a function.

    while (low != high) {
        bool changed = false;
        int a = low;
        int b = (low + high) / 2;
        for (int i = 0; i < N; i++) {
            if (i >= a && i <= b) {
                if (door[i] != -1) {
                    guess[i] = status[i];
                }
                else {
                    guess[i] = !status[i];
                    changed = true;
                }
            }
            else guess[i] = status[i];
        }
    }

The more separate functions there are the easier it is to understand or read the code. This also makes it easier for any programmer to maintain or debug the code.

Use Meaningful Variable Names

The variables r, K and N do not help the reader understand the code. It's not clear at all what the variables r and K are. N is defined only if one reads the problem description, which is not currently included in the question. There are some good variable names such as guess, status, and changed although it might be better to make the array names plural. Variable naming should be consistent. The function name exploreCave is quite clear as well. Using i and j is quite common and understandable, but what is r and K? A second question is why is K needed since r does not change between it's assignment and usage?

Use One Statement to Declare and Initialize a Single Variable

When the arrays status, door and guess are declared as when the variables low and high are declared and initialized it is done so on a single line. This makes the code harder to read and maintain. I initially missed the declaration and initialization of high. To make the code more readable and easier to maintain declare variables on separate lines in new statements.

    int low = 0;
    int high = N - 1;

is much easier to read and maintain than

    int low = 0 , high = N - 1;

You may not be the person maintaining the code, and even if you are it may be multiple years between initially writing the code and modifying it. It is important to make the code as readable as possible.


The implementation of depth-first traversal is correct.
But there are several elements of this program and tests that could be improved.

Prefer empty collections over null values

When the input graph is empty,
it would be better to return an empty list instead of null.
Collections are used for iterating over its elements.
When a collection variable can be null,
that's troublesome, because before you can iterate over it,
you have to check that it's not null.

Constraints and limitations

The implementation will only work with directed graphs without cycles,
otherwise you will have an infinite loop.
This is important to include in the description.
A common follow-up question at an interview is how to make it work in graphs with cycles.

Weak tests

The test knows too much about the implementation.
There are 6 possible valid depth-first traversals of the example graph,
and the test knows exactly which one to expect.
It all comes down to the evaluation order of neighbor,
in your implementation it's the reverse order that they were added.
Either this implementation should be documented,
or the test should not depend on it.

The example graph is not a good choice to demonstrate depth-first traversal,
because A F E B C D would be valid both as depth-first and as breadth-first traversal.
A more expressive example would be:

    A
   / \
  B   C
 /     \
D       E

With this example all depth-first and breadth-first traversals would be distinct.

Lastly, a technical detail,
instead of comparing the elements of a list one by one to values,
you could compare entire lists, which would be a lot easier to type.

List<string> expected = new List<string>(new string[] { "A", "B", "C", "D", "E", "F" });
List<string> result = TraverseDFS(root);
Assert.AreEqual(expected, result);

Don't provide setters if you don't really need

The fields of GraphNode are never modified,
therefore the setters are unnecessary.


Simple Go REST API that returns dummy messages

There's not so much code that it would be hard to read, looks clean enough to me.

Regarding scalable ... in what way?  The switch in Handler will be the limiting factor since adding another route will always have to have a corresponding edit in that function.  Some frameworks will have ways around that (for better or worse), but as long as there are just a handful of routes I doubt it's a real issue (though if this is more of an exercise, go for it: if you have a hundred handlers, how could you register them instead of having a single point like here?).

In ServeHTTP there'll definitely be an issue with the need for additional, more nuanced error codes.  I'm not suggesting a particular solution, but I can see that happening quite quickly ... plus, 404 for an internal error looks wrong too, that should be 500 most likely, only if the route couldn't be found 404 would be appropriate.

Okay two more, returning a string instead of directly writing output will be a scalability problem, it'd be much better to avoid additional memory allocations to construct that string and simply write to the output buffer / writer directly.

And, the result of a errors.New can be stored in a global variable as long as the message doesn't change - one more memory allocation gone.


Searching two different elements in a same list

There's no problem with the performance. Java 8 filtering actually doesn't scan the whole stream, so the processing will be done only until the first element meeting the predicate is hit. So you're fine this way. However, I would do a bit of refractoring here:

private List<UserChannel.AppUser> findLatestAppClients(
            List<Conversion> conversions) {
    Optional<Conversion> iosClient = findFirstWithName(IOS.clientName());

    Optional<Conversion> androidClient = findFirstWithName(ANDROID.clientName());

    List<UserChannel.AppUser> appUsers = new ArrayList<>();

    addIfPresent(appUsers, iosClient);

    addIfPresent(appUsers, androidClient);

    return appUsers;
}

private Optional<Conversion> findFirstWithName(String name){
    return conversions.stream().filter(c -> name.equals(c.getClient())).findFirst();
}

private void addIfPresent(List<UserChannel.AppUser> appUsers, Optional<Conversion> conversion){
    if (conversion.isPresent()) {
        appUsers.add(new UserChannel.AppUser(conversion.get().getClient(),
            conversion.get().getClientId()));
    }
}


You want to import only the functions you're actually going to need:
import Data.List     (group)
import Control.Arrow ((&&&))

As Gurkenglas already said, use concatMap instead of concat . map. This leads to
runLengthExpand :: [(Int, a)] -> [a]
runLengthExpand = concatMap (uncurry replicate)

Your runLengthCompress is fine, although (&&&) might not be known to newcomers.
Now, areInverses is too obfuscated:

About the code itself I fear I have written too little points (arguments) to my functions, hindering readability but I am not sure, maybe the lack of points makes it more readable, not less.

Pointfree style isn't necessarily easier to read:

5 Problems with pointfree
Point-free style can (clearly) lead to Obfuscation when used unwisely.

We can split its functionality in multiple functions:
isInverseOn :: Eq a => (a -> b) -> (b -> a) -> a -> Bool
isInverseOn f g x = x == g (f x)

areInverses :: Eq a => (a -> b) -> (b -> a) -> [a] -> Bool
areInverses f g = all (isInverseOn f g)

This removes the need for =<< completely and is easier to read than your previous (==) =<< f . g.
However, that only checks whether g is an inverse of f, not whether f is the inverse of g. For example, g's codomain might not be the completely covered by f's domain. So a proper areInverses should also check isInverseOn g f for some appropriate values.
You can use QuickCheck to generate appropriate strings and lists of pairs, although you need to generate the latter by hand.


best way to write series of objects to a .ser file using ObjectOutputStream and read them back

Why didn't you provide a constructor for Student class? Was that on purpose? However...

Use serialVersionUID.
In Java it's recommended not to use Vector class, instead use ArrayList.
Write method is serializing a Student individually. But as you stated you are writing a whole list of student into the .ser file. This will take many time for a list of 10,000 students.

Because you are opening two streams for each student. So instead pass the whole list and serialize them after opening the stream only once.
Do not close the stream in the try block. close them into finally block. Even better if you are using Java7 or higher use try-with-resources block. It is easy to use and you don't have to manually close the stream.
In Read method

        for(;;){
            save = new ObjectInputStream(saveFile);

you are creating new stream for every object thats not necessary instead do this

        save = new ObjectInputStream(saveFile);
        for(;;){

Onwards Java7 there is multiple catch statement. Give it a try(pun intended).
In Java we use mixed-case convention for naming a method. So Write and Read would be write and read.


Competition - Qualifications - E - Matrix distance

Your explanation is difficult to follow, but your code explains it. It's simple and clear.
The main thing I want to advise is to not use using namespace std. See this Stack Overflow question for reasons.
You don't show what ll is, I presume it's a long long int type?
For a newline, use '\n' rather than "\n". There's not a huge difference, but it's slightly faster to output a single character than a string containing a single character.
In terms of improving performance, you might want to keep a single vector with a struct:
struct Data {
   int x, y, v;
}
std::vector<Data> data;
// ...
data.emplace_back(a, b, c);

This gives you at least two advantages:

You call malloc/realloc (on push_back) three times as frequently if you have three vectors. If you have only one vector on the stack, there is a good possibility that realloc will simply add space to the end of your block, rather than creating a new block and copying the data over. If you have three vectors, trying to expand one will invariably have another be in the way, forcing the copy.
Of course you could do data.reserve(n) and be sure you'll never call realloc.

Data locality: In your second case, where you iterate over the data, you would read the three values from consecutive locations in memory, rather than from disjoint locations. This will allow a better use of cache. Since you iterate over these frequently, it could make a big difference.

Finally, you can improve your distance computation and do away with one of the calls to std::abs. Note that, for the L-1 norm that you use, distance(p1,p2) == abs(distance(0,p1)-distance(0,p2)). And, given your text "m (maximal dimension for square matrix)", I presume that the coordinates indicate a location within this matrix, and therefore are always larger or equal to 0. If so, computing the distance to the origin requires no std::abs. then your distance
abs(a - x[j]) + abs(b - y[j]) // distance(p1,p2)

can be rewritten as
abs(a + b - (x[j] + y[j])) // abs(distance(0,p1)-distance(0,p2))

The thing that still bothers me is that you are given m, but you don't need it. Maybe we're missing another possibility for optimization there?

(EDIT) Reducing complexity from O(n²) to O(n log n)
It is possible to reduce the complexity of step 2 by adding some (a lot of) complexity to step 1. Both steps (adding a point and computing the weighted distance of a point to all previous points) should turn into operations of logarithmic complexity w.r.t. the number of points seen so far.
We start with the observation that the core distance computation
sum( v[j] * ( abs(a - x[j]) + abs(b - y[j]) ) )

can we rewritten as
sum(v[j] * abs(a - x[j])) + sum(v[j] * abs(b - y[j]))

That is, the two dimensions can be tackled independently. From here on we'll look only at the x-coordinate, and presume we repeat the same operations for the y-coordinate.
Next, we note that we can write
sum(v[j] * abs(a - x[j])) == sum(v[j] * (a - x[j])) // for x[j]<=a
                          == sum(v[j] * (x[j]) - a) // for x[j]>=a

Thus, we need to separate incoming points in step 1 into those that are to the left of a future query point, and those to the right. (Note that if x[j]==a, the distance will be 0, and the point can be ignored or used twice without affecting the output.
So how do we separate incoming points around a coordinate we don't know yet? Use a tree. R-trees are the tool for spatial indexing like this. We need a simplified version, since we don't need to store bounding boxes, only split locations. Maybe it's more similar to a quadree.
Because
sum(v[j] * (a - x[j])) == sum(v[j])*a - sum(v[j]*x[j])

it seems that we need to accumulate sum(v) and sum(v*x) for all points to the left of x (and also for those to the right). Thus our tree needs to store these values. The tree further needs to indicate what the coordinate is that splits its left and right branches. Thus, we can easily find in the tree the nodes that are to the left or to the right when computing a distance in step 2.
I think the tree should have each input point as a leaf node. Each non-leaf node (can I call those branch nodes?) would contain the sum of v and v*x for its two children, as well as the x-coordinate half-way between the two children's x-coordinates. Something like this:
struct Node {
  Node* left;
  Node* right;
  std::uint64 sumV;
  std::uint64 sumXV;
  std::uint32 x;
}

During step 1, it's simply a matter of inserting nodes:
void Node::insert(std::uint32 x, std::uint32 v) {
  if (isLeaf()) {
    // turn this leaf node into a branch node
    // create a new leaf node with {sumV,sumXV,x}
    // create a new leaf node with {v,x*v,x}
    sumV = left->sumV + right->sumV;
    sumXV = left->sumXV + right->sumXV;
    x = (left->x + right->x) / 2;
  }
  if (x <= node->x) {
    left->insert(x,v);
  } else {
    right->insert(x,v);
  }
}

During step 2, find the position of a in the tree, and obtain sumV and sumXV for all nodes to the left, and all those to the right:
std::uint64 Node::sum(std::uint32 a) {
  if (isLeaf()) {
    return std::abs(sumV*a - sumVX);
  }
  if (a>=x) {
    return left->sumV*a - left->sumXV + right->sum(a);
  } else {
    return right->sumXV - right->sumV*a + left->sum(a);
  }
}

I don't have time to write a full implementation and test it, but it was to think about this problem!


Efficiency of grid generated by for-in loop

you can write this code dramatically shorter like

self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

NSArray *array = [[NSArray alloc] initWithObjects:@"Item #1", @"Item #2", @"Item #3", @"Item #4", @"Item #5", @"Item #6", @"Item #7", @"Item #8",  nil];

NSUInteger buttonWidth = 100;
NSUInteger buttonHight = 100;
NSUInteger spacer = 5;
NSUInteger leftOffset = 5;
NSUInteger topOffset = 5;
[array enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
    int row = idx / 3;
    int column = idx %3;

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake((buttonWidth + spacer)*column+leftOffset, (buttonHight+spacer)*row +topOffset , buttonWidth    , buttonHight);
    [button setTitle:obj forState:UIControlStateNormal];
    [self.view addSubview:button];
}];

Note: ARC enabled


Accessing server side variables in views and JavaScript

This is how I see server variables and local variables interacting.  There is not really any other way to get the values between the two that I'm aware of.

As for the code, I one minor point:change Emp to Employee for variable names.  This will eliminate confusion in the future from you, or anybody else reading the code (what does Emp mean?)

Other than that, this is really easy code to read.  Keep it up.


Reading lines from a file in random order

Regarding your questions:

You're reading bytes.  Fortunately, the only three line ending
conventions all involve Newline and Return, both a single byte.
There's nothing more to it.  So if you stay with an encoding using
single bytes for (most of) their characters, such as UTF-8, there will
be no problem.  For other Unicode encodings you'd have to read more
than one byte per character and also do some decoding.

Frankly even without encodings this is a hairy topic,
c.f. Newline on Wikipedia.
Though line-offsets uses the same convention as readLine, so I
guess that's just FYI.
I'd at least not use short/one-letter variable names for function
parameters, because they also serve as documentation.  E.g. r
doesn't tell the reader anything, rdr is barely english, but
reader is clear and doesn't cost that much more in terms of
characters.  Same with s and sequence.  For a, b, c in
line-offsets I'd even say that c1 to c3 would be more helpful.
It'd be best to orient yourself at standard functions.  It's probably
better to have the most important "subject" first, then subsequently
the rest unless there's a good reason not to.  Parameters at the ends
can also very easily be curried, maybe that's another hint to think
about it.

Other than that, yeah, looks good.  I don't quite see why the laziness
is necessary, since it's calling shuffle anyway, but perhaps it's
useful in some situations?


Download image links posted to reddit.com

Never do except Exception:, especially not to pass. You probably want to be catching KeyErrors specifically, or using dict.get in the first case, and in the other cases adjust accordingly.
There's no need to do json.loads(file_like_object.read()), just use json.load(file_like_object).
You can eliminate a race condition in makeSavedir by not calling os.path.exists, just call os.makedirs (and catch the IOError if you'd like to not raise the exception [and make sure to check its errno]).
You can use string formatting in place of adding strings.
Your try blocks are too big. They will catch various exceptions that you aren't handling. This is another instance of my first point.

There are other things, these were just the quick things from reading top to bottom :).

P.S. There's an unofficial Python wrapper for the reddit API at https://github.com/praw-dev/praw that you could consider using.


Is it okay to use multiple repositories from inside a single service implementation in Spring?

Best practice to perform CRUD operations is to have this flow for an entity-

View --passing Dto--> Controller -- passing Dto/Entity--> Service --passing Entity--> Repo

In your example you can have both repositories inside a service as both entities ( company and address ) are associated.

Also, to fall in line you can save address entity along with country entity using cascade


Implementation of Singly Linked List (C++)

struct Node would benefit from its own constructor. As a side note, if you don't want to expose struct Node to the client (and trust me, you don't), better make it private to class LinkedList.

tmp doesn't deserve to be a class member. It is strictly local to each method.

DRY. push_back could and should be streamlined:
  struct Node * tmp = new Node(data);
  if (begin) {
      last->next = tmp;
  } else {
      begin = tmp;
  }
  last = tmp;

display_all should not print anything on the empty list. The caller might be greatly confused.

clear could and should be streamlined. Run the loop till nullptr:
  while (begin) {
      struct Node * tmp = begin->next;
      delete begin;
      begin = tmp;
  }
  last = nullptr;

As a side note, prefer nullptr to NULL.


Laravel Single Page Application Using Angular Js

This code seems okay for the most part - I don't see any major flaws with the code, just a few things that I will critique below.

Despite being spread across quite a few files, this code seems pretty simple. Not that it is by any means wrong, but it is a bit unique to see AngularJS code paired with Laravel code.

  While Laravel does not dictate which JavaScript or CSS pre-processors you use, it does provide a basic starting point using Bootstrap and Vue that will be helpful for many applications.1

The biggest thing I would critique is the lack of request failure handling. While it may be very unlikely that the AJAX requests to get the list of users would fail, due to the simplicity of the controller method and the fact that if that fails it might also be the case that the page wouldn't have loaded in the first place, it is wise to handle such cases gracefully. Typically when calling .then() on a Promise, the second argument should be supplied for the case when the promise is rejected.

$http.get('getusers').then( function(response) {
  $scope.datas = response.data;
},
function(rejectionReason) {
  //handle case when request fails here
});

Or instead of passing the rejection handler as a second argument, it could be passed in a subsequent call to .catch()

Other than that, I would bring up the naming of $scope.datas in the controller:

$http.get('getusers').then( function(response) {
  $scope.datas = response.data;
});

datas is a very generic term. Somebody reading that response could think "After getting the response from getusers, Do we need to abstract the users from response.data? A more appropriate name might just be users:

$http.get('getusers').then( function(response) {
  $scope.users = response.data;
});

Then the markup can be updated accordingly:

   @{{ user.id }}
   @{{ user.name }}
   @{{ user.email }}
   @{{ user.created_at }}

Other than that, I would suggest conditionally showing the table - only if there are entries in the data array. For that, ng-if and/or ng-show can be used. See the snippet below for an example

var mainApp = angular.module("mainApp", []);
mainApp.controller('AddStudentController', function($scope, $http) {
  $scope.requestSent = false;
  updateUsers = function() {
    $http.get('https://jsonplaceholder.typicode.com/users').then(function(response) {
      $scope.users = response.data;
    }, function(rejectionReason) {
      //display error message?
      $scope.error = rejectionReason;
    })
    .finally(function() {
      $scope.requestSent = true;
    });
  };
  setTimeout(updateUsers, 2000); //wait 2 seconds to simulate network latency
});

         Company Name

Home

About Us

          Id
          Name
          Email
          Created At

          @{{ user.id }}
          @{{ user.name }}
          @{{ user.email }}
          @{{ user.created_at }}

1https://laravel.com/docs/5.7/frontend


Advanced love calculator that generates a result based on the similarities between the two names

First, your definition of consonants can be simplified a bit using set operations:

from string import ascii_lowercase

# Storing vowels in a set instead of a list
vowels = {'a', 'e', 'i', 'o', 'u'}

# Read as "Take the set of lowercase letters, and remove the vowels"
consonants = set(ascii_lowercase) ^ vowels

The vowel counting code below that is repetitious. You have the same counting loop twice. This is a good place to make use of a function:

def count_vowels(name):
    count = 0
    for i in vowels:
        count += name.count(i)

    return count

total_vowel1 = count_vowels(name1)
total_vowel2 = count_vowels(name2)

Instead of importing random a few times throughout the script, just import it at the top once. Unless you have a good reason to hold off on importing something until you really need it, just import any modules right at the top for clarity.

Your spacing is kind of a mess. At different points you have:

total_vowel1 =0
consonants1 = 0
love +=random.randint(10,50)
((love<49) or (love == 49))
love +=random.randint(10,30)
love+=random.randint(1,10)

See the problem? You're either being wildly inconsistent in your spacing, or you aren't caring to make sure your code readable and nice looking. Pick a spacing style and stick to it. I'd recommend putting spaces around infix operators (love < 49 or love == 49).

You're using two different counting and naming methods for vowels and consonants: a full loop, and a comprehension:

total_vowel1 =0
for i in ['a','e','i','o','u']:
     total_vowel1 += name1.count(i)

. . .

consonants1 = len([letter for letter in name1 if letter.lower() in consonants])

Again, try to be consistent. You or someone else may need to read your code later, and consistency greatly helps readability.

((love>90) or (love == 90)) is needlessly complicated. Just write love >= 90.

In that same area, you have a bunch of ifs. They're all exclusive of each other though, so really, all the ifs after the first should be elifs.

if love <= 89 and love >= 70 (which I fixed up) could be simply written as 70 <= love <= 89. Python, unlike most languages, allows for comparison chaining.

The last case can just be an else. By elimination, if the other cases weren't picked, the last one must be.

After taking all that into consideration and fixing some more spacing, I ended up with:

from string import ascii_lowercase
import random
import time

name1 = input("Please type Name 1.\n")
name2 = input("Please type Name 2.\n")

vowels = {'a', 'e', 'i', 'o', 'u'}
consonants = set(ascii_lowercase) ^ vowels

def count_vowels(name):
    count = 0
    for i in vowels:
        count += name2.count(i)

    return count

total_vowel1 = count_vowels(name1)
total_vowel2 = count_vowels(name2)

love = 0
if(total_vowel1 == total_vowel2):
    love += random.randint(10, 30)

consonants1 = len([letter for letter in name1 if letter.lower() in consonants])
consonants2 = len([letter for letter in name2 if letter.lower() in consonants])

if(consonants1 == consonants2):
    love += random.randint(20, 40)

line1 = name1
line2 = name2
split1 = line1.split()
split2 = line2.split()
fl1 = [word[0] for word in split1]
fl2 = [word[0] for word in split2]

if (fl1 == fl2):
    love += random.randint(10,30)

if (len(name1) == len(name2)):
    love += random.randint(1,10)

love += random.randint(10,50)

if (love > 100):
    love = 100

print("Calculating...")

print(name1, "and", name2, "have a", love, "% relationship.")

if love >= 90:
    print("They have an unbreakable relationship that will last forever.")

elif 70 <= love <= 89:
    print("They have a strong relationship that will most likely lead to a marriage.")

elif 50 <= love <= 69:
    print("They have a good relationship that can lead to a honeymoon to Paris.")

else:
    print("They have a weak relationship that could have been a 'match made in heaven'.")