Find the length of the longest Common Subsequence

Correctness:

It seems your implementations is incorrect since you are always ignoring the first character.

Here in both loops the range should be closed:

  for(int i = 0; i <= firstWord.length; i++) {
       for(int j = 0; j <= secondWord.length ; j++) {
           ...
       }
   }

And the second if inside the inner loop should look like this:

else if(firstWord[i - 1] == secondWord[j - 1]) {
    ...
}

finally the function should return this:

 return lcsMatrix[firstWord.length][secondWord.length];

DRY your code:

Since in java an array of primitive integers are initialized to zero there is no need for the first if, therefore you can start the loop at i = 1 and j = 1. You could also use a ternary operator after getting rid of the if statement(although some people may prefer the if else).

Final code

    public static int longestCommonSubsequence(char[] firstWord, char[] secondWord) {
        int[][] lcsMatrix = new int[firstWord.length + 1][secondWord.length + 1];
        for(int i = 1; i <= firstWord.length; i++) {
            for(int j = 1; j <= secondWord.length ; j++) {
                lcsMatrix[i][j] = (firstWord[i - 1] == secondWord[j - 1])
                        ? lcsMatrix[i - 1][j - 1] + 1
                        : Math.max(lcsMatrix[i][j - 1],lcsMatrix[i - 1][j]);
            }
        }
        return lcsMatrix[firstWord.length][secondWord.length];
    }


You might not have realised it yet, but all your unimplemented methods will very much look like real_to_dollar:

ask the user how much of the original currency he wants converted;
apply a specific conversion rate;
tell the user the result of the conversion in the desired currency.

So that should be a single function, parametrized by the elements that differ between various calls: name of the origin currency, name of the converted currency, exchange rate.

def convert_currency(from, to, rate):
    user_value = raw_input("How many {}? ".format(from))
    ammount = float(user_value)
    conversion = ammount * rate
    print " {} {} is equal to {} {}.".format(user_value, from, conversion, to)

Also note the use of format to simplify building a string with numbers.

You would then call it convert_currency("reais", "dollars", 0.26) or convert_currency(" dollars", "reias", 3.85).

However, having to use a bunch of ifs to know what parameters to use (like you would have used a bunch of ifs to know which function to call) is not that great and can be a burden to maintain and expand. You could use a second dictionnary to map couples of currencies to exchange rates:

RATES = {
    ("BRL", " USD"): 0.26,
    ("USD", "BRL"): 3.85,
    # Expand as necessary
}

And just have to get the rate using RATES[(user_choice1, user_choice2)].


Prompting the user for employment information

Wrote this on SO so excuse any compilation errors.

As a novice there is a lot to learn, I would start by understanding the SOLID Principles and also looking out for Top 10 errors Java programmers make.

The first thing you want to do is get away from the static main(String[] args) method that starts your program. You do not want to use static methods. Therefore you need instantiate your system (MySystem) so that you are in the world of objects.

You want to keep your responsibilities separate.

Always prefer immutability.

Here I have an immutable Employee object (it cannot be changed once instantiated). From the main method our DetailsRetriever will get the input from the user, this uses the DetailsValidator to ensure the input is correct. If all the details are correct a Factory creates our employee object.

public class UseIt {

    public static void main(String[] args) {
        MySystem foo = new MySystem(new DetailsRetriever(new DetailsValidator()), new EmployeeFactory())
        foo.start();
    }
}

public class MySystem {

   private final DetailsRetreiver detailsRetriever;
   private final EmployeeFactory employeeFactory;

   public MySystem(DetailsRetreiver detailsRetriever, EmployeeFactory employeeFactory) {
         this.detailsRetriever = detailsRetriever;
         this.employeeFactory = employeeFactory;
   }

   public void start() {
         String name = detailsRetriever.retrieveName();
         String jobTitle = detailsRetriever.retrieveJobTitle();
         ..etc

         Employee employee = employeeFactory.create(name, jobTitle, ..etc);
   }

}

public class Employee {

    private final String name;
    private final String jobTitle;
    private final int age;
    private final int salary;

    public Employee(String name, String jobTitle, int age, int salary) {
        this.name = name;
        this.jobTitle = jobTitle;
        this.age = age;
        this.salary = salary;
    }

   public int calcTaxAmount() {
    int calculatedTax;
    if (salary < 10_000)
        calculatedTax = 0;

    if ((salary >= 10_000) && (salary < 30_000))
        calculatedTax = 28;

    if ((salary >= 30_000) && (salary < 80_000))
        calculatedTax = 38;

    if (salary >= 80_000)
        calculatedTax = 48;

    return taxAmount;
}

   public int calcSalary() {
    int calculatedSalaryPostTax = salary - calcTaxAmount();

    return calculatedSalaryPostTax;
   }

}

public class DetailsRetreiver {

    private final DetailsValidator detailsValidator;

    public DetailsRetreiver(DetailsValidator detailsValidator) {
      this.detailsValidator - detailsValidator;
    }

    public String getName() {
        String name = JOptionPane.showInputDialog("Enter your name:");
        if(detailsValidator.validateName(name)) {
          return name;
        } else {
           return getName(); // or throw an exception
        }
    }

    // etc ...

}

public class DetailsValidator {

     public boolean validateName(String input) {
          // add more validation as you need
          return !"".equals(input);
     }

     // etc
}

public class EmployeeFactory {

      public Employee create(String name, String jobTitle, int age, ... etc) {
           return new Employee(name, jobTitle, age .. etc);
      }

}


When it comes to user-input, efficiency really is not the point.... what does it matter if it takes 4 milliseconds to validate some data, or 4 nanoseconds? The user component of time dwarfs the rest.... Obvioulsy, if the code was taking more than 10 milliseconds I would be concerned, but I doubt that is the case.

With user-interface coding though, you have to think differently. In this case, you have to help the user. Specifically, telling a user that their input is wrong is more frustrating if you don't tell the user how to correct it....

Saying: " year not in the allowed range" is going to lead to lots of frustration.

Saying: "year must be between 1950 and 2013" is much better.

EDIT: In fact, when prompting the user to enter the data, it should inform the user what values will be valid before getting the value:

Please enter a year between 1950 and 2013 (inclusive):
...
Sorry, the value 2014 is not between 1950 and 2013, please enter a valid year:


Randomly pick key from dictionary weighted by the keys value

After all this good discussion It looks like this function is as optimize as its going to get for its intended purpose.
I want to note that I was incorrect in its time complexity. The time complexity is actually O(N) not O(N^2) luckily.

Considering this algorithm can perform 1,000 random selections in 0.00194s on a mid range workstation It shouldn't have any performance impact if used many times.

Here are the results of the unit test:

Running random 100 times: 0.0013367s
Key: 30%, Value: 35
Key: 60%, Value: 60
Key: 10%, Value: 5

Running random 1000 times: 0.0019477s
Key: 30%, Value: 378
Key: 60%, Value: 618
Key: 10%, Value: 104

Running random 10000 times: 0.0202942s
Key: 30%, Value: 3391
Key: 60%, Value: 6635
Key: 10%, Value: 1074

Running random 100000 times: 0.191678s
Key: 30%, Value: 33669
Key: 60%, Value: 66427
Key: 10%, Value: 11004

Running random 1000000 times: 1.77491s
Key: 30%, Value: 334075
Key: 60%, Value: 666087
Key: 10%, Value: 110938

Running random 10000000 times: 18.43691s
Key: 30%, Value: 3332173
Key: 60%, Value: 6667785
Key: 10%, Value: 1111142


Entity Framework Core verify SaveChanges count

I can't think of another way of doing this - only the database knows how many rows have been affected. That said, your code has some problems.
You need to dispose of your transaction when you're done with it. This has 2 additional benefits:

You don't need to rollback manually
You don't need to worry about exceptions in SaveChanges (you haven't handled that at all at the moment).

Let's look at how that changes things:
public static int SaveChangesAndVerify(
    this DbContext context,
    int expectedChangeCount)
{
    using (var transaction = context.Database.BeginTransaction())
    {
        var actualChangeCount = context.SaveChanges();
        if (actualChangeCount == expectedChangeCount)
        {
            transaction.Commit();
            return actualChangeCount;
        }
        throw new DbUpdateException($"Expected count {expectedChangeCount} did not match actual count {actualChangeCount} while saving the changes.");
    }
}


Find kth smallest element in binary search tree

The "not happy interviewer" case is probably not connected to the efficiency of the algorithm, but to a few problems with the codes cleanliness:

You modify method parameters. While this is technically possible, it is generally frowned upon as it makes code hard to read and even harder to debug. Don't do this. Period.
Variable names don't match. root becomes a general pointer to a tree node (which is not root any more), right becomes left. This is a mumble jumble of hard to understand code, which is a nightmare to maintain.
The way you find the target element is not obvious at a glance. At least add a comment on what you do and why it solves the original problem.

From the interviewers perspective, you managed to solve a simple problem with a piece of code, which already is problematic to understand and maintain. Imagine what happens if you get a real complex task with 100 classes and 10000 lines of code involved...

Thus: work on maintainability and clarity first.


Cracking the Coding Interview: "Problem 1.5. One Away"

Your code is almost exactly what I would write. The one slight improvement I can recommend is noticing that adding a character to the left string is the exact same thing as removing a character from the right string.

const areOneAway = (left, right) => {
  if (Math.abs(left.length - right.length) > 1) return false;
  let difference = 0;
  let indexLeft = 0;
  let indexRight = 0;
  while (difference < 2 && indexLeft < left.length && indexRight < right.length) {
    if (left[indexLeft] !== right[indexRight]) {
      difference++;
      // Character inserted in left string, or character removed in right string
      if (left[indexLeft + 1] === right[indexRight]) indexLeft++;
      // Character inserted in right string, or character removed in left string
      else if (left[indexLeft] === right[indexRight + 1]) indexRight++;
    }
    indexLeft++;
    indexRight++;
  }
  return difference < 2;
};

let passed = 0;
let failed = 0;

[
  { string1: 'pale', string2: 'ple', expectedResult: true },
  { string1: 'pales', string2: 'pale', expectedResult: true },
  { string1: 'pale', string2: 'bale', expectedResult: true },
  { string1: 'pale', string2: 'bake', expectedResult: false },

  { string1: '', string2: '', expectedResult: true },
  { string1: '', string2: ' ', expectedResult: true },
  { string1: ' ', string2: '', expectedResult: true },
  { string1: '', string2: '  ', expectedResult: false },
  { string1: '  ', string2: '', expectedResult: false },
  { string1: '', string2: 'x  ', expectedResult: false },
  { string1: 'x  ', string2: '', expectedResult: false },
  { string1: 'a', string2: 'a', expectedResult: true },

  { string1: 'ab', string2: 'a', expectedResult: true },
  { string1: 'abc', string2: 'a', expectedResult: false },
  { string1: 'abc', string2: 'abc', expectedResult: true },
  { string1: 'a', string2: 'ab', expectedResult: true },
  { string1: 'a', string2: 'abc', expectedResult: false },

  { string1: 'xab', string2: 'xa', expectedResult: true },
  { string1: 'xabc', string2: 'xa', expectedResult: false },
  { string1: 'xabc', string2: 'xabc', expectedResult: true },
  { string1: 'xa', string2: 'xab', expectedResult: true },
  { string1: 'xa', string2: 'xabc', expectedResult: false },
].forEach(testCase => {
  const { string1, string2, expectedResult } = testCase;

  if (expectedResult !== areOneAway(string1, string2)) {
    console.log(`Failed: areOneAway('${string1}', '${string2}') should be ${expectedResult}`);
    failed++;
  } else {
    passed++;
  }
});
console.log('Passed:', passed, 'Failed:', failed)

