Divide list into n parts in scala The problem is to divide a list into n parts according to a predicate. I found recursive solution but I am sure that a more elegant solution also exists.

def repeatedSpan[T](col: Iterable[T], pred: T => Boolean): List[Iterable[T]] = {
  if (col.isEmpty) Nil
  else {
    val (a, b) = col.span(pred)
    if (a.isEmpty) b.take(1) :: repeatedSpan(b.tail, pred)
    else a :: repeatedSpan(b, pred)
  }
}

scala> repeatedSpan(List(1, 2, 3, 1, 4, 5, 6, 1, 7), (a: Int) => a != 1)
res9: List[Iterable[Int]] = List(List(1), List(2, 3), List(1), List(4, 5, 6), List(1), List(7))

I found about 5 things that can be improved, or maybe it's more accurate to say that I did 5 passes over the code in my efforts to improve it. Here's the changes I would recommend, in the order that I encountered them.

Better Names

The first change was mostly cosmetic, but it was very helpful laying the groundwork for more changes later.

def repeatedSpan[T](iterable: Iterable[T], pred: T => Boolean): List[Iterable[T]] = {
  if (iterable.isEmpty) Nil
  else {
    val (matches, rest) = iterable.span(pred)
    if (matches.isEmpty) rest.take(1) :: repeatedSpan(rest.tail, pred)
    else matches :: repeatedSpan(rest, pred)
  }
}

Naming is hard, particularly as rest is really the element that failed the predicate, and everything past that point.

Multiple Parameter Lists

This change was partially a help for the compiler, and partially to enable a bit of syntax that I'm partial to.

def repeatedSpan[T](col: Iterable[T])(pred: T => Boolean): List[Iterable[T]] = {
  if (col.isEmpty) Nil
  else {
    val (a, b) = col.span(pred)
    if (a.isEmpty) b.take(1) :: repeatedSpan(b.tail)(pred)
    else a :: repeatedSpan(b)(pred)
  }
}

By switching to a signature with multiple parameters, the compiler can infer types more easily, and as an additional bonus users can now use the shortened function literal syntax.

repeatedSpan(basicList, (a:Int) => a != 1) # Not bad to type
repeatedSpan(basicList)(_ != 1)            # Much nicer!

Pattern Matching

The next change moved from if () else to pattern matching. I did this for two reasons. The first is that it allowed better naming that rest and generally made the logic a bit more clear. The second was that it paves the way for one of the other changes that I had my eye on.

def repeatedSpan[T](iterable: Iterable[T])(pred: T => Boolean): List[Iterable[T]] =
  iterable.span(pred) match {
    case (Nil, doesNotMatch :: unTested) =>
      List(doesNotMatch) :: repeatedSpan(unTested)(pred)
    case (matchingPrefix, doesNotMatch :: unTested) =>
      matchingPrefix :: List(doesNotMatch) :: repeatedSpan(unTested)(pred)
    case (matchingPrefix, Nil) => List(matchingPrefix)
  }

This had the added bonus of eliminating a level of nesting, but the big gain was being able to easily decompose the results into matchingPrefix, doesNotMatch, and unTested.

Tail Recursion

One of the big remaining issues is that this will blow the stack on large lists. So the next step, facilitated by the simplification we gained by switching to pattern matching, was to rework it into a tail recursive version.

def repeatedSpan[T](iterable: Iterable[T])(pred: T => Boolean): List[Iterable[T]] = {
  @tailrec
  def loop(accum: List[Iterable[T]], rest: Iterable[T]): List[Iterable[T]] =
    rest.span(pred) match {
      case (Nil, doesNotMatch :: unTested) =>
        loop(List(doesNotMatch) :: accum, unTested)
      case (matchingPrefix, doesNotMatch :: unTested) =>
        loop(List(doesNotMatch) :: matchingPrefix :: accum, unTested)
      case (matchingPrefix, Nil) => List(matchingPrefix)
        matchingPrefix :: accum
    }
  loop(Nil, iterable).reverse
}

This has a major weakness. Tail recursion lets us work with large Iterables, but a List is a singly linked list, and they do not append well. To fix this, I created the list in reverse, then at the end reversed the result. I was not particularly happy with adding this complexity, but it was necessary to gain access to tail-call optimization and avoid blowing the stack with larger lists.

Program to the Interface

The best way to remove the unnecessary complexity introduced in the last step was to switch data structures. This would be more difficult if this had a bunch of code that called it, but it was simple to modify the signature and use a Vector instead, which has excellent append performance.

def repeatedSpan[T](iterable: Iterable[T])(pred: T => Boolean): Iterable[Iterable[T]] = {
  @tailrec
  def loop(accum: Vector[Iterable[T]], rest: Iterable[T]): Iterable[Iterable[T]] =
    rest.span(pred) match {
      case (Nil, doesNotMatch :: unTested) => loop(accum :+ List(doesNotMatch), unTested)
      case (matches, doesNotMatch :: unTested) => loop(accum :+ matches :+ List(doesNotMatch), unTested)
      case (matches, Nil) => accum :+ matches
    }
  loop(Vector(), iterable)
}

Now that we are using a more appropriate data structure, we have regained the simplicity we had before, and don't run out of stack space.


ES6 call `this` in Array.filter Does exist a cleaner way to call a static method inside ES6 Array.filter function ?

mine(input = '') {
    var translatedAnswers = this.constructor.translate(this._defaultAnswers);
    var self = this;
    return translatedAnswers.filter(function (answer) {
        return self.constructor.match(input, answer);
    });
}

With an arrow function I can avoid the var self = this;

mine(input = '') {
    const translatedAnswers = this.constructor._translate(this._defaultAnswers);
    return translatedAnswers.filter(answer => this.constructor._match(input, answer));
}


Maximizing XOR HackerRank challenge I know that there are combinatoric libraries for this kind of thing. However, with me being new to C# and coding in general I found that I couldn't understand the code well enough to implement it in my solution.

Here is the challenge:

  Given two integers: L and R,

  find the maximal values of A xor B given, L ≤ A ≤ B ≤ R

  Input Format  The input contains two lines, L is present in the first line.  R in the second line.

  Constraints  1 ≤ L ≤ R ≤ 103

  Output Format  The maximal value as mentioned in the problem statement.

  Sample Input#00

 1
 10

  Sample Output#00

15

  Sample Input#01

10
15

  Sample Output#01

7

   Explanation for the second example is as follows:

  In the second sample let's say L=10, R=15, then all pairs
  which comply to above condition are

  10⊕10=0   10⊕11=1  10⊕12=6  10⊕13=7  10⊕14=4  10⊕15=5  11⊕11=0  11⊕12=7  11⊕13=6  11⊕14=5
  11⊕15=4  12⊕12=0  12⊕13=1  12⊕14=2  12⊕15=3
  13⊕13=0  13⊕14=3  13⊕15=2  14⊕14=0  14⊕15=1
  15⊕15=0

  Here two pairs (10,13) and (11,12) have maximum xor value 7 and this
  is the answer.

The code below represents my solution to the problem in question. It works but I feel like I reinvented the wheel on this one. Is there a better way of going about it than what I have?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Solution {

    public static List<int[]> Combinations( List<int> number_list )
    {

        // We are only choosing 2 values out of any list of numbers
        int[] TwoList = new int[2];

        List<int[]> result = new List<int[]>();

        List<int> stack = new List<int>(number_list);

        while (stack.Count > 0)
        {

            int StackLast = stack.Count - 1;

            for (int i =0; i < stack.Count; i++)
            {
                TwoList[0] = stack[StackLast];

                TwoList[1] = stack[i];

                result.Add(new int[] {TwoList[0], TwoList[1]});
            }
            stack.RemoveAt(StackLast);
        }

        return result;

    }

    static int MaxXor(int l, int r)
    {

        List<int> NumList = new List<int>(Enumerable.Range(l, r - l + 1));

        // Inserts the list combinations as int arrays
        List<int[]> comboList = Combinations(NumList);

        int max = 0;

        foreach(var two in comboList)
        {

            int XorValue = two[0] ^ two[1];

            max = ( max > XorValue )? max : XorValue;
        }

        return max;
    }

    static void Main(String[] args)
    {

        int _l;
        int _r;

        _l = Convert.ToInt32(Console.ReadLine());

        _r = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine(MaxXor(_l, _r));
    }
}

Couple of basic things with C#

Don't use Egyptian style Bracing, that's for Java.
Watch your indentation, I fixed it in the question.
Casing should follow basic C# standards

PascalCase for all Methods, Constants, and Property names
camelCase for everything else
Protected and public instance variables are UpperCamelCase (to avoid confusion with 3.2) as Jeroen commented

You have more than enough newlines in the code, this can be distracting in your code.
From what I see of your Comments they are all unneeded

old code should be deleted
other comments are not needed to explain the flow of code or the purpose of the code because it is apparent what is going on with your code.

With these Variables I am not sure what was meant by the Underscore on them, they don't look private or look like properties, they should have a more meaningful name as well

   int _l;
   int _r;

   // We are only choosing 2 values out of any list of numbers
   int[] two_list = new int[2];

This seams like a waste of time to me, you want two numbers, not an array of numbers and not a list of numbers, so you should have two numbers.

int number1;
int number2;

and these numbers should not be written outside of the double loop, this brings me to the conclusion that they are not needed at all, and that you should write this:

        for (int i =0; i < stack.Count; i++) {

            two_list[0] = stack[stackLast];

            two_list[1] = stack[i];

            result.Add(new int[] {two_list[0], two_list[1]});

        }

instead like this

for (int i =0; i < stack.Count; i++)
{
    result.Add(new int[] {stack[stackLast], stack[i]});
}


Checking three values are consecutive This question was recently asked: Determining if three numbers are consecutive

It intrigued me, even though it was broken. I have the following implementation I thought would be interesting, and I am looking for reviews on readability, usability, and for any edge cases it may miss, etc.

/**
 * Determine whether three int values can be arranged in to an incrementing sequence.
 *
 * @param a the first value
 * @param b the second value
 * @param c the third value
 * @return true if there is an order of the three inputs which makes them sequential
 */
public static final boolean isSequential(int a, int b, int c) {
    final int x = Math.abs(a - b);
    final int y = Math.abs(b - c);
    final int z = Math.abs(a - c);
    return x + y + z == 4 && x * y * z == 2;
}

I put this together in a unit test. Here's the full file:

import org.junit.Assert;
import org.junit.Test;

public class ThreeInARow {

    /**
     * Determine whether three int values can be arranged in to an incrementing sequence.
     *
     * @param a the first value
     * @param b the second value
     * @param c the third value
     * @return true if there is an order of the three inputs which makes them sequential
     */
    public static final boolean isSequential(int a, int b, int c) {
        final int x = Math.abs(a - b);
        final int y = Math.abs(b - c);
        final int z = Math.abs(a - c);
        return x + y + z == 4 && x * y * z == 2;
    }

