That's pretty good! Some small points...

Motivation

As, some of the comments point out, standard algorithms exist for std::sort and std::partition. You seem to be doing this in order to learn about algorithm implementation. That's fine and good for learning. Please be aware that in general / commercial / production code you should probably not be writing this and should use the above standard library functions instead.

Completeness

As some other comments point out, please try to post complete code. ie include the #include statements so that the code compiles and runs as posted.

Form / style / minor

It is generally discouraged to use using namespace std;; which would
be required to make your code work, because that includes a whole namespace and can cause clashes.
Generally avoid declaring more than one variable on one line.
The size() of containers returns std::size_t, which is usually an
unsigned long. If you enable -Wall -Wextra (on gcc / clang)
during compilation this will often give you warnings when you are
comparing with int. Your code as posted as actually OK on this
front, but it is still good practice to use std::size_t for those
integers which represent an index into a vector or similar  (bigger
max value too, for very large vectors). I usually write a using std::size_t to avoid having to repeat std:: for each variable declaration.
using at() is slower than operator[] because it does bounds checking. This might be what you intended, but given the "closed" nature of the algorithm it should be possible to use operator[] without errors or undefined behaviour.
You could use try using default params to DutchFlag() for low/high to avoid the caller having to specify 0, size() in the external API.
In general C++ and the STL tend to use Iterators and not vector indeces. So it would be more idiomatic for DutchFlag to take begin(), end() iterators.
C++ (like python) also uses the "one past the end" convention for a range of iterators, so DutchFlag (as written) should probably be taking 0, size() and some of your <= should change to <.

Algorithm

I am not an expert on the Dutch flag algo. Clearly a plain quicksort, which you have implemented, works. Are there some efficiencies which can be gained from the knowledge that there are lots of repeats and only 3 possible values? If there are, you should probably try to achieve some of those. Otherwise this is just quicksort? See the example code on std::partition reference page.

For example, one might imagine an algorithm where you just have a local int counts[3]{0} run through the unsorted data and counts[v]++. Then produce an answer which repeats each value count[v] number of times. This is O(N) as opposed to quicksort which is generally O(NlogN).

Something along these lines:

#include <array>
#include <iostream>
#include <iterator>
#include <vector>

using std::size_t;

void DutchFlag(std::vector<int>& nums) {
  auto counts = std::array<size_t, 3>{0};

  for (auto n: nums) ++counts[n];

  auto start = std::begin(nums);
  for (int i = 0; i < 3; ++i) {
    auto end = std::next(start, counts[i]);
    std::fill(start, end, i);
    start = end;
  }
}

int main() {
  std::vector<int> nums = {0, 1, 2, 2, 2, 1, 0, 0};
  DutchFlag(nums);
  std::copy(nums.begin(), nums.end(), std::ostream_iterator<int>(std::cout, " "));
}

It depends on what your motivation is, but such an algorithm would likely be faster for very large inputs and the code is probably simpler (than implementing quicksort by hand).


A few notes on your current code:

Your test case descriptions don't make a lot of sense - try reading them out loud: It should return true 50% of the time... and 75% of the time... and 25% of the time... etc.. Wait, which is it? You're omitting the argument in the description, so the descriptions become confusing and/or meaningless.
You're adding 1 in the percent method, but not in the proportion method. So a zero-in-1 chance always works out to true! And even a 0 in 1,000,000 is still a chance! Probably not what you want. For both methods I'd suggest using a range argument instead.
You're including Singleton for no reason, since you define your methods as class/static methods. So there's no point in instantiating the class - as a singleton or otherwise.
What happens if you pass floating point or negative numbers? That's an exercise for the reader.
Your results.select{|x|x}.count can be simplified to just results.count(&:itself)
Let one method call the other: percent could just call proportion(amount, 100). That way you can focus on testing proportion as that's the only one that actually doesn't anything random. And you'd more easily avoid/fix the bug mentioned above, since it'd only exist in one method, not two.

But as for testing randomness in general: In this case, I'd say don't bother. Because you can't really test it. Your current tests are fuzzy (±10 within target) just so they'll pass more reliably. But that's changing the tests to suit the output, rather than the other way around.

What you want are tests that are strictly pass/fail. This you can do for things like it "raises an ArgumentError for negative arguments" but not so much for the normal operation of the methods.

What it comes down to is whether you trust Ruby to:

do basic arithmetic and comparison
reliably generate pseudo random numbers (here's the C source for Ruby's random, in case you're interested)

If you trust that, well, testing doesn't make much sense anymore.

Instead spend the time reviewing your code throughly. As seen above, your tests didn't cover the zero-in-N chance bug, and you didn't catch it either. For 2 single-line methods, you wrote an order of magnitude more test code - that effort seems misplaced, when the tests are fudged to pass and the code is buggy.

If you still insist on writing a test, then write a single test case that takes maybe a million samples for 50% or 1-in-2, and checks whether the result is within a narrower tolerance. But I'd run this test by itself a dozen times, but disable it when running the full suite (e.g. tag it so it can be included/excluded easily). It may still fail because it is still random, but that's no reason to fail the entire suite if you've tested thoroughly beforehand. (Edit: For a small project, it's fine to run this test every time, but if your code is on a CI server or you have automation relying on the result of the tests - e.g. can't commit/push to SCM without green tests - it's a pain to have all that at the mercy of randomness.)

Meanwhile you can still do single-sample tests for outliers: 0% chance should be false, 100% should be true, and 0-in-1 should be false, 1-in-1 should be true. Those can be run with the rest of the suite everytime - and should they suddenly, randomly fail, well, something's definitely wrong so start debugging.


The answer, I found out now, was that if I moved the Regexes to private fields, and then used those, after the first use it will radically drop down to .4ms, and that's including a WriteLine call. So the real hotspot in this method was the Regex. Thanks everyone!


Calculate the sum of a series with a given accuracy

We're including the wrong headers.  We don't need <cstring>, but we do need <cmath> (for std::fabs).
Don't do this:

using namespace std;

That might not be so harmful in small programs, but it's a bad habit have because it makes larger programs more difficult to follow, and it increases the risk of identifier collisions, especially as the standard library continues to grow.
Never ignore the return value from std::system().  There are two uses of this function, and both of them are going to fail here, since I don't have either of the programs installed.  Is it right that they both create a file called nul?  Or did you just misspell /dev/null?
Never ignore the return value from stream-reading operations.  std::cin >> x leaves x uninitialised (before C++11) or zero (C++11 onwards) if it can't perform the conversion.
I don't think you wanted an integer as x anyway - shouldn't it be double?
Error messages should go to std::cerr, not std::cout.
Instead of multiplying i by 2 all the time, consider incrementing i in steps of 2.
The addition is being done in the wrong order.  When adding floating-point numbers, we want to accumulate the smallest values first, so as not to lose precision.
Instead of using the precision() function of a stream, consider using <iomanip>.  17 decimal digits of precision seems too large, given that the value of eps means we won't achieve 6 digits.
Don't use std::endl except when you genuinely need to flush the stream.  That unnecessarily slows programs down.

Here's a version that's modified to fix the above problems:
#include <cmath>
#include <limits>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>

// FIXME - make this a parameter
constexpr double precision = 0.000'001;

int main()
{
    double x;
    std::cin >> x;
    if (!std::cin) {
        std::cerr << "Invalid input\n";
        return 1;
    }

    if (std::fabs(x) >= 1) {
        std::cerr << "The series is divergent above |x|=1\n";
        return 1;
    }

    std::vector<double> terms;
    double term = 1;
    for (auto i = 2ul;  std::fabs(term) >= precision;  i += 2) {
        terms.push_back(term);
        term *= -x * (i + 3) / i;
        if (i > std::numeric_limits<decltype(i)>::max() - 2) {
            // overflow
            break;
        }
    }
    // add smallest terms first
    auto sum = std::accumulate(terms.crbegin(), terms.crend(), 0.0);

    std::cout << std::setprecision(7) << "sum=" << sum << '\n';
}

As suggested by greybeard in comments, the way the function converges means we can get a good estimate of the rest of the series by halving the last term that we consider, and we can terminate when the sum of two consecutive elements is within our precision value:
std::vector<double> terms;
double term = 1;
std::size_t i = 2;
do {
    terms.push_back(term);
    term *= -x * (i + 3) / i;
    i += 2;
} while (std::abs(term + terms.back()) >= precision);

// term/2 is a good approximation to the rest of the series
terms.push_back(term / 2);


Simple TCP Send Receive with multithreading c#

There are several things that can be improved on the current code.

Starting by the listener, if you want to create a TcpListener you can use

var tcpListener = new TcpListener(IPAddress.Loopback, 20000); or
var tcpListener = new TcpListener(IPAddress.Any, 20000);

The Main method looks a bit like spaghetti code.
Specially because you keep alternating statements between things you need for the TcpListener and things that you need for TcpClient.

One possible thing you could do about this is to let StartTcpListenerThread create the TcpListener himself.
Same goes for StartTcpSendingThread.

  var senderPort = listenerPort + 2;

You don't have to be explicit about the port the client should use, since the operating system
will attribute a port dynamically as long as you use TcpClient tcpClient = new TcpClient("localhost", 20000);

  while (true)    {   }

This is great, if you want to increase your power bill by putting your CPU usage on 100.
If you don't want to do that however, you can use Console.ReadLine(); or Thread.Sleep(Timeout.Infinite);

If possible you should also be consistent on whatever you use var or not.

Here is the code with the things I stated applied to it.

public static readonly int Port = 20000;

public static void Main()
{
    StartTcpListenerThread();
    Thread.Sleep(300);
    StartTcpSendingThread();
    Console.ReadLine();
}