Of course, the next step for making this function more reusable would be to extract the difference calculation to a separate function.

const findDifference = (left, right) => {
  let difference = 0;
  let indexLeft = 0;
  let indexRight = 0;
  while (indexLeft < left.length && indexRight < right.length) {
    if (left[indexLeft] !== right[indexRight]) {
      difference++;
      if (left[indexLeft + 1] === right[indexRight]) indexLeft++;
      else if (left[indexLeft] === right[indexRight + 1]) indexRight++;
    }
    indexLeft++;
    indexRight++;
  }
  difference += left.length - indexLeft;
  difference += right.length - indexRight;
  return difference
}

let passed = 0;
let failed = 0;
[
  { string1: 'pale', string2: 'ple', expectedResult: 1 },
  { string1: 'pales', string2: 'pale', expectedResult: 1 },
  { string1: 'pale', string2: 'bale', expectedResult: 1 },
  { string1: 'pale', string2: 'bake', expectedResult: 2 },

  { string1: '', string2: '', expectedResult: 0 },
  { string1: '', string2: ' ', expectedResult: 1 },
  { string1: ' ', string2: '', expectedResult: 1 },
  { string1: '', string2: '  ', expectedResult: 2 },
  { string1: '  ', string2: '', expectedResult: 2 },
  { string1: '', string2: 'x  ', expectedResult: 3 },
  { string1: 'x  ', string2: '', expectedResult: 3 },
  { string1: 'a', string2: 'a', expectedResult: 0 },

  { string1: 'ab', string2: 'a', expectedResult: 1 },
  { string1: 'abc', string2: 'a', expectedResult: 2 },
  { string1: 'abc', string2: 'abc', expectedResult: 0 },
  { string1: 'a', string2: 'ab', expectedResult: 1 },
  { string1: 'a', string2: 'abc', expectedResult: 2 },

  { string1: 'xab', string2: 'xa', expectedResult: 1 },
  { string1: 'xabc', string2: 'xa', expectedResult: 2 },
  { string1: 'xabc', string2: 'xabc', expectedResult: 0 },
  { string1: 'xa', string2: 'xab', expectedResult: 1 },
  { string1: 'xa', string2: 'xabc', expectedResult: 2 },
].forEach(test => {
  const { string1, string2, expectedResult } = test
  const result = findDifference(string1, string2)
  if (result !== expectedResult) {
    console.log(`Failed: findDifference('${string1}', '${string2}') should be ${expectedResult}, got ${result}`);
    failed++;
  } else {
    passed++;
  }
});
console.log('Passed:', passed, 'Failed:', failed)

With this helper, areNAway could be implemented very easily and areOneAway could just be implemented as (left, right) => areNAway(left, right, 1)

const areNAway = (left, right, n) => {
  if (Math.abs(left.length - right.length) > n) return false;
  return findDifference(left, right) <= n;
}

P.S. You may be interested in the "Official" solution. It is available on GitHub.


Read binary serial data and parse integers

Data Acquisition

You asked:

  Is there a smarter way to accomplish the result of my code above?

So, I have another suggestion, to work on top of the suggestions by Heslacher:

Eliminate the BitConverter work. This is easily done with boolean operators (most specifically the shift operators).

short value1 = (short)((short)encoded[1] << 8 | encoded[2]);
short value2 = (short)((short)encoded[3] << 8 | encoded[4]);
short value3 = (short)((short)encoded[5] << 8 | encoded[6]);

Why? It's fast as hell. And this tends to make it more clear what position each value represents. There's no need to place them backwards as you have to with the BitConverter. Looking at this code, it's extremely easy to determine that each pair consists of the high-byte, followed by the low-byte. With the BitConverter, the lowest byte must be followed by the subsequently higher bytes.

Can it really be faster, with all those casts, shifting (<<) and or's (|), and the fact that Microsoft themselves wrote the BitConverter?

You're damn right it can. Run the following programme:

byte[] encoded = new byte[7];
encoded[0] = 0xF0;
encoded[1] = 0xF1;
encoded[2] = 0xF2;
encoded[3] = 0xF3;
encoded[4] = 0xF4;
encoded[5] = 0xF5;
encoded[6] = 0xF6;

Stopwatch sw1 = new Stopwatch();

short value1 = 0, value2 = 0, value3 = 0;

sw1.Start();
for (int i = 0; i < 100000000; i++)
{
    value1 = BitConverter.ToInt16(new byte[] { encoded[2], encoded[1] }, 0);
    value2 = BitConverter.ToInt16(new byte[] { encoded[4], encoded[3] }, 0);
    value3 = BitConverter.ToInt16(new byte[] { encoded[6], encoded[5] }, 0);
}
sw1.Stop();
Console.WriteLine(sw1.ElapsedTicks.ToString());
sw1.Reset();

Console.WriteLine(value1.ToString("X"));
Console.WriteLine(value2.ToString("X"));
Console.WriteLine(value3.ToString("X"));

sw1.Start();
for (int i = 0; i < 100000000; i++)
{
    value1 = (short)((short)encoded[1] << 8 | encoded[2]);
    value2 = (short)((short)encoded[3] << 8 | encoded[4]);
    value3 = (short)((short)encoded[5] << 8 | encoded[6]);
}
sw1.Stop();
Console.WriteLine(sw1.ElapsedTicks.ToString());
sw1.Reset();

Console.WriteLine(value1.ToString("X"));
Console.WriteLine(value2.ToString("X"));
Console.WriteLine(value3.ToString("X"));

Results:

12956403
F1F2
F3F4
F5F6
1505318
F1F2
F3F4
F5F6

You'll notice that the bitwise-operator method takes 12% of the time the BitConverter method does. And in this situation it makes a great deal of sense. It's easier to reason how the value1, value2 and value3 variables are being filled with the bitwise-operators. It's not so obvious with the BitConverter.

Yes, this is obviously a worst-case environment, you will likely have other bottlenecks and JITer that will influence it, but this at least goes to show that there are other just as good solutions to the same problem. Personally, I've never touched the BitConverter, I always do my own bitwise-arithmetic. To me, it's easier to read and more obvious. To you, it may not be.

I wouldn't suggest going so far as to make a loop. I did just that, and it's actually slower.

short[] myValues = new short[3];

sw1.Start();
for (int i = 0; i < 100000000; i++)
{
    for (int t = 0; t < myValues.Length; t++)
        myValues[t] = (short)((short)encoded[1 + t * 2] << 8 | encoded[2 + t * 2]);
}
sw1.Stop();
Console.WriteLine(sw1.ElapsedTicks.ToString());
sw1.Reset();

for (int t = 0; t < myValues.Length; t++)
    Console.WriteLine(myValues[t].ToString("X"));

Results:

3759655
F1F2
F3F4
F5F6