    private static final int[] FROM = {Integer.MIN_VALUE, Integer.MIN_VALUE + 3, -5, -4, -3, -2, -1,
            0, 1, 2, 3, 100, Integer.MAX_VALUE - 2, Integer.MAX_VALUE};

    @Test
    public void testGoodBlocks() {

        for (int f : FROM) {
            int a = f;
            int b = a + 1;
            int c = b + 1;
            Assert.assertTrue(isSequential(a, b, c));
            Assert.assertTrue(isSequential(b, c, a));
            Assert.assertTrue(isSequential(c, a, b));
            Assert.assertTrue(isSequential(b, a, c));
            Assert.assertTrue(isSequential(a, c, b));
            Assert.assertTrue(isSequential(c, b, a));
        }

    }

    @Test
    public void testBadBlocks() {

        for (int f : FROM) {
            int a = f;
            int b = a + 1;
            int c = b + 2;
            Assert.assertFalse(isSequential(a, b, c));
            Assert.assertFalse(isSequential(b, c, a));
            Assert.assertFalse(isSequential(c, a, b));
            Assert.assertFalse(isSequential(b, a, c));
            Assert.assertFalse(isSequential(a, c, b));
            Assert.assertFalse(isSequential(c, b, a));
        }

    }

    @Test
    public void testSpecials() {
        int[][] specials = {
                {0,0,0},
                {1,0,1},
                {0,0,1}
        };
        for (int[] attempt : specials) {
            Assert.assertFalse(isSequential(attempt[0], attempt[1], attempt[2]));
        }
    }

}

I don't like the idea of having to solve Diophantine equations just to be able to understand the code.  I'll suggest the same solution here as I did for @cody.codes:

public static boolean isSequential(int a, int b, int c) {
    int min = Math.min(a, Math.min(b, c));
    int max = Math.max(a, Math.max(b, c));
    return max - min == 2 && a != b && a != c && b != c;
}

"The minimum and maximum differ by 2, and all three numbers are unique" is easier to understand.


Computing sum of elements with mutlithreads I'm reading about multithreads with C++. My code is to compute the sum of elements using multithread approach. The code is

#include <iostream>
#include <thread>
#include <vector>
#include <atomic>

void func(std::atomic<long long>& sum, const std::vector<long long>& vec)
{
    long long result(0);
    for(int i(0); i < vec.size(); ++i){
        result += vec[i];
    }
    sum += result;
}

int main()
{
    // create a variable to hold the result.
    std::atomic<long long> sum(0);

    // create vector of threads
    std::vector<std::thread> threads;

    // generate numbers
    std::vector<long long> num;
    for(long long i(1); i<=10000000; ++i)
        num.push_back(i);

    // each thread should compute the sum of some numbers
    long long k(0);
    //create 1,000 threads
    for(int i(0); i<1000; ++i){
        // extract elements from the big elements vector (i.e. in this example, each thread handles 10,000)
        std::vector<long long> temp(&num[k],&num[k+10000]);
        k+=10000;
        threads.push_back(std::thread{ func, std::ref(sum), temp });
    }
    for(auto& t : threads){
        t.join();
    }
    std::cout << "Sum = " << sum << std::endl;

    return 0;
}

I would like to know if my code can be enhanced more. The comments should be enough to explain the code. Thank you.

Better algorithm

So the main practical improvement would be to use a roll. Atomics are very slow if multiple threads take turns in accessing it in clockwise/anticlockwise manner, e.g. like a carousel. Let's define the algorithm:

Retrieve number of physical threads, e.g. cores. Sometimes it is not available, so setting it to 4 would be a pretty good guess these days. Number of threads visible to OS would be important if algorithm would have diverse workload, but this is not the case here.
While not reached the end of the vector:

2.1 Allocate all physical threads to sum 1000 numbers in the range. The number might need to be fine tuned, but I believe this already should outweigh the cost of the thread creation.

2.2. Sum the results of each number into result.

The process is actually much harder than it looks like. One has to create a vector of std::promises and get std::futures of them, then create small function that would set the future from outside, then join threads ... Well I guess you got the point. This question should help out with that.

Compute in place

Since the algorithm does read-only access on the container, it could be just passed by reference. The master function could schedule the work and then collect the result.

Iterators

I believe that if the properties of std::vector are not exploited, it doesn't make much sense to hardcode it. Iterators provide powerful abstraction, though they take time to get used to them. Also, they could be used to delegate to std::accumulate, e.g. in the small function it would just call accumulate on range.

More power

I believe the function could be extended without much effort and still retain compatibility and easy of use of original one. Something like this:

template <typename RandomAcessIt,
          typename T = std::iterator_traits<RandomAcessIt>::value_type,
          typename BinaryOp = std::plus<>>
T accumulate(parallel_compute_tag, RandomAcessIt first, RandomAcessIt last, T initvalue = {}, BinaryOp op = {})

So default would still be +, but it could be changed to whatever heart likes. And then instead of using + one could just op(lhs, rhs).

Rolling

Here is a terrible picture (I made my best at it)

As you can see, the scheduled threads "roll into" master thread to provide the result. That is why I said rolling approach. I don't really know the term for this though.


Update SQL query using UNIX time I would like to test the following garbage collector code on a database of sessions.
It should be following the conditions below:

if 'remember me' is enabled by the user, then it should delete all rows which are not active within 2 weeks.
if 'remember me' is disabled by the user, then it should delete all rows which are not active within 30 minutes.

I have times inserted in the LAST_ACTIVITY column, with the UNIX_TIMESTAMP() format.

public function gc( $maxlifetime )
{
    $this->conn->SQL( 'DELETE FROM session WHERE (LAST_ACTIVITY < ? AND REMEMBERUSER = ?) OR (LAST_ACTIVITY < ? AND REMEMBERUSER = ?)' ,
        [ strtotime('-30 minutes'), 'N' , strtotime('-2 weeks'), 'Y']);
    return true;
}

Are the AND or OR operators working properly? I would only like to test the SQL query, and not the gc method.

Observations

Your $maxlifetime parameter is unused.
One of the conditions is redundant: any session older than two weeks should be discarded unconditionally.
The capitalization of your column names is unconventional.  Usually, identifiers are lowercase, and SQL keywords are ALL CAPS.  (Note: identifiers in MySQL are case-sensitive on Unix, but not Windows.)

Proposal

DELETE FROM session
    WHERE last_activity < CURRENT_TIMESTAMP() - INTERVAL 2 WEEK
    OR (rememberuser = 'N' AND last_activity < CURRENT_TIMESTAMP() - INTERVAL 30 MINUTE);

Advantages

This is a fixed query with no parameters, which keeps things simple.
It's almost English-like in readability.

Caveats

This requires your last_activity column to be of the DATETIME or TIMESTAMP type.  You could also make it work with integer Unix timestamps instead, using

DELETE FROM session
    WHERE last_activity < UNIX_TIMESTAMP(CURRENT_TIMESTAMP() - INTERVAL 2 WEEK)
    OR (rememberuser = 'N' AND last_activity < UNIX_TIMESTAMP(CURRENT_TIMESTAMP() - INTERVAL 30 MINUTE));

This assumes that the last_activity times were set according to the database server's clock, not the application server's clock.  Otherwise, if they are running on separate machines, or if you are careless with your treatment of timezones, you could end up with clock skew.  Therefore, it's best to pick one clock and stick with it consistently.  I prefer to use the database server's clock, for several reasons:

If your application runs on multiple application servers, all connecting to a central database, then the database clock is the natural official time source.
Your queries can be simpler, as illustrated above.
Storing the timestamps in a DATETIME column is more meaningful than storing them as integers.

So, to make this work, the last_activity times have to be inserted or updated using CURRENT_TIMESTAMP() or NOW(), or established by default when a TIMEZONE column has no specified value.
Admittedly, this formulation uses MySQL-specific date / time functions, so it is less portable.  Similar solutions exist for other database systems, though.


Improving Speed of VBA Code - Copy/paste two sets of variable, Excel does a calculation, returns a value then copy/paste the output value I am attaching the code here. I am very new to VBA and trying to do a complex calculation using Macro. Please help me improve the speed of the attached code. The code works fine and produces the end output. The program is intended to do the following. I am calling the below two subs after data is filled in the sheet.
Copy and paste two sets of variable in two specified cell
Excel does a complex calculation using FILTER command & other INDEX and MATCH Formulas
Copy and paste the output to a location
This is required to done 1500 times for two sets of data. Present execution time is 10 minutes.
Sub CF_Amb_Pr_NG()
Dim intX As Integer
Dim copyRng As String
X = 43
For X = 40 To 1539
    Sheets("CC_NG_APr").Select
    Range("C2").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = "=R" & X & "C2"
    Range("C3").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = "=R" & X & "C3"
    Range("E2").Select
    Selection.Copy
    Let copyRng = "D" & X
    Range(copyRng).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
Next X
End Sub

Sub CF_RH_NG()
Dim intX As Integer
Dim copyRng As String
X = 33
For X = 32 To 1531
    Sheets("CC_NG_RH").Select
    Range("C2").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = "=R" & X & "C2"
    Range("C3").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = "=R" & X & "C3"
    Range("E2").Select
    Selection.Copy
    Let copyRng = "D" & X
    Range(copyRng).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
Next X
End Sub

Attached screenshot of sheet in formula mode to explain what exactly is going on in E2 based on the values fed in C2 & C3. Basis the value entered in C2 & C3, formula to be chosen to calculate E2 is chosen and final value is shown. I need to get value in E2 for 3000 sets of data in C2 & C3
Thanks a lot for helping !

As best I can tell, Sub CF_Amb_Pr_NG() sets cells C2 and C3 to formulas that changes with each iteration through the loop, then ends with them set to "=R1539C2".
You then copy cell E2 to each row in column D from 40 to 1539.
Unless there's something going on with the value in C2 and C3 that somehow impact E2, if you really want to stick with the .Select and .PasteSpecial this should do the trick:
Sub test()

  With ThisWorkbook.Worksheets("Sheet1")
    .Range("E2").Select
    Selection.Copy
    .Range("D40:D1539").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    .Range("C2").FormulaR1C1 = "=R1539C2"
    .Range("C3").FormulaR1C1 = "=R1539C3"
  End With

End Sub

Otherwise, I'd suggest this which is even easier:
Sub test()

  With ThisWorkbook.Worksheets("Sheet1")
    .Range("d40:d1539").Value2 = .Range("e2").Value2
    .Range("C2").FormulaR1C1 = "=R1539C2"
    .Range("C3").FormulaR1C1 = "=R1539C3"
  End With

End Sub