static void StartTcpListenerThread()
{
    var tcpListener = new TcpListener(IPAddress.Any, Port);
    tcpListener.Start();
    Thread tcpListenerThread = new Thread(() =>
    {
        while (true)
        {
            try
            {
                var bytes = new byte[1024];
                var currentConnection = tcpListener.AcceptTcpClient();
                var stream = currentConnection.GetStream();
                var numBytesReadFromStream = stream.Read(bytes, 0, bytes.Length);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

        }
    });
    tcpListenerThread.Start();
}

static void StartTcpSendingThread()
{
    var tcpSendingThread = new Thread(() =>
    {
        var tcpClient = new TcpClient("localhost", Port);
        while (true)
        {
            try
            {
                tcpClient.Client.Send(new byte[] { 1, 2, 8 });
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    });
    tcpSendingThread.Start();
}

Regarding your question about exceptions it seems reasonable to me, to catch the exception and display what is wrong to the console. Most of the time this will be due to some network issue and there isn't much you can do on those scenarios. Keeping the listener listening requests may or may not be a good decision but I would say it's at least a somewhat decent decision for a first approach.


Not a PHP expert, but things like

if ($conn->affected_rows() == 1) {
    return true;
} else {
    return false;
}

should be

return $conn->affected_rows() == 1;


Code duplication when converting DTO to String messages

This strikes me as an occasion where a custom method with positional format indexing may help (Formatter argument_index). It is a little-known feature of Java's String.format / Formatter class, that you can reference values by their position. Consider the following methods:

@Override
public static final String formatEscrowPayment(String format, EscrowPayment escrowPayment) {
        String nominalAmountStr = formatInteger(new BigDecimal(escrowPayment.getNominal()));
        String paymentDateStr = dateFormat(escrowPayment.getPaymentDate(), "dd/MM/yyyy");
        String interestRateStr = format(escrowPayment.getInterestRate(), "0.00###");
        String paymentAmountStr = format(escrowPayment.getPaymentAmount());
        return String.format(format,
                        escrowPayment.getSecurityId(), // 1
                        nominalStr,                    // 2
                        paymentDateStr,                // 3
                        interestRateStr,               // 4
                        paymentAmountStr);             // 5

}

private static final void sendExcrowMessage(String template, ExcrowPayment escrow) throws BusinessLayerException {
    try {
        String messageText = formatEscrowPayment(template, escrow);
        sendMessage(messageText);
    } catch (MessagingException e) {
        getLog().error("An error occured while sending the email:", e);
        throw new BusinessLayerException("EscrowPaymentMessage.MessageCouldNotBeSent", e);
    }
}

@Override
public void escrowPaymentWillBeDone(EscrowPayment escrowPayment) throws BusinessLayerException {
    sendEscrowMessage("BLAH BLAH some security with ID %1$s of nominal value EUR %2$s "
                    + "at date %3$s BLAH your account with number 1234567890 will be debited to pay "
                    + "EUR %5$s coupon payment for %%%4$s interest.",
                      escrowPayment);

@Override
public void escrowPaymentIsDone(EscrowPayment escrowPayment) throws BusinessLayerException {
        sendEscrowMessage("BLAH BLAH at date %3$s the security with ID %1$s of nominal value EUR %2$s "
                        + "BLAH your account with number 1234567890 has been debited to pay EUR %2$s." ,
}

Note how the substitution values are handled by their positions.... the %1$s references the first format value as a string. The %3$s references the 3rd value. You can change the order of the positional fields without having to change the positions of the values in the actual format call. Have a look at the documentation


Division by zero

Your implementation returns zero if you devide by zero. That is wrong. Division by zero is undefined.

if (divisor === 0 || dividend === 0) return 0;

On other hand, zero divided by nonzero is zero, that's ok. But zero divided by zero is still undefined. And so it should be checked first.

if (divisor === 0) throw "Division by zero";
if (dividend === 0) return 0;

Edge cases

For some reason you are checking combination -2147483648/-1 then you claim it is 2147483647, but that's wrong. Firstly, 2147483648 is representable in js number type. But if you consider it overflow, you should throw overflow error.

if (dividend === -2147483648 && divisor === -1) throw 'Overflow error';

Btw notice, that -2147483648/n would also overflow further in your code because you convert dividend and divisor to positives. And so maybe you should throw overflow error in this case as well no matter the divisor.

if (dividend === -2147483648) throw 'Overflow error';

Simplify conditions

There is unnecesarily complex condition:

(dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)

assuming the first if was already executed, then the eleseif condition can be simplified as

dividend < 0 || divisor < 0

Or even better, split it in two elseifs, because you have a ternary that checks again.

if (dividend < 0 && divisor < 0) {
      dividend = -dividend
      divisor = -divisor
} else if (dividend < 0) {
        negativeFlag = true
        dividend = -dividend;
} else if (divisor < 0) {
        negativeFlag = true
        divisor = -divisor;
}

Notice that I omitted zeroes, because they have been excluded in the beginning.

Negative flag

This flag is unnecesary, you could instead have an integer variable with value of +1 or -1.

let quotientUnit = 1;
if (...) quotientUnit = -1;
let quiotentHolder = 0;
while (divisor <= dividend) {
     dividend -= divisor; //notice -=
     quiotentHolder += quotientUnit;
}
return quiotentHolder;

Performance

Just of curiosity, have you tried something like big/small. Is it fast? It seems to me the bigger the result of the division, the more time consuming your algorithm is... Not sure if there is a faster way though. Division without division is not something I usualy think of :) But I could suppose there is not, because that's why we have division optimized in our CPUs, where it can be fastened by paralel processing (by which i mean paralel nature of logic gates, not running multiple threads inside a CPU)

EDIT: You mentioned that your "time complexity is about 8248 ms". Firstly, time complexity is not a meassure of time. Time complexity is more like a meassure of relative time consumption based on the size of the input. Since in your case there is no "size of input", time complexity makes no sense with this algorithm. If you wanted to define something like time complexity for your algorithm, it would probably be something like O(dividend/divisor), but this is not really a time complexity, but I am still able to make sense of it...

But let's suppose you meant the actual run time. Not sure what input does the 8248 ms refer to. As I said, the speed is different for different inputs.


LeetCode: Binary Tree Level Order Traversal C#

Avoid unnecessary variables

The counter variable is unnecessary.
For each level, you need just a List<int> level,
add the elements of the level to this list,
and then add this list to res.

By eliminating this variable, you also eliminate any concerns about the correctness of res[counter].Add(temp.val);.
With the code changed to level.Add(temp.val),
the mental burden is reduced.

Use more descriptive names

res could be levels
temp could be node
LevelOrder could be GetLevels
BinaryTreeLevelOrderTraversalClass would be better without Class


Implementing `create` and `destroy` functions to replace `new` and `delete` operators

After some research, I'm convinced Christopher Creutzig is right. If you want all your allocations to go through customized functions, you're much better off replacing the global operator new. This will catch all calls to new for the translation unit, whether you replace them with create or not. That means when you create a std::vector<T> myvec(3), it will use your operator new for any heap allocations it needs to do, instead of sidestepping your global policy.

If you need to pass a module id, operator new can handle that as well by accepting extra parameters. I'm unclear how that mixes with examples such as the std::vector<T> heap allocations; it may require using a custom allocator for each STL container. Setting that aside, here's an example like yours following the lead on cppreference.com:

void* operator new(std::size_t cb, uint32_t module_id)
{
    // use module_id
    return calloc(1, cb);
}
void operator delete(void* ptr)
{
    free(ptr);   // I'm unsure if this requires a null check
}

type *p = new(module_id) type;

As an aside, if you're particularly tied to calling functions, I'd be tempted to remove the SFINAE specialization via is_pod<T> and just make it an inline check via is_trivially_constructible<T> and is_trivially_destructible<T>...that is if checking is necessary at all.

template<typename T>
T* create(uint32_t module_id)
{
    // use module_id
    T* p = calloc(1, sizeof(T));
    if (!is_trivially_constructable<T>::value && p)
    {
        new (p) T(forward<Args>(args)...);
    }
    return p;
}


Is there a particular reason you're using a .forEach() instead of for-of?. Because .forEach() uses a function for iteration, you don't have a way to stop early once you've you know the contact is not empty. If you used for-of instead, you can just return false once you know the result will be false.
It looks like you're doing a typeof value === 'object' to check if something is an array. Instead, you can do Array.isArray(value).
You're looping over the keys of the object, but you only use the key to get the field's value. Why not just loop over the values instead with Object.values()?

With these suggestions applied, your code would look something like this:
function isContactEmpty(contact) {
  for (const field of Object.values(contact)) {
    if (typeof field === 'string' && field) {
      return false
    } else if (Array.isArray(field)) {
      for (const { value } of field) {
        if (value.length) return false
      }
    }
  }
  return true
}

But, we can take it a step further. Javascript has a higher-level function to do exactly what we're doing with these loops, but without the boilerplate - array.every(). It takes a callback that returns a boolean and gets called with each element of an array. The return value of every() is true if all the callbacks returned true, or false if one of them returned false. (It'll also stop iterating as soon as one callback returns false).
const isContactEmpty = contact => (
  Object.values(contact).every(field => {
    if (typeof field === 'string') return !field
    if (Array.isArray(field)) return areArrayEntriesEmpty(field)
    return true
  })
)

const areArrayEntriesEmpty = field => (
  field.every(({ value }) => value.length === 0)
)


Format 2 Excel sheets then save both sheets as a new workbook

Most times you have Range.Select followed by Selection.Something you can remove the Select and Selection to leave it Range.Something. This helps clarify what the code is doing. The same may be true of Worksheet.Select (or Activate). But doing this with a worksheet will alter any unqualified Range variables in your code that follows.

Range without VariableName.Range refer to the ActiveSheet and can lead to issues if you're not aware of this. My first step was to go through and everything after Worksheets(2).Select to fully qualify it with

Dim secondSheet As Worksheet
Set secondSheet = Worksheets(2)

Range("AK1").Value = "1" then became secondSheet.Range("AK1").Value = "1" giving me a lot more confidence that removing the .Select shouldn't alter the code. I did the same with Worksheets(1).Select as well. After that I went after the Range.Selects.

Range("N" & Rows.Count).End(xlUp).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply, _
SkipBlanks:=False, Transpose:=False

I took the above Select and Selection to be finding where the last cell on a specific column. Range("N" & Rows.Count).End(xlUp).Select became what follows. My choice of variable names are self describing, helping you immediately understand what the code is there for.

Dim lastCell as range
set lastCell = secondSheet.Range("N" & Rows.Count).End(xlUp)

Going up from this last cell to get a contiguous range Range(Selection, Selection.End(xlUp)).Select became

Dim modifyRange as Range
Set modifyRange = secondSheet.Range(lastCell, lastCell.End(xlUp))

Lastly replace the Selection in Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply, SkipBlanks:=False, Transpose:=False with modifyRange and it's looking a lot better. But this is being done in 3 places on the secondSheet and once on firstSheet. Rather than having duplicated code, create a Sub procedure ConvertToNumeric that takes in 2 parameters ByVal sheetToUse As Worksheet and ByVal columnToFindLastCellOn As String. The names let you know when typing the name ConvertToNumeric<space> and getting intellisense to show you the names of the arguments you'll supply. Any future changes are made in this single location now be reflected wherever it's called at ensuring the update is correct.

Private Sub ConvertToNumeric(ByVal sheetToUse As Worksheet, ByVal columnToFindLastCellOn As String)
    Dim helperCell As Range
    Set helperCell = sheetToUse.Range("AK1")
    helperCell.value = "1"
    helperCell.Copy

    Dim lastCell As Range
    Set lastCell = sheetToUse.Cells(Rows.Count, columnToFindLastCellOn).End(xlUp)

    Dim modifyRange As Range
    Set modifyRange = sheetToUse.Range(lastCell, lastCell.End(xlUp))
    modifyRange.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply, SkipBlanks:=False, Transpose:=False

    helperCell.ClearContents
End Sub

You have a few places with comments like 'Format Amount as Accounting that are describing what you're doing. When this occurs it's pretty safe to make that chunk of code be it's own Sub or Function. Sub if it doesn't return a value or Function if it does.

Using the same idea as above Range("J" & Rows.Count).End(xlUp).Select became a Dim lastCell As Range variable and the Range(Selection, Selection.End(xlUp)).Select became Dim modifyRange As Range. You get

Private Sub FormatAsAccounting(ByVal sheetToUse As Worksheet, ByVal columnToApplyFormatTo As String)
    Dim lastCell As Range
    Set lastCell = sheetToUse.Cells(Rows.Count, columnToApplyFormatTo).End(xlUp)

    Dim modifyRange As Range
    Set modifyRange = sheetToUse.Range(lastCell, lastCell.End(xlUp))
    modifyRange.Style = "Comma"
End Sub

It's called in code FormatAsAccounting secondSheet, "J" where secondSheet is a worksheet variable and columnToApplyFormatTo is a string that tells you what column you'll be using. Admittedly the modifyRange variable isn't actually needed and sheetToUse.Range(lastCell, lastCell.End(xlUp)).Style ... could be used but serves to illustrate how as code becomes simpler many times it helps clean itself.

The same thing occurred with headers as well.

When you get to the saving a workbook that has copies of your worksheets you have variables Dim ws As Worksheet that's never used and Dim wbNew As Workbook that's assigned but then never used. There is also dt and wbNam, neither of which are declared. In the VBE coding window go to Tools>Options>Require Variable Declaration. This will put Option Explicit into any new module and requires you to Dim every single variable. It takes more thought and effort to code, but doing something well generally takes effort. Future-you will thank current-you for doing so because it'll save you from many needless issues in your code. BTW Debug>Compile VBAProject (Alt+D+L for keyboard shortcut) is your friend. That'll tell the compiler to compile the code and if something isn't correct it'll alert you by taking you straight there. Keep doing that until there's no more compile-time problems.

Back to the code.

You're selecting a sheet, filtering the sheet, selecting all cells on the sheet to copy that information to a sheet that was just added. This is done for the sheet "PP" and "BK". Those copied sheets are then copied to a new workbook only to be deleted in your current workbook. You can avoid this by creating a new workbook and using that variable.

Dim saveBook As Workbook
Set saveBook = Workbooks.Add

Putting that code into a Sub and having your cursor on the word Add if you press Ctrl+i or Edit>Quick Info you should see Add([Template]) As Workbook appear. This indicates the Add function on the Workbooks collection returns a Workbook object, which coincidentally is what saveBook has been dimensioned as. Right clicking on Add and choosing Definition (3rd from bottom) will take you to the object browser where you can see at the bottom pane what I just described. This gives you a new workbook to use that you'll eventually save where you want. The Object Browser is another topic, but learning to use it will help tremendously.

You can directly copy a sheet by using the Copy procedure on a worksheet object and tell it where to be copied to with either the Before or After argument.

Dim ppSheet As Worksheet
Set ppSheet = Sheets("pp")
ppSheet.Copy Before:=saveBook.Worksheets(1)

As part of your eventual file name dt isn't descriptive. I used monthPriorDate since that's what you're doing with DateAdd. Putting all the pieces together you get SaveExternalCopy.

Private Sub SaveExternalCopy()
    Dim saveBook As Workbook
    Set saveBook = Workbooks.Add

    Dim ppSheet As Worksheet
    Set ppSheet = Sheets("pp")
    ppSheet.UsedRange.AutoFilter field:=31, Criteria1:="Variable1"

    ppSheet.Copy Before:=saveBook.Worksheets(1)
    Dim ppCopy As Worksheet
    Set ppCopy = saveBook.Worksheets(1)
    ppCopy.Name = "PP1"

    Dim bkSheet As Worksheet
    Set bkSheet = Sheets("Bk")
    bkSheet.UsedRange.AutoFilter field:=16, Criteria1:="Variable2"

    bkSheet.Copy After:=ppCopy
    Dim bkCopy As Worksheet
    Set bkCopy = Sheets.Add(After:=bkSheet)
    bkCopy.Name = "BK1"

    Dim monthPriorDate As String
    monthPriorDate = Format(DateAdd("m", -1, Now), "yyyy_mm")

    'Dont forget to delete any default sheets that are created
    'when the workbook is first created.

    saveBook.SaveAs "\\user\location\" & "BK_PP_" & monthPriorDate & ".xlsx"
    saveBook.Close
End Sub

My final code ended up as follows. Save a copy before running the code as I've not 100% fully tested everything and there might be an unforseen issue that wasn't caught.

PP_Formatting_Saving now is shorter and everything it's doing is self-descriptive. Each Sub that's called is doing one thing, which makes it easier to fix a problem when looking at 10-20 lines of code instead of a single block of around 90 lines of code. Comments are mostly gone. Comments should describe the why of something being done not the what since what is happening should be apparent. Why is for when one choice was made over another, something like 'Doing it this way over <OtherWaysName> is 5 times faster.

Public Sub PP_Formatting_Saving()

    Application.ScreenUpdating = False

    Dim secondSheet As Worksheet
    Set secondSheet = Worksheets(2)
    secondSheet.Select 'This may possible be removable

    ConvertToNumeric secondSheet, "N"
    ConvertToNumeric secondSheet, "AA"
    ConvertToNumeric secondSheet, "G"

    FormatAsAccounting secondSheet, "J"
    FormatTheHeaderOf secondSheet

    secondSheet.Cells.EntireColumn.AutoFit
    secondSheet.Columns("O:O").ColumnWidth = 40
    secondSheet.Cells.AutoFilter '¿Does this turn it on or off? 'Filter all headers

    Dim firstSheet As Worksheet
    Set firstSheet = Worksheets(1)
    firstSheet.Activate 'This may possible be removable also
    firstSheet.Cells.WrapText = False

    FormatAsAccounting firstSheet, "C"
    ConvertToNumeric firstSheet, "B"
    firstSheet.Cells.EntireColumn.AutoFit
    FormatTheHeaderOf firstSheet
    firstSheet.Cells.AutoFilter

    SaveExternalCopy
End Sub

Private Sub ConvertToNumeric(ByVal sheetToUse As Worksheet, ByVal columnToFindLastCellOn As String)
    Dim helperCell As Range
    Set helperCell = sheetToUse.Range("AK1")
    helperCell.value = "1"
    helperCell.Copy

    Dim lastCell As Range
    Set lastCell = sheetToUse.Cells(Rows.Count, columnToFindLastCellOn).End(xlUp)

    Dim modifyRange As Range
    Set modifyRange = sheetToUse.Range(lastCell, lastCell.End(xlUp))
    modifyRange.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply, SkipBlanks:=False, Transpose:=False

    helperCell.ClearContents
End Sub

Private Sub FormatTheHeaderOf(ByVal sheetToUse As Worksheet)
    Dim header As Range
    Set header = sheetToUse.Range(sheetToUse.Range("A1"), sheetToUse.Range("A1").End(xlToRight))
    With header.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = RGB(192, 192, 192) 'RGB(192,192,192) = 12632256
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    header.Font.Bold = True
End Sub

Private Sub FormatAsAccounting(ByVal sheetToUse As Worksheet, ByVal columnToApplyFormatTo As String)
    Dim lastCell As Range
    Set lastCell = sheetToUse.Cells(Rows.Count, columnToApplyFormatTo).End(xlUp)

    Dim modifyRange As Range
    Set modifyRange = sheetToUse.Range(lastCell, lastCell.End(xlUp))
    'NumberFormat could possibly be used instead of Style
    'I'm not sure if you have altered the "Comma" Style though
    'modifyRange.NumberFormat = "_(* #,##0.00_);_(* (#,##0.00);_(* ""-""??_);_(@_)"
    modifyRange.Style = "Comma"
End Sub

Private Sub SaveExternalCopy()
    Dim saveBook As Workbook
    Set saveBook = Workbooks.Add

    Dim ppSheet As Worksheet
    Set ppSheet = Sheets("pp")
    ppSheet.UsedRange.AutoFilter field:=31, Criteria1:="Variable1"

    ppSheet.Copy Before:=saveBook.Worksheets(1)
    Dim ppCopy As Worksheet
    Set ppCopy = saveBook.Worksheets(1)
    ppCopy.Name = "PP1"

    Dim bkSheet As Worksheet
    Set bkSheet = Sheets("Bk")
    bkSheet.UsedRange.AutoFilter field:=16, Criteria1:="Variable2"

    bkSheet.Copy After:=ppCopy
    Dim bkCopy As Worksheet
    Set bkCopy = Sheets.Add(After:=bkSheet)
    bkCopy.Name = "BK1"

    Dim monthPriorDate As String
    monthPriorDate = Format(DateAdd("m", -1, Now), "yyyy_mm")

    'Dont forget to delete any default sheets that are created
    'when the workbook is first created.

    saveBook.SaveAs "\\user\location\" & "BK_PP_" & monthPriorDate & ".xlsx"
    saveBook.Close
End Sub

Lastly Rubberducks Code Inspections brought up a lot of what I addressed and has been very helpful to my VBA knowledge and improving my coding habits. I'm a contributor and openly biased in favor of it.


Optimize Javascript function with many (maybe?) loops inside

Look, ma, no loops!
But seriously, if you were concerned about performance I don't think it's a problem of nested loops per se, $.grep in the loop concerns me much more. Especially since you're doing basically the same grep over and over!
After grep, neither item.parent_id nor i are used again. Looks like we can just cycle through all widgets in one $.grep, and that's exactly what we're going to do.
Also, what you're doing with item.widget_key begs for a switch statement - or, at least, having those radiobutton and dropdown typed twice bugs me and begs for a well-placed typo to cause lots of frustration.
I'm not sure I understand exactly what you do with default_next_step, so correctNextStep probably needs some refinement (like, what if next_step - 1 is not a valid forum section index either?) but the code is supposed to work exactly the same as yours. (or not work, hard to say without test cases:D)
const inArray = (needle, haystack) => (-1 != haystack.indexOf(needle));
const parseIntIfDefined = (item) => ('undefined' === typeof(item) ? null : parseInt(item));

const applyFormSectionIdsToControls = function(formSections) {
  if (!formSections.length) return;

  const formSectionIds = formSections.map((section) => parseInt(section.id));
  const correctNextStep = (nextStep) => {
    if (inArray(nextStep, formSectionIds)) return nextStep;
    return formSectionIds[nextStep - 1];
  };

  $.grep(application_widgets, (item) => {
    if (!inArray(parseInt(item.parent_id), formSectionIds)) return;

    switch (item.widget_key) {
      case 'nextbutton':
        const defaultNextStep = parseIntIfDefined(item.settings.default_next_step);
        if (defaultNextStep) {
          item.settings.default_next_step = correctNextStep(defaultNextStep);
        }
      break;
      case 'radiobuttons':
      case 'dropdown':
        item.settings.answers.map(
          (answer) => answer.next_step = correctNextStep(parseInt(answer.next_step))
        );
      break;
    }
  });
}


Merging tails effectively wastes cycles. The nodes are already linked correctly.

    if (part1 != NULL) {
        current->next = part1;
    }

    if (part2 != NULL) {
        current->next = part2;
    }

is enough.
A single most important feature of merge sort is stability: elements compared equal remain in the original order. A comparison

    if(cmp(&part1->val, &part2->val) < 0)

makes your sort unstable. A correct comparison is either one of

    if(cmp(&part2->val, &part1->val) > 0)
    if(cmp(&part1->val, &part2->val) <= 0)

Less indentation is easier to follow. I recommend to invert a recursion termination condition:

    if (start == stop) {
        start->next = NULL;
        return start;
    }
    ...

Avoid naked loops. The

    for(List *node = start; node != stop; node = node->next) {
        if(i == mid) {
            midNode = node;
        }
        i++;
    }

should be factored out into a function

    List * advance(List * start, int steps);


Excuse me, how many of you are new here? Mind if I JOIN you?

Technically, the full outer join is insufficient.  If during a certain week there was not a single user who posted their first question or answer, the plot for that week needs to be 0.  It would be misleading to plot a direct line from the previous week to the following week, skipping the quiet week.  So, strictly speaking, you need to generate a series of all the weeks, to which you LEFT OUTER JOIN the FirstQuestions and FirstAnswers CTEs.  However, generating a date series in SQL Server is a hassle compared to some developer-friendlier databases.  I'm willing to pretend that there aren't weeks with no new user activity (actually demonstrably false for the week of 2011-01-10).

First rewrite

All of the information you need is contained in the Posts table.  There is no need to join the Users table.

The subselects in the query suggest that your CTEs are underdeveloped.  In my first rewrite below, I've reorganized FirstAnswers and FirstQuestions to perform the role of your subselects.

a and q would make more meaningful table aliases than a and b.

Your function names are inconsistently capitalized: dateadd, datediff, Convert, Min, ISNULL.  I believe that Convert(Date, …) isn't needed at all.

WITH FirstPosts AS (
  SELECT OwnerUserId As UserId
       , PostTypeId
       , DATEADD(week, DATEDIFF(week, 0, MIN(CreationDate)), 0) AS WeekOf
    FROM Posts
    WHERE CreationDate > '2011-01-01' -- There was very little activity prior to this date. Including it skews the graph.
    GROUP BY OwnerUserId, PostTypeId
), FirstAnswers AS (
  SELECT WeekOf
       , COUNT(UserId) AS UserCount
    FROM FirstPosts
    WHERE PostTypeId = 2 -- answer
    GROUP BY WeekOf
), FirstQuestions AS (
  SELECT WeekOf
       , COUNT(UserId) AS UserCount
    FROM FirstPosts
    WHERE PostTypeId = 1 -- question
    GROUP BY WeekOf
)
SELECT ISNULL(a.WeekOf, q.WeekOf) AS WeekOf
     , ISNULL(a.UserCount, 0) AS AnswerCount
     , ISNULL(q.UserCount, 0) AS QuestionCount
  FROM FirstAnswers AS a
    FULL OUTER JOIN FirstQuestions AS q
      ON a.WeekOf = q.WeekOf
  ORDER BY 1;

Better solution

As it turns out, there is a much slicker way to avoid the join altogether by using a conditional COUNT():

WITH FirstPosts AS (
  SELECT OwnerUserId As UserId
       , PostTypeId
       , DATEADD(week, DATEDIFF(week, 0, MIN(CreationDate)), 0) AS WeekOf
    FROM Posts
    WHERE CreationDate > '2011-01-01' -- There was very little activity prior to this date. Including it skews the graph.
    GROUP BY OwnerUserId, PostTypeId
)
SELECT WeekOf
     , COUNT(CASE WHEN PostTypeId = 2 THEN UserId END) AS AnswerCount
     , COUNT(CASE WHEN PostTypeId = 1 THEN UserId END) AS QuestionCount
  FROM FirstPosts
  GROUP BY WeekOf
  ORDER BY WeekOf;


Function takes a dictionary with list as value, returns the key of the biggest list

Your code is difficult to read:

The line is too long (according to the Python style guide all lines should be limited to 79 characters).
The same iterator variable x is used for the outer iteration and also inside the max() function.

It is also inefficient because the maximal list length is determined in each iteration.
Using the key and default argument of the max() function the same can be concisely and efficiently be implemented as
def biggest(aDict):
    return max(aDict, key=lambda k: len(aDict[k]), default=None)

More suggestions:

Have a look at the Python naming conventions (snake_case, not camelCase).
Choose a more descriptive function name.
Use docstrings to describe the function.


Is my Java SQL connection secure from hackers?

Do not store the connection information in a file unencrypted
Assuming that you are connecting to a database somewhere on the internet... If you plan on distributing this application, do not store the connection information unencrypted in a file on the user's device. In fact, preferably don't store the database connection information at all.
Do not let your Android application connect directly to your remote database!
It is not recommended to let your Android application, or any other distributed application, connect directly to your database. This is because it is very easy to decompile an application, which would give information about the connection details, your database structure, and a whole lot of other things.
Instead, perform connections to a server-side script or application that is responsible for handling the connection between your Android application and your database. Only let this script/application that only you control deal with the database connection.
Unless you deal with this, any number of prepared statements your application itself uses doesn't matter, as a user could just find out the connection details from your application and then create their own connection to the database server.


Extending the functionality of lxml.etree

Boilerplate

class etree(old_etree._ElementTree):
  @staticmethod
  def parse(path):
    old_tdx = old_etree.parse(path)
    new_tdx = etree(old_tdx)
    new_tdx._setroot(old_tdx.getroot())
    return new_tdx

  @staticmethod
  def fromstring(string):
    old_tdx = old_etree.fromstring(string)
    new_tdx = etree(old_tdx.getroottree())
    new_tdx._setroot(old_tdx)
    return new_tdx

In those boilerplate functions, I don't know what "tdx" means. I guess it's linked to the file specification you use.

Those functions are the main problem I have with your code. You mixed the lxml.etree module with the lxml.etree.ElementTree class. Those four methods are methods of the module, not the class! I think you should:

have a real etree module
put your current etree class (renamed as ElementTree) in it
add those functions in the module, not the class
fix the return type to return what lxml returns

This would make things way less confusing because it would be closer to how lxml.etree and the standard xml.etree work. Your coworkers would be able to pick your code faster.

You would do from lxml.etree import * and only redefine the functions you want to redefine. Your probably can't expect a perfect compatibility, but at least the basic API would be the same.

I don't have much to say about the implementation of the functions apart from the return type: ugly but I did not find a way to make things better. And yes, it's quite easy to understand them.

  @staticmethod
  def SubElement(*args, **kargs):
    return old_etree.SubElement(*args, **kargs)

  @staticmethod
  def Element(*args, **kargs):
    return old_etree.Element(*args, **kargs)

You no longer would need do to this with my proposal above.

getISOTime

  @staticmethod
  def getISOTime():
    iso_time = datetime.now().isoformat()
    format_time = iso_time.split('.')[0] + 'Z'
    return format_time

Adding the 'Z' means you're saying this is an UTC time, but it's not since you've used datetime.now() instead of datetime.utcnow(). I live in UTC+4, and the format_time you're returning is 4 hours off for me.

getMetaNode

  def getMetaNode(self, name, default=''):
    metas = self.findall('meta')
    for meta in metas:
      if meta.get('name') == name:
        return meta

You can use lxml XPath support here if you want to avoid the loop: meta.xpath("meta[name = $name]", name=name).

Write

  def write(self, path, updateTool=True):
    self.setMetaNode('saved', etree.getISOTime())

    if updateTool:
      self.setMetaNode('version', VERSION)
      self.setMetaNode('type', TOOL)

    super(etree, self).write(path)
    clean_xml(path)

nitpick: Cleaning at the ElementTree would prevent your filesystem to see two different versions. Say at some point you decide to use watchdog, the callback will kick in before you have a chance to run clean_xml, which could cause subtle bugs.

Answering your questions

  Is there a better way to extend the functionality of lxml.etree than inheriting from _ElementTree? Ultimately, I want to be changing the behavior of the method ElementTree.write and to add the methods ElementTree.getMetaNode and ElementTree.setMetaNode.

Since lxml is written in Cython, I think you can't monkeypatch lxml directly anyway, so subclassing is the way to go. lxml could have chosen to make things easier by using __new__ just like numpy does for facilitating ndarray subclassing.

  Is there a better way of incorporating the methods parse, fromstring, SubElement, and Element, rather than just creating thin wrappers that reference the original methods?

See "Boilerplate" above.

  Does anyone understand what my methods parse and fromstring are doing? I know that my method fromstring has different functionality from lxml.etree.fromstring because I want it to return an ElementTree rather than an Element. These methods were written largely through guess-and-check (oops).

Why do you want to get an ElementTree rather than an Element? I think it's a bad idea for two reasons:

It's very easy to get an ElementTree from an Element.
It's already hard enough to reason about the type of object you get when using lxml, if we can't use our knowledge about ElementTree/lxml it's only going to get worse.

  Is there a better way to write the return old_etree.SubElement(...) line so it doesn't have to take up two lines? This isn't major, but...

If anything, I think I would use more than two lines. If you want to stop worrying about such things, I highly recommand yapf.

  Originally, I tried to just overwrite lxml.etree.ElementTree.write directly, but that throws the error AttributeError: 'lxml.etree._ElementTree' object attribute 'write' is read-only. General critiques are also welcomed. I know that I should have comments in here, but everything is pretty straight-forward except for the two methods that I don't understand.

Yep, you can't monkeypatch it (as said in answer to 1.), but that's not what you wanted to do, since you wanted to keep the original implementation too. And a decorator would not have improved things.

Naming

  Also, I'm not sure if anyone is going to think that using the name etree in order to overwrite lxml.etree is a bad idea. The reason for this is so that I only have to change the import line at the top of any previously written file from from lxml import etree to from my_lxml import etree.

Nope, I think using the name etree is a good idea. It's a common way to provide replacements in Python, and this is way the standard library xml.etree does things. However, you need to do things correctly. Again, see the "Boilerplate" section above.

Oh, and PEP 8 recommends against underscores in module names unless it improves readability, but I think mylxml is readable enough. However, simply adding my in front of a module is not such a good idea, because you just lost an opportunity to explain what makes your lxml different. Since it seems specific to the file specification you use, why not use that in the name?


Displaying TimeSpan as largest interval (with units)

The numbers 22.0, 50.0, 40.0, and 500.0 are "magic numbers" (non-obvious hard-coded numbers with no given meaning).

Since they're not commonly used with time, thus are not obvious, you should make the reader aware of their meaning.  This will also improve readability.

Two options for doing this include:

making them into constants with appropriate names

private static readonly double someConstant = 22.0;
// remaining constants

providing comments or full documentation on their meaning


Python server that only returns error 418

Not really smaller but it will respond to any request, not just GET:

class MyHandler(BaseHTTPRequestHandler):
    def handle_one_request(self):
        self.send_error(418, 'I am a Teapot')

Usually, handle_one_request delegates to the appropriate do_METHOD method, but since we want to treat all of them equal, we may as well not let that delegation take place.

In the interest of making things shorter, you generally don't need the server.socket.close(), unless you plan on restarting a server on that same port right after shutting down this server.


API to verify whether a Redis entry exists

if(typeof req.body.data !== 'undefined' && req.body.data ...

// to

if(req.body.data && req.query.hash && typeof req.body.id)

Assuming that false, 0, null and an empty string has no special meaning in this program, you can simply use loose comparison. Anything falsy (null, undefined, false, 0, NaN, empty string) will just fall off.

function foo(bar){
  if(bar !== 'foo'){
    if(bar !== 'bas'){
      if(bar !== 'bam'){
        // ok, bar is what it is
      } else {
        throw new Error('not bar');
      }
    } else {
      throw new Error('not bar');
    }
  } else {
    throw new Error('not bar');
  }
}

// to

function foo(bar){
  // Expanded for emphasis. You can actually combine
  if(bar === 'foo') throw new Error('not bar');
  if(bar === 'bas') throw new Error('not bar');
  if(bar === 'bam') throw new Error('not bar');

  // ok, bar is what it is
}

Another approach to flattening conditionals is to "return early". Usually, when you have nested if statements, you can invert the condition and the code will look flat. But your mileage may vary, depending on your code.

Now for your errors, HTTP response numbers will cover that for you.

To start, 4xx errors mean the client did something wrong. On the other hand, 5xx errors means the server did something wrong.
A "wrong parameters type" means the client sent the wrong data. That's a 400 (Bad Request) and not a 403 (Forbidden).
A database error or a parse error should be a 500 (Internal Server Error).
If the token does not exist or has the wrong id, that counts as a 401 (Unauthorized). The difference between 401 and 403 is that a 401 can be lifted if you are authenticated (ie. token exists, validation passes etc.) while 403 is more of a permanent unauthorized access.

With that, and removing the logging, this should be all that's left. Feel free to add back the brackets. I usually omit them if I deal with one-liner bodies.

http.checkParam = function CheckParam(req, cb) {
  if(!req.body.data || !req.query.hash || ! req.body.id) cb(400);
  else redis.get(req.query.hash, function(err, data) {
    if(err) cb(500);
    else if(!data) cb(401);
    else try {
      var obj = JSON.parse(data);
      if (obj.member.id !== req.body.id) cb(401);
      else cb(200);
    } catch(error){
      cb(500);
    }
  });
};


to answer your questions first:

you don't need begin/end if it covers whole method, you can rescue directly from method,
Net::HTTP already handles timeout, no need to build custom wrapper around it,

now there are few other things that should be addressed:

inline things when possible
don't use @@ ever, use constants if you need to
don't rescue from Exception, rescue from StandardError instead (or nothing as ruby defaults to StandardError anyways)
try to be consistent with returned result, i.e. header should always return hash, never nil. Otherwise you will need to add conditions in places where you handle code
OpenSSL::SSL::VERIFY_NONE this is bad, you want to verify certificate.
do not use Net::HTTP, there are much more rubout gems available, i.e. Typhoeus

Finally it could be rewritten to something like this:

def https_request(server_url, header, content)
  hack_ssl_options
  uri = URI.parse(server_url)

  connection = Net::HTTP.new(uri.host, uri.port)
  connection.use_ssl = true
  connection.ssl_options = OpenSSL::SSL::OP_NO_SSLv2 + OpenSSL::SSL::OP_NO_SSLv3 + OpenSSL::SSL::OP_NO_COMPRESSION
  connection.verify_mode = OpenSSL::SSL::VERIFY_NONE
  connection.read_timeout = TIMEOUT_PERIOD

  request = Net::HTTP::Post.new(uri.path, initheader = header)
  request.body = content

  response = connection.request(req)

  { code: response.code, header: response.to_hash, body: response.body }
rescue Net::ReadTimeout => e
  { code: CODE_TIMEOUT, header: {}, body: e.message }
rescue => e
  { code: CODE_UNKNOWN, header: {}, body: e.message }
end

This code works slightly different from your original version, you may need to adjust it.


Deriving from IEqualityComparer versus EqualityComparer.

The MSDN docs say the following:

  We recommend that you derive from the EqualityComparer class instead of implementing the IEqualityComparer interface, because the EqualityComparer class tests for equality using the IEquatable.Equals method instead of the Object.Equals method. This is consistent with the Contains, IndexOf, LastIndexOf, and Remove methods of the Dictionary class and other generic collections.
  MSDN docs: IEqualityComparer

Dictionary versus Lookup

For grouping together objects from a sequence, where there might be a varying amount of items in each group, a Lookup is better than a Dictionary:

 var lookup = strs.ToLookup(key =>
 {
     var array = key.ToCharArray();
     Array.Sort(array);
     return array;
 }, new CharComparer());
 return lookup.Select(grouping => (IList<string>)grouping.ToList()).ToList();

Comparing char-arrays

Since we're using Linq, let's use Linq:

public override bool Equals(char[] x, char[] y)
{
    if (x == null || y == null)
    {
        return false;
    }

    if (x.Length != y.Length)
    {
        return false;
    }

    return x.SequenceEqual(y);
}

The null behaviour is different and the length shortcut may stay, but the last loop we can offload to Linq.

Hashcode

Both Dictionary and Lookup rely on the hashcode returned by the equalitycomparer to categorise the keys into bins. These bins is what allows these collections to get times in \$O(1)\$. Always returning the same value is going to cause problems when your inputs get bigger. It will effectively turn the collections into single arrays which have to be looped over to get to the correct key.

Creating good hashcodes is hard though, and I don't really know a good rule of thumb for creating them.

char[] versus string

All in all, the hashcode and equalitycomparer is such a headache, it's probably easier, and more readable to convert the sorted char[] back into a string, and use that as the key for the lookup:

 var lookup = strs.ToLookup(key =>
 {
     var array = key.ToCharArray();
     Array.Sort(array);
     return new string(array);
 });
 return lookup.Select(grouping => (IList<string>)grouping.ToList()).ToList();


Calling error is fine for a small program like this.

For more advanced error handling see the Failure page on HaskellWiki.

Some comments about your code:

unhex (x:[]) = error "invalid input length"

x is not used here, use this pattern instead: (_:[])

unhex (x:y:xs) = [(shiftL (hex2val x) 4) .|. (hex2val y)] ++ unhex xs

[x] ++ xs is usually written x : xs

hex2val' $ (x .|. 0x20)

$ is useless here.


Your first compile method can be replaced by a single call to String.split.

Assuming the intended behavior for the second compile method is such that "/foo/b[a]r/baz" will compile to {"foo", "?", "baz"}, it can be replaced by a call to split and then iterating over the result and replacing any string the includes square brackets with "?".

If the intended behavior is rather that it will compile to {"foo", "b", "?", "r", "baz"}, you can first replace [anything] by /?/ using String.replace and then use String.split.


Tracking hours worked for the days of the week

The first step to reducing repetition is to use variables instead of literals. Why call DOTW['Monday'] when you could just use day as your key. Importantly, this will avoid errors like the one you created in the Sunday block, where you actually display Monday's hours instead of Sunday's.

The only difference between days is in the messages that you print to the user. You've given custom messages, but you could just put those in a dictionary and access them the same way you access DOTW. Here's an example of how the greeting could look:

today_messages = {
                "Monday": "Today is %s, How many hours would you like to add today?",
                "Tuesday": "Ah, Today is %s, How many hours have you worked?",
                "Wednesday": "Ah, Today is %s, How many hours have you worked?",
                "Thursday": "Ah, Today is %s, How many hours have you worked?",
                "Friday": "FINALLY IT'S FRIDAY!!! How many hours have you worked?",
                "Saturday": "Ah, Today is %s, How many hours have you worked?",
                "Sunday": "Ah, Today is %s, How many hours have you worked?",
                 }

With those changes you could make it all one block with just one test because Friday's message is an exception that doesn't need the string formatting argument.

def main(day):
    if day == "Friday":
        print today_messages[day]
    else:
        print today_messages[day] % day

    hours = int(raw_input())
    DOTW[day] = DOTW[day] + hours
    print hours_worked[day] %(day, DOTW[day])
    want = raw_input("Do you want to add more time? y/n \n > ")
    overtime()
    leave(want)

Also you should use the newer str.format method. Using % is the old way, and str.format has a lot of useful formatting options. You don't particularly need them in your case but it's clearer and cleaner syntax. The basic way to use it is like this:

                "Sunday": "Ah, Today is {}, How many hours have you worked?",

...

print today_messages[day].format(day)

The particular advantage for you here is that formatting a message that takes no arguments won't raise errors, unlike with %.

>>> string = "Ignore me"
>>> "Hello World!" % string

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    "Hello World!" % string
TypeError: not all arguments converted during string formatting
>>> "Hello World!".format(string)
'Hello World!'

This means you no longer need to test for "Friday", since the format call will just be ignore for that string:

def main(day):
    print today_messages[day].format(day)
    hours = int(raw_input())
    DOTW[day] = DOTW[day] + hours
    print hours_worked[day].format(day, DOTW[day])

    want = raw_input("Do you want to add more time? y/n \n > ")
    overtime()
    leave(want)


One piece of feedback is that your error handling code is very repetitive.  You are calling CoUninitialize in every failure block.  That might seem OK for one cleanup task (though I'd tend to disagree), but once you have N things to clean up on failure (or even successful return), it gets to be a lot of effort and maintenance.

There are a few ways around this that I've seen.

Have a single block that cleans up (frees any buffers, unintializes COM, whatever).  That goes at the end if your function.  Make all failure and success paths reach this block.

As an example of how you might do that in COM code, here's the "wrong" way:

hr = Foo();
if (FAILED(hr))
{
   Cleanup();
}

hr = Bar();
if (FAILED(hr))
{
   Cleanup();
}

Cleanup();

There are several choices for the "right" way.  One of them would be:

if (SUCCEEDED(hr))
   hr = Foo();
if (SUCCEEDED(hr))
   hr = Bar();

Cleanup();

If you are not religiously opposed to goto (this probably makes more sense in C than C++), this approach is also common:

   hr = Foo();
   if (FAILED(hr))
      goto cleanup;
   hr = Bar();
   if (FAILED(hr))
      goto cleanup;

cleanup:
   Cleanup();

There are of course more C++ like (rather than C style) ways to prevent cleanup from becoming too much of a hassle.  In particular it would probably be a better idea to wrap initialization and de-initialization in the RAII idiom.  In this example (COM initialization), you might have a class that (1) initializes COM, (2) tracks that it's been initialized, and (3) in its destructor, deinitializes COM if it has been initialized.  Something like this: [nb: I am typing in a web form, it may not be perfect :-)]

Example:

class ComInitialization
{
   bool init;
public:

   ComInitialization() : init(false) {}

   HRESULT Initialize()
   {
      HRESULT hr = S_OK;

      if (!init)
      {
         hr = CoInitializeEx(/* ... */);
         if (SUCCEEDED(hr))
         {
            init = true;
         }
      }

      return hr;
   }

   ~ComInitialization()
   {
      if (init)
      {
         CoUninitialize();
      }
   }
}

With this approach you can have simply:

ComInitialization comInit;

hr = comInit.Initialize();

Then after this block, you can return in any place you like, success or failure, even throw exceptions, and COM will still get uninitialized.

(Notice I didn't initialize COM in a constructor.  This allows us to inspect the HRESULT on failure without wrapping it in an exception.  I'm sure many would suggest wrapping HRESULTs in exceptions.  This is not personally my taste.  YMMV.)


SQL Inserting up to 10'000 records from a table to a secondary table

Ideally, you should provide all relevant code (including the whole query) in order to receive more targeted answers (and also obey site's rules), but based on you have provided, one way to optimize the insertion is the following:

1) Define a session table which will hold all the keys that require inserting the data for

ThermalPrinterSession

ThermalPrinterSessionId INT PRIMARY KEY,
SessionId UNIQUEIDENTIFIER,
Quantity INT,
Label VARCHAR(100),
Id INT

2) Create a stored procedure that will be able to process data for a session

CREATE PROCEDURE uspProcessThermalPrinterData
(
   @SessionId UNIQUEIDENTIFIER,
   @Quantity INT,
   @Label VARCHAR(100),
   @Id INT
)
AS
BEGIN
   INSERT INTO PRINT_TABLE(ID, KEYNAME1,
       KEYNAME2, KEYNAME3, KEYNAME4,
       PRINTFORMATSTRING, PRINTQUANTITY, COLLECTION, COLLECTION_OWNER,
       MANAGER, LOCATIONID )
   SELECT 1                       -- all columns for insertion
   FROM ThermalPrinterSession S
      JOIN OtherTable1 T ON T.Id = S.Id        -- other joins and other tables come here
   WHERE T.SessionId = @SessionId
END
GO

3) For each insert session you can define a new unique identifier

Guid.NewGuid();

4) Actual insertion can be done using bulk insert for improved performance. Entity framework has an extension that helps with bulk inserts and an elegant generic solution can also be found here.

5) call the stored procedure for current session

6) Session table maintenance

