Traversing List of Integers and ending on the last index which should be 0

This function relies on no object state, so I would make it static.

You don't need both listSize and lastIndex.  To reduce clutter, I would keep just lastIndex.

currentIndexValue is too cumbersome a name, in my opinion.  "Current" is superfluous, especially when there is no "previous" or "next" involved.  "Index" just adds confusion.  So, I'd simply call it value.

The for loop is trying to do too much.  Considering that currentIndexValue is defined elsewhere, you can't understand how the loop behaves just by looking at the loop header.  So, I would just make it count iterations.

If currentIndexValue is 0, but i is not lastIndex, then i is never going to move.  You might as well return false immediately in that case.

It would be better to avoid triggering IndexOutOfBoundsException when i is negative.

public static boolean isSolvable(List<Integer> list) {
    if (list == null) {
        throw new IllegalArgumentException("List is null");
    }

    int lastIndex = list.size() - 1;
    int i = 0;
    for (int loopCounter = 1; loopCounter <= lastIndex; loopCounter++) {
        if (i < 0 || i > lastIndex) {
            return false;
        }
        int value = list.get(i);
        if (value == 0) {
            return i == lastIndex;
        }
        i += value;
    }

    return false;
}


Beware of hard-coding the first element of a list like aggregateFeaturesForML.get(0). This can throw an exception is aggregateFeaturesForML is empty so you should check for that first.
Do not compare String with == (or !=). In the following

if(ip != previousIp)

you are comparing the Strings ip and previousIp with !=. Strings are compared using their equals method, so you should have instead:

if(!ip.equals(previousIp))

Prefer to program against interfaces. Instead of

HashMap<String, String> mapForIP = aggregator.get(previousIp);

use:

Map<String, String> mapForIP = aggregator.get(previousIp);

As a side-note, if you are using Java 8, your code could be written a lot more simply using the Stream API, that directly provides a way to group elements with a classifier, using the groupingBy collector. In this case, when two elements are classified the same way, they are collected into a Map with the toMap collector.

Map<String, Map<String, String>> aggregator =
    aggregateFeaturesForML.stream()
                          .collect(Collectors.groupingBy(
                              SingleResult::getSourceip,
                              Collectors.toMap(SingleResult::getKey, SingleResult::getValue)
                          ));


Synchronizing scrollbars, scrollTop and scroll event loops

As you never want to handle a triggered event, I can suggest making it simpler using a single sentinel flag:

$left = $("#left")
$right = $("#right")

// Use a simple sentinel to say we are busy handling an event
var scrolling = false;
var timer;
$left.scroll(function () {
    //console.log("left "  + $left.scrollTop() + " : " + $.now());
    if (!scrolling) {
        //console.log("SCROLLING LEFT");
        clearTimeout(timer);
        timer = setTimeout(function () {
            scrolling = true;
            $right.scrollTop($left.scrollTop());
            scrolling = false;
        }, 10);
    }
});

$right.scroll(function () {
    //console.log("Right " + $right.scrollTop() + " : " + $.now());
    if (!scrolling) {
        clearTimeout(timer);
        timer = setTimeout(function () {
            //console.log("SCROLLING RIGHT");
            scrolling = true;
            $left.scrollTop($right.scrollTop());
            scrolling = false;
        }, 10);
    }
});

Update:

With FireFox, it triggers multiple scroll events, in sequence, for a single mouse wheel move. The trick is to wait until it settles using a timer. I found 10ms seems to work fine.

JSFiddle: http://jsfiddle.net/8xaw2896/8/


Calculate daily average for selected period in PHP

The only change I would make is in your two foreach loops. If you see below, I have made the change I would recommend making. This will make the loop a bit shorter and more accurate.

// Store occurrence of same days
$countDays  = array('Mon' => 0, 'Tue' => 0, 'Wed' => 0, 'Thu' => 0,
     'Fri' => 0, 'Sat' => 0, 'Sun' => 0);

// Store values
$output = array('Mon' => 0, 'Tue' => 0, 'Wed' => 0, 'Thu' => 0,
     'Fri' => 0,'Sat' => 0, 'Sun' => 0);

// Count days
foreach($data as $key => $value) {

    $dayName = date('D', strtotime($key));

    $countDays[$dayName]++;
    //add up all the qty when you go through the array the first time
   // IE all the Tuesdays in the array get added up.
    $output[$dayName] += $value;
}

// Calculate average
foreach($output as $key => $value) {
    //now take all the totals you just made in the other loop, and avg them
    $output[$key] = round($value / $countDays[$key]);
}

This is the only way I can see to improve the code. This way, you have a 'shorter' second foreach loop, which may improve the speed of your code a bit. You could also do the $value by reference and change it on the fly, but I think the way I have it now is clearer. This way you aren't doing the math more then once per array element, so you only do the avg for something like Tuesday once.

As Pinoniq stated you can drop the second foreach loop and add a function, and use array_map to do the rounding. Leave the first foreach loop the same and then add this, instead of the other foreach loop.

function average($a, $b){
    return round($a/$b);
}
$output = array_map("average",$output,$countDays);
//var_dump($output); //<-only if you want to test results.

Downside: You lose your index keys if you do it like this. However, you can easily fix that by just keeping the keys in an array, and then print them out at the same time, or use array_combine($keys,$values); to get your output array back.


You limit yourself to anagrams of 15 letters.

#define CH_LEN 15
char first_word[CH_LEN];
char sec_word[CH_LEN];

But you don't actually use words after they are input.
You can fix the limitation (and a potentially serious bug) by not using the concept of a line. Just read characters.

In the code just read characters:

char nextInput = getchar();

No all alphabets are 26 letters.

#define N 26

I would have done this for clarity to show that you are looking at a-z:

#define N  ('z' - 'a' + 1)

Also N is not that descriptive. Personally I would have preferred a global static variable.

static const AlphabetSize = ('z' - 'a' + 1);

You basically repeat the same piece of code twice. This violates the DRY principle. Remove this code into a function and call the function passing parameters for the differences.

    int i;
    for(i = 0; i < CH_LEN; i++) {
        first_word[i] = getchar();
        if(first_word[i] == '\n')
            break;
        if(!isalpha(first_word[i]))
            --i;

        track_letters[(tolower(first_word[i]) - 'a')]++;

    }
    printf("Enter second word: ");
    for(i = 0; i < CH_LEN; i++) {
        sec_word[i] = getchar();
        if(sec_word[i] == '\n')
            break;
        if(!isalpha(sec_word[i]))
            --i;
        track_letters[(tolower(sec_word[i]) - 'a')]--;

    }

I would write like this:

    ProcessesAnagram(track_letters, +1);  // Reads first Line
    ProcessesAnagram(track_letters, -1);  // Reads second line