It copies E2 to D40 through D1539, then it sets C2 and C3 to the final values they have in your loop.
Make a similar change to Sub CF_RH_NG().

If the value in E2 changes with the values as determined in C2 and C3 for each iteration through the loop, I'd strongly suggest that you add a helper column (out in column Z or LLL or someplace) that calculates E2 for the current row, then simply make the formula in D40 read =LLL40 (manually copy that formula down to D1539 one time), and be done with it - no need for code at all.

These simple assignments should execute in a second or two (Excel is notably slow in copying in my recent experience), but significantly less than the 10 minutes you're currently experiencing.

Based on the update, a loop is required, avoiding .Select will still help performance:
Sub test()

  On Error GoTo CleanExit
'  Application.ScreenUpdating = False
  Dim row As Long
  For row = 40 To 1539
    With Sheet1
      .Range("C2").FormulaR1C1 = "=R" & CStr(row) & "C2"
      .Range("C3").FormulaR1C1 = "=R" & CStr(row) & "C3"
      .Range.Cells.Item(4, row).Value2 = .Range("e2").Value2
    End With
  Next

CleanExit:
  Application.ScreenUpdating = True

End Sub

Note in this case the With Sheet1 - you can use the worksheet's (Name) property as a direct reference to it (you'll have to modify this for your Workbook):

Note that this is not the same as the .Name of the worksheet as displayed on the "tab":
Additionally, I've added Application.ScreenUpdating = False, but left it commented out for now. Make sure your new code is working properly before enabling this. This will prevent Excel from refreshing the screen with each step it takes. Removing all the UI activity reduces the amount of execution time (it's not a panacea, though). Note the addition of the On Error Goto... to ensure that if anything were to go wrong during execution, it will reenable ScreenUpdating. If you don't weird and confusing things happen.


Shuffling a JSON array in Java Since I did not get a satisfactory answer here (and I really needed to get it going on this weekend), I decided to implement my own Fisher–Yates shuffle, porting the code I found in other SO posts. I know my programming technique is far from optimal, so I decided to post this here.

What do you think? Can it be improved?

public static JSONArray shuffleJsonArray (JSONArray array) throws JSONException {
    // Implementing Fisher–Yates shuffle
        Random rnd = new Random();
        for (int i = array.length() - 1; i >= 0; i--)
        {
          int j = rnd.nextInt(i + 1);
          // Simple swap
          Object object = array.get(j);
          array.put(j, array.get(i));
          array.put(i, object);
        }
    return array;
}

It runs in \$O(n)\$ time so I'm not sure there's a way to improve this.  It looks like you've implemented the algorithm pretty well, according the Fisher-Yates shuffle.

You might consider not using Object if you can use the type that's stored in the array instead.

I also thought I read somewhere that it should be safe to loop to \$n/2\$ instead of \$n\$ (because you're swapping with elements from \$1 \cdots n\$ so in theory, you shouldn't need to swap every element), but I don't have hard proof of that, so you take your chances ;)


Changing the default printer in Windows Where I work there's two different printers being used on a daily basis, one of them prints things from a particular program, which only uses the default printer. A lot of the times, during busy periods, people forget to switch the default printer, resulting in that program using the wrong printer, which isn't suitable for what's being printed.

The work PC is ancient and getting into the printers menu can take up to a few minutes. I am hoping my program will reduce spending so much time on the computer just to change the default printer.

This is the first time I've done up an interface in Tkinter, so I'd appreciate feedback if it can be done better.

import tkinter as tk
import tkinter.ttk as ttk

import win32print

def get_available_printers():
    return [printer[2] for printer in win32print.EnumPrinters(2)]

class PrinterManager(tk.Frame):

    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)
        self.master = master
        self.configure_interface()
        self.create_widgets()

    def configure_interface(self):
        self.master.title('Printer Manager')
        self.master.geometry('350x100')
        self.master.resizable(False, False)
        self.master.config(background='#626a77')

    def create_widgets(self):
        self.default_printer_label = tk.Label(self.master, bg='#626a77', fg='white')
        self.default_printer_label.place(x=10, y=12)
        self.update_default_printer_label()

        refresh_button = tk.Button(self.master, text='Refresh', command=self.update_default_printer_label)
        refresh_button.place(x=285, y=10)

        selected_printer = tk.StringVar()
        printer_choice_menu = ttk.Combobox(self.master, textvariable=selected_printer, values=get_available_printers(), width=35, state='readonly')
        printer_choice_menu.place(x=12, y=62)

        set_default_printer_button = tk.Button(self.master, text='Set', command=lambda: self.set_default_printer(selected_printer))
        set_default_printer_button.place(x=285, y=60, width=50)

    def update_default_printer_label(self):
        default_printer = win32print.GetDefaultPrinter()
        default_printer_text = 'Default printer: {}'.format(default_printer)
        self.default_printer_label.config(text=default_printer_text)

    def set_default_printer(self, printer_name):
        win32print.SetDefaultPrinter(printer_name.get())
        self.update_default_printer_label()

if __name__ == '__main__':
    root = tk.Tk()
    PrinterManager(root)
    root.mainloop()

That is great as a first tkinter application. I like the fact you wrote two specific functions update_default_printer_label() and set_default_printer(). Most programmers will just do all what you did in one function and they believe as long as it does not exceed 25 lines length they are near perfection. With your approach, you have fine grain control on your program as unit testing is simplified (because you have small functions doing one clear task).

I do not have much to say about your program. There are very few imperfections but some may argue it is Ok. Nevertheless, I do not see the reason you let the function get_available_printers() orphan (I mean it can be integrated into the class PrinterManager, it is its right place and you will add only self. to call it where you did)

I would like to add one or two extra notes: given the description of the problematic, I think it would be reasonable to create a stand alone executable for your application using pyinstaller since you are trying to avoid navigating the printer menu and, why not, schedule your program (using python-crontab) to switch to the default printer (you need to add some code to check before switching) at a specific time (for example everyday at 08:10 AM)


Calling common async code from a derived method I'm implementing a number of classes in C# that have async methods. However, each of these methods needs to implement some boilerplate code that is common to all. Therefore I've implemented the common code in an async method of a base class; the async methods on the derived classes then call this base class method.

Here's the base class, containing the method that does the common stuff (GetResultAsync).

namespace Redacted
{
    abstract class RepositoryBase : IRepository
    {
        protected RepositoryBase(IRepositoryConfiguration configuration)
        {
            Configuration = configuration;
        }

        protected IRepositoryConfiguration Configuration { get; private set; }

        protected FleetContext CreateDatabaseContext()
        {
            return new FleetContext(Configuration.DatabaseConnectionString);
        }

        protected async Task<IApiResult<TValue>> GetResultAsync<TValue>(
            IApiCallerContext context,
            Func<FleetContext, CancellationToken, Task<TValue>> getTask)
        {
            using (new SynchronizationContextChange())
            using (FleetContext db = CreateDatabaseContext())
            {
                bool isSystemOnline = await db.IsSystemOnlineAsync();
                if (!isSystemOnline)
                {
                    return ImmutableApiResult<TValue>.Offline;
                }

                bool isValidSession = await db.IsValidSessionAsync(context.Caller);
                if (!isValidSession)
                {
                    return ImmutableApiResult<TValue>.Blocked;
                }

                Task<TValue> task = getTask(db, context.CancellationToken);
                TValue value = await task;

                return ImmutableApiResult.Create<TValue>(value);
            }
        }
    }
}

Basically, I have an Entity Framework database context (FleetContext) that exists for the duration of the call. I then perform some common DB-related tasks by calling custom async methods that have been added to the context class. Depending on the result of these calls, I may exit the method early: in such cases, the IApiResult object returned by the method is different than when the method runs through to the end normally.

Here's an example of a derived class that contains a method which calls the base class:

namespace Redacted
{
    sealed class CompanyRepository : RepositoryBase, ICompanyRepository
    {
        public CompanyRepository(IRepositoryConfiguration configuration)
            : base(configuration)
        {
        }

        public Task<IApiResult<ICompanyIdentity>> GetCompanyIdentityAsync(int companyId, IApiCallerContext context)
        {
            return GetResultAsync<ICompanyIdentity>(
                context,
                async (db, cancellationToken) =>
                {
                    Company company = await db.Companies.FindAsync(cancellationToken, companyId);
                    return ImmutableCompanyIdentity.Create(company);
                }
                );
        }
    }
}

As you can see I'm using an asynchronous anonymous function to return the Task object required by the GetResultAsync method.

This all works but seems somewhat inside-out to me, in that the API method (GetCompanyIdentityAsync) passes a function to the base class, rather than the more typical approach of the derived class calling the base method as part of its normal processing.

Am I worrying unnecessarily, or are there obvious alternate ways of calling the boilerplate code from the derived classes?

In your code you create 2 boolean variables for a simple if statement conditional, personally I think that you shouldn't create these variables unless you are going to use them in more than one place or for complex condition statements.

        using (FleetContext db = CreateDatabaseContext())
        {
            bool isSystemOnline = await db.IsSystemOnlineAsync();
            if (!isSystemOnline)
            {
                return ImmutableApiResult<TValue>.Offline;
            }

            bool isValidSession = await db.IsValidSessionAsync(context.Caller);
            if (!isValidSession)
            {
                return ImmutableApiResult<TValue>.Blocked;
            }

            Task<TValue> task = getTask(db, context.CancellationToken);
            TValue value = await task;

            return ImmutableApiResult.Create<TValue>(value);
        }

You can also avoid creating the Task variable at the end as well and just create the value.

using (FleetContext db = CreateDatabaseContext())
{
    if (!(await db.IsSystemOnlineAsync()))
    {
        return ImmutableApiResult<TValue>.Offline;
    }
    else if (!(await db.IsValidSessionAsync(context.Caller)))
    {
        return ImmutableApiResult<TValue>.Blocked;
    }

    TValue value = await (getTask(db, context.CancellationToken));

    return ImmutableApiResult.Create<TValue>(value);
}

This shortens the code a little bit and gets straight to the point.  Nothing really wrong with the way that you did it, and I haven't really done anything different here either, I just...well... golfed it a bit I guess.  I just didn't think we needed to create all those variables


Creating unique names for uploaded images I am trying to create a unique name for my uploaded images. It works, but I wonder whether I should make a few changes or not.

HTML

    <form action="upload.php" method="post" enctype="multipart/form-data" name="uploadform">
        <input type="hidden" name="MAX_FILE_SIZE" value="350000">
        <input name="picture" type="file" id="picture" size="50">
        <input name="upload" type="submit" id="upload" value="Upload Picture!">
    </form>

PHP