If this table is not going to be very big (depends on session inserts), it is better not to perform deletes during the working hours and truncate it once a day (e.g.in a nightly job)


Is this an optimal implementation for the knapsack algorithm?

I don't understand what you mean by "the knapsack problem white fraction is allowed," not even if I assume that the word "white" should have been "while" or "what" or "where". The whole thing that makes the knapsack problem NP-hard is that you're not allowed to break up a single item into "fractions." So to understand what you meant, I tried to look at the code.

The first thing I do to understand a piece of code is, I look at its function signature. What arguments does the function take? What verbs and prepositions are used in its name? Consider:

def countPrimesUpTo(n):
def listPrimesUpTo(n):
def printPrimesLessThan(n):

Here's your function signature.

def calculateKnapsack():

Well, that didn't give me any information at all...!

The second way I try to understand a piece of code is to look at what it does; that is, look at its unit-tests.

assert listPrimesUpTo(10) == [2,3,5,7]
assert listPrimesUpTo(5) == [5]
assert listPrimesUpTo(1) == []

Here's your unit tests.

pass

Okay, I guess I should just give up on understanding what the code is intended to do, and focus on the code itself.

    userinputNW = list(map(int, input().split()))
    n = userinputNW[0]
    weight = userinputNW[1]

Oh hey! Here's something that looks like function arguments. You could immediately refactor your function into