Twice the time the non-loop method took. With a dynamic List you can expect that it will be even slower. (Haven't done any experiments with that method, but one can estimate it would take longer.)

Commenting // when is too much and not enough

Another suggestion, based on his answer: put a comment on the while(SerialPort.BytesToRead > 50){ line describing why we only want it if there are more than 50 bytes left to read. From your current code it's impossible to reason why.

Comments are very powerful; and though I am very liberal with my comments (placing one every 2-10 lines), you don't have to be. But they should be often enough that you don't have to examine a 200+ line file to get the relevant bits. Add minor information on where these values are used, what are they for, if you are using indices like this, then markup what each index represents. You don't have to go ape-s*** on them. Just describe what it is you are doing, and why.


Coordinating Threads with Reactive Streams

You are jumping through a lot of hoops to get your queue, consumer, and observer strategies aligned. I look at your code, and I don't really follow it all. Part of the reason is that I don't know RxJava at all, but, normally, I can follow these things without much research.

So, your code streams the tasks, for each one, it creates an Observable for it which is subscribed on the Reactive computation engine. The observer for the Observable is set to add the result to the queue.

Now, for the queue, you create an Observer that registers one action for each expected result. You then loop over those events, and print the result.

I can understand why you may want to use RxJava for some situations, but, that last part makes no sense to me... Let me show you your code:

//as tasks get resolve and enter the queue, this other observer process the results
//in my current thread, not in any of the task threads.
consumer(queue, 3).forEach(item -> {
        System.out.println("Received " + item + " at " + Thread.currentThread().getName());
    });

where consumer is:

static <T> Observable<T> consumer(BlockingQueue<T> queue, int count) {
    return Observable.<T>create(subscriber -> {
        for (int i = 0; i < count; i++) {
            try {
                T text = queue.take();
                subscriber.onNext(text);
            }
            catch (InterruptedException ex) {
                subscriber.onError(ex);
            }
        }
        subscriber.onCompleted();
    }).observeOn(Schedulers.immediate());
}

What does that code do? It looks for three strings on a queue, and prints them.

for (int i = 0; i < 3; i++) {
    System.out.println("Received " + queue.take() + " at " + Thread.currentThread().getName());
}

What's wrong with that (apart from the 3 constant)? ^^^^

Having figured out all the loops you are going through, I struggled to understand the advantage that RxJava is giving you, especially when Java has already got the "right tool" in the java.util.concurrent.* toolbox.

Let me explain, the CompletionService concept says: Submit a bunch of jobs to the service, and the service will tell you when they complete. It has a submit(...) method to add jobs to the service, and a take(...) method which will wait until the next-completed task, and return it.

Creating a Thread Factory that matches the names you have in RxJava quickly, I have this code:

private static final AtomicInteger threadId = new AtomicInteger(0);

private static Thread threadFactory(Runnable r) {
    Thread t = new Thread(r, "RxComputationThreadPool-" + threadId.incrementAndGet());
    t.setDaemon(true);
    return t;
}

private static ExecutorService pool = Executors.newCachedThreadPool(Reactive::threadFactory);

That code creates an ExecutorService which has threads named things like your code's results.

Now, with that code available, I can have a really simple problem space:

public static void main(String[] args) throws InterruptedException, ExecutionException {
    List<Callable<String>> tasks = Arrays.asList(
            () -> "One: " + Thread.currentThread().getName(),
            () -> "Two: " + Thread.currentThread().getName(),
            () -> "Three: " + Thread.currentThread().getName()
        );

    int count = tasks.size();

    CompletionService<String> completor = new ExecutorCompletionService<>(pool);

    tasks.stream().forEach(completor::submit);
    for (int i = 0; i < count; i++) {
        System.out.println("Received: " + completor.take().get() + " at " + Thread.currentThread().getName());
    }

}

Note that the CompletionService returns a completed Future<String>, not the actual String, so you have to get() the string from the Future<String>.

I have put this code up on to ideone so you can see it in action.

Note, the solution I provided has no need for RxJava, and that's because, if you want to execute a bunch of things asynchronously, and retrieve the results in a single thread, then perhaps the observable pattern is not the right one....


import os, os.path
def getDirs(path):

Python convention is to use lowercase_with_underscores for function names

    sub = os.listdir(path)

Don't needlessly abbreviate, and at least have it be a plural name.

    paths = {}
    for p in sub:

You don't need to store things in a temporary variable to loop over them

        print p

Do you really want this function printing?

        pDir = '{}\{}'.format(path, p)

Use os.path.join to join paths. That'll make sure it works regardless of your platform.

        if os.path.isdir(pDir):
            paths.update(getAllDirs(pDir, paths))

You shouldn't both pass it and update it afterwords. That's redundant.

        else:
            paths[p] = pDir
    return paths

def getAllDirs(mainPath, paths = {}):

Don't use mutable objects as default values, they have unexpected behavior.

    subPaths = os.listdir(mainPath)
    for path in subPaths:
        pathDir = '{}\{}'.format(mainPath, path)
        if os.path.isdir(pathDir):
            paths.update(getAllDirs(pathDir, paths))
        else:
            paths[path] = pathDir
    return paths

This whole section is repeated from the previous function. You should combine them.

Take a look at the os.walk function. It does most of the work you're doing here and you could use to simplify your code.


A Ruby implementation of derangement (secret santa) algorithm

I'm a bit unsure about whether the question is about a game of Secret Santa or if it's actually about derangement, specifically. Derangement requires that no element can appear in its original position. But that's irrelevant for a game of Secret Santa, since there's no ordering to speak of.

Edit: As tokland rightly points out in the comments derangement is of course related to the game. I wasn't thinking it through.

For derangement, Rosetta Code has a Ruby implementation you might be able to use or learn from.

For a game of Secret Santa, though, the specs are pretty much as you summed up in your 3 rules (although #3 "Assignment must be random" is a bit difficult to define/verify.) So here, things can be simplified; you need not worry about derangement "by itself" as long as the rules are obeyed. For instance, you might simply do:

players = %w[Mohamad Carolina Sami Tania Ikram Jose].shuffle
players << players.first # repeat the first player

assignments = players.each_cons(2).to_a

which will give you an array of santa/gift-receiver pairs such as:

[["Carolina", "Ikram"],
 ["Ikram", "Mohamad"],
 ["Mohamad", "Jose"],
 ["Jose", "Tania"],
 ["Tania", "Sami"],
 ["Sami", "Carolina"]]

Alternatively, you can get the "Santa targets" for several rounds by doing something like

players = %w[Mohamad Carolina Sami Tania Ikram Jose].shuffle
assignments = players.each_with_index.map do |santa, index|
  others = players.rotate(index+1)[0...-1]
  [santa, others]
end

Which will give you something like

[["Tania", ["Mohamad", "Sami", "Ikram", "Carolina", "Jose"]],
 ["Mohamad", ["Sami", "Ikram", "Carolina", "Jose", "Tania"]],
 ["Sami", ["Ikram", "Carolina", "Jose", "Tania", "Mohamad"]],
 ["Ikram", ["Carolina", "Jose", "Tania", "Mohamad", "Sami"]],
 ["Carolina", ["Jose", "Tania", "Mohamad", "Sami", "Ikram"]],
 ["Jose", ["Tania", "Mohamad", "Sami", "Ikram", "Carolina"]]]

There's a pattern of course (if you've given Ikram a gift, next you'll be giving Carolina a gift, then José, etc.). But if it's Secret Santa, the players shouldn't be able to figure that out anyway unless they cheat (and if they do, well, all bets are off).

You could of course use Array#combination or Array#permutation to achieve similar results. I highly encourage you to check out all of the built-in array methods, and those included from the Enumerable module. There's a lot of good stuff there.

As for a more OOP approach, I wouldn't make a class called "Derangement". Derangement is a method. It's an action, an operation, a means of achieving a certain result or state - not something that is itself stateful.
The simple solution, given your code, is to rename you class to "Game" or something along those lines.


After some testing I discovered that HomeActions._ajaxSettings is indeed static and would cause issues if simultaneous calls were made to the API. After some time away from the code  the obvious solution popped into my head as shown below. I've been too caught up in learning the confusing syntax of javascript that the basics of OOP design fell to the wayside just so I could get a working prototype.

I added a "class" called Action and moved the Start() method to it and in each static method, RefreshCache and IndexAllRecords, I now return a new Action class which maintains its state separately with each call to the API.

var MVC;
(function (MVC) {
    var Action = (function () {
        function Action(ajs) {
            this.ajs = ajs;
        }
        Action.prototype.Start = function () {
            return $.ajax(this.ajs);
        };
        return Action;
    }) ();
    var HomeActions = (function () {
        function HomeActions() {}
        HomeActions.RefreshCache = function (key, returnUrl, ajaxSettings) {
            ajaxSettings = ajaxSettings || {};
            ajaxSettings['data'] = JSON.stringify({
                key: key,
                returnUrl: returnUrl
            });
            ajaxSettings['url'] = MVC.Home.ActionNames.RefreshCache;
            if ('type' in ajaxSettings == false) ajaxSettings['type'] = 'POST';
            if ('context' in ajaxSettings == false) ajaxSettings['context'] = this;
            if ('contentType' in ajaxSettings == false) ajaxSettings['contentType'] = 'application/json';
            return new Action(ajaxSettings);
        };
        HomeActions.IndexAllRecords = function (ajaxSettings) {
            ajaxSettings = ajaxSettings || {};
            ajaxSettings['data'] = JSON.stringify({
            });
            ajaxSettings['url'] = MVC.Home.ActionNames.IndexAllRecords;
            if ('type' in ajaxSettings == false) ajaxSettings['type'] = 'POST';
            if ('context' in ajaxSettings == false) ajaxSettings['context'] = this;
            if ('contentType' in ajaxSettings == false) ajaxSettings['contentType'] = 'application/json';
            return new Action(ajaxSettings);
        };
        return HomeActions;
    }) ();
    var HomeActionNames = (function () {
        function HomeActionNames() {}
        HomeActionNames.RefreshCache = '/refreshcache';
        HomeActionNames.IndexAllRecords = '/indexallrecords';
        return HomeActionNames;
    }) ();
    var Home = (function () {
        function Home() {}
        Home.Actions = HomeActions;
        Home.ActionNames = HomeActionNames;
        return Home;
    }) ();
    MVC.Home = Home;
}) (MVC || (MVC = {}));


Should I pass a list of objects or an object to a domain object method?

I will simply go from top to bottom without ordering by priority.

Person is not supposed to be a base class (at least now) then it should be marked as sealed.

Sports is a public field. There is not any level of protection. Caller might do anything with it: set it to null, clear the content. Add/remove items in an uncontrolled way (is, for example, null a valid item?) The very first thing to do is to make it a read-only property:

public List<Sport> Sports { get; }

You can assign an instance in your ctor (as you're doing now) or directly where it's declared:

public List<Sport> Sports { get; } = new List<Sport>();

The second problem is the type. You're exposing List<T> which is, at best, an implementation detail. Which operations the caller is allowed to do? Add/remove items? Clear the collection? You may change its type to IEnumerable<Sport> like this:

private readonly List<Sport> _sports = new List<Sport>();
public IEnumerable<Sport> Sports => _sports;

However we're just postponing the problem to the future. I'd introduce a SportCollection class which exposes exactly what you need (and to begin with it might be as little as IEnumerable<Sport>).

public SportCollection Sports { get; } = new SportCollection();

We fixed the declaration, we fixed the type but we still need to fix the name. It does not communicate almost anything. It's the list of sports that this person may play but its name is saying nothing: you have to read the code to understand how it's populated.

public SportCollection LikeableSports { get; } = new SportCollection();

I'm sure someone else can suggest a much better name but I hope you understood the point.

AddSports() method again does not say what it's actually doing. It's not adding generic sports but only sports this person may play/like. Change the name to reflect its behavior.

allSports parameters is List<Sport> but you if you change it to IEnumerable<Sport> you code compiles. Do it, always pick the less restrictive requirement for your parameters (what if the list comes from a DB? Do you want to materialize the whole thing in memory because AddSports() wants a list?)

You're clearing the list before adding the new items. It's not what I expect from a method named Add*(). Change the logic or change the name to reflect it.

You do not need to cast Sports to List<Sport>, just drop it.

Again a word about naming: I read sport.CanPlay(this) as "Can Sport play Person?" and it sounds weird. If this responsibility is in the Sport class then it should be at least named CanBePlayedBy().

Sport has the responsibility to check if it can be played/liked by Person. It's debatable if this responsibility should be in Sport, in Person or much better (IMO) in a separate class. I'd go with a separate class because:

I can switch algorithm in any moment, even from configuration and at run-time without changing anything else.
It makes testing much easier.
It keeps responsibilities separate and clear.
If you add more rules to determine a match (proximity of the structure to play that sport and public transportation to/from that place, for example) you will have a single clear place where these knowledge has to be managed (unless you want to pollute your Sport class with references to StructureCollection and PublicTransportationTripPlanner, of course...)

Do not ignore this suggestion, it's the last one but I think this is more important than most of the other considerations in my post: you can live with a non sealed class but putting responsibilities in the wrong place will make you code a nightmare to maintain. Micro design is easy to change (with better knowledge of the domain and of the language) but wrong architectural decisions are much much MUCH more expensive to deal with (on the long term).


This isn't really aimed at the core of your code and is more a reflection of the code challenge you're solving.

BadLengthException isn't a great name for the exception being represented.  It doesn't tell the caller that the name was too short (the exception could be used to represent a length that was too long).  The exception as you've implemented it has no why, so the exception itself doesn't contain sufficient information to tell the caller that it was too short / too long.  With that in mind, I would have been tempted to actually implement a TooShortException and then create typedef so that the supplied code still worked:

typedef TooShortException BadLengthException;


Emulator for representing hardware and operating systems

That's not what friends are for. Friends are for tightly integrated classes which need to be able to play with each other's private data. OS and Hardware are not tightly related; they interact through a specifically designed interface.

If you don't want other classes besides OS to call the hardware functions, don't write code in those other classes which call the hardware functions. Better yet, simply only give the Hardware pointer to the OS class so only it can call the hardware functions.

For callbacks have a look at the boost::function library. It will allow you to create callbacks to the OS methods. You can create pointers to methods but you need both the method pointer and the object point for it to work. Boost::function hides all of this behind the scenes.

pImpl is workaround because C++ is such a silly language. Its purpose is to make it so that you do not have to recompile the header file whenever the private members of the class change. More modern languages essentially do this automatically for all classes. pImpl makes sense only when your compile times get too large. A class project probably doesn't get large enough for that to be a big concern.


The only way to know is to measure it.

And, of course, the only reason to measure it is if it actually matters;  if you have a real world performance issue that can be tracked to this code.

If not, don't worry about it.

However, there are a few issues to consider:

every append* is going to cause an allocation and memory copying, those are expensive
every *WithFormat: is going to cause a string to be parsed (and there will be allocations/copying)
all of this is likely entirely moot unless you are doing this 10s of thousands of times often.   If you are, it begs the question as to why?

And, finally, note that this kind of string manipulation is going to make localization more difficult.


Here's another way to implement the list() method:

switch(elements.size()) {
    case 0:
        null
        break
    case 1:
        elements[0]
        break
    case 2:
        elements.join(" $conjunction ")
        break
    default:
        new StringBuilder().with {
            append elements.take(elements.size() - 1).join(', ')
            append " $conjunction "
            append elements.last()
        }.toString()
        break
}

This makes use of join() to handle most of the String building, instead of looping and appending to StringBuilder. The StringBuilder only comes in during the case of 3 or more items.

Revised

It's possible to knock out one of the cases like this:

switch(elements.size()) {
    case 0:
        ''
        break
    case 1:
        elements[0]
        break
    default:
        new StringBuilder().with {
            append elements.take(Math.max(elements.size() - 1, 1)).join(', ')
            append " $conjunction "
            append elements.last()
        }.toString()
        break
}

So now there are cases for an empty list, a one-item list, and more-than one-item list.


You should only pass the list to the second form. If you pass the entire first form you are exposing somethings that wouldn't be best, and coupling the two forms tightly.


Functions for scanning command line options

The bash code all looks reasonably fine to me.

The -h and --help output doesn't look right (it will print the actual parameters passed, but should print the list of allowable options/parameters?)

Options like --this-will-break won't work with --will or --break.

I'm not clear if parameters with spaces in them will work, as in: testmygetopts "this is one argument"

I think 'isoption' could be simplifed to just be the [[ ]] expression (since it will return 0 or 1 already).


In this case it's totally fine to not define any functions or classes. It does not always make sense to use those things just because you can.

In this case for loops do indeed make sense.

The structure is pretty straight forward, but you should revise what if, else and elif do.

correct = word

Not quite sure what you are doing here by having two variables with the same content.

clue = word[0] + word[(len(word)-1):(len(word))]

You can use negative indexes to count from the end of the sequence:

That would make this line:

clue = word[0] + word[-1]

letter_guess = ''
word_guess = ''
store_letter = ''
count = 0
limit = 5

you could use more descriptive names like: guess_limit, guess_count etc. Some of these variables don't need to be set here yet, e.g. letter_guess.

while count < limit:

Here you would use a for loop (for guess_count in range(limit)) like you suspected.

    letter_guess = input('Guess a letter: ')

I recommend you add some checking here to see if the letter is actually valid.

    if letter_guess in word:
        ...

    if letter_guess not in word:

If it was in the word previously, it still is. No need to re-check, you can just use else

            print('\n')

you can just use an empty print() to print a new line

        if clue_request == 'y':
            ...

        if clue_request == 'n':
            ...

what happens here if clue_request is neither 'y' nor 'n'?

while word_guess:

what is the purpose of this while loop? All cases hit break

    if word_guess.lower() == correct:
        ...

    elif word_guess.lower() != correct:
        ...

You can just use else here again

Full program:

"""
Word Guess Game

by Coal_
"""
import random

WORDS = ('apple', 'oracle', 'amazon', 'microsoft')
correct_word = random.choice(WORDS)
clue = correct_word[0] + correct_word[-1]

store_letter = ''
limit = 5

print('Welcome to "Guess the Word Game!"')
print('You have 5 attempts at guessing letters in a word')
print('Let\'s begin!')
print()

for guess_count in range(limit):
    while True:
        letter_guess = input('Guess a letter: ')

        if len(letter_guess) == 1:
            break
        else:
            print("Oops! Guess a letter!")

    if letter_guess in correct_word:
        print('yes!')
        store_letter += letter_guess
    else:
        print('no!')

    if guess_count == 2:
        print()
        clue_request = input('Would you like a clue?')
        if clue_request.lower().startswith('y'):
            print()
            print('CLUE: The first and last letter of the word is: ', clue)
        else:
            print('You\'re very brave!')

print()
print('Now its time to guess. You have guessed', len(store_letter), 'letters correctly.')
print('These letters are: ', store_letter)

word_guess = input('Guess the whole word: ')
if word_guess.lower() == correct_word:
    print('Congrats!')
else:
    print('Unlucky! The answer was,', correct_word)

print()
input('Press Enter to leave the program')


If i'm understanding your question correctly what you have is pretty much there already. The only change I can suggest is to let your HTML establish the relationship between your trigger button and the template containing your new HTML like so:

http://jsfiddle.net/vax6hp28/5/

HTML

    <button data-target="#template-addText">Click Me</button>

Javascript

var appendResize = function(e) {
    var parent = $(this).parent();
    var oldHeight = parent.height();
    var templateRef = $($(this).data('target'));

    $(this).fadeOut(400, function() {
        this.remove();

        var template = templateRef.html();
        var paragraph = $(template).appendTo(parent);
        var newHeight = parent.height();

        paragraph.fadeIn(2000);
        parent.height(oldHeight).animate({height: newHeight});
    });
}

$(document).on('click', 'button', appendResize);

This allows you to create as many buttons/template combinations as you like without having to change the javascript.


You don't need neither Select and can get the same result by using only GroupBy:

var valuePairs = sharePointResult
    .GroupBy(
        dict => dict["PA"],
        dict => int.Parse(dict["TO"]),
        (key, items) => new
        {
            PA = key,
            Sum = items.Sum(f => f)
        });

where the parameters are respectively:

.GroupBy(keySelector, elementSelector, resultSelector);

I used int.Parse for testing - it's not a part of my review ;-)


Searching for a pattern in a list of tuples

If I understand correctly, your problem can be defined as:

take the longest uninterrupted chain of True elements ending in X
take X regardless of value
take all True elements after X until the first False one

So the actual position of X is not relevant, we only need to know if we encountered it or not. Based on this, we can generate the result with only one pass through the input list. This works if at most one X element is present.

Bellow you can see my quick and dirty version of the implementation:

from itertools import count, izip
from collections import namedtuple
Elem = namedtuple('Elem', ['name', 'value'])

def valid_elements(elem_lst):
    valid_elem = []
    found_x = False

    for elem in elem_lst:
        if elem.name == 'X':
            found_x = True
            valid_elem.append(elem)
        elif elem.value:
            valid_elem.append(elem)
        elif found_x:
            break
        else:
            valid_elem = []

    if found_x:
        return valid_elem
    return []

z = [Elem('C', True), Elem('X', False), Elem('D', True), Elem('C', False), Elem('S', True)]
print [elem.name for elem in valid_elements(z)]


Filter function implementations using copy_if algorithm vs. for loop

I'll respectfully disagree with other answers that suggest using anything but the first option. The only thing the other two std-library-heavy approaches accomplish is to obfuscate the code. Never underestimate the importance of keeping it simple. Complexity is the number one enemy of any piece of software.

The first one is not only more explicit about what is happening, but it is also universal. Any high-level programming language has the concept of a for-loop, so an occasion reader coming from another language background can still clearly see what's going on over there. A JavaScript programmer would have a very hard time figuring out what an inserter or a placeholder is. Even a novice C++ programmer with limited knowledge of the library would have to waste time digging through documentation to understand a simple function that does a conditional copy.

Don't get me wrong here, I'm not making a case against the Standard Library,
I'm just pointing out that, like any programming language feature, it can be overused. In the three examples presented by the OP, the second and third clearly are overusing the std lib just for the sake of using library feature XYZ. My opinion.


Helper that hold methods for evaluate and calculate data

There are some (potentially bizarre to me) things going on here.  A slightly larger view of the system may be helpful in further refining this method.  In any case, here's how I'd restructure this.  I've also included notes about some things I found odd...

public Tuple<DataType, byte> EvaluateDataType(double value, MeasureStatus? status = null)
{

    // As much as possible, initialize a local variable to the proper value
    // when you declare it (as if it had Java's *final* attatched).
    // This isn't always possible, of course
    DataType dataType;
    // Really, these are the only two datatypes that use 1 decimal place?
    int decimalPlaces = (MeasureType == Unit.kWh || MeasureType == Unit.ºC) ? 1 : 2;
    // Structure your code so that it's values and executions give the -reasons-
    // or the -why-.  The code itself says -what- is happening, but it's usually -why-
    // that's actually important.
    // Among other things, this means you should (usually) avoid magic numbers.
    bool valueOutOfRange = Math.Abs(value) >= (Int16.MaxValue / (10 * decimalPlaces));

    // status == null is considered -present-?
    if (status != null && status == MeasureStatus.Missing)
    {
    // Note, never leave off brackets - {} - you run a nasty risk of
    // someone writing indented code that isn't actually part of the block.
    // Also, as much as possible, test for -affirmative- results, not negative ones.
    // Although, multiple negatives should still be avoided.
        if (valueOutOfRange)
        {
            dataType = DataType.MISSING_LONG;
        }
        else
        {
            dataType = DataType.MISSING_SHORT;
        }
    }
    else
    {
        if (valueOutOfRange)
        {
            if (decimalPlaces == 1)
            {
                dataType = DataType.LONG_1DEC;
            }
            else
            {
                dataType = DataType.LONG_2DEC;
            }
        }
        else
        {
            if (decimalPlaces == 1)
            {
                dataType = DataType.SHORT_1DEC;
            }
            else
            }
                dataType = DataType.SHORT_2DEC;
            }
        }
    }

    // Are you sure you don't mean "byte nibbled = (byte) (Aggregate & dataType);"?
    // I'm assuming you're attempting to mask Aggregate for the cast, and that
    // you haven't done anything -too- out there in the operator override.
    byte nibbled = (byte) (Aggregate | dataType);
    return new Tuple<DataType, byte>(dataType, nibbled);
}

Although, I'm a little suspicious of anything that's moving some sort of DataType around like this (especially because you're only storing a byte).  Normally it's best to prefer some sort of implemented generic, so you can get compile time checking of your datatypes.  Nothing like mismatches at runtime to crash your probe into Mars (granted, that was a mismatch in the measure type, which you're attempting to cover here.  However, you still need to deal with value mis-matches...).


Simple Sieve of Eratosthenes in Python 3

The second for-loop doesn’t look very nice with the break ...

You can remove that for-loop if you test p for being prime in the while-loop:

while p ** 2 < max_n:
    if sieve[p]:
        # p is prime: cross-out all true multiples of p:
        for z in range(2 * p, max_n, p):
            sieve[z] = False
    p += 1

  Are there still any simplifications possible? Or non-hackish ways to increase performance?

Here are two simple changes which increase the performance:
First, since 2 is the only even prime, you can increment p by two after the first iteration:

    p = p + 2 if p > 2 else 3

Second, it suffices to “cross-out” the multiples of p starting at p*p (instead of 2*p) because all lesser multiples have been handled before:

        for z in range(p * p, max_n, p):
            sieve[z] = False


C# Pseudo-Code improvement/peer revision

When it comes to pseudo-code there are different standards depending on your organization, target group, etc, but here is my input:

The comments in your pseudo-code are redundant.

17 and 18 should be merged.

Variable declaration (such as 3. Declare String content) are not needed.

Not sure if every Console.WriteLine() is needed. This could be replaced with something like "Display data regarding Agegroup"


The crate rayon implements similar functionality:
use rayon::prelude::*;

let mut par_iter = (0..5).into_par_iter().map(|x| x * x);

let squares: Vec<_> = par_iter.collect();

In your solution, the multithreading part looks OK.
The part where you collect results could be done more efficiently. Specifically, one alloc and data copy could be avoided with use of a little unsafety.
let mut output_vec: Vec<U> = Vec::with_capacity(initial_len);
unsafe {
    output_vec.set_len(initial_len);
}
while let Ok((res, index)) = out_r.recv() {
    let old = mem::replace(&mut output_vec[index], res);
    mem::forget(old);
}

Same optimization could be done a little more succintly with ptr::write. Further, you may need to assert that output_vec has correct length, and forget the vec beforehand in case the assertion fails. My concern is that above proposed code is not protected against incorrect drops if U has a destructor and code panics.
Your bound of U as Default appears to be unnecessary.


using jquery:

html

css

html { background-color: #B94FC1; }
body { margin:0; }
.gradient { content: ""; height: 100%; width: 100%; position: fixed; z-index: -6; }
.gradient.one { background-image: linear-gradient(to bottom, #5856D6 0%, #C644FC 100%);}
.gradient.two { background-image: linear-gradient(to bottom, #C643FC 0%, #FF5F37 100%); display:none; }

javascript

$(function() {
    fadeToggle( $('.gradient.one') );
    fadeToggle( $('.gradient.two') );
});

function fadeToggle(el) {
    el.fadeToggle(5000,null,function() { fadeToggle(el); });
}

fiddle: http://jsfiddle.net/aMVBk/2/


In order to correctly work in parallel, you must follow the Actor Model, which basically says that each iteration should not share memory when doing their work. In your code, you pass a List<Message> to the child processes, which they are expected to fill. Each child process changes his own copy of the list, which makes the final result unexpected.

To build your actors correctly, each should create its own solution vector, and later its parent process should merge the result of the children, and pass them on (you can see samples here).

If the order of the messages is important to you, even this is not enough, since you don't know which child process will finish first, so the messages in the resulting list will not be in the same order as in the input list.

After all being said and done - you might find out that you do not get better performance, and sometimes even worse performance.

My suggestion is to keep it simple - the actual work you are doing on the array is simple enough - do a straight forward iteration. By they way you describe your use-case - at most you will have to wait a couple of minutes (tens of minutes?) for the initial bulk to be computed, but at least you'll be confident that you have the correct result. I assure you it would take less time to run it synchronously than to develop and debug a fork/join solution...


Random integer generation in given range

First of all. Move srand() out of the function call. For now, it is not random at all if you manage to execute function twice in the same second. You will reset the random seed to the same value with time(0) as it normally has a 1s resolution.

Then I would suggest to do a conditional swap, and then perform "generate random" thing. This way you will split it into "preparation of arguments" and the "actual work parts".

You will have one exit point, which is a bit more readable and AFAIK tend to be a bit more optimizer friendly. Also, modern processors don't like too many ifs, especially unpredictable. So I would further suggest refactoring the "job" part into a separate function int rand_hi_lo(int upper, int lower) maybe even inlined. You could skip the branch at all then in certain cases.

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

void swap_int(int* a, int* b){ int tmp = *a; *a=*b; *b=tmp; }

inline int rand_int_hi_lo(int upper, int lower){
  return((rand() % (upper-lower+1)) + lower);
}

int rand_int(int a,int b)
{
    if (b > a) swap_int(&a,&b);
    return rand_int_hi_lo(a,b);
}

int main()
{
    int a,b;
    srand(time(0));
    printf("\nEnter the range in which the a random no. is required: ");
    scanf("%d %d", &a, &b);
    printf("%d\n", rand_int(a,b));
}

It might be even possible to skip the conditional at all. But I am not sure about the negative modulo arithmetics. I think it is possible. Also my c is rusty, so I hope I wrote swap correctly.

EDIT:
I also skipped the a==b. I don't think it is worth to put there at all unless you are sure it happens more than rarely. If necessary I would put if (a==b) return a; it before the swap_int.


Continuously execute runnables on the UI thread

Your variable names could be more clear.  h is a poor choice, for example.  loop is probably not a great name for a method either - maybe startLoop?
You have inconsistent code style.  Some one-line if blocks are in curlies while others are not.
Why final Runnable first?  It's fine if you want to use final wherever possible, but that doesn't appear to be the case with the rest of the code, and there's no explicit reason for it be final, so what is the strategy here?
I'd save the Runnable you pass to postDelayed as an instance member instead of creating a new one each time.
Why do you use an explicit this in this.breakLoop.set, but nowhere else?  I'd choose one or the other.
If you've got those tests to ensure everything is happening on the main thread, then why h.post(first)?  Wouldn't first.run() to the same thing?


I don't see anything in this code that needs to be commented. To echo what other people said, comments should clarify code and they should never say what the code already says.

I would recommend commenting code under these conditions:

You can't tell what the code is doing by reading it
You encountered a wonky bug that took you a long time to figure out, and the fix does not look clear or uses a programming construct or pattern that isn't normally used.

Really, the biggest problem I see is one of the biggest problems in Software Engineering. As Martin Fowler once said:

  ... there are two hard things in computer science: cache invalidation, naming things, and off-by-one errors.

The names of your variables and methods could use a little polishing.

For instance, does Socket::recvln() mean:

Receive Line
Receive Lane
Recover Line...

Even if names become a little long, make them obvious. Don't abbreviate. Some people say that abbreviating well known terms within your industry are OK. I'm from the camp that disagrees. Never assume that the next programmer is an expert in your industry.

When it comes to "reducing lines" I have mixed feelings about omitting optional curly brackets. It looks nicer, but becomes extra typing when you have to add one line of code. I go back and forth on that and have come to a compromise with myself.

If omitting the curly brackets makes the code a two-liner, that's OK

if (count >= size)
    count = 0;

If I would be omitting curly brackets for nested structures, I'll put the curly brackets in even if I don't need to

for (count = 0; count < size; count++)
{
    if (recvBuffer.at(count) == '\n')
    {
        break;
    }
    else
    {
        result[count] = recvBuffer.at(count);
    }
}

But sometimes within a nested structure, I'll omit the optional brackets if it is obvious:

for (count = 0; count < size; count++)
{
    if (recvBuffer.at(count) == '\n')
        break;
    else
        result[count] = recvBuffer.at(count);
}

If I have a structure with one-liners and multi liners, I never omit the curly brackets:

if (count > size)
{
    count = 0;
}
else
{
    foo = count + 10;
    bar = foo * -1;
}

Lastly, I recommend putting spaces around operators to make the code easier to read:

recvBuffer.erase(recvBuffer.begin(), recvBuffer.begin() + count);

(notice the spaces around the "+" sign)


Thread safe object pool, is this object pool thread safe?

Assuming only PacketPool ever called the Init() and UnInit() methods on a Packet.

I think that's not an assumption you should make. If the user of your code shouldn't call some methods, then don't let him do it, don't just assume that he won't.

What you could do is to return a facade to Packet that doesn't contain the two methods, instead of returning Packet directly.


Create a List

List<String> al = new ArrayList<String();

and add (you can also use something like while(! stringRead.isEmpty()) {..} )

name = Keyboard.readChar()).toLowerCase();
al.add(name.substring(0, 1).toUpperCase() + name.substring(1));

EDIT after comment

1°) then Sort (the list is 'cloned') and print directly frome the Constructor return This solution is recommended to protect data published in a Web page.

System.out.println(new TreeSet<String>(al).toString());

2°) The List is sorted then printed

Collections.sort(al);
System.out.println(al.toString());


Comparing columns in pandas different data frames and fill in a new column

I’ll take the hypothesis that your first dataframe (df) has unique company names. If so, you can easily reindex it by said company name and extract the (only one left) Main_Text Series to make it pretty much like a good old dict:

main_text = df.set_index('supplier_company_name')['Main_Text']

Now we just need to iterate over each line in samp, fetch the main text corresponding to the first column and generate a truthy value based on that and the second column. This is a job for apply:

target = samp.apply(lambda row: row[1] in main_text.loc[row[0]], axis=1)


Script to check for failed logins and then trawl users' .bash_history for keywords

Don't embed terminal escapes in your strings

You don't know what terminal will be displaying your output - or even whether output will be going to a terminal.  The standard tool to get the appropriate strings (if they exist) is tput.  You'll want something like:

sgr0="$(tput sgr0)"
sgr93="$(tput sgr 93)"

which you can then use in your strings

echo -e isn't portable

Since you're using printf, you can conveniently use that when you don't want a newline:

printf "\n%s" "$sgr93*** Failed Login Checker ***$sgr0"

Pointless sleeping

sleep 2
read -r -p "Press [Enter] key to continue..."

These server only two purposes - annoy the user, and make it harder to use in a pipeline.

Unquoted variable expansion

Although the value you've given $HOLDINGDIR is currently safe to expand without quotes, I recommend you quote its expansion anyway, to give you the freedom to change it later (for example, you might want its value to incorporate $HOME instead of hard-coding /root).

No check that mkdir succeeded

If $HOLDINGDIR already exists as a regular file, or its parent directory doesn't exist or can't be written, then it won't be created, and we don't check that it succeeded.  The easy way to deal with this is to make any failed command abort the script:

set -x

Unbounded find

Do you really mean to search recursively for .bash_history files?  It probably makes more sense to look in each user's home directory only.  And not all home directories are necessarily under /home.  I'd be more inclined to iterate over awk -F: '{ print $6 "/.bash_history" }' /etc/passwd instead:

awk -F: '{ print $1, $6 "/.bash_history" }' /etc/passwd \
 | while read u f
   do if test -e "$f"
      then cp -v "$f" "$HOLDINGDIR/${u}_history"
      fi
   done

Replace copy+edit with a pipeline

You copy files and then process them with sed.  It's much better to simply have sed take its input from the original file and send its output to the new file, so instead of the cp above we can just:

sed -e 's/^#([0-9]+).*$/date -d @\1/e' "$f" >"$HOLDINGDIR/${u}_history"

and remove the following for loop.

And drop the chmod 755: you don't really want to make the transformed history files executable and readable by everybody.

Interactive reading of search term

read -r -e -p "Enter search term: " -i "sudo su" search

Again, this makes it hard to run from anything other than a terminal.  And if you mistype it, you have to start right from the beginning, seeking out all the history files again.  Instead, you could provide the terms as positional arguments, then you can

for search in "$@"
do grep -FiH -B1 "$search" "$HOLDINGDIR"/*_history
done

Even better, you could search for all the search terms together, remembering that grep -F accepts a newline-separated list of search terms:

grep -FiH -B1 "$(printf '%s\n' "$@")" "$HOLDINGDIR"/*_history

Modified program

#!/bin/bash

set -e

if [ "$#" = 0 ]
then
    echo "No search terms specified!" >&2
    exit 1
fi

HOLDINGDIR=/root/check_history
test -d "$HOLDINGDIR" || mkdir "$HOLDINGDIR"

awk -F: '{ print $1, $6 "/.bash_history" }' /etc/passwd \
 | while read u f
   do if test -e "$f"
      then sed -e 's/^#([0-9]+).*$/date -d @\1 "+#%c"/e' "$f" >"$HOLDINGDIR/${u}_history"
      fi
   done

grep -FiH -B1 "$(printf '%s\n' "$@")" "$HOLDINGDIR"/*_history


Razor view to render simple scaffolding for complex type

Having a chain of if...elseif s it is a  good place to start having a registry/resolver container instead.

Please take a look at my answer here.

After refactoring the code and removing the nested if....else s you will have all the logic and actions in one place to look at and you can refactor them in order to be DRY.


Different implementation of an Interface along with additional parameters

Since I am using DI to instantiate classes

I have to disappoint you... there is no DI in your code. The only service you are using is instantiated inside the class using it:

private ContactService _contactService = new ContactService();

DI would be if you passed it to ContactBusinessImpl via constructor.

public string Token { get; set; }

public void SetToken(string token)
{
    Token = token;
}

We don't usually do that. A value is either a mandatory one, then we use a constructor so the user must provide it or it's optional so we create a get/set property for it and don't enforce it via constructor. Having a method that sets a property that has a setter is pointless.

public void Add(Contact c)
{
    var client = new HttpClient();
    client.SetBearerToken(Token);
    var stringContent = new StringContent(JsonConvert.SerializeObject(c), Encoding.UTF8,"application/json");
    client.PostAsync("api/add", stringContent);
}

Creating HttpClient on each call is a bad idea. At some point you'll run out of sockets.


Some points in addition to what checkorbored pointed out:

You should use character classes and the i flag for your regexen. E.g. instead of /a|e|i|o|u|A|E|I|O|U/ you can write /[aeiou]/i.
You should get rid of the explicit return statements where not necessary.
return foo if bar
return baz

should really be written as

if bar
  foo
else
  baz
end

Except if foo and baz are booleans in which case the whole thing can just be replaced by bar or !bar.
def initialize (options = {:dash => true})
  @dash = options[:dash]
end

In this case it doesn't matter because there's only one option in your options hash, but the usual idiom to implement keyword arguments with defaults looks like this:

def initialize (options = {})
  options = {:dash => true}.merge(options)
  @dash = options[:dash]
end

The reason that (options = {defaults}) is generally not used, is that it doesn't allow the user to specify some options, but use the default for others. So if you do def bla(options = {:foo => 42, :bar => 23}) and the user calls bla(:bar => 24) the value for :foo will be nil, not 42. That doesn't happen if you use merge instead.


Service status checker... Is there a more efficient way?

PHP is not suitable for multi-threading. Though there are some extensions that offer ways of multithreading, they all are, basically, hacks IMO. The best way forward in your case would be: to use a tool that is async by nature, and update the url's as you go along.
Thankfully, such a thing exists, and it goes by the name JavaScript (AJAX calls), here's what I'd do:

foreach ($sites as $key => $value)
{
    echo '
',$key, ' (', $value, ')	',
    '
';
}

This will present the client with a complete overview of urls (since that's what you say they are), each row showing a gif (optional, of course) of one of those circular loading things This one, for example.
On the page, have script that goes something like this:

window.addEventListener('load',function l()
{
    var pending = document.querySelectorAll('td.pending'),i=0,
    callNext = function(elem)
    {
        var urlMatch = elem.parentNode.cells[0].textContent.match(/\(([^)]+)/)[1],
        xhr = new XMLHttpRequest;
        xhr.open('POST','ajax.php', true);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = callback;
        xhr.send('url=' + encodeURI(urlMatch));
    },
    callback = function()
    {
        if (this.readyState === 4 && this.status === 200)
        {
            var resp = JSON.parse(this.responseText);
            pending[i].setAttribute('class','error');//default error
            if (resp.success)
            {
                pending[i].setAttribute('class','success');
            }
            pending[i].replaceChild(
                document.createTextElement(resp.cellText),
                pending[i].firstChild
            );
            if (++i < pending.length)
            {
                callNext(pending[i]);
            }
        }
    };
    callNext(pending[i]);
    window.removeEventListener('load',l,false);
},false);

Then, the ajax.php script, could just be the Visit function (BTW: please follow the PHP-FIG-coding standards as much as possible, and lower-case that function name). Instead of $url just use:

$url = isset($_POST['url']) && filter_var($_POST['url'], FILTER_VALIDATE_URL) ? $_POST['url'] : false;
if (!$url)
{
    echo json_encode(array('cellText' => 'invalid URL'));
    exit;
}
//do curl request
echo json_encode(array('success' => true, 'cellText' => 'valid'));//or invalid, depending on curl results

This way, the client gets to see the page quite quickly, and sees it's being updated once every 6~7 seconds, depending on how long the curl request takes to complete.
In addition to that, look into caching extensions, such as APC, and set the cache options for the cUrl requests, too. This usually requires some trial and error to find the right balance...


I believe the while() loops are the best way to accomplish your task with how your code is now, so I'm not sure why you "can't stand" them.
You could use a for() loop, and break out of it using an if statement to check the same thing that your while loops are doing, but I would prefer the while loops myself.

One other thing I'd like to mention: if your input is always going to be similar to your example you have nothing to worry about, but your code might not work correctly on the following examples:

Extra line of blank space:
1,1,1,1,1,0,0,0,1,1,1,1,1
0,0,0,1,1,0,0,0,1,1,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0
No wall separator before the entrance:
1,1,1,1,1,0,0,0,1,1,1,1,1
0,0,0,0,0,0,0,0,1,1,0,0,0
No wall separator before the entrance #2:
0,0,0,1,1,1,1,1,1,1,1,1,1
0,0,0,1,1,1,1,1,1,1,1,1,1

You'd catch the ArrayIndexOutOfBounds exception as an "unguessable entry", which I assume is the intentional response - but thought I'd put this here just in case.


Run 'N' Number of PHP Scripts on shell forever in a loop

I think more than even a code review, what you are really needing to think about is your architecture.  In the modern age of event-based workflows and parallel computing should you really be managing and executing a complex set of scripts in this manner (i.e. via shell automation)?

My advice is to look for better tooling that will allow you to orchestrate your pieces of logic via an automated workflow of some sort.  Even consider things like map reduce tools (Hadoop, Elastic Map Reduce, etc.) which are ideal for parallel workload execution with aggregation of results.


Personally, I'd prefer to use @export() or @export(globals()), rather than manually perform the @ sugar.
I don't like using __globals__, even if it is writeable.
Honestly, I think the cleanest solution would be to abuse lists, and use a closure.
I do however agree that inheriting from Exception, is the best parent to inherit from.

And so I'd personally use something more like:

class ExportError(Exception):
    """Exception if redundant names attempted exporting"""

def build_export(__all__=None):
    if __all__ is None:
        __all__ = []
    def export(obj):
        name = obj if isinstance(obj, str) else obj.__name__
        if name in __all__:
            raise ExportError(f'{name} already exported')
        __all__.append(name)
        return obj
    return __all__, export

__all__, export = build_export()

@export
class Foo:
    pass

@export
def bar():
    pass


This python code converts integers to strings and strings to ints without the inbuilt functions "int()" and "str()"

Keep it simple
Your functions are way too complicated. First, you can convert a single digit from integer to character by using ord() and the fact that the ordinals of the characters '0' to '9' are consecutive. Furthermore, you don't need to calculate the length of an integer if you reverse the way you build up the string. Here are example implementations that are simpler:
def str_to_int(num_str):
    num = 0

    for char in num_str:
        num *= 10
        num += ord(char) - ord('0')

    return num

def int_to_str(num_int):
    word = ""

    while num_int:
        word = chr(ord('0') + num_int % 10) + word
        num_int //= 10

    return word or "0"

Integers can be negative
Your code (and my example simplification above) does not handle negative integers.


Improving readability of enabling method

A method like this should do at least two things in addition to MrSmith42's answer:

It should return boolean to indicate whether it succeeded or not (i.e. return enable; at the end)
if it declares a parameter tryEnable = true then it should either use it, or remove it.

EDIT: after edit and comment from OP.

After your changes I think my point-1 remains valid, but your changes make the 'smell' even worse.... ;-)

You should change the method name to trySetCRUDEnabled(...)
what if the settings are currently enabled, and the user calls trySetCRUDEnabled(false) ... it makes the logic hard to understand.... in fact, it's broken because now it does not matter what the security-level is ... ;-) (you are changing the code in haste, and making mistakes).

Incorporating MrSmith42's suggestion for simplifying the code, it should read:

bool enable = tryEnable && _securityLevel < MINSECURITY;


The selector $('thead > tr th') is not specific enough, if you have multiple tables in the page.  You want the headings of the same table that was clicked: $(this).closest('table').find('thead > tr th').

var array is an unsatisfying name.  I can see that it's an array — but what does it do?  How about calling it tableHeadings?

You formed tableData using Array.map(); why not do the headings the same way?

var tableHeadings = $(this).closest('table')
                           .find('thead > tr th')
                           .map(function() {
    return $(this).text();
}).get();


How can I improve this 31-bit SuperFastHash implementation in VBA?

This is quite possibly the most clever VBA code I have ever seen.

There's not much room for improvement here, except a couple naming nitpicks:

If that's what they stand for, functions shr and shl could afford to be called ShiftRight and ShiftLeft.
I don't see a reason for shr and shl to not follow the PascalCasing naming convention.
Given the almost-flawlessly consistent camelCasing convention for locals & parameters, I don't see a reason for Value and Shift parameters to not stick to it. (except perhaps VBA/VB6's stubornness with casing?)

As for string handling, as per this source AscW is faster than Asc so again, good call:

  AscW(Mid$(..)) considerations

  Don't copy too many characters with Mid$. AscW only examines the first
  character anyway. AscW(Mid$(s, x, 1)) is the best call. Note that if
  you call AscW(Mid$(s, x)) without the third parameter, Mid$ executes
  slowly when s is a long string.

  Example of potentially slow code:

For x = 1 To Len(s)
    If AscW(Mid$(s, x)) = ... Then ...
Next

  The above is better written as:

For x = 1 To Len(s)
    If AscW(Mid$(s, x, 1)) = ... Then ...
Next


A very efficient algorithm (Algorithm U) is described by Knuth in the Art of Computer Programming, Volume 4, Fascicle 3B to find all set partitions with a given number of blocks.  Your algorithm, although simple to express, is essentially a brute-force tree search, which is not efficient.

Since Knuth's algorithm is not very concise, its implementation is lengthy as well.  Note that the implementation below moves an item among the blocks one at a time and need not maintain an accumulator containing all partial results.  For this reason, no copying is required.

def algorithm_u(ns, m):
    def visit(n, a):
        ps = [[] for i in xrange(m)]
        for j in xrange(n):
            ps[a[j + 1]].append(ns[j])
        return ps

    def f(mu, nu, sigma, n, a):
        if mu == 2:
            yield visit(n, a)
        else:
            for v in f(mu - 1, nu - 1, (mu + sigma) % 2, n, a):
                yield v
        if nu == mu + 1:
            a[mu] = mu - 1
            yield visit(n, a)
            while a[nu] > 0:
                a[nu] = a[nu] - 1
                yield visit(n, a)
        elif nu > mu + 1:
            if (mu + sigma) % 2 == 1:
                a[nu - 1] = mu - 1
            else:
                a[mu] = mu - 1
            if (a[nu] + sigma) % 2 == 1:
                for v in b(mu, nu - 1, 0, n, a):
                    yield v
            else:
                for v in f(mu, nu - 1, 0, n, a):
                    yield v
            while a[nu] > 0:
                a[nu] = a[nu] - 1
                if (a[nu] + sigma) % 2 == 1:
                    for v in b(mu, nu - 1, 0, n, a):
                        yield v
                else:
                    for v in f(mu, nu - 1, 0, n, a):
                        yield v

    def b(mu, nu, sigma, n, a):
        if nu == mu + 1:
            while a[nu] < mu - 1:
                yield visit(n, a)
                a[nu] = a[nu] + 1
            yield visit(n, a)
            a[mu] = 0
        elif nu > mu + 1:
            if (a[nu] + sigma) % 2 == 1:
                for v in f(mu, nu - 1, 0, n, a):
                    yield v
            else:
                for v in b(mu, nu - 1, 0, n, a):
                    yield v
            while a[nu] < mu - 1:
                a[nu] = a[nu] + 1
                if (a[nu] + sigma) % 2 == 1:
                    for v in f(mu, nu - 1, 0, n, a):
                        yield v
                else:
                    for v in b(mu, nu - 1, 0, n, a):
                        yield v
            if (mu + sigma) % 2 == 1:
                a[nu - 1] = 0
            else:
                a[mu] = 0
        if mu == 2:
            yield visit(n, a)
        else:
            for v in b(mu - 1, nu - 1, (mu + sigma) % 2, n, a):
                yield v

    n = len(ns)
    a = [0] * (n + 1)
    for j in xrange(1, m + 1):
        a[n - m + j] = j - 1
    return f(m, n, 0, n, a)

Examples:

def pretty_print(parts):
    print '; '.join('|'.join(''.join(str(e) for e in loe) for loe in part) for part in parts)

>>> pretty_print(algorithm_u([1, 2, 3, 4], 3))
12|3|4; 1|23|4; 13|2|4; 1|2|34; 1|24|3; 14|2|3

>>> pretty_print(algorithm_u([1, 2, 3, 4, 5], 3))
123|4|5; 12|34|5; 1|234|5; 13|24|5; 134|2|5; 14|23|5; 124|3|5; 12|3|45; 1|23|45; 13|2|45; 1|2|345; 1|24|35; 14|2|35; 14|25|3; 1|245|3; 1|25|34; 13|25|4; 1|235|4; 12|35|4; 125|3|4; 15|23|4; 135|2|4; 15|2|34; 15|24|3; 145|2|3

Timing results:

$ python -m timeit "import test" "test.t(3, [[]], 0, [1, 2, 3, 4])"
100 loops, best of 3: 2.09 msec per loop

$ python -m timeit "import test" "test.t(3, [[]], 0, [1, 2, 3, 4, 5])"
100 loops, best of 3: 7.88 msec per loop

$ python -m timeit "import test" "test.t(3, [[]], 0, [1, 2, 3, 4, 5, 6])"
10 loops, best of 3: 23.6 msec per loop

$ python -m timeit "import test" "test.algorithm_u([1, 2, 3, 4], 3)"
10000 loops, best of 3: 26.1 usec per loop

$ python -m timeit "import test" "test.algorithm_u([1, 2, 3, 4, 5, 6, 7, 8], 3)"
10000 loops, best of 3: 28.1 usec per loop

$ python -m timeit "import test" "test.algorithm_u([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], 3)"
10000 loops, best of 3: 29.4 usec per loop

Notice that t runs much slower than algorithm_u for the same input.  Furthermore, t runs exponentially slower with each extra input, whereas algorithm_u runs almost as fast for double and quadruple the input size.


Remove duplicates from string without additional buffer

Method Signature: your method should return a result, instead of printing it to increase reusability and (automatic) testability.
Complexity: The complexity of your method is higher than it has to be. One simple improvement would be to start the second loop at int j = i to avoid duplicate checks.
Performance/Duplication: You check word[i] == word[j] twice. Just move the if (count > 1) check inside the first if to avoid this duplication.
Argument Checks: Just returning in case of an invalid argument (null in this case) is not a good idea; throw an exception instead to avoid possible bugs in the future.
Argument Checks: Returning nothing in case of a word length of 1 or 0 seems like a bug. I would expect an empty array or an array with the one entry to be returned (ie removeduplicate(['a']) should equal ['a'], not nothing).
Result Value: Your array still contains entries in the positions where duplicate characters were (eg aaaaab -> [a, , , , , b]. This isn't what I would expect (also, the question talks about accepting a string, and presumably returning a string as well; it then also talks about arrays, so using an array internally - instead of eg charAt - is presumably correct, but I would still expect the input and output to be strings).
count = count + 1 can be written as count++.
Naming: removeDuplication would be a lot clearer. removeDuplicateCharacters would be even more precise.
Formatting: Your spacing is inconsistent, leading to less readable code.
Declare variables as late as possible to increase readability. For example, count isn't needed until inside the first loop.

Taking this all together, you would get something like this:

public static String removeDuplicateCharacters(String word) {
    Objects.requireNonNull(word);

    char[] wordArray = word.toCharArray();

    int len = wordArray.length;
    for (int i = 0; i < wordArray.length; i++) {
        int count = 0;
        for (int j = i; j < wordArray.length; j++) {
            if (wordArray[i] == wordArray[j]) {
                count++;
                if (count > 1) {
                    wordArray[j] = 0;
                }
            }
        }
    }
    return String.valueOf(wordArray);
}

It's a bit too nested for my taste, but otherwise I think it's mostly ok.


Using Linq instead of multiple foreach loops

The LINQ would be:

var participantList = communities.SelectMany(c => c.Tournaments
                                                   .SelectMany(t => t.Rounds
                                                                     .SelectMany(r => r.Matches)))
                                  .Where(m => m.Home.ParticipantId.IsNotNull() ||
                                              m.Away.ParticipantId.IsNotNull())
                                  .ToList();

LINQ does not add much imo, if the logic was more complicated the for loops are nicer to debug.

One downside with LINQ for this is that it requires formatting to be readable. If you rename things the formatting needs to be maintained.

With the foreach loops you get formatting for free.

Edit:
As per @RobH's suggestion:

var participantList = communities.SelectMany(c => c.Tournaments)
                                 .SelectMany(t => t.Rounds)
                                 .SelectMany(r => r.Matches)
                                 .Where(m => m.Home.ParticipantId.IsNotNull() ||
                                             m.Away.ParticipantId.IsNotNull())
                                 .ToList();

Chaining is indeed nicer.


(I do not intend to address the better algorithm angle beyond stating that this is another hackerrank problem seeking the series for a sequence and quoting one advice: Pen down a few iterations yourself and you will find a way to compute the function value directly.)

Following the code presented top to bottom:

Document/comment your code. In the code.
What is the class about, each method, its parameters?
Don't specify sweeping includes you don't use.
Here, just use java.util.Scanner and not a single include
Class names should be CamelCase: class SimplestSum
provided arithmetic assignment operators and conditional expressions, I'd code accumulating
totalSum += z * (mul < b ? k*a : (b-count)+1);
you introduce a variable for k*a, but use it in one place out of three, only.
at the end of simplestSum()'s code, I think it does try and use a series: explain in the method comment.
Accumulation may exceed the range of int (applies to maxSum() as well)
maxSum()'s indentation is off ever so slightly
maxSum() does not try and use a series
do not open code closing AutoCloseables: use try-with-resources
in main(), using single letter variable names from the problem statement suggests itself - not so for nQueries.
And why introduce another variable, why name it a0 (instead of query or even q (OK for an iteration variable in an inner loop, especially when not used otherwise))
a and b are input using java.util.Scanner.nextInt() where the Constraints allow ≤ 10^18
depending on where and how large inputs are handled, this will necessitate declaring variables/parameters to handle numbers beyond the range of int more likely than not.


Grouping elements in array by multiple properties

I felt compelled to write that you probably should combine forEach and map with the answer of Alexey Lebedev.

function groupBy( array , f )
{
  var groups = {};
  array.forEach( function( o )
  {
    var group = JSON.stringify( f(o) );
    groups[group] = groups[group] || [];
    groups[group].push( o );
  });
  return Object.keys(groups).map( function( group )
  {
    return groups[group];
  })
}

var result = groupBy(list, function(item)
{
  return [item.lastname, item.age];
});


Your code seems to work and is split into small functions. Here are a few things to make it easier to understand.

Try to avoid nested functions

Nested functions can be really useful but in your case, it makes the code hard to understand because it is nested on many levels.

Also, because some parameters are not explicitly provided but somehow used as part of the functions context, it is hard to tell what is used/not used, input/output, updated/unchanged.

This is fairly easy to change to make the code more linear with the different functions defined one after the other (in order to do so, you need to add parameters in the function signatures and in the function calls). Also, you could take this chance to extract a few constant (and name them in UPPERCASE):

EMPTY = '.'
BODY = '*'
DEAD = 'X'
HEADS = {'v': (1, 0), '^': (-1, 0), '<': (0, -1), '>': (0, 1)}

def get_next(x, y, snake, gameBoard):
    for key, direc in HEADS.items():
        new_x, new_y = x + direc[0], y + direc[1]
        if new_x in range(len(gameBoard)) and new_y in range(len(gameBoard[0])):
            if (new_x, new_y) not in snake:
                if gameBoard[new_x][new_y] == BODY:
                    return (new_x, new_y)

def find_snake(gameBoard):
    # Get the head and the next body opposite of snake's direction
    snake = []
    for i, row in enumerate(gameBoard):
        for head in HEADS:
            if head in row:
                snake.append((i, row.index(head)))
                snake.append((snake[0][0] + HEADS[head][0] * -1, snake[0][1]  + HEADS[head][1] * -1))

    # Append the rest of the body
    while True:
        n = get_next(snake[-1][0], snake[-1][1], snake, gameBoard)
        if n is None:
            break
        snake.append(n)

    return snake

def move_snake(snake, gameBoard):
    head = gameBoard[snake[0][0]][snake[0][1]]
    new_x, new_y = snake[0][0] + HEADS[head][0], snake[0][1]  + HEADS[head][1]
    new_snake = []
    if new_x in range(len(gameBoard)) and new_y in range(len(gameBoard[0])) and (new_x, new_y) not in snake:
        new_snake.append((new_x, new_y))

        for pos in snake[:-1]:
            new_snake.append(pos)

        return new_snake

def snakeGame(gameBoard, commands):
    new_direc = {'v': {'L': '>', 'R': '<'},
                 '^': {'L': '<', 'R': '>'},
                 '<': {'L': 'v', 'R': '^'},
                 '>': {'L': '^', 'R': 'v'}}

    # Find starting snake
    snake = find_snake(gameBoard)

    for command in commands:
        if command in "LR":
            # Change the head
            gameBoard[snake[0][0]][snake[0][1]] = new_direc[gameBoard[snake[0][0]][snake[0][1]]][command]
        else:
            temp = move_snake(snake, gameBoard)

            # if not valid move return dead snake
            if temp is None:
                for pos in snake:
                    x, y = pos
                    gameBoard[x][y] = DEAD
                return gameBoard

            # else move snake
            for a, b in zip(snake, temp):
                gameBoard[b[0]][b[1]] = gameBoard[a[0]][a[1]]

            gameBoard[snake[-1][0]][snake[-1][1]] = EMPTY
            snake = temp

    return gameBoard

def test_snake(gameBoard, commands, expected):
    out = snakeGame(gameBoard, commands)
    if out != expected:
        print(out, commands, expected)

test_snake([['.', '.', '.', '.'],
            ['.', '.', '<', '*'],
            ['.', '.', '.', '*']],
           "FFFFFRFFRRLLF",
           [['.', '.', '.', '.'],
            ['X', 'X', 'X', '.'],
            ['.', '.', '.', '.']])
test_snake([['.', '.', '^', '.', '.'],
            ['.', '.', '*', '*', '.'],
            ['.', '.', '.', '*', '*']],
           "RFRF",
           [['.', '.', 'X', 'X', '.'],
            ['.', '.', 'X', 'X', '.'],
            ['.', '.', '.', 'X', '.']])
test_snake([['.', '.', '*', '>', '.'],
            ['.', '*', '*', '.', '.'],
            ['.', '.', '.', '.', '.']],
           "FRFFRFFRFLFF",
           [['.', '.', '.', '.', '.'],
            ['<', '*', '*', '.', '.'],
            ['.', '.', '*', '.', '.']])

Getting rid of indices (almost) everywhere

In your code, element access (foo[i]) is used everywhere:

to get/set a particular cell of the grid
to get the x (or y) part of coordinates
the get the direction from a particular "head" characters

It may make things confusing but you can use a few techniques to get rid of it:

When you iterate over a dictionnary, you can choose if you are interested in keys, values or both. Then you don't need to get my_dict[my_key].
You can use iterator unpacking when you know the number of elements in it. This is very convenient when you handle coordinates: x, y = my_coor. Also, this can be used in the for syntax: for head, (dx, dy) in HEADS.items().
Instead of using list access to get the element you've just added to the (empty) list, you can use temporary variables:

            snake.append((i, row.index(head)))
            snake.append((snake[0][0] + heads[head][0] * -1, snake[0][1]

becomes

                beginx, beginy = i, row.index(head)
                snake.append((beginx, beginy))
                snake.append((beginx - dx, beginy - dy))

It "costs" an additional line but it makes things clearer to me. (Also I took this chance to replace a + b * -1 by a - b).

Combining all these techniques, you'd get something like:

EMPTY = '.'
BODY = '*'
DEAD = 'X'
HEADS = {'v': (1, 0), '^': (-1, 0), '<': (0, -1), '>': (0, 1)}

def get_next(x, y, snake, gameBoard):
    for (dx, dy)  in HEADS.values():
        new_x, new_y = x + dx, y + dy
        if new_x in range(len(gameBoard)) and \
           new_y in range(len(gameBoard[0])) and \
           (new_x, new_y) not in snake and \
           gameBoard[new_x][new_y] == BODY:
            return (new_x, new_y)

def find_snake(gameBoard):
    # Get the head and the next body opposite of snake's direction
    snake = []
    for i, row in enumerate(gameBoard):
        for head, (dx, dy) in HEADS.items():
            if head in row:
                beginx, beginy = i, row.index(head)
                snake.append((beginx, beginy))
                snake.append((beginx - dx, beginy - dy))

    # Append the rest of the body
    while True:
        n = get_next(snake[-1][0], snake[-1][1], snake, gameBoard)
        if n is None:
            break
        snake.append(n)

    return snake

def move_snake(snake, gameBoard):
    headx, heady = snake[0]
    head = gameBoard[headx][heady]
    dx, dy = HEADS[head]
    new_x, new_y = headx + dx, heady + dy
    new_coord = new_x, new_y
    new_snake = []
    if new_x in range(len(gameBoard)) and \
       new_y in range(len(gameBoard[0])) and \
       new_coord not in snake:
        new_snake.append(new_coord)
        for pos in snake[:-1]:
            new_snake.append(pos)
        return new_snake

def snakeGame(gameBoard, commands):
    new_direc = {'v': {'L': '>', 'R': '<'},
                 '^': {'L': '<', 'R': '>'},
                 '<': {'L': 'v', 'R': '^'},
                 '>': {'L': '^', 'R': 'v'}}
    # Find starting snake
    snake = find_snake(gameBoard)

    for command in commands:
        if command in "LR":
            # Change the head
            headx, heady = snake[0]
            gameBoard[headx][heady] = new_direc[gameBoard[headx][heady]][command]
        else:
            temp = move_snake(snake, gameBoard)

            # if not valid move return dead snake
            if temp is None:
                for (x, y) in snake:
                    gameBoard[x][y] = DEAD
                return gameBoard

            # else move snake
            for a, b in zip(snake, temp):
                gameBoard[b[0]][b[1]] = gameBoard[a[0]][a[1]]

            tailx, taily = snake[-1]
            gameBoard[tailx][taily] = EMPTY
            snake = temp

    return gameBoard

Other code simplifications

Now that we provide the full snake to the get_next function, it doesn't really need to x and y values.

def get_next(snake, gameBoard):
    x, y = snake[-1]
    ....

In the move_snake function, you write a loop to add elements from snake[:-1]. You could use a simple + operation on lists.

Also, it is clearer to add return None at the end of a function whose return value is used. This is one of the latest addition to PEP 8:

  Be consistent in return statements. Either all return statements in a
  function should return an expression, or none of them should. If any
  return statement returns an expression, any return statements where no
  value is returned should explicitly state this as return None, and an
  explicit return statement should be present at the end of the function
  (if reachable).

Then, the whole function becomes:

def move_snake(snake, gameBoard):
    headx, heady = snake[0]
    head = gameBoard[headx][heady]
    dx, dy = HEADS[head]
    new_x, new_y = headx + dx, heady + dy
    new_coord = new_x, new_y
    if new_x in range(len(gameBoard)) and \
       new_y in range(len(gameBoard[0])) and \
       new_coord not in snake:
        return [new_coord] + snake[:-1]
    return None

Other ideas

At the moment, we have the snakes represented in 2 ways : as a list of body parts (which makes sense given how convenient it is to make the snake go forward) and as a drawing on a grid (which makes sense because it is our input and our output).

Also, for every step forward, we need to update both representations. Maybe, it would make sense to keep the listy-snake (and other data you might need) during the computations of the different steps and only generate the output grid at the very end.

As an exercice, I've tried to do this. I went for an object approach to store the different data needed and interact easily with them. I've tried to keep as much as possible from your code:

EMPTY = '.'
BODY = '*'
DEAD = 'X'
HEADS = {'v': (1, 0), '^': (-1, 0), '<': (0, -1), '>': (0, 1)}

class Snake(object):
    # Heads and body parts are (x, y, char)
    def __init__(self, head, dimx, dimy):
        self.dimx = dimx
        self.dimy = dimy
        self.body = [head]
        self.alive = True

    def add_queue(self, body_part):
        self.body.append(body_part)

    def turn(self, direc):
        new_direc = {'v': {'L': '>', 'R': '<'},
                     '^': {'L': '<', 'R': '>'},
                     '<': {'L': 'v', 'R': '^'},
                     '>': {'L': '^', 'R': 'v'}}
        x, y, head = self.body[0]
        new_head = new_direc[head][direc]
        self.body[0] = (x, y, new_head)

    def move_forward(self):
        x, y, char = self.body[0]
        dx, dy = HEADS[char]
        new_x, new_y = x + dx, y + dy
        if self.position_is_free(new_x, new_y):
            self.body = [(new_x, new_y, char)] + [(x, y, BODY)] + self.body[1:-1]
        else:
            self.die()

    def position_is_free(self, x, y):
        return x in range(self.dimx) and \
               y in range(self.dimy) and \
               not any(x == x2 and y == y2 for (x2, y2, _) in self.body)

    def die(self):
       self.alive = False
       self.body = [(x, y, DEAD) for (x, y, _) in self.body]

    def get_as_grid(self):
        g = [[EMPTY for i in range(self.dimy)] for j in range(self.dimx)]
        for x, y, c in self.body:
            g[x][y] = c
        return g

def find_head(gameBoard):
    for i, row in enumerate(gameBoard):
        for head, (dx, dy) in HEADS.items():
            if head in row:
                return Snake((i, row.index(head), head), len(gameBoard), len(gameBoard[0]))

def get_next(snake, gameBoard):
    x, y, _ = snake.body[-1]
    for (dx, dy) in HEADS.values():
        new_x, new_y = x + dx, y + dy
        if snake.position_is_free(new_x, new_y) and \
           gameBoard[new_x][new_y] == BODY:
            return (new_x, new_y, BODY)

def find_snake(gameBoard):
    # Get the head
    s = find_head(gameBoard)

    # Append the rest of the body
    while True:
        n = get_next(s, gameBoard)
        if n is None:
            break
        s.add_queue(n)
    return s

def snakeGame(gameBoard, commands):
    # Find snake
    s = find_snake(gameBoard)

    for command in commands:
        if command in "LR":
            # Change the head
            s.turn(command)
        else:
            s.move_forward()
            if not s.alive:
                break
    return s.get_as_grid()

Something I had forgotten

if new_x in range(len(gameBoard)) can be rewritten if 0 <= new_x < len(gameBoard).

On Python2, this is much faster (because a list is generated and then we perform a linear search on it).
On Python3, the performance impact may not be so big.


Refactored code for updating user password, email and other info

A few obvious things would be:

1) You shouldn't include current_email and current_password in the sanitized_params since you don't want to update these only validate them.

2) Similarly for new_email and new_password, you have aleady updated these manually

3) So really you aren't updating anything else currently.

4) If your first two tests fail you render a json error but don't stop processing so the last if clause will still execute and you will get a double render error. You should probably test all your conditions before executing any code.

I would consider moving the update logic into methods on the User model (update_email, #update_password that do the validation for you.