// if something was posted, start the process...
if (isset($_POST['upload'])) {

// define the posted file into variables
    $name = $_FILES['picture']['name'];
    $tmp_name = $_FILES['picture']['tmp_name'];
    $type = $_FILES['picture']['type'];
    $size = $_FILES['picture']['size'];

// if your server has magic quotes turned off, add slashes manually
    if (!get_magic_quotes_gpc()) {
        $name = addslashes($name);
    }

// open up the file and extract the data/content from it
    $extract = fopen($tmp_name, 'r');
    $content = fread($extract, $size);
    $content = addslashes($content);
    fclose($extract);

// connect to the database
    include "../cn/connect.php";

    $name = md5($name);
    $name = $name . uniqid($name);

    $path = $_FILES['picture']['name'];
    $ext = pathinfo($path, PATHINFO_EXTENSION);
    $name = $name.".".$ext;

// the query that will add this to the database
    $stmt = $sqli->prepare("INSERT INTO image1(name, type, size) VALUES (?,?,?)");
    $stmt->bind_param("sss", $name, $_FILES['picture']['type'], $_FILES['picture']['size']);
    $stmt->execute();
    $stmt->close();
    echo "Mission has been completed, sir!";

    if (!empty($_FILES)) {
        $target = "upload/";
        $target = $target . basename($_FILES['picture']['name']);
        $ok = 1;
        $picture_size = $_FILES['picture']['size'];
        $picture_type = $_FILES['picture']['type'];
        //This is our size condition
        if ($picture_size > 5000000) {
            echo "Your file is too large.
";
            $ok = 0;
        }

        //This is our limit file type condition
        if ($picture_type == "text/php") {
            echo "No PHP files
";
            $ok = 0;
        }

        //Here we check that $ok was not set to 0 by an error
        if ($ok == 0) {
            Echo "Sorry your file was not uploaded";
        } //If everything is ok we try to upload it
        else {
            if (move_uploaded_file($_FILES['picture']['tmp_name'], $target)) {
                echo "The file " . basename($_FILES['picture']['name']) . " has been uploaded
";
            } else {
                echo "Sorry, there was a problem uploading your file.";
            }
        }
    }

    echo "Successfully uploaded your picture!";
} else {
    die("No uploaded file present");
}

It looks like your code works fine, so these comments are my opinion on how I would handle this if I were in your shoes.

This is a pretty standard requirement. Users upload images, and you want to save them with a filename that is (a) unique, and (b) won't cause you grief down the road with funny characters in the file name.

You also need to handle the case where people upload files with the same name over and over again, without creating duplicates.  For instance, for a certain model of camera the first photo on the "camera roll" might always have the same name. Several people might own the same model of camera. Or, dissatisfied with the results of uploading an image, the user edits it locally and uploads a fresh copy. With the same file name as before.

The simplest solution is to skip all the md5 and uniqid() stuff, and simply add a record to a database which has an auto-increment ID field. You would add the original name of the image to the database (for future reference, tooltip etc), but not the name of the file on disk. Once you get the new ID, you copy/move/rename the image file based on the new ID. This gives you nice short, simple file names.

I think this is tidier than inventing a unique file name before adding the database record. Databases have a built-in unique ID feature, so you can get a unique ID "for free!" with each new record. Why invent your own?

If the name of the image file ends up being used in URL's, so you don't want it to be easily guessable, then you want to mess up the file name to make it more complicated. If this is the case, you are better off placing the files where they are not accessible directly via URL.

If you, as an administrator, want to be able to browse through the image files and have the names make sense, or if you want the image names to appear in the URL to assist visitors or for SEO or Google Image search benefits, then you may want to name the images like blog post titles, i.e. simple lower-case-hyphen-separated words with a unique ID on the end. There is lots of code around that will do that for you. (I've got code if you can't find it elsewhere).


Cleanup and server restart script I have written a simple script for managing our Tomcat and Apache instances for deployment. What this script basically does is, when called, it copies the ROOT.war from its pwd and pushes them to two Tomcat instances. Before that, it removes the old ROOT.war file and ROOT folder, restarts them, cleans the log files, restarts both Tomcat instances and Apache webserver (load-balancer and failover guy).

I have just pasted commands in a script and thought would learn more about it when I optimize this script, such as adding checks.

#!/bin/bash
sh /home/deploy/tomcatfirst/bin/catalina.sh stop
rm -rf /home/deploy/tomcatfirst/webapps/ROOT/
rm -rf /home/deploy/tomcatfirst/logs/
rm /home/deploy/tomcatfirst/webapps/ROOT.war
cp ROOT.war /home/deploy/tomcatfirst/webapps/
mkdir /home/deploy/tomcatfirst/logs

sh /home/deploy/tomcatfirst/bin/catalina.sh stop
rm -rf /home/deploy/tomcatsecond/webapps/ROOT/
rm /home/deploy/tomcatsecond/webapps/ROOT.war
rm -rf /home/deploy/tomcatsecond/logs/
mv ROOT.war /home/deploy/tomcatsecond/webapps/
mkdir /home/deploy/tomcatsecond/logs

sh /home/deploy/tomcatfirst/bin/catalina.sh start
sh /home/deploy/tomcatsecond/bin/catalina.sh start
service apache2 restart

Adding checks? Just specify

set -e

at the beginning of the script. Should any command fail, the script will stop running, instead of wreaking more damage.

Using variables for repeated paths might make the script more readable.

tomcat1=/home/deploy/tomcatfirst
tomcat2=/home/deploy/tomcatsecond

sh "$tomcat1"/bin/catalina.sh stop

(BTW, shouldn't the second stop use $tomcat2?)

Once you have them, changing the above line to

set -eu

might be another improvement - the script will fail if a variable is not defined, which can happen if you mistype its name.

As the commands for both the server are the same, you can wrap them in a loop:

for tomcat /home/deploy/tomcat{first,second} ; do
    sh "$tomcat"/bin/catalina.sh stop
    # ...
done

If the servers are critical, you should specify the commands with full paths (e.g. /bin/mkdir).


Implementation Async/Await I have a simple ASP.NET Web API project. Now I want to make all basic methods as asynchronous. I tried to do something, and it's working but I'm not sure that it was implemented properly.

Please check whether I properly implemented async/await in my project.

I had implemented methods like below in my repository:

        public T GetById(object id)
        {
            return this.Entities.Find(id);
        }
        public void Insert(T entity)
        {
            try
            {
                if (entity == null)
                {
                    throw new ArgumentNullException("entity");
                }
                this.Entities.Add(entity);
                this.context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        errorMessage += string.Format("Property: {0} Error: {1}",
                        validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;
                    }
                }
                throw new Exception(errorMessage, dbEx);
            }
        }

I tried to create async methods:

        public Task InsertAsync(T entity)
        {
            return Task.Run(() => Insert(entity));
        }
        public Task<T> GetByIdAsync(object id)
        {
            return Task.Run(() => GetById(id));
        }

And now I'm using it as:

      public async virtual Task<HttpResponseMessage> Post([FromBody]T entity)
      {
                try
                {
                    await repository.InsertAsync(entity);
                    return Request.CreateResponse(HttpStatusCode.Created, entity);
                }
                catch (Exception ex)
                {
                    return ErrorMsg(HttpStatusCode.InternalServerError, ex.Message);
                }

       }
       public async virtual Task<HttpResponseMessage> GetById(int id)
       {
            var entity = await repository.GetByIdAsync(id);

            if (entity == null)
            {
                var message = string.Format("No {0} with ID = {1}", GenericTypeName, id);
                return ErrorMsg(HttpStatusCode.NotFound, message);
            }
            return Request.CreateResponse(HttpStatusCode.OK, entity);
       }

Your implementation is technically correct, but...
There is no benefit in using Task.Run in an web application.
All you're doing is deferring work from one thread to another. So, in fact, not only is there no benefit, you're actually adding overhead.
I'll quote Stephen Cleary, because I could nevet put it better:

There are (at least) four efficiency problems introduced as soon as you use await with Task.Run in ASP.NET:

Extra (unnecessary) thread switching to the Task.Run thread pool thread. Similarly, when that thread finishes the request, it has to enter the request context (which is not an actual thread switch but does have overhead).
Extra (unnecessary) garbage is created. Asynchronous programming is a tradeoff: you get increased responsiveness at the expense of higher memory usage. In this case, you end up creating more garbage for the asynchronous operations that is totally unnecessary.
The ASP.NET thread pool heuristics are thrown off by Task.Run “unexpectedly” borrowing a thread pool thread. I don’t have a lot of experience here, but my gut instinct tells me that the heuristics should recover well if the unexpected task is really short and would not handle it as elegantly if the unexpected task lasts more than two seconds.
ASP.NET is not able to terminate the request early, i.e., if the client disconnects or the request times out. In the synchronous case, ASP.NET knew the request thread and could abort it. In the asynchronous case, ASP.NET is not aware that the secondary thread pool thread is “for” that request. It is possible to fix this by using cancellation tokens, but that’s outside the scope of this blog post.

So, unless you're doing true async I/O, do it synchronously.
Alternatively, if you want to expose an async interface, where the implementation may or may not perform asynchronous I/O, synchronous implementation should use Task.FromResult instead of Task.Run. Example:
interface IRepository<T>
{
     public Task<T> GetByIdAsync(object id)
}

// implementation that uses synchronous I/O
class SyncRepository<T> : IRepository<T>
{
    public Task<T> GetByIdAsync(object id)
    {
        T t = this.Entities.Find(id);
        return Task.FromResult(t);
    }
}

// implementation that uses async I/O
class AsyncRepository<T> : IRepository<T>
{
    public Task<T> GetByIdAsync(object id)
    {
        return this.Entities.FindAsync(id);
    }
}

Read also:

Stephen Toub's Should I expose synchronous wrappers for asynchronous methods?.
Stephen Cleary's Task.Run Etiquette Examples: Don't Use Task.Run in the Implementation


Hotel reservation system with discounts and deposits I'm making a hotel reservation app that has the following features:

Promo Codes:

The guest can choose to pay half a certain percent of the total_amount or the entire total_amount. I want to use stripe, PayPal and authorize.net as payment gateways.

Reservations are stored here:

CREATE TABLE `reservations` (
 `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
 `user_id` int(11) NOT NULL,
 `guest_id` int(11) NOT NULL,
 `currency` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'USD',
 `accommodation_id` int(11) NOT NULL,
 `from_date` date NOT NULL,
 `to_date` date NOT NULL,
 `guests` int(11) NOT NULL,
 `total_amount` decimal(13,4) NOT NULL,
 `deposit_amount` decimal(13,4) NOT NULL,
 `remaining_amount` decimal(13,4) NOT NULL,
 `isDeposit` enum('true','false') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'false',
 `promo_id` int(11) NOT NULL,
 `paid` tinyint(1) NOT NULL DEFAULT '0',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

An example reservation:

id|user_id  | guest_id  | currency  | accommodation_id  | from_date  | to_date        | guests  | total_amount  | deposit_amount | remaining_amount
2 | 4       | 10        | USD       | 55                | 2015-07-02 | 2015-07-04     | 20      | 200           | 20             | 180

| isDeposit | promo_id | paid
| true      | 2        | 0

Payments are stored here:

CREATE TABLE `payments` (
 `id` int(11) NOT NULL,
 `reservation_id` int(11) NOT NULL,
 `method` enum('stripe','paypal','authorize') NOT NULL,
 `type` enum('deposit','total','remaining') NOT NULL,
 `reference` varchar(255) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1

If the guest pays that deposit_amount of 20 using stripe:

id | reservation_id | method | type     |  reference        |
1  | 2              | stripe | deposit  | 56544564545       |

and pays the remaining of 180 using PayPal:

id | reservation_id | method | type           | reference    |
1  | 2              | paypal | remaining      | 68985578474  |

then I will make column paid to 1 in reservations table.

How does this look to you?

Not a full & detailed answer but some initial thoughts.

Some of the fields in the reservations table look decidedly non-normalised - remaining_amount, isDeposit and paid. Shouldn't these be derived from the payments table when needed for a view or a query? Otherwise, when you receive a payment you would also have to update at least two of these fields. Are you planning on using triggers for these updates?

If you want to keep the isDeposit field, then think carefully how you use it. Does it tell you that only a deposit has been paid so it gets set to 0 once the full amount is paid? Or does it tell you that the guest initially paid a deposit so it gets set to 1 when the deposit is paid and then gets left?

What happens when a reservation gets cancelled? There is no status field and presumably you cannot delete the record (and any payments records)?

You've also got user_id, guest_id and guests fields. If you want the user to enter names of any guests for the reservation you will need another structure.


Order of evaluation of function arguments From SICP:

  Exercise 3.8

  When we defined the
  evaluation model in section 1.1.3, we
  said that the first step in evaluating
  an expression is to evaluate its
  subexpressions. But we never specified
  the order in which the subexpressions
  should be evaluated (e.g., left to
  right or right to left). When we
  introduce assignment, the order in
  which the arguments to a procedure are
  evaluated can make a difference to the
  result. Define a simple procedure f
  such that evaluating (+ (f 0) (f 1))
  will return 0 if the arguments to +
  are evaluated from left to right but
  will return 1 if the arguments are
  evaluated from right to left.

I wrote this solution:

(define it false)
(define (f x)
  (if it
      it
      (begin (set! it (/ x 2)) it)))

(+ (f 1) (f 0))

Is there a better way?

Your code returns 1/2 if the (f 0) is evaluated first, not 0. A better way would be to return the last argument to f, with a default of 0.

(define last 0)
(define (f x)
  (define temporary last)
  (set! last x)
  temporary
)

When (+ (f 0) (f 1)) is evaluated with (f 0) first, execution is as follows:

f is called with 0
temporary is set to 0 (the default last)
last is set to 0 (the argument to f)
temporary (0) is returned
f is called with 1
temporary is set to 0
last is set to 1
temporary (0) is returned
0+0=0

If (f 1) is evaluated first, then execution is as follows:

f is called with 1
temporary is set to 0 (the default last)
last is set to 1 (the argument to f)
temporary (0) is returned
f is called with 0
temporary is set to 1
last is set to 0
temporary (1) is returned
0+1=1


jQuery buttons to show/hide info and search I've used multiple tutorials to get the exact look for show/hide using jQuery, but now that I've done it's too repetitive, I've tried to edit it using variables, but it didn't work. Is there a way to avoid repetitiveness here?

$(document).ready(function() {
  $(document).click(function(event) {
    if ($(event.target).is(".info-icon") || $(event.target).is(".info-tab") || ($(".info-tab").has(event.target).length == 1)) {
      if ($(".info-tab").height() != 0 && !$(event.target).is(".info-tab") && !($(".info-tab").has(event.target).length == 1)) {
        $(".info-tab").css("max-height", "0");
      } else {
        if ($(".search-tab").height() != 0) {
          $(".search-tab").css("max-height", "0");
          setTimeout(function() {
            $(".info-tab").css("max-height", "200px");
          }, 300);
        } else {
          $(".info-tab").css("max-height", "200px");
        }
      }
    } else if ($(event.target).is(".search-icon") || $(event.target).is(".search-tab") || ($(".search-tab").has(event.target).length == 1)) {
      if ($(".search-tab").height() != 0 && !$(event.target).is(".search-tab") && !($(".search-tab").has(event.target).length == 1)) {
        $(".search-tab").css("max-height", "0");
      } else {
        if ($(".info-tab").height() != 0) {
          $(".info-tab").css("max-height", "0");
          setTimeout(function() {
            $(".search-tab").css("max-height", "200px");
          }, 300);
        } else {
          $(".search-tab").css("max-height", "200px");
        }
      }
    } else {
      $(".info-tab").css("max-height", "0");
      $(".search-tab").css("max-height", "0");
    }
  });
});

JSFiddle for what it does is here: https://jsfiddle.net/msms92/L9L0tqvp/

The first thing that comes to my mind is that what you're trying to do is handling all of the click events in just one handler function! Don't!

Use delegate event listeners instead:

$(document)
    .on("click", ".info-icon, .info-tab", function(e) {
       e.stopPropagation();
       // Deal with .info-icon or .info-tab
    })
    .on("click", ".search-icon, .search-tab", function(e) {
       e.stopPropagation();
       // Deal with .search-icon or .search-tab
    })
    .on("click", function(e) {
       // Other clicks
    });

Secondarily, define CSS classes list .info-tab-open and .search-tab-open like these:

.info-tab-open {
    max-height: 200px;
}

(And remember: using magic numbers is bad, especially when styling with JavaScript.)

So you'll end up doing this instead:

var $infoTab = $(".info-tab");
if ($infoTab.hasClass("info-tab-open")) {
    $infoTab.removeClass("info-tab-open");
} else {
    var $searchTab = $(".search-tab");
    if ($searchTab.hasClass("search-tab-open")) {
        $searchTab.removeClass("search-tab-open");
        setTimeout(..., 300);
    } else {
        $infoTab.addClass("info-tab-open");
    }
}

Third: since the handler's code is basically the same and repeating code is a code smell, you'll probably be better off if you use a factory function for the handler:

function toggler(selectedClass, otherClass) {
    return function(e) {
        e.stopPropagation();
        var $selectedTab = $("." + selectedClass);
        if ($selectedTab.hasClass(selectedClass + "-open")) {
            $selectedTab.removeClass(selectedClass + "-open");
        } else {
            var $otherTab = $("." + otherClass);
            if ($otherTab.hasClass(otherClass + "-open")) {
                $otherTab.removeClass(otherClass + "-open");
                setTimeout(..., 300);
            } else {
                $selectedTab.addClass(selectedClass + "-open");
            }
        }
    };
}

$(document)
    .on("click", ".info-icon, .info-tab", toggler("info-tab", "search-tab"))
    .on("click", ".search-icon, .search-tab", toggler("search-tab", "info-tab"))
    .on("click", function() {
        $(".info-tab").removeClass("info-tab-open");
        $(".search-tab").removeClass("search-tab-open");
    });


Identify Java Callback I have this common design in my application:

public class MyListener1{
  MyTask1 task1;
  MyTask2 task2;

  public class MyListener1{

    public MyListener1(){
      task1 = new MyTask1(this);
      task2 = new MyTask2(this);
      task1.execute();
      task2.execute();
    }

    public void onResult1(String result){
      //extract result
    }

    public void onResult2(String result){
      //extract result
    }
}

public class MyTask1 extends AsyncTask{

  MyListener1 myListener1;

  public MyTask1(MyListener1 myListener1){
    this.myListener1 = myListener1;
  }

  @Override
  public void onResult(String result){
    myListener1.onResult1(result);
  }

}

public class MyTask2 extends AsyncTask{

  MyListener1 myListener1;

  public MyTask2(MyListener1 myListener1){
    this.myListener1 = myListener1;
  }

  @Override
  public void onResult(String result){
    myListener1.onResult2(result);
  }

}

The AsyncTask is a library class that execute the code in a method doInBackground() in another thread when calling execute(), and call onResult(String result) when task finished.

Of course, I summarize the code, MyTask1 and MyTask2 have a little bit more code, but I soon realized that they could be factorize on a common task:

public class MyListener1{
  MyTask task1;
  MyTask task2;

  public class MyListener1{

    public MyListener1(){
      task1 = new MyTask(0,this);
      task2 = new MyTask(1,this);
      task1.execute();
      task2.execute();
    }

    public void onResult(int taskId, String result){
       switch(taskId){
         case(0) : //extract result from task 0
         case(1) : //extract result from task 1
    }
}

public class MyTask extends AsyncTask{

  int id;
  MyListener1 myListener1;

  public MyTask(int id, MyListener1 myListener1){
    this.id = id;
    this.myListener1 = myListener1;
  }

  @Override
  public void onResult(String result){
    myListener1.onResult(id, result);
  }

}

I heard some people telling me to avoid "switch case" to identify a source and prefer to use "polyphormism" instead. In that case, I don't know what they mean.

So here is my question:

Is there a better way to identify the source (the object calling) of a callback method than using an identifier for the caller?

A listener and callback mechanism is a common pattern in many places in Java.

The logical place to look for examples is in the Swing API. Will get back to that in a second, but, there are two items that are useful first:

Instead of using an int value to track the source of the event/Task, you should use the task itself.

   public void onResult(String result){
     myListener1.onResult(this, result);
   }

The Listener itself should implement an interface, something like: TaskResultListener:

 public interface TaskResultListener {
     public onResult(Task task, String result);
 }

and the constructor for the Task should take an instance of a TaskResultListener instead of a MyListener1

For examples of how this is used, consider the ActionListener interface and usage in Swing:

ActionListener
Example implementation of ActionListener: TextAction
Example component that calls-back to an ActionListener: JButton / AbstractButton

In the Swing API, it is common to have support for multiple listeners. You have just one. That is OK.


Finding two indices of numbers which sum to N I'm solving some online puzzles and I had this problem:

  Given a vector, write code to find the indices of TWO values which sum to a given number N

so if I'm given [2, 5, 6] and N = 8, I should output the 0-based indices [0, 2].

I wrote the following code to do this in O(N)

vector<int> twoSum(vector<int>& nums, int target) {
    unordered_multimap<int, int> numbers_multimap;
    numbers_multimap.reserve(nums.size());
    for(size_t i = 0; i < nums.size(); ++i) {
        numbers_multimap.emplace(nums[i], i);
        auto interval = numbers_multimap.equal_range(target - nums[i]);
        for (auto it = interval.first; it != interval.second; ++it) {
            int other_position = it->second;
            if (other_position != i)
                return vector<int>{i, other_position};
        }
    }
    return vector<int>{};
}

and it works, but I noticed that there are faster solutions.

Since I suppose the algorithm is already quite fast, I'd like to know if there are additional pro tips to improve the runtime of this code.

You can emplace after testing for the complementary, it simplifies the code and avoids using a multimap:

vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int, int> numbers;
    //removed because can be very inefficient if nums is big or there are a lot of duplicates
    //numbers.reserve(nums.size());

    //a micro optimization could be to loop from the back and compare
    // i to 0 in the test but it doesn't weigh much against container operations
    for(size_t i = 0; i < nums.size(); ++i) {
        int num = nums[i];
        if (num > target) {
            continue; //no need to waste time storing it either, assuming all numbers are unsigned
        }

        auto it = numbers.find(target - num);
        if (it != numbers.end()) {
           return {i, it->second};
        }
        //no need to emplace for integers? actually slower than insert if key is already present
        numbers.insert({num, i});
    }
    return {};
}

If the values are in a range comparable to the size of the vector, you can just create a valarray<int> of size maxValue+1, fill it to -1 on initialization, and use that instead of the map to check if a value is already present.

Another small optimization that can be done would be to have your loop like that:

int i = 0;
for (int num : nums) {
    //...
    //calls to 'continue' can be replaced by goto endloop

endloop:
    i++; //equivalent in performance to ++i for basic types
}

Iterating over the container like this (which is actually moving a pointer forward) is faster than accessing the element of the vector by its index every time. Although it's a relatively small optimization given that there are map operations used in the loop itself.


Determine if number is a prime number I made a function that takes an argument x and returns True if x is a prime number and False if x is a non-prime number.

I am a beginner and think the code can be improved. I had to add the else statement because for is_prime(2), I kept getting None instead of True. I think this was because when x is 2, list_n = range(2,2) prints [].

Are there ways I could change this so there is not a separate else statement?

def is_prime(x):
    list_n = range(2,x)

    if x <= 1:
        return False
    elif x-1>2:
        for n in range(len(list_n)):
            list_n[n] = x % list_n[n]
        for n in list_n:
            if n == 0:
                return False
        for n in list_n:
            if n > 0:
                return True
    else:
        return True

To begin with, you don't need list_n at all: a decision that the number is composite can be made on the fly, as soon as some remainder becomes 0. If none of them were 0, you know that the number is prime:

    for n in range(2, x):
        if x % n == 0:
            return False
    return True

is effectively what your code is doing, but without the list, and without special case for 2.

That said, of course the algorithm could be greatly improved, but it is beyond the point of this exercise.


Better card validity check in JS card game I am writing a card game in Javascript. The game is played with a 32 card deck.

When a card is selected to be played by a user, i do a validity check on the server to check whether it matches the games rules.

These are

A card may be played when it matches either the color or the value of the last card on the stack
If a 7 is played, the next player must either draw 2 cards or counter with another 7. If he draws, he may play another card that complies the rule above.
A jack may be played anytime when there is no 7 to be countered or the player has drawn. It does not have to match the color or value of the last card. When a player plays a jack, he may decide the color of the next card to be played.

I created a class of game that, amongst others, implements a function iscardLegal()

Game.prototype.isCardLegal = function(card,player){

    if(player.flags.forcedDraw > 0 && card.value !== '7'){
        player.setTask('forced draw');
        return false;
    }

    // A jack may be played anytime if there is no 7 on top of the stack
    if(card.value === 'J'){
        return true;
    }

    if(this.forcedColor && this.forcedColor !== card.color){
        player.setTask('color mismatch');
        return false;
    }

    // If there is a forced color due to the playing of a jack, we must ignore the stack#s top card color
    if(this.forcedColor && this.forcedColor === card.color){
        return true;
    }

    if(this.lastCardOnStack().color !== card.color && this.lastCardOnStack().value !== card.value){
            player.setTask('invalid card');
            return false;
    }

    return true;

};

I am unhappy with this function because I end up with a chunk of if rules that need to be in a certain order to match all the rules. If I imagine writing a slightly more complex game, I think this would be unmaintainable.

I am looking for ideas and / or examples of better implemenations of this functionality.

This is my new attempt

Game.prototype.isCardLegal = function(card,player){

    var requirements = this.getRequirements();

    if(this.cardsToDraw() > 0 && card.value !== '7'){
        player.setTask('forced draw');
        return false;
    }

    if (card.color !== requirements.color && card.value !== requirements.value && card.value !== 'J') {
        player.setTask('invalid card');
        return false;
    }

    return true;

};

When a card is played the game state will be updated with the required color / value. When the played card is a jack or a 7, the respective requirements are set accordingly. So I don't have to distinguish between the color of the last card palyed and a possible forced color any more, as in both cases the game state property will be updated.

I'm still looking for ideas, though.


Ruby function to capitalize all words in a string The task is to write a function, which capitalize the first letter of all words in a string. For this we'll class a word as any characters separated by a blank. Because the standard String.capitalize method only capitalizes the first character of the string I have written the following.

Could the task be accomplished with writing less code? Any other improvements-suggestions concerning the function?

Here's the code I have written:

def capitalizeAllWords(str)
    caps = str.split(" ").map do |word|
        word.capitalize
    end
    caps.join " "
end

puts capitalizeAllWords "Red orange green blue indigo violet"
# Prints: "Red Orange Green Blue Indigo Violet"

You could make it a one liner. If you want to get fancy checkout Rail's implementation https://apidock.com/rails/v5.2.3/ActiveSupport/Inflector/titleize

str.split.map(&:capitalize).join(' ')


Convert string to spinal case Due to an excercise, I've made a function that converts given string to spinal case just-like-this-one (all lower case).
I did it with two regular expressions. Can it be done with one, or generally better?

function spinalCase(str) {
  //if string is not delimited
  if(str.search(/[_\s]/) === -1){
    // insert dash before every uppercase letter
    return str.replace(/(?=[A-Z])/g , '-').toLowerCase();
  } else {
    //change delimiters to dashes
    return str.replace(/[_\s](?=[a-zA-Z])/g, '-').toLowerCase();
  }
}

edit:
variable naming was forced by excercise (wouldn't complete otherwise).
Example converted input:

"This Is Spinal Tap"

"thisIsSpinalTap"

"The_Andy_Griffith_Show"

"Teletubbies say Eh-oh"

This does it in two steps:

Add spaces before each uppercase, which allows the uppercases to be handled by...
The delimiter case.  This is the same regex you already wrote, although I am collapsing multiple delimters down to a single one.

Having two transformation passes, similar to using a unix pipeline, is easier to reason about that breaking it up into two cases with an "if else".

Note the cryptic (?!^) matches "not at the beginning of a line" only

function spinalCase(str) {
  return str.replace(/(?!^)([A-Z])/g, ' $1')
            .replace(/[_\s]+(?=[a-zA-Z])/g, '-').toLowerCase();
}

All of your test cases pass:

this-is-spinal-tap
this-is-spinal-tap
the-andy-griffith-show
teletubbies-say-eh-oh


Retrieving HKLM nodes of Windows10 Registry I have used below code, code is working fine, also retrieved the data, but there are performance issues. Retrieving the HKLM registry nodes is taking around 6 mins time. Please suggest any solution.

Private Function f_AddNodes(ByVal WindowsRegistryKey As RegistryKey, ByVal TreeNode As TreeNodeCollection, ByVal RegParent As Integer) As Integer
        Dim root As TreeNode
        If count = 1 Then
            root = TreeNode(RegParent)
        Else
            Dim KeyName = WindowsRegistryKey.Name
            Dim nLastIndex = KeyName.LastIndexOf("\")
            KeyName = KeyName.Substring(nLastIndex + 1, (KeyName.Length - 1) - nLastIndex)
            root = TreeNode.Add(KeyName) 'Node adding
        End If

        For Each subkeyName As String In WindowsRegistryKey.GetSubKeyNames
            Try
                Form_LoadingBar.Value(WindowsRegistryKey.Name)
                count = count + 1
                Dim vSubKey As RegistryKey = WindowsRegistryKey.OpenSubKey(subkeyName)
                f_AddNodes(vSubKey, root.Nodes, -1)
            Catch ex As SecurityException
                sExceptionHandling.Append(WindowsRegistryKey.Name + "\" + subkeyName + "," + ex.Message + vbNewLine)
            Catch ex As Exception
                MsgBox(ex.ToString)
                Return -1
            End Try
        Next`enter code here`
        Return 0
    End Function

It looks to me, one of your biggest problems is working directly with the Nodes of the TreeView.  This necessitates calling Paint() everytime you add a node.  If you start with a new TreeNode as root, and build the tree on that, you can add the whole thing to the TreeView by adding the root to the Nodes.

I also found that running VS as administrator greatly reduced the number of errors, which also sped it up.

By using a custom TreeNode class that inherits from Forms.TreeNode, you can recursively fill the tree inside the class.  This also allows you to store the actual RegistryKey object in each node.  Here's a relatively simple way of doing it:

Public Class RegistryTreeNode
    Inherits TreeNode
    Private Class SecurityExceptionLogger
        Private Shared Property Exceptions As New List(Of (String, SecurityException))
        Private Shared TempFileName As String = Path.GetTempFileName()
        Private Shared writer As StreamWriter
        Private Shared reader As StreamReader
        Public Shared Async Sub Add(exception As SecurityException)
            Exceptions.Add((Now.ToUniversalTime, exception))
            Using writer = New StreamWriter(TempFileName, True)
                Await writer.WriteLineAsync($"{Now.ToUniversalTime} - {exception.Message}")
            End Using
        End Sub
        Public Shared Sub PrintExceptions(stream As StreamWriter)
            Using stream
                Exceptions.ForEach(Async Sub(x)
                                       Await stream.WriteLineAsync($"{x.Item1} - {x.Item2.Message}")
                                   End Sub)
            End Using
        End Sub

    End Class
    Private _RegKey As RegistryKey

    Private Property RegKey As RegistryKey
        Get
            Return _RegKey
        End Get
        Set
            _RegKey = Value
            Name = _RegKey.Name
            Text = Name
            For Each key In _RegKey.GetSubKeyNames
                Try
                    Nodes.Add(New RegistryTreeNode(_RegKey.OpenSubKey(key)))
                Catch ex As SecurityException
                    SecurityExceptionLogger.Add(ex)
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try
            Next
        End Set
    End Property

    Public Sub New()
        MyBase.New()
        RegKey = Registry.LocalMachine
    End Sub
    Public Sub New(newRegistryKey As RegistryKey)
        MyBase.New()
        RegKey = newRegistryKey
    End Sub
End Class

I hardcoded the default key to Registry.LocalMachine for your uses.  Simply Dim root = New RegistryTreeNode() and the whole tree will build itself.

You'll notice I made a simple logger that writes to file as well as keeping a record in memory, instead of just in memory, just as an exercise.

Another way to speed things up, is to only load the first sub level of nodes on start up.  You can then use the AfterSelect event handler to load the sub nodes of the key you want to expand.  Something like this:

Public Class Form1
    Dim root = New RegistryTreeNode(Registry.LocalMachine)
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        TreeView1.Nodes.Add(root)
    End Sub

    Private Sub TreeView1_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterSelect
        Dim node = DirectCast(TreeView1.SelectedNode, RegistryTreeNode)
        For Each key In node.GetSubKeyNames
            Try
                Dim regKey = New RegistryTreeNode(node.OpenSubKey(key))
                If Not regKey Is Nothing Then
                    node.Nodes.Add(regKey)
                End If

            Catch ex As SecurityException
                SecurityExceptionLogger.Add(ex)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        Next

    End Sub

End Class
Class SecurityExceptionLogger
    Private Shared Property Exceptions As New List(Of (String, SecurityException))
    Private Shared TempFileName As String = Path.GetTempFileName()
    Private Shared writer As StreamWriter
    Private Shared reader As StreamReader
    Public Shared Async Sub Add(exception As SecurityException)
        Exceptions.Add((Now.ToUniversalTime, exception))
        Using writer = New StreamWriter(TempFileName, True)
            Await writer.WriteLineAsync($"{Now.ToUniversalTime} - {exception.Message}")
        End Using
    End Sub
    Public Shared Sub PrintExceptions(stream As StreamWriter)
        Using stream
            Exceptions.ForEach(Async Sub(x)
                                   Await stream.WriteLineAsync($"{x.Item1} - {x.Item2.Message}")
                               End Sub)
        End Using
    End Sub

End Class
Public Class RegistryTreeNode
    Inherits TreeNode

    Private _RegKey As RegistryKey

    Private Property RegKey As RegistryKey
        Get
            Return _RegKey
        End Get
        Set
            _RegKey = Value
            Name = _RegKey.Name
            Text = Name.Substring(Name.LastIndexOf("\"c) + 1)

        End Set
    End Property

    Public Sub New()
        MyBase.New()
        RegKey = Registry.LocalMachine
    End Sub
    Public Sub New(newRegistryKey As RegistryKey)
        MyBase.New()
        RegKey = newRegistryKey
    End Sub
    Public Function GetValueNames() As List(Of String)
        Return _RegKey.GetValueNames().ToList()
    End Function
    Public Function GetValueKind(name As String) As RegistryValueKind
        Return _RegKey.GetValueKind(name)
    End Function
    Public Function GetValue(name As String) As Object
        Return _RegKey.GetValue(name)
    End Function
    Public Function GetSubKeyNames() As String()
        Return _RegKey.GetSubKeyNames()
    End Function
    Public Function OpenSubKey(key As String) As RegistryKey
        Return _RegKey.OpenSubKey(key)
    End Function
End Class

I moved the SecurityExceptionLogger outside the RegistryTreeNode class.  You can also load the values for the keys, if needed, by looping through them after the sub nodes are added.


Solving roots of negative numbers As part of an assignment for college summer classes, I was tasked with writing a program that solves roots of negative numbers. I've ran it through the test cases I was provided and it computes correctly. I'm looking for any feedback, especially about the determine_factors function, which really should be renamed. It looks messy and I don't like it, but it's all I could come up with. I'll be tweaking it since it's not due for a while, but I wanted to get some experienced eyes on this.

"""
Helper tool for solving negative square roots.

@author Ben Antonellis
@date 06-08-2020
"""

from math import isqrt

from typing import List, Union, Tuple

def is_perfect(number: int) -> bool:
    """
    Returns if a number is a perfect square.
    """
    return number == isqrt(number) ** 2

def get_factors(number: int) -> List[List[int]]:
    """
    Returns all the factors of a number.
    """
    factors = [[x, number // x] for x in range(2, number + 1) if number % x == 0]
    factors = factors[:len(factors) // 2] # Removes duplicates and any [1, x] pairs #
    return factors

def determine_factors(factors: List[int], num: int) -> str:
    """
    Determines what factors are left at the end of calculation.
    """
    simplified, remainder = 0, 0
    for number, times_in_number in factors:
        if number == times_in_number:
            return f"{number}i"
        if get_factors(number) == [] and get_factors(times_in_number) == []:
            return f"√({num})i"
        if is_perfect(number):
            simplified += isqrt(number)
            if not is_perfect(times_in_number):
                if get_factors(times_in_number) == [] or not any(is_perfect(x) or is_perfect(y) for [x, y] in get_factors(times_in_number)):
                    remainder += times_in_number
                    return f"{simplified}√({remainder})i"
        elif is_perfect(times_in_number):
            simplified += isqrt(times_in_number)
            if not is_perfect(number):
                if get_factors(number) == []:
                    remainder += number
                    return f"{simplified}√({remainder})i"
    if not any(is_perfect(number) or is_perfect(times_in_number) for number, times_in_number in factors):
        return f"√({num})i"

def solve(num: int) -> str:
    """
    Solves a negative square root with the passed number.
    """
    num = abs(num)

    # Check for prime numbers #

    if not any(num % i == 0 for i in range(2, num)):
        return f"√({num})i"

    # Find all factors #

    factors = get_factors(num)

    # Determine what factors to use and weed out perfect numbers #

    return determine_factors(factors, num)

def main():
    num = int(input("Enter negative inside square root: "))
    result = solve(num)
    print(result)

if __name__ == "__main__":
    main()

Test cases are below

Input -> Output
---------------
-52 -> 2√(13)i
-20 -> 2√(5)i
-35 -> √(35)i
-36 -> 6i
-30 -> √(30)i
-18 -> 3√(2)i
-70 -> √(70)i
-90 -> 3√(10)i
-100 -> 10i

Style
You've done a great job of style from a technical point of view.

You're following PEP-8 guidelines.
The functions have type-hints
The functions have docstrings

Defects:

The docstrings aren't very useful:
>>> help(get_factors)

Help on function get_factors in module __main__:

get_factors(number: int) -> List[List[int]]
    Returns all the factors of a number.

This doesn't explain what the factors are going to be.  A list of list of integers, yes, but no clue what that means, or to expect that [1, x] will be excluded.

the determine_factors method is a wall of code, with not a single comment insight describing how it is supposed to work.

is_perfect()
This is actually pretty close to perfect.  :-)
get_factors()
You are (without any indication to the caller) omitting [1, x] (should be at least mentioned in the docstring.
You are finding all factors from 2 up to (and including!) number, which means the last pair generated is [number, 1].  Why do you skip generating [1, number] by starting at 2, yet continue up to number + 1?
How does factors[:len(factors) // 2] remove duplicates, when it is using truncating integer division, and you can have an odd number of factor pairs?
Why bother generating the factor pairs if you are just going to discard half of them anyway?  Just iterate from 2 up to (and including) isqrt(number).  Way more efficient.
determine_factors()
I have no idea how this function works.  simplified += ... and remainder += ...?  Multiplication of factors is not additive, so this doesn't make sense.
Moreover, the function doesn't work.  -54 and -96 return nothing:
>>> solve(-54)
>>> solve(-96)

A better algorithm
Instead of computing all of the factors of number, determine the prime factorization of number.  For instance:
$$ \sqrt {96} = \sqrt { 2^5 * 3^1 } $$
Any odd power will result in that factor to the power of 1 under the square root.  After removing those, you've got primes raised to even powers, which can all be divided by two, and moved out from the square-root:
$$ \sqrt {96} = \sqrt { 2^4 } * \sqrt {2^1 * 3^1} = 2^2 * \sqrt {2^1 * 3^1} $$


Select latest phase of objects not marked "remove" I have the following table in a PostgreSQL DB (simplified for the question), where I want to select only the rows marked with *:

uuid | status | info1 | info2
-------------------------------
1234 |   CONF |     - | 10
1234 |  START |   abc | 10
1234 |    FIN |   abc | 10 *
-------------------------------
7890 |   CONF |     - | 20 *
-------------------------------
1111 |   CONF |     - | 30
1111 |  START |   zzz | 30
1111 |    FIN |   zzz | 30
1111 |    REM |   zzz | 30
-------------------------------
2222 |   CONF |     - | 100
2222 |  START |   ijk | 100 *

The separating lines between different values of uuid are only for clarity, as I will explain now.

The logic for selection is the following:

Partition the table by the column uuid in order to create groups of all the different values.
Discard all the groups where there is at least one row with status REM.
For all the remaining groups, select only the one with the last status. The values of this column define a custom order like this: CONF < START < FIN. The value REM is only used to remove this group of the selection.

I wrote this query that does the job, but I think there might be a better solution, and I have the sensation of abusing the subtable structures:

SELECT *
FROM (
    SELECT MAX(numericphase.phase) OVER (PARTITION BY numericphase.uuid) AS s
    , *
    FROM(
        SELECT
         CASE
                WHEN status = 'FIN' THEN 3
                WHEN status = 'START' THEN 2
                WHEN status = 'CONF' THEN 1
                ELSE -1
            END AS phase
        , *
        FROM (
            SELECT *
            , BOOL_OR(status = 'REM')
            OVER (PARTITION BY uuid) AS removed
            FROM mytable
        ) nonremoved
        WHERE NOT removed
    ) numericphase
) lastphase
WHERE s = phase
AND s > 0

Here I'm doing the following operations (from inner to outer):

First, select all rows where status is not REM (using BOOL_OR).
Then, map each status value to a numeric one so they can be sorted.
Compute the maximum value of each uuid group (corresponding to the last status following the custom sorting).
Finally, select only rows where status = max(status). This way, only the rows corresponding to the maximum status for each group are selected.

Any possible status that does not correspond to any value in this question is not suitable, so they are mapped to -1 and discarded.

I think is easier to understand the problem by looking at the table than trying to redact it, so feel free to correct me if something is not clear.

As I wrote in my edit of the question, I came to the following solution, which I think could be better optimized, but does the job:

SELECT *
FROM (
    SELECT *
    , MAX(numericphase.phase) OVER (PARTITION BY numericphase.uuid) AS s
    FROM (
        SELECT *
        , CASE
            WHEN status = 'REM' THEN 4
            WHEN status = 'FIN' THEN 3
            WHEN status = 'START' THEN 2
            WHEN status = 'CONF' THEN 1
            ELSE -1
        END AS phase
        FROM mytable
    ) numericphase
) lastphase
WHERE phase != 4
AND s = phase
AND s > 0


Large table updates using AJAX in Internet Explorer 11 I have a website which only needs to support IE11. It is a single page application, which has about 200 table rows and each table row has 5 child rows.

There is a pulsing function that updates the table as records come in. Table rows are skipped over if no update comes in.

However, when receiving large updates (which should only occasionally happening), the application will hang as it slowly processes the javascript. I've tried to limit the JavaScript as much as possible, but still have a long running function.

I am a backend developer by nature, and was wondering if anyone had any tips to help support large table Ajax updates for IE since IE so poorly handles JS.

function writeTableLines(tempRows){
    /* This Function takes care of updating the text and coloring of
    required dynamic fields.
    All other values are not dynamically written.
    */
    for( i in tempRows){
   //i is the computer name
        tempValues = tempRows[i];
        // For Row
        selector = "[id='"+i+"']";

        // Network Name
        network_selector = "[id='"+i+"_network']";
        $(network_selector).text(tempValues['network']);

        if (tempValues['network_color']){
            $(network_selector).addClass(tempValues['network_color']);
            $(selector).find('.name').addClass(tempValues['network_color']);
        }else{
            $(network_selector).removeClass('warning');
             $(selector).find('.name').removeClass('warning');
        }

        // Boot Time
        boot_selector = "[id='"+i+"_boot']";
        $(boot_selector).text(tempValues['boot']);
        if (tempValues['boot_color']){
            $(boot_selector).addClass(tempValues['boot_color']);
            $(selector).find('.name').addClass(tempValues['boot_color'])
        }else{
            $(boot_selector).removeClass('issue');
            $(selector).find('.name').removeClass('issue');
        }

        // Last Checked In Timestamp
        check_in_selector = "[id='"+i+"_checked_in']";
        $(check_in_selector).text(tempValues['checked_in']);
        if (tempValues['service_unresponsive']){
            $(check_in_selector).addClass('redline');
            $(selector).find('.name').addClass('redline');
        }else{
            $(check_in_selector).removeClass('redline');
            $(selector).find('.name').removeClass('redline');
        }

        util_selector = $(selector).find('td.util').find('a');
        $(util_selector).text(tempValues['util'])
         if (tempValues['util_class']){
            $(util_selector).addClass(tempValues['util_class']);
        }else{
            $(util_selector).removeClass('redline warning');
        }

        workgroup_selector = $(selector).find('td.workgroup');

        if (($.trim(tempValues['workgroup'])) != $.trim($(workgroup_selector).text())){
            if ((tempValues['workgroup'] != selected) && (selected != 'All')){
                $(workgroup_selector).addClass('warning');
            }else{
                $(workgroup_selector).removeClass('warning');
            }
        }
        $(workgroup_selector).text(tempValues['workgroup'])
        toggle_links(i, tempRows[i]);
        $('#connectionGrid').trigger('updateAll', [false]);
    }
}

This function iterates over only received data. For each row item that was received, update the text of the cell, and add coloring as necessary.

I'm thinking I might just be screwed since its IE, but am open to all suggestions and ideas.

Image of the rows - child rows only available when expanded, but still need updates.

Searching a whole, large DOM for elements is a real performance killer. When possible, always try to search a fragment, or traverse the DOM relative to a known element.

With a little rearrangement of the HTML, "network", "boot" and "check_in" elements can be found within the corresponding "selector" element, similar to the way "util" and "workgroup" elements are currently found. This alone should give a significant performance boost.

HTML

There's a missing
 somewhere.
Move
 and
 inside the loop/if lines to give one tbody per computer block. (Hopefully tbodys will not mess up tablesorter).
Move id="{{computer.name}}" into the
 tag.
Give a class name to elements that need to be addressed :

For example, change :

{{ computer.active_drive.name }}

to:

{{ computer.active_drive.name }}

Then, if they are not required elsewhere, purge all IDs in the repeated block.

Javascript

The javascript can now be written to exploit the tbody wrappers.

function writeTableLines(tempRows) {
    /*
     This Function takes care of updating the text and coloring of required dynamic fields.
     All other values are not dynamically written.
    */
    var tempValues, $tbody, $name, $network, $boot, $check_in, $util, $workgroup,
        $connectionGrid = $('#connectionGrid');

    // Avoid creating so many strings in the loop by defining class names and selectors here.
    // This is more a memory consideration than speed.
    var clss = {
        'warning': 'warning',
        'issue': 'issue',
        'redline': 'redline'
        'redlineWarning': 'redline warning',
    };
    var selectors = {
        'network': '.network',
        'boot': '.boot',
        'check_in': '.checked_in',
        'name': '.name',
        'util': 'td.util a',
        'workgroup': 'td.workgroup'
    };

    for(i in tempRows) {
        tempValues = tempRows[i];

        // Find the container
        $tbody = $('#' + i); // This is the only element in each block that needs an ID.

        if($tbody.length == 0) return; // avoid unnecessary work if element is not found

        // Now find elements by class, within the container
        $network = $tbody.find(selectors.network);
        $boot = $tbody.find(selectors.boot);
        $check_in = $tbody.find(selectors.checked_in);
        $name = $tbody.find(selectors.name);
        $util = $tbody.find(selectors.util);
        $workgroup = $tbody.find(selectors.workgroup);

        // In all the code below, address tempValues properties with dot.notation, not associative['notation']

        $network.text(tempValues.network);
        if (tempValues.network_color) {
            $network.addClass(tempValues.network_color);
            $name.addClass(tempValues.network_color);
        } else {
            $network.removeClass(clss.warning);
            $name.removeClass(clss.warning);
        }

        $boot.text(tempValues.boot);
        if (tempValues.boot_color) {
            $boot.addClass(tempValues.boot_color);
            $name.addClass(tempValues.boot_color);
        } else {
            $boot.removeClass(clss.issue);
            $name.removeClass(clss.issue);
        }

        $check_in.text(tempValues.checked_in);
        if (tempValues.service_unresponsive) {
            $check_in.addClass(clss.redline);
            $name.addClass(clss.redline);
        } else {
            $check_in.removeClass(clss.redline);
            $name.removeClass(clss.redline);
        }

        $util.text(tempValues.util);
        if (tempValues.util_class) {
            $util.addClass(tempValues.util_class);
        } else {
            $util.removeClass(clss.redlineWarning);
        }

        if (($.trim(tempValues.workgroup)) != $.trim($workgroup.text())) {
            if (tempValues.workgroup != selected && selected != 'All') {
                $workgroup.addClass(clss.warning);
            } else {
                $workgroup.removeClass(clss.warning);
            }
        }
        $workgroup.text(tempValues.workgroup);

        toggle_links(i, tempValues);
        $connectionGrid.trigger('updateAll', [false]);
    }
}

Some of the code looks to be as little dodgy. For example, .addClass(tempValues.network_color) ... .removeClass('warning') means that any added class that is not warning will never be removed (unless by some other code). Contrast with .addClass('redline') ... .removeClass('redline'), which is guaranteed to add/remove the same class.

Aside: With the tbodys in place, you could consider styling them with eg a border that will expand/contract as the details are shown/hidden.

If performance is still poor, you'll need to investigate deeper to discover what's taking time. Though I'm not an expert driver, Chrome debug tools are very good for diagnosis.

Edit

Back to a single
 but with class="info network", class="info boot", class="info check_in", in place, try selecting as follows :

// Find the parent row
var $tr = $('#' + i); // A parent row

if($tr.length == 0) return; // avoid unnecessary work if element is not found

var $childRows = $tr.nextUntil(".parent"); // the parent's child rows

$network = $childRows.find(selectors.network);
$boot = $childRows.find(selectors.boot);
$check_in = $childRows.find(selectors.checked_in);

$name = $tr.find(selectors.name);
$util = $tr.find(selectors.util);
$workgroup = $tr.find(selectors.workgroup);

This will be slightly less efficient than finding elements within tbody containers but still better than finding by ID - and Tablesorter will still work.


Square root approximation with Newton's method I designed a program that calculates the square root of a number using Newton's method of approximation that consists of taking a guess (g) and improving it (improved_guess = (x/g + g)/2) until you can't improve it anymore:

#include <iostream>
#include <iomanip>
using namespace std;

template <class Y>
Y sqrt (Y x)
{
    double g (1), ng;
    while (true) {
        ng = (x/g + g)/2;
        if (g != ng) g = ng;
        else if (g == ng) break;
    }
    return g;
}

void menu()
{
    double x, g;
    string a = "";
    do {
        cout << "Enter a number to get the sqrt of: ";
        cin >> x;
        g = sqrt(x);
        cout << "The result is: " << setprecision(100) << g << endl;
        cout << "Result^2 = " << setprecision(100) << g*g << endl;
        cout << "\nDo it again ? <y/n> ";
        cin >> a;
        cout << endl;
    } while (a == "y");
}

int main()
{
    menu();
    return 0;
}

Can you see any way to improve this ? Like in the "do it again" part, I just couldn't use y/n...

Looks fairly good over all, but a few things jumped out at me. Please note that the stylistic ones are opinion based.

Make sure you don't get into a habit of using namespace std;. It's acceptable in some places, but it can form a bad habit very easily. Your code is a perfect example of this since your sqrt will conflict with std::sqrt if you include cmath or math.h. A lot more discussion on the matter can be found here.

If you're not going to put your function in a namespace, I would avoid calling it sqrt. In fact, unless you have a compelling reason, it's best to avoid names from the standard library in general.

I would leave a blank space after your header lines. The typical format is:

#include "local1.h"
#include "local2.h"

#include <blah1>
#include <blah2>

// stuff here

Also, I would consider alphabetizing the headers. When there's a long list of headers, it can help make quick mental scanning easier.

You forgot to include string.

Your c variable in sqrt isn't used.

I don't like the use of the constructor form initialization of primitives. I would stick with plain old equals.

Also, it's fairly typical to define one variable per line when values are being assigned during declaration.

double g = 1;
double ng;

I'm not quite sure why sqrt is templated. By using doubles internally, you've basically restricted it to doubles. If you're going to make it templated, use the templated type all the way through.

Y is a bad typename. Use something more descriptive like FloatingPoint or Number.

Consider taking x by const reference in sqrt. If an expensive-to-copy class is used as the template parameter, you're causing an unnecessary copy since x is never modified.

In menu, you should check if reading in a double was successful:

if (std::cin >> x) {
    // Use x
} else {
    std::cerr << "Invalid value provided\n";
}

Try to declare variables as close to usage as possible. For example, your g = sqrt(x); could be double g = sqrt(x);. Seeing a giant list of variables declared at the top of a function is overwhelming. If they're defined where they're used, it's much simpler to see their relation to the overall code.

If you're using C++11, avoiding naming types except where necessary. This will ease future change of type. For example, imagine that at some point you want to use some kind of Complex class instead of a built in double. If you only name the type for the input x and use auto else where, you'll only have to change one thing (provided the class overrode operator>> for istreams). You can read more about this here.

When it's not possible for the program to return a non-0 exit code, I like to omit it. This signifies at a simple glance that the program always exits with a success code.