def computeKnapsack(n, weight):

But then I go on and I see there's more input happening later...

    weightvaluedict = {}
    for x in range(n):
        vw = list(map(int, input().split()))
        weightvaluedict[vw[1]] = vw[0]/vw[1]
    weightvaluedict = {k: v for k, v in sorted(
        weightvaluedict.items(), key=lambda item: item[1], reverse=True)}

So now our knapsack function looks like

def computeKnapsackRevenue(weights, capacity):
    revenue = 0
    for size, value in weights.items():
        if capacity == 0:
            break
        if size < capacity:
            revenue += size * value
            capacity -= size
        else:
            revenue += capacity * value
            capacity = 0
    return revenue

and we have some boilerplate user-input code that looks like

    num_items, capacity = map(int, input().split())
    weights = {}
    for x in range(num_items):
        v, k = map(int, input().split())
        weights[k] = v / k
    weights = {k: v for k, v in sorted(
        weights.items(), key=lambda kv: kv[1], reverse=True)}

That last line isn't doing anything at all. It doesn't matter how you permute the list of items, if all you're doing with the result is stuffing it back into an unsorted dict. So we can erase that line.

    num_items, capacity = map(int, input().split())
    weights = {}
    for x in range(num_items):
        v, k = map(int, input().split())
        weights[k] = v / k
    revenue = computeKnapsackRevenue(weights, capacity)
    print(revenue)