Since we are not longer bound by a word size. I would change the loop to check for the end of line (or end of input)).

 void ProcessesAnagram(int* track_letters, int increment)
 {
    int nextLetter = getchar();
    for(;nextLetter != EOF && nextLetter != '\n'; nextLetter = getchar())
    {
        if(!isalpha(nextLetter)
        {    continue;           // If not a letter just start the next iteration
        }

        // Note: increment is +1 first anagram
        //       increment is -1 second anagram (so they will cancel out)
        track_letters[(tolower(nextLetter) - 'a')] += increment;
    }
 }

There is a bug here

You are using the wrong size: CH_LEN is the size of the words. But the track_letters array has a size of N.

    for(i = 0; i < CH_LEN; i++) {
        if(track_letters[i] != 0) {
            printf("The words are not anagrams");
            return 0;
        }
    }


The character set is named ISO-8859-1, not ISO-8895-1.  Rename your function accordingly.

Change the return value to be more informative:

Return 0 on success.
If max_size is too small, return the minimum value of max_size that would be sufficient to accommodate the output (including the trailing \0).

I would also change the parameter to take a signed char * to be a bit more natural.

I think that the implementation could look tidier if you dealt with pointers instead of offsets.

It would be nice if you NUL-terminated the result, so that the caller does not have to zero out the entire buffer before calling this function.

size_t iso8859_1_to_utf8(char *content, size_t max_size)
{
    char *src, *dst;

    //first run to see if there's enough space for the new bytes
    for (src = dst = content; *src; src++, dst++)
    {
        if (*src & 0x80)
        {
            // If the high bit is set in the ISO-8859-1 representation, then
            // the UTF-8 representation requires two bytes (one more than usual).
            ++dst;
        }
    }

    if (dst - content + 1 > max_size)
    {
        // Inform caller of the space required
        return dst - content + 1;
    }

    *(dst + 1) = '\0';
    while (dst > src)
    {
        if (*src & 0x80)
        {
            *dst-- = 0x80 | (*src & 0x3f);                     // trailing byte
            *dst-- = 0xc0 | (*((unsigned char *)src--) >> 6);  // leading byte
        }
        else
        {
            *dst-- = *src--;
        }
    }
    return 0;  // SUCCESS
}


You could do the following. (I assume you already have a resourceful route for your documents right?)

resources :documents do
  collection do
    get 'reports'
    get 'charts'
  end
end

To take advantage of the nested routing provided by rails (see the docs)

Which will generate the following urls:

           Prefix Verb   URI Pattern                                                                    Controller#Action
reports_documents GET    /documents/reports(.:format)                                                   documents#reports
 charts_documents GET    /documents/charts(.:format)                                                    documents#charts

If you don't have any resourceful route, you have to declare it like you already did. The only thing to do would be iterating over an array like this:

scope controller: :documents do
  %w(reports charts).each do |action|
    get action
  end
end

But IMO this hurts the readability of the code, and is only necessary when dealing with a lot of routes.


I think what you are looking for is a ternary operator.
const configColors = (isSingle, isDarkMode) => {
  return {
      configAxisLabelColor : isDarkMode ? Colors.white : Colors.lineGray,
      configAxisGridColor : isDarkMode ? Colors.gridLineGray : Colors.transparent
      configAxisColor: isSingle ? (isDarkMode ? Colors.white: Colors.transparent) : Colors.lightBarGray
      // so on
  }

Another option that reads better could be to create a separate config for each possible combination you want to return.
const configColors = (isSingle, isDarkMode) => {

  const configSingleDark = {
    configAxisLabelColor : Colors.white,
    configAxisGridColor : Colors.gridLineGray
  }

  if (isSingle && isDarkMode) {
    return configSingleDark
  } else if (isSingle && !isDarkMode) {
    return configSingleLight
  } else {
    //
  }
}


Interpolating given value and legacy value from serialization buffer

If I understand your question correctly, using the RefTrait policy in your second solution is acceptable but you want to avoid specifying template parameters from the client code that's using it.

If so then perhaps one possible idea is to create an inline wrapper function around your interpolate for marshaling the call so type deduction happens automatically:

template <>
struct RefTrait<Vector> { typedef const Vector &Ref; };

template <typename T>
T interpolateImp(Buffer& buffer, typename RefTrait<T>::Ref currentValue, const float prop)
{
    T bufferValue;
    buffer.readT(&bufferValue);
    return currentValue + (bufferValue-currentValue)*prop;
}

template <typename T>
inline T interpolate(Buffer& buffer, T &currentValue, const float prop)
{
    return interpolateImp<T>(buffer, currentValue, prop);
}

It doesn't avoid the overloading but it'll at least help with the automatic type-deduction when you try to use it:

floatVal  = interpolate(buffer, floatVal, 0.5f);
vectorVal = interpolate(buffer, vectorVal, 0.5f);

And the interpolate wrapper should get optimized away into just a interpolateImp call when the compiler inlines it.

But I would recommend taking a look at what Mike said first and find out really how much of a performance impact this is. If afterwards you still decide to pursue this route there are two things to keep in mind.

Caveat with using your current RefTrait. At the moment, T bufferValue; in your interpolate creates a locate T variable but doesn't initialize it. This poses a problem if T = const Vector&. Furthermore, it also means you're unable to change this T object later on should you need to. One possible way to fix it is to also add a valueType to your RefTraits policy. You would then use typename T::valueType to create any locates you would need inside interpolate.
Using templates in this matter will reduce code clarity unless you're extra dilgent. The syntax has a matter of exploding in your face and could be difficult to get right especially if you're trying to cover the funny corner cases. Be sure to weight the tradeoffs.

Edit: After thinking about my above code some more, I noticed it could be simplified a bit by just keeping the syntax the same as the OP. I've updated mines to reflect that.


Attaching an interrupt to a member function

Yes; the key issue here is that you are dynamically determining values that can be determined statically.

Luckily, you are working in a language with extensive static analysis capabilities (template metaprogramming), so let's use that!  (This sounds more complicated than it is.)

Also: I'm not sure why you determine the sign of multiplier separately from whether you should add or subtract it from distance.  If statements are slow, because the processor needs to predict the correct branch (at best) or flush the pipeline (at worst).   So I've removed that; hopefully it will get optimized into a setcc or similar.  (I should also mention I'm not familiar with Arduino processors; it is entirely possible these changes are irrelevant.)

Finally, since you're working in C++, you really should use constructors or uniform initializers, rather than assignments.  Yes, a decent compiler will optimize away the temporary, but it is always better to be easy on your poor compiler.

template<int const pinIndex, int const pinIndex2>
void interrupt(void)
{
    volatile static int pinState(digitalRead(pinIndex2)), distance(0);
    int const newState(digitalRead(pinIndex2)), multiplier(((HIGH == digitalRead(pinIndex)) ^ (newState == pinState)) ? -1 : 1);
    distance += multiplier;
    pinState = newState;
}

template<int const pinIndex, int const pinIndex2>
void registerInterrupt(void)
{
    pinMode(pinIndex, INPUT);
    pinMode(pinIndex2, INPUT);
    attachInterrupt(digitalPinToInterrupt(pinIndex), &interrupt<pinIndex, pinIndex2>, CHANGE);
}
void registerInterrupts(void)
{
    registerInterrupt<18, 22>(void);
    registerInterrupt<19, 23>(void);
}

If you're confused how this holds state, look at the static variables.  These also might slow the interrupt down; if so, make them static members of a templated struct, like so:

template<int const pinIndex, int const pinIndex2>
struct interruptData
{
    volatile static int pinState(digitalRead(pinIndex2)), distance(0);
}

Then change the references inside the interrupt.

Beyond this, I don't see a way to improve your interrupt.  It's pretty bare-bones to begin with.


Finding the closest value and matching it with the correct item in the list

You cannot use a dictionary but you can use the GroupBy and then search for the closest key. The values of the group will be the items with same values.

var values = new[]
{
    new Foo{ Id ="A", Value = 1.2 },
    new Foo{ Id ="B", Value = 4.2 },
    new Foo{ Id ="C", Value = 7.2 },
    new Foo{ Id ="D", Value = 4.2 }
}
.GroupBy(x => x.Value);

where

struct Foo
{
    public string Id;
    public double Value;
}


I have some suggestions.
MessageViewerProgram

Instead of brute forcing all the messages in the directory, I suggest that you list them and iterate on them instead. You can use the method java.io.File#listFiles() for this.

File file = new File(saveDir);
File[] files = file.listFiles();

This will give you an array of the files in the message folder, and you can iterate.
File saveDir = new File(".save/messages/");

for (File currentMessageFile : saveDir.listFiles()) {
   try (FileInputStream fis = new FileInputStream(currentMessageFile);
            ObjectInputStream ois = new ObjectInputStream(fis)) {

      Message message = (Message) ois.readObject();
      System.out.println(message.getSenderName() + ": " + message.getMessage());
   } catch (IOException e) {
      e.printStackTrace();
   } catch (ClassNotFoundException e) {
      e.printStackTrace();
   }
}

MessageWriterProgram

The initialization of the MessageWriterProgram#scanner variable outside the constructor is useless, it's created  inside the constructor already.

private Scanner scanner;

public MessageWriterProgram() {
   scanner = new Scanner(System.in);
}

I suggest that you rename the method mainLoop in start or run or even execute.

MessageWriterProgram#saveMessage method

Rename the variable filename into fileName

I suggest that you extract the logic of counting the next file name in a method.

public void saveMessage(Message message) {
   // create file name that isn't used
   int fileName = getNextFilename();
   //[...]
}

private int getNextFilename() {
   int fileName = getNextFilename();

   while (true) {
      File file = new File(SAVE_DIR_NAME + fileName);
      if (file.exists()) {
         fileName++;
      } else {
         break;
      }
   }

   return fileName;
}

Instead of counting the messages in the loop, you can use the java.io.File#listFiles() and check the number of files in the folder.

private int getNextFilename() {
   File messageDirectory = new File(SAVE_DIR_NAME);
   File[] files = messageDirectory.listFiles();

   if (files != null) {
      return files.length + 1;
   } else {
      return 1;
   }
}

MessageWriterProgram#login method
In my opinion, this method is a bit useless and add confusion, since it does more than one thing.

Check if the User is present.
Update the identity variable.

If you inline it, it will be more readable and you can convert the identity variable to a local variable.
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Password: ");
String password = scanner.nextLine();

User identity = userManager.retainUserIdentity(name, password);

if (identity == null) {
   System.out.println("Login was not successful.");
   return;
}

Refactored MessageWriterProgram class
public class MessageWriterProgram {
   public static void main(String[] args) {
      MessageWriterProgram mwp = new MessageWriterProgram();
      mwp.mainLoop();
   }

   private static final String SAVE_DIR_NAME = ".save/messages/";

   private Scanner scanner;
   private UserManager userManager;

   public MessageWriterProgram() {
      scanner = new Scanner(System.in);
      userManager = new UserManager();
   }

   public void mainLoop() {
      System.out.print("Name: ");
      String name = scanner.nextLine();
      System.out.print("Password: ");
      String password = scanner.nextLine();

      User identity = userManager.retainUserIdentity(name, password);

      if (identity == null) {
         System.out.println("Login was not successful.");
         return;
      }

      System.out.println(identity.getName());

      while (true) {
         System.out.print("> ");
         String input = scanner.nextLine();

         if (!input.isEmpty()) {
            Message message = new Message(identity.getName(), input);
            saveMessage(message);
         }
      }
   }

   public void saveMessage(Message message) {
      // create file name that isn't used
      int fileName = getNextFilename();

      File file = new File(SAVE_DIR_NAME + fileName);

      // store message
      try (FileOutputStream fos = new FileOutputStream(file);
               ObjectOutputStream oos = new ObjectOutputStream(fos)) {
         oos.writeObject(message);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   private int getNextFilename() {
      File messageDirectory = new File(SAVE_DIR_NAME);
      File[] files = messageDirectory.listFiles();

      if (files != null) {
         return files.length + 1;
      } else {
         return 1;
      }
   }
}


This looks nice, though I don't actually know kotlin.

One suggestion I'd make is that when you have multiple relational conditions in a statement like this:

assert(i >= 0 && i < size)

It's slightly more readable if you arrange the terms in increasing order of their values, like this:

assert(0 <= i && i < size)


Wrapping JS file in function, and assigning that function to a variable

From a organizing perspective you are doing fine, in essence you used the Module Pattern. I would just advise you to consider placing 'use strict'; in the beginning of your function.

As you probably figured out, $ does not collide with jQuery. Though, for this piece of code I would not create a one line function if you are only going to call that function once.

For the email thing, I think it might fool a number of scrapers, I'd keep it.

For fizzbuzz, while your code is working, I think the goal is to use a minimum amount of modulo statements, your code could be written with fewer modulo statements..

My counter suggestion is very close to your code:

// codereview.js:
var codeReview = (function() {

    // "public" functions
    return {
        fizzbuzz: function() {
            var output, i;
            for (i = 1; i <= 100; i++) {
                output = '';
                if (i % 3 == 0) {
                    output = 'Fizz';
                }
                if (i % 5 == 0) {
                  output += 'Buzz';
                }
                output = output || i;
                console.log(output);
            }
        },
        email: function() {
            var first = 'test@em';
            var last = 'ail.com';
            var email = first + last;
            return document.getElementById('my_email').innerHTML = email;
        }
    }
})();

codeReview.fizzbuzz();

This was an interesting read, which provided an alternative inner loop which is more code review friendly:

            for (i = 1; i <= 100; i++) {
                if (i % 15 == 0) {
                    output = 'FizzBuzz';
                }
                else if (i % 3 == 0) {
                    output = 'Fizz';
                }
                else if (i % 5 == 0) {
                  output += 'Buzz';
                }
                else{
                  output = i;
                }
                console.log(output);
            }


Multiple lines of code in if statement without curly braces

The problem with massively nested if statements without the { } is that it is a fragile structure. It is easy to come in and add a new statement and not realize whether it is or is not in one of the ifs or not. It also makes else statements harder to follow as not everyone is completely familiar with the precedence rules for else statements.

It works, it's entirely valid code - but it is bad style.

In this particular case you don't even need the nested ifs:

if (ggcCompareGrid.TopLevelTable != null)
{
        foreach (GridRow row in ggcCompareGrid.TopLevelTable.Rows)
        {
            if (row.DisplayElement.ParentGroup != null &&
                  row.DisplayElement.ParentGroup.Category != null &&
                  (int)row.DisplayElement.ParentGroup.Category == key &&
                   row.Record == null)
            {
                  row.DisplayElement.ParentGroup.IsExpanded = false;
                  break;
            }
        }
  }

You could also consider in this case having a private boolean function that does the comparison:

 private boolean checkParentGroup(ParentGroup group, int key, Record record) {
      return ((group != null) && (group.Category != null) &&
                  ((int)group.Category == key) &&
                   (record == null))
 }

if (ggcCompareGrid.TopLevelTable != null)
{
        foreach (GridRow row in ggcCompareGrid.TopLevelTable.Rows)
        {
            if (checkParentGroup(row.DisplayElement.ParentGroup, key, row.Record)
            {
                  row.DisplayElement.ParentGroup.IsExpanded = false;
                  break;
            }
        }
  }

This makes every part of the code simpler and clearer.

Obviously the checkParentGroup method should have a better name though, describing what it is actually checking.


Solve with math
This is a math problem. Let say we have a competition: [a, b, c] score [5, 2, 10], this means that the scoring is:
$$
\begin{array}{|l|r|r|r|}
& \textrm{a} & \textrm{b} & \textrm{c} & \textrm{res} \\
\hline
\textrm{a} & \text{NaN} & 3 & -5 & -2 \\
\textrm{b} & -3 & \text{NaN} & -8 & -11\\
\textrm{c} & 5 & 8 & \text{NaN} & 13
\end{array}
$$
As you should be able to see, you don't need to calculate the sum again and again for each pair.
Solution:
For each team:
\$\text{team's score} \times \text{number of teams} - \text{total score}\$.
score[a] =  5 * 3 - 17 =  -2
score[b] =  2 * 3 - 17 = -11
score[c] = 10 * 3 - 17 =  13

The time complexity of this is \$O(n)\$. Calculate all pairs is \$O(n^2)\$.
Some code
Here I will save the total score for each team (not the history of the scores _  the code change for that would not be big tho).
from collections import Counter, defaultdict

# test data
games = [['A', 'B'], ['B'], ['A', 'B', 'C', 'D', 'E'], ['B'], ['A', 'B', 'C'], ['A'], ['B', 'C'], ['A', 'B'],
         ['C', 'A', 'B'], ['A'], ['B', 'C']]

gamescores = [[1.0, 5.0], [3.0], [2.0, 7.0, 3.0, 1.0, 6.0], [3.0], [5.0, 2.0, 3.0], [1.0], [9.0, 3.0], [2.0, 7.0],
              [3.0, 6.0, 8.0], [2.0], [7.0, 9.0]]

wd = defaultdict(float)

for players, scores in zip(games, gamescores):
    if len(players) == 1:
        continue
    total_sum = sum(scores)
    for player, score in zip(players, scores):
        wd[player] = wd[player] + score * len(scores) - total_sum

print(wd)

Result
defaultdict(<class 'float'>, {'A': -12.0, 'B': 32.0, 'C': -17.0, 'D': -14.0, 'E': 11.0})

Edit: Grouping based on last results
OP clarified that each competition affect the total score taking from the previous competition because the grouping changes.
In the example, scores: [1.0, 5.0], [3.0], [2.0, 7.0, 3.0, 1.0, 6.0], [3.0], [5.0, 2.0, 3.0], [1.0], [9.0, 3.0], teams: [a,b], [b], [a,b,c,d,e], [b], [a,b,c],
A scores as:

1st game: -4
2nd game:  0 (he was not participant)
3rd game: -6 (because at 5th game, only A, B, C are competing)

For that, we can pre-process the groups to make sure that only the competitors of next game are considered.
Pre-processing idea
That is just an example how to solve the issue using the pre-processing. Notice that is a backward thinking. Next game determines which competitors matter in terms of scoring. Therefore, the processing is done in reverse order.
def pre_process(games, gamescores):
    last_game = {}
    result = []
    for game in zip(reversed(games), reversed(gamescores)):
        game_dict = dict(zip(game[0], game[1]))
        if len(game[0]) == 1:
            result.append(game_dict)
            continue
        if len(last_game) != 0:
            union_set = set(game_dict.keys()).intersection(set(last_game.keys()))
            last_game = game_dict
            game_dict = {k: game_dict[k] for k in union_set}
        else:
            last_game = game_dict
        result.append(game_dict)
    return result

pairs = list(reversed(pre_process(games, gamescores)))
wd = defaultdict(float)
for game in pairs:
    players = list(game.keys())
    scores = [game[k] for k in players]
    if len(players) == 1:
        continue

    total_sum = sum(scores)
    for player, score in zip(players, scores):
        wd[player] += score * len(scores) - total_sum
    print(wd)


Get Users and related roles and show on View

partial is meant to be used when the class spans multiple files, not when the class is to be extended. If you want to use virtual there is no need to mark the class as partial unless it really does exist in multiple files (a bad design for the most part anyway, with few good uses). If you want to force the class to be inherited, use abstract instead of partial.

You can remove the default constructor (and the warning suppression) by using default values:

public class User
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<UserToRole> UserToRoles { get; set; } = new HashSet<UserToRole>();
}

It is now functionally the same but has less code to maintain.

Nullable properties can also be defined shorthand:

public class UserToRole
{
    [Key]
    public int Id { get; set; }
    [ForeignKey("Role")]
    public int? RoleId { get; set; }
    [ForeignKey("User")]
    public int? UserId { get; set; }

    public virtual Role Role { get; set; }
    public virtual User User { get; set; }
}

The int? is effectively the same as Nullable<int>, it is a little easier on the eyes without having to mentally parse generics.

The last comment is about your repo method. It could be shortened up a little bit:

public List<UserViewModel> GetUsers()
{
    return db.Users
        .Include(u => u.UserToRoles.Select(ur => ur.Role))
        .Select(u => new UserViewModel
        {
            UserName = u.Name,
            Roles = u.UserToRoles.Select(ur => ur.Role.Name)
        })
        .ToList();
}

Or, if you really want to shorten it up:

public List<UserViewModel> GetUsers() => db.Users
                                           .Include(u => u.UserToRoles.Select(ur => ur.Role))
                                           .Select(u => new UserViewModel
                                           {
                                               UserName = u.Name,
                                               Roles = u.UserToRoles.Select(ur => ur.Role.Name)
                                           }).ToList();

The only reason I would use the intermediate users variable in the method is to do debugging inside the method. You could add a breakpoint on the return users; line and debug the value. If you are confident in the operation of the query and the results, shortening it up helps with code maintenance.


Python address index +1 with list comprehension

EDIT: As pointed out by an anonymous user, my first version did not skip numbers that follow an even number of 13's.

Use an iterator. While you for loop over an iterator you can skip items with next.

def lucky_nums(nums):
    nums = iter(nums)
    for i in nums:
        if i == 13:
            while next(nums) == 13:
                pass
        else:
            yield i

print sum(lucky_nums([12,13,14,15]))


Tower of Hanoi Recursive Implementation using Python with OOP

Your code seems to be working and trying to use OOP is a nice touch.
Let's see what can be improved.

Style

There is an official standard Python style guide called PEP 8. This is a highly recommended reading. It gives guidelines to help writing code that is both readable and consistent. The Python community tries to follow these guidelines, more or less strictly (a key aspect of PEP 8 is that it provides guidelines and not strict rules to follow blindly).

It deals with various aspects of the code style: naming conventions, indentation convention, etc.

You'll find various tools to try to check whether your code is PEP 8 compliant and if is it not, to try and fix this:

pycodestyle package (formerly known as pep8) to check you code
pep8online to check your code with an online tool
autopep8 package to fix your code automatically
Also, this is also checked by various linters: pylint, pyflakes, flake8, etc.
There also a code formatter getting very popular in the Python communinity called Black.

In your case, various things can be modified: class names should start with an uppercase letter, whitespace can be improved, etc.

Docstring

There is also a document describing Docstring conventions called PEP 257.

The comments you've written on top of the functions definition could be used as the function docstring.

The Disk class

It seems like num is not needed. Thus, the whole class could be written:

class Disk:
    def __init__(self, size):
        self.size = size

Ultimately, we could try to see if such a class is needed at all.

Building disks

disk_num could be written in uppercase as it is a constant.

disks could be initialised using list comprehension:

# Generating disks of increasing size
DISK_NUM = 8
disks = [Disk(i) for i in range(DISK_NUM)]

Building rods

You could use keyword arguments to provide only the position value without the need to provide the disks value (and thus, rely on the default behavior). Another option could be to change the argument order to have the position first - by the way, maybe "name" would be better than "position" as it conveys better the fact that it is not an integer used for computation but just a string just for logging.

rods.append(Rod(position="Left"))
rods.append(Rod(position="Middle"))
rods.append(Rod(position="Right"))

We could once again use list comprehension to define the rods here:

# Generating rods
rods = [Rod(position=p) for p in ("Left", "Middle", "Right")]

Comparison to boolean

You don't need to write: if announce==True, you can simply write: if announce.

Rewrite logic in add_to_top

You could use elif to make the various cases easier to identify and remove a level of indentation in the second part of the function.

def add_to_top(self,current_disk,announce=True):
    """Add a disk to the top of a rod. Only allows in two conditions a. No disks currently on that rod b. Disk smaller than the disk below it."""
    if len(self.diskslist) == 0:
        if announce:
            print(f"on to the top of the {self.rod_position} Rod", end="\n")
        self.diskslist.insert(0,current_disk)
        return True
    elif current_disk.size < self.diskslist[-1].size:
        if announce:
            print(f"on to the top of the {self.rod_position} Rod", end="\n")
        self.diskslist.insert(0,current_disk)
        return True
    else:
        return False

It is now clearer that the 2 first cases are identical and can be merged:

def add_to_top(self,current_disk,announce=True):
    """Add a disk to the top of a rod. Only allows in two conditions a. No disks currently on that rod b. Disk smaller than the disk below it."""
    if (len(self.diskslist) == 0) or (current_disk.size < self.diskslist[-1].size):
        if announce:
            print(f"on to the top of the {self.rod_position} Rod", end="\n")
        self.diskslist.insert(0,current_disk)
        return True
    else:
        return False

Also, maybe you could throw an exception when the disk size is invalid instead of just returning False:

def add_to_top(self,current_disk,announce=True):
    """Add a disk to the top of a rod. Only allows in two conditions a. No disks currently on that rod b. Disk smaller than the disk below it."""
    if self.diskslist and current_disk.size >= self.diskslist[-1].size:
        raise Exception("Invalid disk size")

    if announce:
        print(f"on to the top of the {self.rod_position} Rod", end="\n")
    self.diskslist.insert(0,current_disk)

Reconsider the Rod initialisation

A disk list can be provided to the Rod initialisation.

Two things are a bit awkward here:

you are using Mutable Default Arguments which is a common Gotcha in Python
the provided list may be unsorted: if we really want to provide the list, maybe we should pass it through the add_to_top logic element by element or just check that it is sorted.

It may be easier to weaken the API by getting rid of it and default to [].

def __init__(self, name=""):
    self.diskslist = []
    self.rod_name = name

At this stage, the code looks like:

class Rod:
    move_count = 0

    def __init__(self, name=""):
        self.diskslist = []
        self.rod_name = name

    def remove_top(self):
        """Remove the top disk of a rod."""
        print(f"Move the disk of size {self.diskslist[0].size} from {self.rod_name} Rod ", end="")
        Rod.move_count += 1
        return self.diskslist.pop(0)

    def add_to_top(self,current_disk,announce=True):
        """Add a disk to the top of a rod. Only allows in two conditions a. No disks currently on that rod b. Disk smaller than the disk below it."""
        if self.diskslist and current_disk.size >= self.diskslist[-1].size:
            raise Exception("Invalid disk size")

        if announce:
            print(f"on to the top of the {self.rod_name} Rod", end="\n")
        self.diskslist.insert(0,current_disk)

class Disk:
    def __init__(self, size):
        self.size = size

def recursive_solve(current_rod, lower_range, target_rod):
    # If only moving the top disk, execute it
    if lower_range == 0:
        rods[target_rod].add_to_top(rods[current_rod].remove_top())
    # If not, keeping simplifying the recursion.
    else:
        alt_rod = 3 - current_rod - target_rod
        recursive_solve(current_rod, lower_range - 1, alt_rod)
        recursive_solve(current_rod, 0, target_rod)
        recursive_solve(alt_rod, lower_range - 1, target_rod)

# Generating disks of increasing size
DISK_NUM = 8
disks = [Disk(i) for i in range(DISK_NUM)]

# Generating rods
rods = [Rod(name=p) for p in ("Left", "Middle", "Right")]

# Attaching all disks to the left rod
for i in range(len(disks)):
    rods[0].add_to_top(disks[len(disks)-i-1],False)

print(f"The steps needed to move {DISK_NUM} pieces of disks are:")
recursive_solve(0,len(disks)-1,2)

for i in range(len(rods)):
    print(f'\n For rod number {i+1}:',end=" ")
    for j in range(len(rods[i].diskslist)):
        print(rods[i].diskslist[j].size,end=" ")

print(f'\n The number of moves taken in total is {Rod.move_count}')

Loop with the proper tools

I highly recommend Ned Batchelder's talk "Loop like a native". Basically, anytime you use something like for xxx in range(len(yyy)), there is a better way to do it. In your case, enumerate can help you as well to write:

# Attaching all disks to the left rod
for d in reversed(disks):
    rods[0].add_to_top(d, False)

print(f"The steps needed to move {DISK_NUM} pieces of disks are:")
recursive_solve(0,len(disks)-1,2)

for i, rod in enumerate(rods):
    print(f'\n For rod number {i+1}:',end=" ")
    for d in rod.diskslist:
        print(d.size,end=" ")

Also, we could consider that we can refer to rod by their name instead of their positions and thus get rid of positions altogether:

for rod in rods:
    print(f'\n For rod {rod.rod_name}:',end=" ")
    for d in rod.diskslist:
        print(d.size,end=" ")

The recursive_solve function

The fact that you access rods from the recursive_solve function seems a bit weird to me. It may be easier to provide the 3 rods to the function.

Also, providing the length of disks should not be necessary: in the best possible world, we could just rely on the number of disks on the starting rod.

I've performed a few changes to handle this, using an intermediate function:

def recursive_solve(start_rod, end_rod, third_rod, nb_disk_to_move):
    if nb_disk_to_move == 1:
        end_rod.add_to_top(start_rod.remove_top())
    # If not, keeping simplifying the recursion.
    else:
        recursive_solve(start_rod, third_rod, end_rod, nb_disk_to_move - 1)
        recursive_solve(start_rod, end_rod, third_rod, 1)
        recursive_solve(third_rod, end_rod, start_rod, nb_disk_to_move - 1)

def move(start_rod, end_rod, third_rod):
    nb_disk = len(start_rod.diskslist)
    print(f"The steps needed to move {nb_disk} pieces of disks are:")
    recursive_solve(start_rod, end_rod, third_rod, nb_disk)

...
move(rods[0], rods[2], rods[1])

Also, that removes the need for the disks variable:

# Attaching all disks to the left rod
for i in reversed(range(DISK_NUM)):
    rods[0].add_to_top(Disk(i), False)

move(rods[0], rods[2], rods[1])

Finally, the function can be slightly simplified:

def recursive_solve(start_rod, end_rod, third_rod, nb_disk_to_move):
    if nb_disk_to_move:
        recursive_solve(start_rod, third_rod, end_rod, nb_disk_to_move - 1)
        end_rod.add_to_top(start_rod.remove_top())
        recursive_solve(third_rod, end_rod, start_rod, nb_disk_to_move - 1)

More OOP

One of the principle of OOP is the encapsulation. In our case, disklist could be considered as an implementation detail which is best not to rely on. In order to print the content on a rod, we could write a __str__ magic method. Then, the calling code becomes much simpler:

    def __str__(self):
        return self.rod_name + ": " + " ".join(str(d.size) for d in self.diskslist)

for rod in rods:
    print(f' For rod {rod}')

At this stage, the code looks like:

class Rod:
    move_count = 0

    def __init__(self, name):
        self.diskslist = []
        self.rod_name = name

    def remove_top(self):
        """Remove the top disk of a rod."""
        print(f"Move the disk of size {self.diskslist[0].size} from {self.rod_name} Rod ", end="")
        Rod.move_count += 1
        return self.diskslist.pop(0)

    def add_to_top(self,current_disk,announce=True):
        """Add a disk to the top of a rod. Only allows in two conditions a. No disks currently on that rod b. Disk smaller than the disk below it."""
        if self.diskslist and current_disk.size >= self.diskslist[-1].size:
            raise Exception("Invalid disk size")

        if announce:
            print(f"on to the top of the {self.rod_name} Rod", end="\n")
        self.diskslist.insert(0,current_disk)

    def __str__(self):
        return self.rod_name + ": " + " ".join(str(d.size) for d in self.diskslist)

class Disk:
    def __init__(self, size):
        self.size = size

def recursive_solve(start_rod, end_rod, third_rod, nb_disk_to_move):
    if nb_disk_to_move:
        recursive_solve(start_rod, third_rod, end_rod, nb_disk_to_move - 1)
        end_rod.add_to_top(start_rod.remove_top())
        recursive_solve(third_rod, end_rod, start_rod, nb_disk_to_move - 1)

def move(start_rod, end_rod, third_rod):
    nb_disk = len(start_rod.diskslist)
    print(f"The steps needed to move {nb_disk} pieces of disks are:")
    recursive_solve(start_rod, end_rod, third_rod, nb_disk)

# Generating rods
rods = [Rod(name=p) for p in ("Left", "Middle", "Right")]

# Attaching all disks to the left rod
DISK_NUM = 8
for i in reversed(range(DISK_NUM)):
    rods[0].add_to_top(Disk(i), False)

move(rods[0], rods[2], rods[1])

for rod in rods:
    print(f' For rod {rod}')

print(f'\n The number of moves taken in total is {Rod.move_count}')

I have to stop here, I'll try to continue.


A Python script to plot data and save to PDF

coding style

Your code is almost pep-8 compliant. There are a few spaces missing after comma's, but all in all this is not too bad. I myself use black to take care of this formatting for me.

some of the variables names can be clearer. What does nc1 mean for example

magic numbers

The number 3, 2 and 6 are the number of rows and columns on the grid. Better would be to make them real variables, and replace 6 with rows * columns. If you ever decide you want 4 columns, you don't have to chase down all those magic numbers

looping

You are looping over the indexes of var and df. Better here would be to use zip to iterate over both tables together. If you want to group them per 6, you can use the grouper itertools recipe. and enumerate to get the index of the different subplots.

rows, columns = 3, 2

for group in grouper(zip(var1[1:], df1[1:]), rows * columns):
    fig = plt.figure(figsize=(11, 7))
    for i, (label, row) in enumerate(filter(None, group)):
        ax = fig.add_subplot(rows, columns, i + 1)
        ax.plot(df1[0], row, linestyle="-", color="black")
        ax.set(title=label, xlabel="seconds", ylabel="")

The filter(None,...) is to eliminate the items that get the fillvalue in the grouper

Is a lot clearer than the juggling with nc1 and j

functions

This would be a lot easier to test an handle if you would separate the different parts of the script into functions

reading the file
making 1 page plot
appending the different pages

This will also allow each of those parts to be tested separately

reading the file

Instead of loading the file twice  and using numpy, using pandas, which supports data with names and indices will simplify this part a lot

df = pd.read_csv(<filename>, sep="\s+", index_col=0)

this is a labelled DataFrame, so no more need to use var1  for the column names

making the individual plot:

group the columns per 6

def column_grouper(df, n):
    for i in range(0, df.shape[1], n):
        yield df.iloc[:, i:i+n]

this simple helper generator can group the data per 6 columns

make the plot

def generate_plots(df, rows=3, columns=2):
    for group in column_grouper(df, rows * columns):
        fig = plt.figure(figsize=(11, 7))
        for i, (label, column) in enumerate(group.items()):
            ax = fig.add_subplot(rows, columns,i + 1)
            ax.plot(column, linestyle='-', color='black')
            ax.set(title=label, xlabel='seconds', ylabel='')
        yield fig

saving the pdf

Here a simple method that accepts an iterable of figures and a filename will do the trick

def save_plots(figures, output_file):
    with PdfPages(output_file) as pdf:
        for fig in figures:
            pdf.savefig(fig)

pulling it together

def parse_file(input_file, output_file, rows=3, columns=2):
    df = pd.read_csv(input_file, sep="\s+", index_col=0)
    figures = generate_plots(df, rows, columns)
    save_plots(figures, output_file)

and then calling this behind a main guard

if __name__ == "__main__":
    input_files = ['file1.out', 'file2.out']
    output_file = 'file_output.pdf'

    for input_file in input_files:
        parse_file(input_file, output_file)

If this still is too slow, at least now the different parts of the program are split, and you can start looking what part of the program is slowing everything down


Find plane (walls, floor, ceiling) that a falling car will land on

Don't hardcode values
There are lots of magic values that you are using in your code, from the terminal velocity, the wall coordinates to the numbering of the walls. Try to give everything a name: declare constants for the coordinates and terminal velocity, and create an enum for the six faces of the enclosing box:
enum Face {
    FACE_RIGHT,
    FACE_LEFT,
    FACE_BACK,
    FACE_FRONT,
    FACE_TOP,
    FACE_BOTTOM,
};

static const double terminal_velocity = 2300;
static const double right_wall_position = 4080;
...

It's a little bit more typing, but there are several benefits. In particular, it makes the code more self-documenting. Consider the return type of find_landing_plane():
enum Face find_landing_plane(...) {
    ...
    if (l.x > right_wall_position)
        return FACE_RIGHT;
    ...
}

You also don't need to add a comment to this line anymore:
if (magnitude(v) < terminal_velocity)

Consider using arrays to avoid repetition
You could get rid of the repeated if-statements by treating the vector as an array, and also having an array to encode the positions of the planes. It would look like this:
static const double plane_positions[6] = {4080, -4080, 5110, -5110, 2030, 20};
...
enum Face find_landing_plane(Vector car_location, Vector *car_velocity, double *gravity)
{
    ...
    while (1)
    {
        // update l
        ...

        double *l_vec = &l.x;

        for (int i = 0; i < 6; i++) {
            if (i % 2 == 0 ? l_vec[i / 2] >= plane_positions[i] : l_vec[i / 2] <= plane_positions[i])
                return i;
        }
    }
}

However, I'm not sure it is all that better, as it uses a complex expression and no longer uses the enum values by name, making it harder to understand and easier to make mistakes.
Solve the problem analytically
Finding the plane the car hits by updating the position in a loop is inefficient. The problem can be solved analytically. The trajectory the car follows is a parabola up to the point the terminal velocity is reached. You can solve for time the parabola intersects each of the the six planes, and also solve for the time the terminal velocity is reached. If the earliest time found that is not in the past is a plane, you know that plane was hit first. If the earliest time is when the terminal velocity is reached, you then now that the rest of the trajectory is a straight line, so you can then do the even easier step of solving for the intersection of a straight line with six planes.
This is more code to write, although here you could also make an array with the parameters describing each of the six planes, and use a for-loop to check for the intersection with each of them. The advantage is that it should be much more efficient and much more precise (consider that you have a bias in your algorithm when the car hits very close to a corner).
Add a better description of the special exception
Why is fabs(l.y) > 5120 special? You commented that it is an exception, but that still doesn't tell me why. Why is it 5120 (consider making a constant for that as well), and why do you need to handle this case at all, when it looks like the rest of the code would handle that fine?


A PHP MVC controller to display a form and add an item to the database

If we talk about good practice then "Better not to do much in __constructor()".
Constructors are built to instantiate a class. They must not be overloaded with huge code. For providing variant functionalities, use methods instead. This is how to work in modules. For a specific kind of task, it is better to call the specific function instead of overloading the same method.

However, you can do so (and you are doing), but it is not a good approach.
Consider an example,

You have to perform 10 actions for a given event. You can do so in same function. But it would one day become much complex to add new functionalities in future. However if you are dividing the whole task in modules, you can and will be able to add new functionalities with no overhead. Also this makes your code:

General
Flexible
Easily understandable
Easily modifiable
Clean
Best practice

Also not all frameworks follow complete MVC but you can see in any one of them, separate functions and classes are there for specific task/action. This may cause to write more lines of code but since this is a good practice, almost all the developers follow the same mechanism.

However, it is user specific opinion. At last, you can do anything you want to do cos you are developing & may be this approach is somehow good in your context. Choice is yours.


Polyglot array_extend() function for Javascript and PHP

You may want to replace object key access notation with dot notation.

For example, instead of the following.

$object['keys']($elem);

Write this.

Object.keys($elem);

This works, because Object is interpreted as a constant, dot as concatenation, and keys($elem) as function call. Use of undefined constant doesn't warn if the code with it is not executed. Unknown functions don't error if they aren't called.


Printing out all possible combination of printable ASCII 7-bit characters to stdout

It can be smaller if you remove the pointless ascii array, like this:

int main(void){
    int i,j,x,y,z;
    i = j = x = y = z = 0x00;
    char result[] = {0x00,0x00,0x00,0x00,0x00,0x00};
    for (i=0x20; i<0x7e; i++){
        result[0] = i;
        for (j=0x20; j<0x7e; j++){
            result[1] = j;
            for (x=0x20; x<0x7e; x++){
                result[2] = x;
                for (y=0x20; y<0x7e; y++){
                    result[3] = y;
                    for (z=0x20; z<0x7e; z++){
                        result[4] = z;
                        printf("%s\n", result);
                    }
                }
            }
        }
    }
    printf("\nDone...\n");
    return 0;
}

And, it would seem logical that puts(result) should be faster than printf("%s\n", result), though the compiler might optimize both to the same thing anyway.


I like the second approach since it allows you to exit as soon as a false condition is reached and is simpler than the first.  I would offer one minor optimization, keep the check for isletter separate and only check for duplicate if isletter is true:

static bool IsIsogram(string str)
{
    //TRICK: HashSet<T>.Add(T) returns false if an item already exists in HashSet<T>,
    //otherwise returns true and add the character to the datastructure

    var charHash = new HashSet<char>();

    foreach (var ch in str.ToLower())
    {
        //check if the charHash.Add() returns false, if it does then terminate
        //as it means the character already exists
        if(char.IsLetter(ch))
        {
            if (!charHash.Add(ch))
                return false;
        }

    }
    return true; //otherwise return true
}


A simple bubble sort implementation in Java

Bug

On the array { 3, 1, 4, 5, 2 }, the result will be { 3, 1, 2, 4, 5 }. In order to fix this, in the inner for loop change

int comparisons = 1;

to

int comparisons = 0;

API

The Java coding conventions dictate that sorting routines are declared static, return nothing (have type void), and provide the version of the routine that can sort a particular subarray within an array.

Also, you might prefer to declare the constructor of BubbleSort as private, since that object does not do anything of interesting on its own.

Algorithm

Your algorithm runs always in \$\Theta(N^2)\$, whereas the actual bubble sort runs in \$\Theta(N)\$ on almost sorted input. Refer to the Wikipedia for pseudocode that is more adaptive.

Printing an integer array

Instead of

for (int iterations = 0; iterations < numbers.length; iterations++) {
    System.out.println(numbers[iterations]);
}

you can easily write

System.out.println(Arrays.toString(yourArray));

Hope that helps.


The attempt is quite good, you managed to elude the most critical faults. There are only rather minor and architectural nitpicks.

First of all, I don't know what does DataSanitizer to do here but it shouldn't be any part of a query builder. Data sanitization is tangential to data persistence and they have nothing in common. So it should be just taken away.

As of the query builder, there are two main problems

a potential vulnerability which I explained recently in the other answer. At the very least all identifiers must be formatted according to database rules.
select is unusable in the real life. Nobody have seen such a method in the wild, it lurks only in such educational builders. If you want a query builder for SELECT, then either create a real one, with distinct methods for each SQL clause, or stick to a free-form query() method. Trust me, SQL is a precious and powerful programming language, do not diminish it to a crippled gibberish.

Also

Looks like class variables beside $db are just for decoration, cause they never used in the code? And for the good, so just ditch them away.
consider implementing PSR-4 Autoload for your classes.
usually, the data format for such methods as insert and edit is like

'col1' => value1,
'col2' => value2,

so you have to provide only one array with data. However it has other drawbacks with security already explained above and so must be used with caution

All in all, I believe you would benefit from my article on the common mistakes in database wrappers even if yours is a query builder, not a wrapper.


Program to tell which if any of three numbers is in the middle

Well, first of all, consider adopting one of the myriad common indentation-styles and use it consistently.
Doing so will make your code far easier to read and write.
You should test whether you really got three numbers.
Currently, you don't, which leads to UB.
If in doubt, sort.

That eliminates an astonishing number of problems.
You aren't using anything from <math.h>, so don't include it.
exit(0); and return 0; have nearly the same effect when done in main.
The only differences are when main is called recursively, and we won't do such an abomination outside the IOCCC. (Or if we change to a different language, like C++, but who would do that?)

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

typedef struct namednumber {int num; char name; } namednumber;

static int comp_namednumber(const void* pa, const void* pb) {
    int a = ((namednumber*)pa)->num,
        b = ((namednumber*)pb)->num;
    return (a > b) - (a < b);
}

int main() { // No need for void in the parameter-list, this is a definition
    int a, b, c;
    printf("Please enter three numbers:\n");
    if(3 != scanf("%i %i %i", &a, &b, &c)) {
        printf("You didn't enter three numbers. Aborting.\n");
        return EXIT_FAILURE;
    }

    if(a == b || b == c || c == a) {
        printf("There is no gap.");
        return 0;
    }

    namednumber data[] = {{a,'a'},{b,'b'},{c,'c'}};
    qsort(data, 3, sizeof *data, comp_namednumber);
    printf("%c is between %c and %c\n", data[1].name, data[0].name, data[2].name);

    return 0; // This line is implicit in C99+
}

Actually, getting out qsort is severe overkill, so here with a standard sorting-network:

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

static void sort2(int* a, char* na, int* b, char* nb) {
    if(*a < *b) return;
    int t = *a;
    *a = *b;
    *b = t;
    char nt = *na;
    *na = *nb;
    *nb = nt;
}

int main() {
    int a, b, c;
    printf("Please enter three numbers:\n");
    if(3 != scanf("%i %i %i", &a, &b, &c)) {
        printf("You didn't enter three numbers. Aborting.\n");
        return EXIT_FAILURE;
    }

    if(a == b || b == c || c == a) {
        printf("There is no gap.");
        return 0;
    }

    char na = 'a', nb = 'b', nc = 'c';
    sort2(&a, &na, &b, &nb);
    sort2(&a, &na, &c, &nc);
    sort2(&b, &nb, &c, &nc);
    printf("%c is between %c and %c\n", nb, na, nc);
}


Filtering by value X from array Y with a fallback

Edit:

  You code is over complex knowing there are some really good built in php functions to filter an array.

I think that is where the 'special hardcore dev' started disliking your code. Here an example that uses an anonymous function and array_filter. It also does the same as in the other answer. Loop over the $types instead of the tags. I think it is safe to say that there will be more tags then types.

function filterTagsByType($tags, $types, $count = 1)
{
    $tagFilter = function($type) {
        return function($tag) use($type) {
            return $tag->type == $type;
        };
    };

    foreach ($types as $type) {
        $filteredTags = array_filter($tags, $tagFilter($type));
        if ( count($filteredTags) > 0 ) {
            return $filteredTags;
        }
    }

    return array();
}

You should ofcourse still add the count check. this is easy with array_slice:

return array_slice($filteredTags, 0, $count);

Not sure how this is performance wise, but it shouldn't be an issue.


Singletons are evil
Even if you do want to use it, use Lazy<T> instead of manually doing double-checked locking

Best solution would be to leverage IoC container to inject dependencies you need.


Verifying private class members in Unit Testing

how can I test Reset function? I can call this function, but I can't review its result. Specially with the Option 2 where I don't have any references to this Array.

You always test only public APIs so you need to verify the results of the many public functions whether they behave they way you expect them after resetting the table.

They are your contract and their expected results you need to verify.

  Is the option 2 better way to go? (although in that case, there's no way to test it

There is, the public APIs. If the initialization didn't work correctly you will get invalid results from them.

  I don't have any references to this Array

This is an internal detail that could change at any time. You don't test it. You test the public contract that you usually must not change.


Changing the where to a let allows you to skip passing the secret. Passing guesses in and messages out purifies the control flow part of the program. zip [1..] makes clear: The number of tries during each step does not depend on the control flow. interact, lines and foldr replace the recursion. (Recursion is too powerful for brains to handle in general, so we should avoid it when we have a simpler tool.) Your mileage may vary on any of these suggestions.

secret <- randomRIO (smallest, biggest) :: IO Integer
let foo :: (Integer, Integer) -> String -> String
    foo (tries, guess) = case compare guess secret of
      LT -> (++) "Too small!\n"
      GT -> (++) "Too big!\n"
      EQ -> const $ printf "You found the number in %d tries!\n" tries
printf "Find the number between %d and %d.\n" smallest biggest
interact $ foldr foo undefined . zip [1..] . map read . lines


Given the main added value in this class is a sort of error handler, I would suggest to make a little addition to your connection code that will make mysqli  report errors by itself, which will make your class pretty much obsoleted.

Just add the following line before new mysqli...

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

and you won't need to do things like echo $mysqli->error anymore simply because mysqli will do everything you wrote here by hand.

Which means that you will perfectly do with vanilla mysqli:

$query = "SELECT * FROM `posts` WHERE `ID` = ? AND `author` = ?";
$stmt = $DB->prepare($query);
$stmt->bind_param("ss", $ID, $author);

$ID = 1;
$author = 'Admin';
$results = $stmt->get_result();

$ID = 2;
$author = 'Admin';
$results = $stmt->get_result();
$stmt->close();

and there is even get_result_array() available in mysqli out of the box:

$query = "SELECT * FROM `posts` WHERE `author` = ?";
$stmt = $DB->prepare($query);
$stmt->bind_param("s", $author);
$results = $stmt->get_result()->fetch_all();
                                ^^^^^^^^^ notice this part

What I would do if I would decide to create a prepared statement shortcut class, is a method that accepts both query and parameters executes them together, like

$query = "SELECT * FROM `posts` WHERE `ID` = ? AND `author` = ?";
$results = DB::run($query, [$ID, $author])->get_result()->fetch_all();

such a function I would call a shortcut


Interface

The parameters passed to the function are not orthogonal; they are subject to a number of restrictions, such as

length == len(numbers)
length == len(str(target))
target is composed of precisely the elements of numbers

If any restriction is violated, the function fails with an exception, or produces the wrong result. You may want to validate the input, or revise the interface to infer as much as possible from as little as necessary.

For example, it is reasonable to assume that length is len(numbers), and don't pass it at all. It is also reasonable to assume that target is well formed, and infer the alphabet from it.

By passing target as an integer you severely restrict the utility of a function. I highly recommend to pass it as a list of (comparable) elements.

Efficiency

First obvious inefficiency is recalculation of factorial, which drives the complexity quadratic by length. I recommend precompute factor = factorial(length) before the loop, and do

    factor /= length
    ind += factor * times
    length -= 1

to reduce the complexity to linear.

Second, extraction of leading digit also involves heavyweight computations. Even if the target is passed as integer, you'd be better off by converting it to an iterable, e.g.

    target = str(target)

and access individual digits positionally. And let me reiterate, it is better to pass target as iterable in the first place.


Some nitpicking:

/// <summary>
/// Performs a comparison of two identical sized byte arrays.
/// Performs in constant time to prevent timing/side channel attacks
/// </summary>

This does not answer arguably the main question one would have: what does it mean for one array to be "larger" than another, when both have equal size? Do you compare sums of the elements? Do you compare first non-equal pair of elements (looks like this one is correct)? Do you use some other even less obvious criteria? You should explain this in above documentation, so it is not necessary to read through obscure boolean logic in order to get the answer.

public int CompareConstantTime(byte[] bytesA, byte[] bytesB)

This method should probably be refactored into static extension method, so it is easier to re-use if needed.

public static int ConstantTimeCompareTo(this byte[] bytes, byte[] otherBytes)

throw new ArgumentOutOfRangeException("byte length must be equal");

There is no range per se at this point. I think base ArgumentException is a better fit.


The best solution I have for this. If my understanding is good, this is a fairly simple to solve and you do not need anything else than a set.

There might be a better way than rebuilding entirely the set.

words = ['foo', 'foog', 'food', 'asdf']
prefixes = set()

for w in words:
    if any(p for p in prefixes if w.startswith(p)):
        # A prefix exists in the prefixes set.
        continue

    # Re-build the set with all elements not matching the set.
    prefixes = set(p for p in prefixes if not p.startswith(w))
    prefixes.add(w)

print(prefixes)


Square root calculation with Newton's method

Somewhere between primitive recursion and grossly clever one-liners we can find a happy medium using functions from the Prelude.

To start though I'll look at the cosmetic. Immediately I'm confused by name and signature of the function, the square root is a function of a single number, not two. It's confusing for your function to be named sqrt' when typically the tick mark is used in Haskell to distinguish strict functions from lazy ones, or to name successive iterations on some value. When you're browsing your Haddock documentation later or coming back to this code in three years you'll be stupefied by sqrt', but probably have a pretty good idea what refineSqrtGuess might do.

Next, I would rewrite the function so that x isn't copied around everywhere. Since its value doesn't change, make that clear.

refineSqrtGuess :: Double -> Double -> Double
refineSqrtGuess x = refine
  where
      refine guess
        | guessIsGoodEnough = guess
        | otherwise         = refine improvedGuess
        where
          -- Test the precision of the guess
          precision          = 0.001
          guessIsGoodEnough  = abs (guess * guess - x) < precision * x
          -- Improve our guessed square
          improvedGuess      = (guess + x / guess) / 2

Also those comments are unnecessary, I think it's fairly clear from your descriptive names what's going on.

Alright now for the fun stuff. Let's begin by identifying the individual components of what your function is doing.

It's applying a mathematical function to a value.
It's producing a sequence by applying that function recursively.
It's choosing the first value from that sequence which matches a predicate.

Your function is a very imperative, monolithic implementation of those three components, but in Haskell-land composition is king. Let's try tackling each separately and see how they can be composed.

Number one is easy since we already know the math we're going to be doing, just roll up the improvedGuess value into a function.

next :: Double -> Double -> Double
next x guess = (guess + x / guess) / 2

Number two requires we know a bit about creating sequences in Haskell, which of course are usually lists, so we can take a look at the documentation for Data.List. As it turns out there's a function that repeatedly applies a function f to a value x for us, iterate. Here's how we'd use it.

guesses :: Double -> Double -> [Double]
guesses x initial = iterate (next x) initial

Now the third bullet on my list should really be broken in two, one bullet point for the predicate, and another for searching the sequence with it. But that's alright of course, our personal design documents don't have to be perfect from the get-go to be useful.

The predicate is of course the guessIsGoodEnough value, expressed as a function.

acceptGuess :: Double -> Double -> Bool
acceptGuess x guess = abs (guess * guess - x) < precision * x
    where precision = 0.001

And if we look back at the documentation for Data.List, sure enough under the section heading "Searching with a predicate" find looks like it does what we want, just note that it returns a Maybe a value. This is of course because the predicate we provide might not match any element of the given list, which now obligates me to point out that you should always code defensively and consider the totality of your functions on any given input. I'll address some concerns in iterations on my solution but here's how we'd put it all together.

import Data.List (find)
import Data.Maybe (fromJust)

refineSqrtGuess :: Double -> Double -> Double
refineSqrtGuess x initial = fromJust $ find (acceptGuess x) (guesses x initial)

By using higher order functions to handle the iterative and recursive aspects of the problem, we end up with a solution that almost reads like prose.

Appendix: Edge Cases & Errors

There's a lot that could go in this section, so I'll just point out a few things so this doesn't get tedious.

fromJust should be avoided, it isn't total and if we did call it on a Nothing value we'd get a big fat *** Exception: .... Consider changing the signature of the function to return a Maybe Double.

This could happen if we changed our code to not produce an infinite list of guesses (guesses x initial = take 500 $ iterate ...). What if precision was changed to 0 by another programmer (or future you) or floating point math throws you a curveball?

Appendix: Two-liner

After writing your function in terms of higher order functions it's usually trivial to then turn it into a one-liner, just inline all of the function calls. In this particular case we've got a two-liner unless your terminal happens to be very wide.

refineSqrtGuess :: Double -> Double -> Maybe Double
refineSqrtGuess x initial = find (\guess -> abs (guess^2 - x) < 0.001 * x)
                          $ iterate (\guess -> (guess + x / guess) / 2) initial

I wouldn't use that version, I think it's a little opaque with all of that inlined math. But I would definitely use this one.

refineSqrtGuess :: Double -> Double -> Maybe Double
refineSqrtGuess x initial = find withinPrecision $ iterate newtons initial
    where
          withinPrecision guess = abs (guess^2 - x) < 0.001 * x
          newtons guess = (guess + x / guess) / 2


Median of two sorted equal sized arrays on combination

Short Review

I have spent some hours trying to understand what you do, and why. Given the mess I made of the previous posting of this question, I thought I should spend extra effort to get this one right.

I have failed. I cannot understand the full intent of your code, and, even though it appears to work, I have this nagging feeling that some well-constructed uses cases will cause the code to fail - you have too many edge-case conditions in the code which are not documented, and not contextualized enough to ascertain whether they work, or what conditions they are supposed to handle.

Bottom line is that your program is not understandable in a reasonable amount of time, and it was your responsibility to make your code understandable, not the reviewer's responsibility to decode your system. Just because you may have your solution 'straight' in your head, it does not mean that you have expressed it well in the code. You have to write and document the code so that someone who has only just seen the problem can understand it and the solution with 'reasonable' effort. In this case, I don't believe you have succeeded.

Longer Review

In a 'real' review there is no "reference implementation" to compare against. All there is, is a specification. In this case, the specification is to identify the median (middle value, or average of middle-pair if the data-set is even-sized). In addition to the expected result, the data is assumed to be in two equal-sized arrays of sorted data.

Given those specifications you can also make a couple of assumptions:

the ending-dataset will always have an even number of elements (2 * x is always even for any integral value x), which means we will always be doing some form of average.
There will always be n-1 values smaller than the smaller of the mid-point-pair, and n-1 values larger than the higher of the mid-point-pair.

OK, based on those specifications and assumptions, we can review the code, and see how it solves the problem.

First thing I note is that there are two variables which have names that don't seem to relate to any feature of the problem space, lb and hb. There is no comment to indicate what these variables are, so the only choice is to inspect the code to see how it is used. This means we have to trust that the code is doing the right thing just so we can understand what the intended use of the variable is.

This is a bad practice, and is solved by using self-documenting variable names. This has been pointed out to you before. You need to start improving your code-style.
When I try to track down what lb and hb are supposed to be, I find that they are used as a loop condition, which does not help us in this case because the loop condition is not documented. They are also used to calculate the variables a1Median and a2Median. Unfortunately, a1Median, although it is a descriptive name, does not mean what it says it means.... it is not the Median of array a1. It starts off being the approximate midpoint of a1 (the median is the value at the midpoint, not the position of the midpoint), but then, to make things worse, the a1Median is modified in each loop! So, this descriptive variable name has the completely wrong description. This is worse than having a non-descriptive name because, now the person reading the code has to keep remembering that "a1Median is not the median of array a1"!

At this point, in any 'serious' review, you would be facing a lot of criticism. There are times when it is OK for code to be hard to read... but that is only when the problem is very complicated. What you have here is unnecessarily hard to read.

OK, after some study (and I literally mean some serious head-scratching, debugging, and paper-worked examples), I think I can see your algorithm.....

set up lb and hb (still not sure what those are supposed to stand for - low-something and high-something ?) as pointers in to the first array.
we will manipulate these high and low pointers to select a 'candidate' value in the first array.
we then use the candidate point in the first array and calculate a candidate point in the second array. The second array's candidate is always going to be where there are n-1 values smaller/larger than the two candidate positions. If our candidate in array1 is x then the candidate in array2 will be array2 - x - 1 which would satisfy the midpoint-pair condition.
if the values at these candidate positions are in fact the midpoints, then we can return a success.
if we have a success, we do not actually know if the candidate values are in fact the actual pair, all we know is that one of the candidates is the midpoint. The other candidate may not be part of the solution if we have two of the same values on our side... in which case both of the candidates need to come from one array.
if we do not have a success, we essentually do a 'bifurcation' of the data to do a binary search-style partitioning of the data to look for a candidate.

So, your algorithm has this isMedian() method. Unfortunately, this method re-uses two already bad variable names as parameters. We now have a different a1 and a2, which are not the same as the a1 and a2 in the calling method, because sometimes the calling method swaps the order of these.... Still, this method returns true under conditions which make no apparent sense. Why is there a median when pos == 0 ? That seems pretty arbitrary.

This same problem exists in the untangling method calculateMedian(). a1 and a2 which are not the same as before.

Speaking of untangling, why do you need to untangle? You should not get in to a tangle to start with!

Right, so you have an apparent algorithm, but there are still blanks in what it should be doing, or how it gets it done.

At this point I cheated, and looked at the sample code in the problem description, and your system does none of the algorithms.

The first sample algorithm uses naive searching for the median points. Your algorithm does not match that.

The second algorithm uses a reduction-to-size-2 system, and then does a Min/Max formula to get the final result. You do not do this either.

The final algorithm uses recursion and bifurcation. You do not do recursion.

Bottom line is that you are using an algorithm that is hard to read, not comparable to reference systems, and, in the long run, is not much fun to review.

Since I do these reviews for my (twisted) satisfaction as well, I can't say that this one was worth it.

Your opening request is:

  I'm looking for code review, clever optimizations, adherence to best practices. etc.

The problem-page you pulled this question from does a perfectly fine job of presenting good code (albeit in C), clever optimizations (that are reproducible in Java quite easily), and the best practices shown there are not great given that it is for C and not Java, but certainly consistent and readable. You have taken those suggestions and ruined them.

Code Review is for reviewing code. I have had to resort to debugging your code just to get a sense of what it does. This is not where code should be when you present it for review.


Functions

Split the code into functions, also split the generation and the presentation. Your algorithm has some clear distinct tasks, so split along these lines:

read input
assemble chain
construct new poem
output

This way, you can reuse parts of the code, save intermediary results and test the parts individually.

generators

instead of keeping all the intermediary lists in memory, generators can be a lot more memory efficient. I try to use them as much as possible. substantiating them to a list or dict when needed is easy.

read the input

There is no need to assemble the intermediary list in ''.join([i for i in poems if not i.isdigit()]). join is perfectly capable of handling any iterable, so also a generator expression.

use the with statement to open files:

def read_input(filename):
    """reads `file`, yields the consecutive words"""
    with open(filename, 'r') as file:
        for line in file:
            for word in line.split(''):
                if word and not word.isdigit():
                    yield word

with regular expressions, and by hoisting the IO, you can ease this method even more:

def read_input_re(file):
    pattern = re.compile("[a-zA-Z][a-zA-Z']+")
    for line in file:
        for word in pattern.finditer(line):
            yield word.group()

which then can be called with a file:

def read_file(filename):
    with open(filename, 'r') as file:
        return read_input_re(file)

or with any iterable that yields strings as argument. For example if poem holds a multi-line string with a poem:words = read_input_re(poem.split('\n'))

This refactoring also makes loading the different poems from different textfiles almost trivial:

filenames = ['file1.txt', 'file2.txt', ...]
parsed_files = (read_file(filename) for filename in filenames)
words = itertools.chain.from_iterable(parsed_files)

If you want all the words in the chain lowercase, so FROM and from are marked as the same word, just add

words = map(str.lower, words)

assemble the chain

Here a collections.defaultdict(list) is the natural datastructure to for the chain.

Instead of using hard indexing to get the subsequent words, which is impossible to do with a generator, you can do it like this:

def assemble_chain(words):
    chain = defaultdict(list)
    try:
        word, following = next(words), next(words)
        while True:
            chain[word].append(following)
            word, following = following, next(words)
    except StopIteration:
        return chain

or using some of itertools' useful functions:

from itertools import tee, islice

def assemble_chain_itertools(words):
    chain = defaultdict(list)
    words, followings = tee(words, 2)
    for word, following in zip(words, islice(followings, 1, None)):
        chain[word].append(following)
    return chain

Or even using a deque:

from collections import deque
def assemble_chain_deque(words):
    chain = defaultdict(list)
    queue = deque(islice(words, 1), maxlen=2)
    for new_word in words:
        queue.append(new_word)
        word, following = queue
        chain[word].append(following)
    return chain

whichever is more clear is a matter of habit and experience, If performance is important, you will need to time them.

create the poem

Since you will be asking for a new word a lot, it can pay to extract it to its own function:

def get_random_word(choices):
    return random.choice(list(choices))

Then you can make an endless generator yielding subsequent words:

def generate_words(chain):
    word = get_random_word(chain)
    while True:
        yield word
        if word in chain:
            word = get_random_word(chain[word])
        else:
            word = get_random_word(chain)

We then us islice to gather the number of words we need, which then can be pasted together with ' '.join()

length = 10
poem = islice(generate_words(chain), length)
poem = ' '.join(poem)

"be tatter'd we desire famine where all eating ask'd where"

Once you have that, making a poem of a number of lines with set length is also easy:

def construct_poem(chain, lines, line_length):
    for _ in range(lines):
        yield ' '.join(islice(generate_words(chain), line_length))

lines = construct_poem(chain, 4, 10)
lines = map(str.capitalize, lines)
print('\n'.join(lines))

Be tatter'd we desire famine where all eating ask'd where
Deep trenches that thereby the riper substantial fuel shall beseige
Treasure of small pity the riper eyes were to the
Foe to the riper by time spring within and make

I think it makes sense to do the capitalization after the line has been assembled. Yet another separation of generation and presentation:

def construct_poem2(chain, line_lengths):
    for line_length in line_lengths:
        yield ' '.join(islice(generate_words(chain), line_length))

line_lengths = [10, 8, 8, 10]
lines = construct_poem2(chain, line_lengths)
lines = map(str.capitalize, lines)
print('\n'.join(lines))

Be tatter'd we desire famine where all eating ask'd where
Deep trenches that thereby the riper substantial fuel
Shall beseige treasure of small pity the riper
Eyes were to the riper memory but eyes were to


Count occurrences of date-time in large CSV

Syntax

Your code does not have valid Python syntax.
The first closing parentheses in this line should not be there:

with open('WaypointCount.csv'),'w', newline='') as output: #saves to csv

Improvements

Use if __name__ == '__main__'

If you run script code, enclose it within an if block checking for __main__:

if __name__ == '__main__':
    <your_code_here>

LBYL vs. default dicts

The check statement

if row_date in dates:
    dates[row_date] += 1
else:  #If date not in dictionary add entry
    dates[row_date] = 1

can be optimzed using a collections.defaultdict:

from collections import defaultdict

dates = defaultdict(int)

dates[row_date] += 1

The defaultdict will automatically initialize a non-existant key's value with 0, by calling the provided factory int without parameters iff the requested key does not exist.

Dict key and value sorting

The line

rows = zip([k for k in sorted(dates)],[dates[k] for k in sorted(dates)])

seems quite cumbersome to me.
You iterate and sort the dict twice and then zip the keys and values.
I suggest changing that to:

with open('WaypointCount.csv','w', newline='') as output: #saves to csv
    wr = csv.writer(output)
    for row in sorted(dates.items()):
        wr.writerow(row)

Use fitting datatypes

In the line

row_date = row_date.strftime("%Y-%m-%d %H:00:00") #Strips minute and below info

You already convert the datetime back to a str although you later will sort by it.
While this should have the same beaviour iff the datetime string is in ISO format, you may want to store the actual datetime value instead of the string representation and later convert it into the desired output format.

with open('WaypointCount.csv','w', newline='') as output: #saves to csv
    wr = csv.writer(output)
    for timestamp, occurences in sorted(dict.items()):
        timestamp_str = timestamp.strftime("%Y-%m-%d %H:00:00")
        wr.writerow((timestamp_str, occurences))

PEP8

Last, but not least, consider PEP8.
Espacially your variable naming and line length.


Some improvements:

Try to minimize all mutable state and side effecting methods to single places. Don't divide them through the whole program.
Scala is object oriented. Therefore use methods of the objects you want to work with instead of global functions.
use methods with an empty parameter list only if these methods has side effects.
search the API for methods you can work with.

That's what I came up with:

object Game {

  import util.Random

  val rand: Random = new Random
  val mutations: Seq[Int => Int] = Seq(x => x, x => x + x, x => x * x)

  case class Cell(f: Int => Int, value: Int) {
    def mutate = {
      def nextMutation: Int => Int =
        mutations(((mutations indexOf f) + 1) % mutations.size)
      Cell(nextMutation, f(value))
    }

    override def toString = "["+value+"]"
  }

  case class Breed(generation: Int, cells: Seq[Cell]) {
    def mutate: Breed =
      Breed(generation + 1, cells map { _.mutate })

    override def toString: String =
      "BREED: ["+generation+"] = "+cells.mkString
  }

  def makeCells(num: Int) = {
    def randomMutation =
      mutations(rand nextInt mutations.size)

    def makeCell =
      Cell(randomMutation, (rand nextInt 10))

    (Seq fill num) { makeCell }
  }

  def test() {
    val firstBreed = Breed(0, makeCells(10))
    val breeds = ((1 to 10).iterator scanLeft firstBreed) {
      (b, _) => b.mutate
    }
    printBreeds(breeds)
  }

  def printBreeds(breeds: Iterator[Breed]) {
    (breeds sliding 2) foreach {
      case Seq(b, mutated) =>
        println("BREED: size="+b.cells.size)
        println(b+" ---> "+mutated)
    }
  }

}


Iterate over a list of list names as file names

As you already noticed you have repeated code. you have variable names for your lists and also string definitions for list names which most probably should match. while this is no big problem for just 3 lists it could get cumbersome on adding another list. A simple way to avoid such name-to-string matching edits is to hold such variables in a dict() and have the string definition only.

The second problem is to have different iterables which must match in length and order to be zipped lateron. Avoid this by holding tuples (or other containers) in a single iterable from the beginning. key-value pairs in a dict() also provide this binding.

I your case I'd recommend to use the strings as keys

#avoid named variables
lists = {name:[] for name in ('singles', 'multiples' , 'zeros')}

#access lists via name
lists['singles'].append(0)

#access via temporary
l = lists['singles']
l.append[0]

#iterate for saving
for s, l in lists.items():
    writelist(list=l, fname=s + '.csv')

EDIT:

Above answer applies to the first version of code where all that list init was skipped. While all still valid this can now be applied to the real code. concise and following the KISS principle. Names could be improved but are left here for outlining changes only.

lists = {name:[] for name in ('singles', 'multiples' , 'zeros')}

for row in df.itertuples():
    query = best_q(row)
    hits, uri = ask_rkd(query)
    if hits == 0:
        query = bracket_q(row)
        hits, uri = ask_rkd(query)

    if hits == 1:
        lists['singles'].append([row.priref, row.name, hits, uri])
    elif hits > 1:
        lists['multiples'].append([row.priref, row.name, hits])
    elif hits == 0:
        lists['zeroes'].append([row.priref, str(row.name)])  # PM: str!!

for s, l in lists.items():
    listfile = '{}_{}.csv'.format(input_fname, s)
    writelist(list=l, fname=listfile)

outfile = fname + '_out' + ext
df.to_csv(outfile, sep='|', encoding='utf-8-sig')


I'm still a bit fuzzy on how to compute latency, but using iaca v2.2, it reports your code as:

Block Throughput: 10.65 Cycles
Throughput Bottleneck: Dependency chains

I'm calling that "the number to beat."

A brief fiddle with your code gives me:

xor eax, eax
xor r10d, r10d

mov r9d, [r8]   ; read the value
btr r9d, edx    ; read and clear the edx bit

setc al         ; convert cf to bit
shl eax, cl     ; shift bit to ecx position

btr r9d, ecx    ; read and clear the ecx bit

mov ecx, edx    ; need edx in ecx for shift
setc r10b       ; convert cf to bit
shl r10d, cl    ; shift bit to edx position

or r9d, eax     ; copy in old edx bit
or r9d, r10d    ; copy in old ecx bit

mov [r8], r9d   ; store result

Which iaca describes as:

Block Throughput: 4.30 Cycles
Throughput Bottleneck: FrontEnd

That's the best I can do for the moment.

Update: Actually, I can do a bit (haha) better:

xor eax, eax        ; build a mask using both bits
bts eax, ecx
bts eax, edx

mov r9d, [r8]       ; read the value
mov r10d, r9d       ; copy the value

and r10d, eax       ; and out the 2 bits we are looking for
jpe done            ; if neither or both bits are set, we're done

xor r9d, eax        ; swap the bits
mov [r8], r9d       ; store the result

done:

jpe is a relatively uncommon instruction which means 'jump parity even.'  Parity is set by the and to indicate the parity of the result.  Parity 'even' means that an even number of bits are set (0 is even).  If an even number of bits are set, then either both bits were zero, or both bits were 1.  In either case, swapping will have no effect since the bits are the same.

iaca v2.3 rates this as:

Block Throughput: 2.00 Cycles
Throughput Bottleneck: FrontEnd

FYI: If you change this api such that the parameter is a mask containing the 2 bits to swap instead of 2 discrete parameters, the time drops to 1.24.  Not knowing the details of the caller, I'm not sure how practical that is.  If you are really working with 2 different computed values for your bit positions, moving this work up to the caller doesn't buy you anything (in fact it probably makes things worse).  But it's something to think about.

So, we started with 10.64 (OP's code).  First cut dropped that to 4.3.  Using BMI2 instructions, I dropped it to 3.  Now using common instructions again, we're down to 2.00 (with a chance at 1.24).

I'm pretty sure I'm done now.  Pretty sure.

Update 2: <sigh>

xor eax, eax        ; build a mask using both bits
bts eax, ecx
bts eax, edx

test [r8], eax      ; compute parity
jpe done            ; if neither or both bits are set, we're done

xor [r8], eax       ; swap the bits

done:

While I might think that loading r8 into a register, testing it, modifying it and then writing it back would be faster, iaca doesn't see it that way.  I'd probably have to test it to be sure.  I'll leave that as an exercise for the student.  Still, this gives us:

Block Throughput: 1.50 Cycles
Throughput Bottleneck: FrontEnd

If this thing gets any faster, it's going to start giving cycles back...

As OP has pointed out, the JPE that I used above only works for bits in the first byte.  Oops.

So, this is my next best:

xor r9d, r9d    ; build mask
bts r9d, ecx
bts r9d, edx

mov r10d, r9d   ; duplicate mask

and r9d, [r8]   ; Load the bits
jz done         ; neither bit set

cmp r9d, r10d   ; Both bits set?
je done

xor [r8], r10d  ; Swap the bits

done:

It's not the 1.5 I was getting above, but it's a respectable 2.00.  Still a pretty good improvement from the 10.65 we started with.

There are some things that might be worth trying when you roll this back into your original code.  While iaca is useful for counting latency, nothing beats real life tests.

I was a little bit iffy about the two jumps, but iaca doesn't much care for replacing them with cmovxx.
Seems like loading the value into a register instead of anding directly from memory, then using that register instead of xoring back into memory should have been a win.
And as I've mentioned below, writing this in C instead of asm might also be a win (nb: MSVC's _bittestandset doesn't optimize well, so creativity may be required).  However since this post was about asm, that's what I'm limiting myself to.

One last point:

Since this code has now gone from 'small' to 'trivial,' I'd suggest re-visiting the decision to write it in assembler.  While I doubt that a C compiler will end up using the jpe instruction, it seems likely it could do a credible job of producing code using basically this approach.

And let's not forget that there are costs associated with calling assembly code from C:

7 very valuable and scarce registers (rax, rcx, rdx, r8-r11) are assumed changed by the code (even if the asm never actually uses them).  Avoiding/spilling these has performance implications for the code making the call.
The stack must be set up/torn down (even though this code never uses the stack, by spec room must always be allocated for the first 4 parameters).
The actual call and ret statements must be executed, while an optimizer might well inline a C routine.
There is no chance that the C optimizer can interleave instructions from the surrounding code to take advantage of available ports/microfusing, or can improve the code based on compile time constant values.

Given all this, I'd expect that writing this in C using intrinsics (ie _bittestandset) would turn out to be a net win despite the fact that it might use a (slightly) less optimal set of instructions (assuming it doesn't figure out a way to do it even better).

I'm struggling with myself to NOT do this here, since it is clearly a separate question.  No wonder I can't rack up any karma.


Your concept is an interesting one, but it has a number of concerns in it.

The most significant issue I can see is related to the errors that can be returned. There's no way to match an error to the function that caused it.

Other concerns are that your error channel is unbuffered, which could potentially leave go-routines unnecessarily hanging around waiting for the channel to be drained.

Still, even if that's OK, there's still a usability issue. My concern here is about the requirement to manage a relatively sensitive life-cycle outside the Pool code. Your user has to know that they create a new Pool, then Run a few items, and then Wait. The order cannot be changed, and you cannot reuse a pool after Waiting for it.

My feeling is that you could use a much simpler mechanism of having a single mechanism that "does it all". The user's code would look something like:

toRun := []func() error{}
toRun = append(toRun, func() error{fmt.Println("one"); return nil});
....
errors := pool.Run(toRun...)

There's no notion in the above of the internal implementation of the pool. That's a good thing. You use basic Go mechanisms like slices to aggregate functions to run, and you use basic go parameter manipulation to expand the slice for entry.

I played around a bit, and settled on this function:

// Run will run all the supplied functions in separate Go-routines, and return any errors in the resulting slice,
// and also return a boolen ok indicator which will be true if all goroutines succeeded.
func Run(toRun ...func() error) ([]error, bool) {

    count := len(toRun)
    var wg sync.WaitGroup
    wg.Add(count)
    errors := make([]error, count, count)
    ok := true
    for i, fn := range toRun {
        // create a closure for the error index and the function
        go func(index int, fn func() error) {
            defer wg.Done()
            errors[index] = fn()
        }(i, fn)
    }
    wg.Wait()
    for _, e := range errors {
        if e != nil {
            ok = false
        }
    }
    return errors, ok
}

The Run method thus encapsulates all the sequencing logic. There's no need for an external struct. There's no need for an error channel, and the errors are indexed relative to the input functions (so you can associate an error to a function). Also, the function returns a boolean "OK" flag to be used in a similar way as other Go-like functions.

The Use-Cases I tested were things like:

func main() {

    runs := []func() error{}

    runs = append(runs, func() error {
        fmt.Println("one")
        return nil
    })
    runs = append(runs, func() error {
        fmt.Println("two")
        return nil
    })
    runs = append(runs, func() error {
        fmt.Println("three")
        return nil
    })

    fmt.Println("Run one")
    if errs, ok := Run(runs...); !ok {
        fmt.Printf("Some errors: %v\n", errs)
    } else {
        fmt.Println("OK")
    }

    runs = append(runs, func() error {
        fmt.Println("fail")
        return errors.New("Failed")
    })

    fmt.Println("Run Two")
    if errs, ok := Run(runs...); !ok {
        fmt.Printf("Some errors: %v\n", errs)
    } else {
        fmt.Println("OK")
    }

}

Note that you can see the above all running in the playground: https://play.golang.org/p/9_MrR6gvj2