And there's our program! We might add some unit tests to prove that it does what we expect:

    assert computeKnapsackRevenue({10: 8, 10: 9, 10: 10}, 0) == 0
    assert computeKnapsackRevenue({10: 8, 10: 9, 10: 10}, 20) == 190
    assert computeKnapsackRevenue({10: 8, 10: 9, 10: 10}, 25) == 230
    assert computeKnapsackRevenue({10: 8, 10: 9, 10: 10}, 30) == 270
    assert computeKnapsackRevenue({10: 8, 10: 9, 10: 10}, 40) == 270
    assert computeKnapsackRevenue({}, 40) == 0

We might even find that it has a bug. :)


Makefile which only forwards to subdirectories

It could be a matter of personal taste, but I use functions as the last resort. Consider

.PHONY: $(subdirs)

all: $(subdirs)
clean: $(subdirs)

$(subdirs):
    make -C $@ $(MAKECMDGOALS)


In situations like this, when dealing with odd-offset values, and byte-manipulation, I recommend four things:

use a logical frame of reference.
get familiar with bit-wise operations.
pre-computing results at compile time is very efficient at runtime.
switch statements are high-performance lookup tables

End-of-data frame of reference

What I mean by frame-of-reference, is that your common reference point between the input string, and the output array, is the last character, and the last member of the byte[] array. You should line up your reference points, and work out from there. In this case, it means working backwards.

The next thing that you have as a frame of reference, is your input value. You use this value to drive the calculation of the output array size, and also to drive the iteration in the loop. In this case, what it means is that you should be using the input chars to drive the loop, not the size / 2.

Putting this together, consider a loop that iterates from the last char, to the first char, and then populates the last byte, to the first byte. We can then do math from the end of the input/output arrays based on the loop.

Bitwise manipulations

There are some bitwise manipulation tricks you can do here that help:

Because exactly 2 input chars are required to populate a byte, and because we are working in a base-2 (binary) system, we can take advantage of a trick in counting.... As we count from the end of the input chars to the beginning, we notice that every time we count 2, we move another output byte. If we divide the count by 2, we get the relative position from the output end.
Remember, a right-shift is the same as dividing by 2 (integer division):

int x = 10;
x = x >> 1; // right shift once...
// x now is 5.

Bit-wise ANDing of a value with 1 tells you what the last bit is.

int x = 5;
x = x & 1;
// x now is 1

Bit-wise ORing of two values sets the respective output bits to 1 if either of the input bits are 1.

int a = 0x0a;
int b = 0xb0;
int c = a | b;
// c now is 0xba;

switch statements for fast lookups

The compiler is able to optimize a switch statement very effectively. Consider the following switch statement that converts a character in to the corresponding hex value. This is very efficient because it is based on fancy compile-time logic. It takes some effort to code, but the results are worth it:

private static int HexToInt(char c)
{
    switch (c) {
        case '0':
            return 0;
        case '1':
            return 1;
        case '2':
            return 2;
        case '3':
            return 3;
        case '4':
            return 4;
        case '5':
            return 5;
        case '6':
            return 6;
        case '7':
            return 7;
        case '8':
            return 8;
        case '9':
            return 9;
        case 'a':
        case 'A':
            return 10;
        case 'b':
        case 'B':
            return 11;
        case 'c':
        case 'C':
            return 12;
        case 'd':
        case 'D':
            return 13;
        case 'e':
        case 'E':
            return 14;
        case 'f':
        case 'F':
            return 15;
        default:
            throw new FormatException("Unrecognized hex char " + c);
    }
}

On a character-by-character basis this will be faster than the use of ToUInt32()

Lookup Tables in memory

Again, there are only 16 hex values, this makes the memory usage very small, and you can do some memory lookup tricks.

Putting it together

use a loop that counts back from the end of the input/output. Then you don't need special odd-length input handling.
identify whether an input char is going to be a high or low nibble in the result.
use a lookup table (low/high nibble) to find a byte value for that input.
use a bit-wise OR to add the low and high nibbles together
use bitwise AND and bitwise right-shift to convert the input character to the output byte/nibble position.

The following code is a 'simple' loop, that is efficient, and works for your input cases:

private static readonly byte[,] ByteLookup = new byte[,]
{
    // low nibble
    {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f},
    // high nibble
    {0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0}
};

private static byte[] ConvertHexToBytesX(string input) {
    var result = new byte[(input.Length + 1) >> 1];
    int lastcell = result.Length - 1;
    int lastchar = input.Length - 1;
    // count up in characters, but inside the loop will
    // reference from the end of the input/output.
    for (int i = 0; i < input.Length; i++) {
        // i >> 1    -  (i / 2) gives the result byte offset from the end
        // i & 1     -  1 if it is high-nibble, 0 for low-nibble.
        result[lastcell - (i >> 1)] |= ByteLookup[i & 1, HexToInt(input[lastchar - i])];
    }
    return result;
}

Thus, you can accomplish the conversion with efficient switches, array lookups, and 'simple' math in the loops.

I have put together an Ideone implementation of this code so you can compare it with your code.


Rails configuration variants for production / development environments

Rails already has environment-specific configuration via the files in config/environments. As explained in the Rails Guides, you can simply do

# in config/application.rb (the default config)
config.authentication_providers = %w(weibo open_wechat wechat)

and

# in config/environments/development.rb (overrides the default)
config.authentication_providers = %w(weibo open_wechat wechat developer)

Edit: Or, as 200_success points out in the comments, you can simply add "developer" to the existing list:

# add another item to the default config instead of redefining it completely
config.authentication_providers += %w(developer)

or

config.authentication_providers << "developer"

Note that the strictest configuration is used as the default - the less strict one you have to explicitly set for a given environment (such as development or test).

You code then becomes:

class Authentication
  PROVIDERS = Rails.configuration.authentication_providers
end

Or you can simply skip the constant, since there's no need for it anymore; the list isn't being defined in class at all.

But another, and often times better, way to handle stuff like this is to use environment (ENV) variables, as explained in chapter 3 of "The 12 Factor App" (read it). You'll set the variables one way for production, another way for development, yet another for test perhaps, and so on if you have more environments.

Another great explanation, although it's now subscription-only*, is this Railscast episode. While the episode isn't brand-new anymore, the advice in it is absolutely still valid.

Anyway, one major point is that ENV configuration do not need to be included in source control, which is great if the configuration contains sensitive things like API keys or passwords. Rails already hits upon this point for the secret_key_base variable, where, in config/secrets.yml, it says simply:

# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

There are many ways to set ENV vars; personally, I often use this gem, but there are many others. And of course the ENV handling built into you OS.

Again, there are many way to handle it. The basic premise is that stuff that changes from environment to environment should be accessed through the ENV. That's what it's for, after all. Again, read this.

*) Well worth the $9! Since Railscasts on indefinite - possibly permanent at this point - hiatus, you'll only be charged $9 for the first month, but there won't be a monthly charge (unless Ryan decides to start back up again). See this announcement for details.


Don't test for port-in-use in advance. Just let your application do what it wants to do, and catch the exception there. The situation can change between the time you test and when you actually try to use the port.

Furthermore, if you are trying to write a server application, you can have Java automatically pick a free port for you.  From the JavaDoc for ServerSocket(int):

  Creates a server socket, bound to the specified port. A port number of 0 means that the port number is automatically allocated, typically from an ephemeral port range. This port number can then be retrieved by calling getLocalPort.


You can wrap the single entity into an IQueryable.  Something like this should work:

SingleResult.Create(new[]{entity}.AsQueryable());

You could write a helper function that uses this trick to convert from a single T to an IQueryable<T>.  There may even be a built-in way of doing this.


Given a string containing just parentheses, determine if the input string is valid

The code looks quite succinct and sufficient. The only suggestions I would offer are minor tweaks:

for the imperative solution, a for...of loop could be used to eliminate the need to do bookkeeping on the counter variable and use it to index into the string to get each character:

for(const c of s) {
  if (par[c]) {
    rep.push(par[c]);
  } else {
  if (rep.pop() !== c) {
    return false;
  }
}

for the functional solution, the callback function could be declared on a previous line, and then the return line can be reduced to a single line:

const pushOrPopMatch = x => par[x] ? rep.push(par[x]) : rep.pop() === x
return [...s].every(pushOrPopMatch) && !rep.length;

That line defining pushOrPopMatch() is 73 characters long, which some might argue is too long for a line, given it would be inside a function and indented at least two spaces, so it may not be ideal


What exactly do you have in the javascript (json) file?  Can you get the product code from anywhere other than the the path?

Here is what I suggest:

Just include the javascript file.  Don't bother pulling it via JSON.  Doing so just adds overhead you don't need since you are checking this file on every page anyway.
Within the javascript file store the product codes in an array.

var productCodes = ['code1', 'code2', 'etc...']

Put the test in a separate function.

function pageNeedsProcessing() {
    // add any special rules here to avoid checks when not needed.
    if (location.pathname.indexOf('/product-p/main-product.htm')) {
        return true;
    }

    // do whatever you need to get the product code.  This may require parsing the path.
    var prodCode = ???;

    // if the product code is in array (established in #2) then return true.
    return $.inArray(prodCode, productCodes)
}

Add your code to be processed.

if (pageNeedsProcessing()) {
      //DO SOMETHING TO THESE SPECIFIC PAGES
}

One caveat here is that doing it exactly like this will introduce some variables into global scope.  But there are ways around that.


There's a simpler way.

To get the next line

take two copies of the line,
extend them respectively with 0 at the start and with 0 at the end, and
add the corresponding elements.

In Clojure,

(defn pascal []
  (iterate
    #(mapv + (cons 0 %) (conj % 0))
    [1]))

=> (take 5 (pascal))
([1] [1 1] [1 2 1] [1 3 3 1] [1 4 6 4 1])

This avoids the partitioning.

Not sure if it's what you're looking for, but showing off was irresistible.


This review is in response to the request for help on "overall coding practice." It does not delve into the syntax or semantics of the C++ language. There are three levels: Computer Science, Architecture, Variable Names.
Computer Science
Technically the implementation is not a stack because:
myStack.push(4);
myStack.pop();

does not return 4. To be a proper stack, rather than returning void, pop should be:
int pop();

In other words, pop() must return something that was pushed onto the stack (or an error, but that's an architectural issue not a principle of computer science).
Architecture
Strictly speaking topElement() could return a void and write a message to the console, but it is conventional for it to return something of the same type as the top element of the stack - in the case of reference types, the question of whether it should be a copy [and what type of copy] or a reference to the object itself muddies the waters.
The current implementation of void pop(); points to a larger architectural issue, a low degree of modularity. Currently, user interface is spread across the code and the stack data structure even writes messages to the console. The effect:

The implementation of stack is not broadly reusable.
The user interface does not have a clear design and would be hard to debug at a larger scale. There's a bit of the "spaghetti design pattern."

A more modular approach to implementing stack might be:
public:
    Mystack();
    void push(int x);
    int pop();
    int topElement();
    bool isEmpty();
    bool isFull();  // added to allow bounds checking
    void print();   // could be handled elsewhere but that's pure opinion.

and placing - from the viewpoint of the stack -  all the user interface code in Main. Whether the user interface logic all lives there or in it's own class/module is another question. But reusability and maintenance certainly offer suggestions.
For example, breaking out the user interface and its logic and its content into modules allows handling nasty issues like multiple languages and the quirks of UniCode to be handled more gracefully. String output is the one of the places Your-Not-Gonna'-Need-It [YNGNI] fails and why it is a baked in module for so many development frameworks.
Variable Names
A, num, ch, and s1 though perhaps conventional for C++ example code, don't really scale well because they lack information. Even in the original code:
cout << "top:  " << A[i]<< endl;

is more than 50 lines from:
private:
    int A[MAX_SIZE];

and that distance is only likely to grow as a useful program adds features.
Final Thought
I cannot help but recommend McConnell's Code Complete as a guide to deepening one's understanding of the ways in which software can be organized.


Get better conclusions from a javascript randomizer

Math.random() should be adequate for most pseudo-random use cases that don't need to be cryptographically secure.

You can consider using RandomSource.getRandomValues() (MDN Documentation) for a a more random distribution, but this may also come at the cost of more resources being utilized in generating the random number.

You may also have cross-browser compatibility issues as this is newer javascript API.


First thing I noticed is that your fulfilling the wrapper promise by way of other promises inside it. Seems like and extra step that isn't needed. Especially the final .then(resolve, reject) feels like a big anti-pattern especially since it is a repeated pattern. So the rational is to catch the exception. My take on this is to wrap only _hasDataTypeA in it's own promise and then use that result to manage the following promises:

function _hasDataTypeAPromised() {
  try {
    return Promise.resolve(_hasDataTypeA());
  } catch (e) {
    return Promise.reject(e);
  }
}

function _getData() {
  return _hasDataTypeAPromised()
    .then(function(hasDataTypeA) {
      if(hasDataTypeA) {
        return SomeBackendAccessObject.getTypeAData();
      } else {
        return SomeBackendAccessObject.getTypeBData();
      }
    });
}

You could even ternary-ize the method with:

var method = hasDataTypeA ? 'getTypeAData' : 'getTypeBData';
return SomeBackendAccessObject[method]();


Program that should output nth arrangement of paintings

I have thought of the following algorithm that is NOT recursive at all and thus has linear \$o(n)\$ complexity (n being the total number of works meaning a+b+c+d+e...):

The order of arrangements in the list is alphabetical.  This means that the list will forever begin with arrangements beginning with A and then arrangements beginning with B and so on. So looking at the example list in the question, the first column of letters shows consecutive ranges of letters: AAABBBBBBCCC. You can calculate this "list of first letters" based on the input values of how many artists and how many works for each artist (I will let you figure out the exact formula, its pretty easy). So now you can determine the first letter of the nth arrangement directly from this formula.

Once you have that, it's pretty easy to calculate the rest of the letters by removing the first letter and applying the formula as if the input was one work less.


Subset sum whose set contains only positive integers

First of all I, for one, do not think your code is self-explanatory. I've read it quite a few times, and if I do understand the code you've written, but I still fail to properly understand your logic. In other words, your code would benefit greatly from some test cases, with proper explanations around them. Even a link to which algorithm you are attempting to implement would be better.

So here are some other stylistic and code review items:

Spacing is good, but could have more comments – I like both your vertical and horizontal spacing. This renders the code easy, but I do miss some comments here and there to indicate more of the algorithmic meaning of your code.
Somewhat good naming – You are not very fond of long names, I gather, and some of the like the loop indices, i, j, I don't mind. And I kind of understand the m for matrix, but the s is just a little random. I would consider at least explaining some of the latter ones even if you keep them short for brevity of the code.
Function naming is somewhat unclear – I would rather use build_subset_sum_matrix() instead of get, as you don't simply fetch a value, you do build an entirely new matrix.

The same applies for the subset_sum, it is not quite clear what this function actually does. It does something related to subsets and sum, but what?
Don't understand your range's – Using range(1, s + 1) seems kind of strange, and I think I would have used range(s) instead. Similarily later down you do range(1, len(subset) + 1), when you could have done range(len(subset)). This would of course change that instead of i and i - 1 you do i - 1 and i, or similar.
Why reset 0 to 0? – Within your first function you first set all element to 0, and then you reset  m[0][i] = 0. Why?  (I would also consider switching around i and j to match the other function...)

In fact you simplify the entire function to a list comprehension like the following:

def build_subset_sum_matrix(subset, size):
    return [[0 if i > 0 else 1 for i in range(size + 1)]
            for _ in range(len(subset) + 1)]

Most of these comments are minor issues, and some personal preferences, as the main issue you are trying to solve still alludes me somewhat. In other words, I'm not sure that your code actually does what you want it to do, and that it is the optimal solution.

Add testing

To accommodate this I would strongly suggest to add multiple tests to your code to verify correctness. Try to vary these tests as much as possible to cover most edge cases, and use them to further explain your algorithm.

There are loads of variations, and I'll only suggest two of the more standard approaches. Namely that of the modules unittest and doctest.

The latter one allows stuff like the following variant of the modified build subset sum matrix:

    def build_subset_sum_matrix(subset, size):
        """Initialize a matrix with 1's and 0's.

        >>> build_subset_sum_matrix([1, 4, 10], 4)
        [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]
        """
        return [[0 if i > 0 else 1 for i in range(size + 1)] for _ in range(len(subset) + 1)]

This could be run always by doing an import doctest, and then a doctest.testmod() somewhere in your file. If the test runs expectedly, you don't see anything, but if the wrong result is generated you get some error messages. See more information in the links given above.


A double-for-loop over x and y seems appropriate.

Also, it seems like a good idea to assign (SmartSquare)board.getSquareAt(...) to a variable.

int bombNum = 0;
for    (int xOffset = -1; xOffset <= 1; xOffset++)
   for (int yOffset = -1; yOffset <= 1; yOffset++)
   {
      if (xOffset == 0 && yOffset == 0)
      {
         continue;
      }
      SmartSquare neighbour = (SmartSquare)board.getSquareAt(xLocation+xOffset, yLocation+yOffset);
      if (neighbour != null && neighbour.getBomb())
      {
         bombNum++;
      }
   }
return bombNum;


The opposite of CodeLess Questions query

If your aim is to find code dumps, then you can do better.

Disclaimer: the example posts linked in the following paragraphs are code dump suspects. Maybe they are code dumps, maybe not. Judge for yourselves.

In particular,
answers that start with "I prefer:", or "Try:", or "Yes:",
and then followed by a code dump, won't be matched by the posted query,
but effectively they are still code dump suspects.

Similarly, answers that start with a code dump suspect and end with "etc...",
"and so on", or "?" are also code dump suspects.

Generally speaking, a code dump suspect looks like this:

Contains mostly code
Too short (or no) introductory text
Too short (or no) closing text

What is too short? There cannot be rule for that. The longer the text, the more false positives, and the shorter the text, the more code dumps missed. It's probably a good idea to make the text length before and after parameters of the query.

In addition to adding these parameters to widen the search,
it's natural to include the text before and after in the query result,
to make it easier to judge code dump suspects at a glance.

Something like this:

DECLARE @MaxTextLenBeforeCode AS INT = ##MaxTextLenBeforeCode:int?0##;
DECLARE @MaxTextLenAfterCode AS INT = ##MaxTextLenAfterCode:int?0##;

SELECT
  Id AS [Post Link],
  Score,
  CHARINDEX('
', Body) - 1 AS TextLenBeforeCode,
  LEFT(Body, CHARINDEX('
', Body) - 1) AS TextBeforeCode,
  LEN(Body) - CHARINDEX('
', Body) - LEN('
') AS TextLenAfterCode,
  RIGHT(Body, LEN(Body) - CHARINDEX('
', Body) - LEN('
')) AS TextAfterCode,
  CreationDate
FROM Posts
WHERE PostTypeId = 2  -- answers
  AND CHARINDEX('
', Body) > 0
  AND CHARINDEX('
', Body) - 1 <= @MaxTextLenBeforeCode
  AND CHARINDEX('
', Body) + LEN('
') >= LEN(Body) - @MaxTextLenAfterCode
  AND ClosedDate IS NULL
ORDER BY Score DESC, CreationDate


Well, I don't see much you can do with the first method (being as it has a different responsibility than the other two). You can just combine the latter two methods into one and make the time object a parameter, like such:

def time_string(time_obj, meridian=true)
  if time_obj
    str = "%l:%M"
    str += " %p" if meridian
    time_obj.strftime(str).lstrip
  else
    ""
  end
end

This should reduce complexity some, since both latter methods have essentially the same responsibility.


Binary search using recursion, iteration, shifted array

If numberToFind > array[mid] then the lower bound should be set to mid + 1 as the value at array[mid] does not match. In the opposite case the upper bound should be set to mid - 1. If you don't do so, you might get stuck in an endless recursion. Say you are looking for 12 (at index 6) and you have indexMin = 5 and indexMax = 6. mid becomes 5. Now calling

FindIndexRecursive(numberToFind, array, mid, indexMax);

gives the same indexes again and array[mid] will never be 12!

I am also irritated by the test array[mid] < numberToFind. It seems more natural to me to perform the equivalent test numberToFind > array[mid]:

if (numberToFind > array[mid])
{
   return FindIndexRecursive(numberToFind, array, mid + 1, indexMax);
}
else if (numberToFind < array[mid])
{
    return FindIndexRecursive(numberToFind, array, indexMin, mid - 1);
}
else
{
    return mid;
}

mid can be found more easily with:

int mid = (indexMin + indexMax) / 2;


Bank account balance, withdraw, deposit: compartmentalize without losing functionality

This code is already quite compact. Some PEP8 code styling will not hurt. Some spaces here and there, consistency in using quotes in string literals. Also some comments can be turned into docstrings. (and comment like "constructor" is not necessary - everyone who knows Python will recognize that).

However, one thing probably good to make sure: The balance better use proper type, for example, decimal. Float is terribly wrong type for monetary transactions.


I do believe this could be done easier. You could use the || shortcut to set min and max if you could not find a speed range, and you could extract the numbers into a data structure and go from there.

Something like this:

function getRange(speed){
    //Speed range config, in array to preserve order
    var speedRanges = [
            { name: 'slow',   min: 1  , max : 35 },
            { name: 'medium', min: 36 , max : 75 },
            { name: 'fast',   min: 76 , max : 100 }
        ],
        min, max, i, range;
    //Build logic once for arrays, if we are not dealing with an array,
    //then turn speed into an array
    if (!Array.isArray(speed))
        speed = [speed];
    //Check for each speed range, apply if applicable
    for (i = 0; i < speedRanges.length; i++) {
        range = speedRanges[i];
        if (~speed.indexOf(range.name)) {
            min = min || range.min;
            max = range.max;
        }
    }

    min = min || 1;
    max = max || 100;
    return [min, max];
}

If you absolutely need slow to be 0 to 35 then you will have to enhance min = min || range.min; since 0 counts as not set..


Simple console directive, revised using provider

Just quick comments, as so far your code looks good

ng-class can receive an ng-model variable, the class being displayed matching the ng-model content, so you can directly state

 ng-class="{event.type}"

Maybe you want to extract the logic to check if the event exists to some functions with proper naming

    if (events.length > 0 && isFirstEvent(events, type, data)) {

Mine is probably not the best example but it will help to have an idea what's happening

Plus extracting the html of the directive to a template will help readability and maintainability

Hope it helps!


1. Introduction

This question is difficult because:

It's not clear what the function countlower does. It's always a good idea to write a docstring for a function, specifying what it does, what arguments it takes, and what it returns. (And test cases are always appreciated.)
It's not clear what the role of the arguments n1 and n2 is. The code in the post only ever passes len(v1) for n1 and len(v2) for n2. So is that a requirement? Or is it sometimes possible to pass in other values?

I am going to assume in what follows that:

the specification of the countlower function is Return the number of pairs i, j such that v1[i] < v2[j];
n1 is always len(v1) and n2 is always len(v2);
the Cython details are not essential to the problem, and that it's OK to work in plain Python.

Here's my rewrite of the countlower function. Note the docstring, the doctest, and the simple implementation, which loops over the sequence elements rather than their indices:

def countlower1(v, w):
    """Return the number of pairs i, j such that v[i] < w[j].

    >>> countlower1(list(range(0, 200, 2)), list(range(40, 140)))
    4500

    """
    return sum(x < y for x in v for y in w)

And here's a 1000-element test case, which I'll use in the rest of this answer to compare the performance of various implementations of this function:

>>> v = np.array(list(range(0, 2000, 2)))
>>> w = np.array(list(range(400, 1400)))
>>> from timeit import timeit
>>> timeit(lambda:countlower1(v, w), number=1)
8.449613849865273

2. Vectorize

The whole reason for using NumPy is that it enables you to vectorize operations on arrays of fixed-size numeric data types. If you can successfully vectorize an operation, then it executes mostly in C, avoiding the substantial overhead of the Python interpreter.

Whenever you find yourself iterating over the elements of an array, then you're not getting any benefit from NumPy, and this is a sign that it's time to rethink your approach.

So let's vectorize the countlower function. This is easy using a sparse numpy.meshgrid:

import numpy as np

def countlower2(v, w):
    """Return the number of pairs i, j such that v[i] < w[j].

    >>> countlower2(np.arange(0, 2000, 2), np.arange(400, 1400))
    450000

    """
    grid = np.meshgrid(v, w, sparse=True)
    return np.sum(grid[0] < grid[1])

Let's see how fast that is on the 1000-element test case:

>>> timeit(lambda:countlower2(v, w), number=1)
0.005706002004444599

That's about 1500 times faster than countlower1.

3. Improve the algorithm

The vectorized countlower2 still takes \$O(n^2)\$ time on arrays of length \$O(n)\$, because it has to compare every pair of elements. Is it possible to do better than that?

Suppose that I start by sorting the first array v. Then consider an element y from the second array w, and find the point where y would fit into the sorted first array, that is, find i such that v[i - 1] < y <= v[i]. Then y is greater than i elements from v. This position can be found in time \$O(\log n)\$ using bisect.bisect_left, and so the algorithm as a whole has a runtime of \$O(n \log n)\$.

Here's a straightforward implementation:

from bisect import bisect_left

def countlower3(v, w):
    """Return the number of pairs i, j such that v[i] < w[j].

    >>> countlower3(list(range(0, 2000, 2)), list(range(400, 1400)))
    450000

    """
    v = sorted(v)
    return sum(bisect_left(v, y) for y in w)

This implementation is about three times faster than countlower3 on the 1000-element test case:

>>> timeit(lambda:countlower3(v, w), number=1)
0.0021441911812871695

This shows the importance of finding the best algorithm, not just speeding up the algorithm you've got. Here an \$O(n \log n)\$ algorithm in plain Python beats a vectorized \$O(n^2)\$ algorithm in NumPy.

4. Vectorize again

Now we can vectorize the improved algorithm, using numpy.searchsorted:

import numpy as np

def countlower4(v, w):
    """Return the number of pairs i, j such that v[i] < w[j].

    >>> countlower4(np.arange(0, 20000, 2), np.arange(4000, 14000))
    45000000

    """
    return np.sum(np.searchsorted(np.sort(v), w))

And this is six times faster still:

>>> timeit(lambda:countlower4(v, w), number=1)
0.0003434771206229925

5. Answers to your questions

In comments, you asked:

"What does vectorizing mean?" Please read the "What is NumPy?" section of the NumPy documentation, in particular the section starting:

  Vectorization describes the absence of any explicit looping, indexing, etc., in the code - these things are taking place, of course, just “behind the scenes” (in optimized, pre-compiled C code).

"What is meshgrid?" Please read the documentation for numpy.meshgrid.

I use meshgrid to create a NumPy array grid containing all pairs of elements x, y where x is an element of v and y is an element of w. Then I apply the < function to those pairs, getting an array of Booleans, which I sum. Try it out in the interactive interpreter and see for yourself:

>>> import numpy as np
>>> v = [2, 4, 6]
>>> w = [1, 3, 5]
>>> np.meshgrid(v, w)
[array([[2, 4, 6],
       [2, 4, 6],
       [2, 4, 6]]), array([[1, 1, 1],
       [3, 3, 3],
       [5, 5, 5]])]
>>> _[0] < _[1]
array([[False, False, False],
       [ True, False, False],
       [ True,  True, False]], dtype=bool)
>>> np.sum(_)
3