Partition - Pivot selection
There are 2 bugs in the pivot selection code, in combination allowing for \$\mathcal{O}(n^2)\$ worst case runtime.
Bug #1: Wrong average calculation
I guess this is just a typo:
auto middle = data[(p + 2) / 2];

Most likely, (p + r) / 2 was intended instead, and that would fix this problem (disregarding overflow).
Bug #2: Missing a case
if (first > middle) {
    if (middle > last) {
        pivot = middle;
    } else {
        pivot = last;
    }
}

This snippet doesn't handle the case correctly if \$middle < first < last\$. Even though first should be assigned as pivot, last will be.
The fix is simple: Change pivot = last; to pivot = std::min(first, last);.
Consequences
These two bugs allow for runtime complexity to degrade to \$\mathcal{O}(n^2)\$, because they introduce a huge bias towards last as pivot value:
For any call with p >= 4, middle will have the value of an element to the left of data[p], thus being guaranteed to be smaller than first or last due to previous runs of _partition. So `last will be chosen as pivot, due to bug #2.
For any call with p == 2 or p == 3, middle will be assigned the value of data[1], which is equal to first. In that case, pivot will always be assigned the value of middle/first.
For any call with p == 0 or p == 1, the median calculation will work with a slight bias towards last (due to bug #2).
Partition - Moving values
There seems to be an assumption that data[r] == pivot. This might have been a good assumption before due to bug #2, but that isn't necessarily the case once that bug is fixed. There a multiple ways to fix that.
Also, technically it isn't necessary to move values around that are equal to the pivot value: It doesn't actually matter whether they are left or right of the final pivot position.
Multithreading
The current multithreading solution isn't actually that efficient at using threads: Nearly half the threads at a time are waiting for the others to finish. (The first thread is waiting on threads #2 and #3 it spawned, they then are waiting on threads #4-7, ...)
As mentioned in the comments, this could be fixed by letting the original thread keep working on one of the subsections before waiting, i.e. changing this:
        std::thread lower(&quicksort::_sort<T>, this, data, p, q - 1);
        std::thread upper(&quicksort::_sort<T>, this, data, q + 1, r);
        lower.join();
        upper.join();

to:
        std::thread lower(&quicksort::_sort<T>, this, data, p, q - 1);
        _sort(data, q + 1, r);
        lower.join();

Another point to make is that it rarely benefits performance to have a number of threads much larger than the number of available (logical) cores. The final number is likely between #cores and 2 * #cores, but to find the best amount you'll likely need to measure.
Bug #3: No protection for concurrent calls
Since we're already in the multithreaded environment, what happens if a second thread calls quicksort::sort after the first thread, but before that call finished?
It resets thread_count, thus allowing for the creation of more threads than intended. Once they are finished, thread_count will be negative! This might cause problems if that case isn't expected.
Solution: Either don't reset thread_count, or wait until it reaches zero before starting to work on the next dataset.


Inefficient DNA heterodimerization script

Here is your original code with comments on which lines should be revised for clarity
import sys
from Bio import SeqIO
from Bio.Seq import Seq

def hetero_dimerization():
    script = sys.argv[0]  # script is unused; the line should be removed
    file1 = sys.argv[1]
    list = []  # list is a python built-in python; overwrite it at your own peril. I'd suggest renaming this variable
    list2 = []
    with open(file1, 'r') as file:
        for record in SeqIO.parse(file, 'fasta'):
            for i in range(len(record.seq)):
                kmer = str(record.seq[i:i + 6])
                if len(kmer) == 6:  # this check is redundant. kmer is guaranteed to be of length 6
                    list.append(kmer)
            #print(record.seq)  # if you submit code for review, avoid commented out source code. it is confusing
            #print(list)  # same here, avoid commented out code

            # this is a bug. You add every kmer to the list even if you discard the sequence
            # you also add redundant ones, which causes considerable slowdown
            for kmers in list:
                C_kmer = Seq(kmers).complement()
                list2.append(C_kmer[::-1])
            #print(list2)  # avoid commented out code

            # adding a counter for a simple if is not very clean
            # instead consider `if not any(...):`
            cnt=0
            if any(items in record.seq for items in list2):
                cnt +=1

            if cnt == 0:
                print('>'+record.id)
                print(record.seq)

if __name__ == '__main__':
    hetero_dimerization()

Your code contains a bug (@danzel already pointed that out), as you append the list if inverse complements for every 6mer you encounter, irrespective of it being from a sequence you wish to discard and irrespective of it being already contained in the list. You've fixed the bug in your updated code and in the process also changed the algorithm to avoid a lot of unnecessary work.
You can slightly (~15%) improve this further by (a) switching the complement list to a set and searching the set for each 6mer in the sequence (instead of the other way around) and by stopping the search early (breaking) if you encounter a 6mer that is already in the list. I also took the liberty to python-ify your code a bit in the process.
def kmer_generator(record, k=6):
    sequence = record.seq
    for idx in range(len(sequence) - (k-1)):
        yield sequence[idx:(idx+6)]

def hetero_dimerization_optimized():
    taboo_list = set()
    resulting_sequences = list()
    with open("fasta-file", 'r') as file:
        for record in SeqIO.parse(file, 'fasta'):
            new_taboo_items = set()
            for kmer in kmer_generator(record):
                if str(kmer) in taboo_list:
                    break
                complement = str(kmer.reverse_complement())
                new_taboo_items.add(complement)
            else:
                # this is entered only if no break occurs
                # i.e. if no kmer was in the taboo_list :)
                taboo_list = taboo_list.union(new_taboo_items)
                resulting_sequences.append(record.seq)
    return resulting_sequences

From here, your most noticable speedups would come from (a) writing your own reverse_complement function that reduces constant overhead (~50% of the runtime is spend on this line), (b) switching to numpy and using chararray to get access to np.view and avoid further copies of your data; this is in addition to (a) and could save you an additional 20%+ runtime.
After this, you could look into multiprocessing to use additional cores to pre-filter sequences, but tbh. this will likely be over-engieered for a mere 9000 sequences.


Appending data to a web page from a form using a JavaScript class

The convention with class names is that they are usually written in pascal case, for example, PascalCase. So you should use Data for your class name.

While it's great that you're experimenting with javascript classes, I feel that they're not the right tool to use for this. The main idea of a class is that they can be used to create multiple objects based off the class.

Here's a pseudo-code example of when using a class is ideal.

class Vehicle {
    constructor(model, regNumber) {
        this.model = model;
        this.regNumber = regNumber;
    }

    start() {}
    accelerate(acc) {}
    brake() {}
}

class Car extends Vehicle {
    // additional methods
}

const ford = new Car('Ford', 'HR28AP0000');
const auto = new Vehicle('ExampleDX', 'TN09XX0000');

The vehicle class has some attributes and methods. This example lends itself very well to the idea of classes.

For your code, it's best to use an append function instead.

I'd suggest looking up Object Oriented Programming. Some well written books and blogs will do a much better job of explaining when and where to use classes and objects and other OOP principles.

Edit: About try-catch, it's common to throw an Error object or one of it's descendants.

if(email == '' || url == '' || number == '' ) {
    throw new Error("Empty");
}


Algorithm to transform a string according to occurrence count of each character

def compression(string):

Naming can be hard, but it is important to get right.  If I were to call compression('abcd'), I would expect the result length to be at-most the length of the input string.  "compression" doesn't really describe what is happening within the function.  So what exactly is your function doing?  From your description:

  I have this algorithm that counts the frequency of character occurrence in a string, and outputs a new string based on that.

A lot of nice verbs in that description you can use for a function name (serialize_frequencies?).

string = string.lower()

Does case-sensitivity have anything to do with your stated goals of calculating and serializing the frequency of characters?  It depends on the context in which this function is used.  Case-sensitivity isn't always required.  If you really want to provide a mechanism for case-insensitive frequency generation, consider a toggle parameter or another function that transforms the input then calls this function.

serialize_frequencies(string, case_insensitive = False):
    if case_insensitive:
        string = string.lower()

    freq_count = {}

    for index, char in enumerate(string):
        if char not in freq_count:
            freq_count[char] = 1
        else:
            freq_count[char] += 1

A function that performs a single operation is simpler to understand, test, and reuse.  Don't be afraid to break functions up into suitable logical parts and parameterize.

enumerate is a nice utility when you need to iterate through a sequence but also want to know the index.  Since you don't need the index, you can just iterate through the string itself.

    for char in string:
        if char not in freq_count:
            freq_count[char] = 1
        else:
            freq_count[char] += 1

With that said, Python's collections includes a dictionary sub-class to count frequencies (Counter).

    freq_count = Counter(string)

    return_string = ''
    for key in freq_count:
        return_string += key + str(freq_count[key])

If you want to iterate a dictionary by its key-value pair, Python's built-in dictionary includes the method items().

    return_string = ''
    for key, value in freq_count.items():
        return_string += key + str(value)

You can write the loop that appends each pair using the string method join.

    return_string = ''.join(k+str(v) for k,v in freq_count.items())

    print(return_string)

Debugging artifact?

  My question is, am I making this algorithm less efficient by using dict to memoize values.

No.  But as 200_success has noted, calling compression('abcd') might result in 'a1b1c1d1' or 'c1d1b1a1' depending on the implementation.  Ordering for the built-in dictionary is arbitrary and could change between implementations, versions, or possibly application executions.  If ordering matters, then you should use a sorted container (OrderedDict, SortedDict) or manually sort the resulting dictionary before serializing.


You should compartmentalize your "handlers" for each of the packets.  Each handler should contain a canHandle method that determines whether it can process the packet and a process method that does the work.  Example:

var packet300Handler = {
    canHandle: function(packet) {
        return packet.id === 300;
    },
    process: function(packet) {
        // Do work here.
    }
};

var handlers = [packet300Handler, packet301Handler, packet302Handler];

client.on('data', function(data) {
    parser.extract('DATA', function(packet) {
        for (var i = 0; i < handlers.length; i++) {
            var handler = handlers[i];

            if (handler.canHandle(packet)) {
                handler.process(packet);
                break; // Leave loop now that something has handled the packet.
            }
        }
    });
});


Let's go over the basics first!

The indentation is quite a mess. But I suppose that might be related to the SE formatting. Otherwise, you should make your indentation coherent. Stuff like :

public interface IGYDataAccess
    {
        void GetUserInfo(Action<GYUser, Exception> act, string id);
    }

shouldn't be in production code, it looks bad and gives headaches to maintainer (that could be you!)

Why are your classes prefixed of GY? Maybe there's a good reason, but I'm pretty sure your names would make just as much sense without that prefix. The pattern you're using for caching uses the Repository design pattern. It abstracts the implementation to access to data. So that pattern name should be found in your naming! IRepository, LocalDataRepository, WebDataRepository. Some might argue that it's useless, but I think it's good to see the pattern's name in the class name, so we know what we're dealing with.

Multi-line lambdas are... okay, I guess. But I think in your case they should be in a method. A lambda is an anonymous function, something that doesn't matter that much in your code. But that code is important, don't let it crawl in the shadows, that code deserves a method. (The lambda in GetUserInfo)

Don't keep your connection string as a const in your code, that's a very bad practice. It should be in a configuration file, and you should get it using the ConfigurationManager class (In System.Configuration).

private members should be camelCased, not PascalCased, so DataBase -> dataBase (In GYLocalData). Also, you should specify the private accessor, so I know it wasn't forgotten or something like that. See, if it's not there. I don't know your clear intent. Maybe you wanted this field to be public but you forgot because you were out of coffee. I'll never know because you didn't specify it.

I want to give a little warning that might be unnecessary. The CheckDatabase method isn't thread safe. That means if your GYLocalData object can be called from multiple threads at once, you might create the database twice. And that's a costly operation. That's bad.

You should only use var when you can figure the Type by reading the code. In the example below, I can't figure it out, so it's harder to know what's happening and even harder to review! :)

var user = DataBaseProfiles.GetInfo(id);

You could use some Dependancy Injection in your GYWebData class. You want to store everything that is took from the web API in a another storage. So the GYWebdata class should receive in the constructor a GYLocalData instance where you would store the information :

public class GYWebData : IGYDataAccess
{
    private GYLocalData storage;

    public GYWebData(GYLocalData storage)
    {
        this.storage = storage;
    }

    public void GetUserInfo(Action<GYUser, Exception> act, string id)
    {
        GYUserAPI.GetInfo(id, (result, error) =>
            {
                if (error != null)
                {
                    act.Invoke(null, error);
                    return;
                }

                act.Invoke(result.Result, null);
                storage.UpdateUserInfo(result.Result);
            });
    }
}

Now this isn't exactly Dependency Injection because I give a concrete class as parameter. You would need another interface, IDataUpdater, maybe :

public interface IDataUpdater
{
   void UpdateUserInfo(GYUser user);
}

The LocalData class should implement that interface, and then :

public class GYWebData : IGYDataAccess
{
    private IDataUpdater updater;

    public GYWebData(IDataUpdater updater)
    {
        this.updater = updater;
    }

    public void GetUserInfo(Action<GYUser, Exception> act, string id)
    {
        GYUserAPI.GetInfo(id, (result, error) =>
            {
                if (error != null)
                {
                    act.Invoke(null, error);
                    return;
                }

                act.Invoke(result.Result, null);
                updater.UpdateUserInfo(result.Result);
            });
    }
}

Boom, you now have zero dependency between the local storage and the web storage.

Finally, looking at your workflow, you could use the Proxy design pattern to help a bit. The Proxy would be used to get info from the web and cache it in the local storage. The proxy would be the only class you use for storage. I don't want to give it all to you, because you'll learn better by yourself! :) But know that the Proxy is a good case for this!


You should have added error checking:

 node * newp=(node *)malloc(sizeof(node));
 newp->data=(char *)malloc(sizeof(strlen(data));

malloc can return NULL if there wont be enough Virtual Adress Space. Would be great if function return error code.

add {} it could bite your next time

  if(listp==NULL)
   listp=nextp ;
  else
   listp->nextp=newp;
   //next live goes here, looks like next statment in else, but it's not.

Use PascalCase or camelCase

// initialize mergedlistp;
node* mergedlistendp=NULL; // mergedList is a better name
list* leftlistp = NULL;

Stick to one style, once you have:

if (list1p == NULL) leftlistp=list2p;
if(list2p == NULL) leftlistp = list1p;

another one

  if(listp==NULL)
   listp=nextp ;

or

  if(list2p == NULL)
   {leftlistp=list1p; break;}

One statment per line

 if(list2p == NULL)
 {leftlistp=list1p; break;} // put break in the next line.


Finding an index in an array of objects with 3 possible outcomes

You can group the two conditions for finding into a single || condition, since the post.id can match only one of tempId or id.

let postIndex = currentUserPosts.findIndex(post => {
  return post.id === upsertParams.id || post.id === upsertParams.tempId
});

if (postIndex === -1) {
  currentUserPosts.push(upsertParams);
} else {
  currentUserPosts[postIndex] = upsertParams;
}

You could, if possible, also change the currentUserPosts from array to a dictionary mapping your post.id to the post itself. This entirely depends on your further usage of the currentUserPosts across application.

Based on updated question content:

let currentUserPosts = {}
for (let post of data.currentUser.posts) {
  currentUserPosts[post.id] = post
}

This way, you'd only have to check against id using the in operation:

let newId = upsertParams.id || upsertParams.tempId
if (newId in currentUserPosts)
  // do unspeakable things


Common interface with different return types

Normally when you need "different return types", you can use generics. However, since you want these Counters to be in a List of some sort, using generics goes out the window since a List cannot be defined properly to contain both Counter<List<File>> and Counter<Integer>, so the only solution would be to have a List<Counter<?>> in which case the reason for using generics in the first place is lost.

Your CounterDTO class makes sense if a Counter counts more than one of the things. If the counter is only meant to return an int or a list of files, then using a CounterDTO is quite useless since many fields will be null.

Regarding Banthar's comment to your question, you could modify your existing interface to

int count(List<File> files);

It would then be the job for a single utility method (or two) to create a list of files from these parameters: File startDirectory, boolean recursive, List<String> fileExtensions.

As for the question about return type... If you need an interface for this or not depends on how you are using these counters. And also: Which possible counters are there? If you have one counter for returning total line count and one for returning a Map<File, Integer> of line counts, then you don't need two different counters. Since you need to know all the line counts in all the files to know the total line count, using a CounterDTO makes perfect sense here.


Using CakePHP models/controllers properly

To me your code and relations looks good! You removed the redundancy in your database by splitting the tables up. Your cake really looks cakes way to me!

Just make sure you actually do something with the exception thrown and it should be all good.

Edit : I know this is a little late, but I wanted to complete my answer for the sake of completeness.

Your code style looks pretty good to me. The functions names are well chose. What I mean by that is by putting verb first you make the function a lot easier to find and understand.

Also, putting the logic in the model is the good choice. Continue to keep thin controllers.


Centering an item over an image with absolute positioning and flexbox

Is there any benefit to using the flexbox solution?

The principal benefit will be more concise, easier-to-maintain code.

That's not to say there's anything wrong with position: absolute (there isn't). Just that with display: flex you can achieve more with less.

That is, once you have declared justify-content and align-items on a flex parent, you don't necessarily need to apply any further positioning to flex-children at all - they will automatically display in the right position, regardless of browser viewport size and dimensions.

  IE11 isn’t playing ball.

True: https://caniuse.com/#feat=flexbox

But IE11 is from October 2013.

Even Microsoft says IE is not a browser and no-one should be using it:

https://www.zdnet.com/article/microsoft-security-chief-ie-is-not-a-browser-so-stop-using-it-as-your-default/

Flex Example:

.cat {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 340px;
  height: 180px;
  background: url('https://hackernoon.com/hn-images/1*mONNI1lG9VuiqovpnYqicA.jpeg') 0 0 / 100% 100%;
}

.center {
  background: rgba(255, 255, 255, 0.6);
  padding: 12px;
}

  I want to center this


One possibility would be to use an std::initializer_list:

#include <initializer_list>
#include <numeric>
#include <iostream>

double average(std::initializer_list<double> input) {
    double sum = std::accumulate(input.begin(), input.end(), 0.0);
    return sum / input.size();
}

int main() {
     std::cout << "Average: " << average({1, 2, 3, 4, 5, 6, 7, 8});
}

You could have the function take (for example) a vector instead, and it'd still work pretty much the same way (because vector already has a constructor that takes an initializer_list). Either way works out pretty much the same way though.

If you want to use just a list of numbers rather than having to add the {} around the list to force it into an initializer_list you can add var-args template function to wrap the call.

template<typename... Args>
double average(Args... args)
{
    return average({args...});
}

Looking at your code, a few things nearly jump out. First and foremost, you're using a C-style variable parameter list. This is mostly frowned upon in C++ for a number of reasons such as lack of type-safety. For example, if you'd accidentally passed your 25.0 as just 25, it'd be passed as an int instead of a double, and the whole thing would break.

The second is similar: using printf to print out the result has exactly the same problem for exactly the same reason (printf also uses a C-style variable parameter list).

Third, related to those but technically a separate issue (since it's about values, not types) is the problem you've apparently already noticed: it requires you to count the number of parameters. If you make a mistake, you get bad results (and if you tell it you're passing more parameters than you really do, undefined behavior).

Simply put, although your code won't compile as-is with a C compiler, it's still basically C-style code. It does nothing to fit with (or take advantage of) anything in C++ that wasn't a part of C 20+ years ago. If used correctly, it works, but it's all too easy to use it incorrectly.


Producer consumer that simulates the interaction of threads controlling a hardware device

I have some minor things to point out:

There is not a single empty line in this code, and this essentially looks like globals, functions, and comments stacked on top of each other.  You should have each type separated so that the code is easier to read (especially with the function names and return types on separate lines).
Since you're using C++11, you should be using <random> in place of std::rand.  It has been determined that rand() is harmful and should no longer be used in C++11.
Unless I'm misunderstanding the use of multithreading here, I don't think you should be using any global variables, as they're prone to bugs.  If that's the case, then you should just be passing them to functions as needed.  If not, then at least put them all towards the top (they're already global, so it doesn't make a difference to have them in different places outside the functions).
You don't need to be using std::endl everywhere.  It doesn't appear that you're needing to flush the buffer each time, which can also affect performance.  Instead, output a "\n" to produce a newline without also flushing the buffer.


Find largest substring in alphabetical order in a given string

Here are a few details :

Variable declaration

It is usually a good idea to move your variable declaration in the smallest possible scope as close as possible to where they are getting used.

This for instance shows that sub is never used.

Also, you can take this chance to change your while loop into a for loop and declare i in it.

Warnings

It is a good thing to activate all warnings. For instance, I get :

  warning: comparison between signed and unsigned integer expressions
  [-Wsign-compare]

Simplifying things

Instead of messing with prev, you can detect if i has been increased already by considering the value of check.

Cast

I do not think these casts are useful.

Length

It could be a good idea to store the length of the string in a variable not to retrieve it at every iteration.

Using namespace

using namespace is sometimes frowned upon.

At this stage the code looks like :

#include <iostream>
#include <string>

int main()
{
    std::string s = "vjvdfkjckvjkjrdsfjsdkjfliureyqnbcxvfjhdeiutogfvjdsvkdfcdcoivjriofdjsrs";
//    std::cin >> s;
    int count = 0, pos = 0; // keeping count of number of alphabetical ordered substring characters

    for (size_t i = 1, len = s.size() ; i < len ; )
    {
        int check = 1;
        while (s[i] >= s[i - 1])
        {
            ++check;
            ++i;
        }
        if (check > count)
        {
            count = check;
            pos = i - check;
        }

        if (check == 1)
            ++i;
    }
    std::cout << "Longest substring in alphabetical order is :" << s.substr(pos, count) << std::endl;
}

Algorithmic trick

A trick could be to say that if you have a current result of length n, you don't care about any substring of length m < n. Thus, you can check backward from position i + n : as long as it is in descending order, you continue, otherwise, it gives you a starting position to start again.

I am not sure if this is really clear. I'll tr to improve asap.


my $cols   = {'list'=>0, 'email'=>1, 'sub'=>2};

I'd call this

my %index_of = { 'list' => 0, 'email' => 1, 'sub' => 2 };

and later, change $return to

my $index = $index_of{'email'};

The following is used oddly:

print get_list(@ARGV);
foreach (@ARGV) {

You are calling the function with parameters @ARGV but you never use the parameters in the function.  Instead, you use @ARGV again.  Better would be to use the function parameters:

my @arguments = @_;
foreach my $argument (@arguments) {
   my ($key, $value) = split {=}, $argument;

I also switched to using a named element instead of letting it default to $_.

Alternately, you could pass nothing into the function and use @ARGV in the foreach as you did.  That would work but isn't a best practice.

You may not have realized but the '=' was a regular expression with single quotes as the delimiters.  I prefer to use curly brackets for regular expressions.  If you wanted to be really plain about it, you could have said qr{=}.

# default patterns that can be overridden by command line arguments
my $list   = qr{[a-z0-9_\- ]+};
my $email  = qr{[a-z0-9@\._\-]+};
my $subls  = qr{[a-z0-9\. ]+};
  $value = qr{} if not defined $value;

Using qr{} here makes it more obvious that these are regular expression patterns.

open my $fh, '<', $file

I'd prefer a variable here rather than a globally scoped bareword.

my $SEPARATOR = qr{\s*\t\s*}
my %emails = map { (split $SEPARATOR)[$return] => 'tacos' }
             grep m{^${list}${SEPARATOR}${email}(${SEPARATOR}${subls})?\s*$}gi,
             <$fh>;

By defining $SEPARATOR, we make the regular expressions clearer and reduce the amount of repeated code.

my @entries = ();
while ( my $line = <$fh> ) {
   @columns = m{\A(${list})${SEPARATOR}(${email})(${SEPARATOR}(${subls}))?\s*\z}gi;
   if ( scalar @columns >= 2 ) {
      push @entries, $columns[$index];
   }
}
close $fh;

return (join ', ', @entries);

This is clearer about what it is doing than the map of the grep results.  Also, it doesn't parse each line twice.  And of course it doesn't define a hash just to get the keys.

In general, I would make more use of paragraphing.  This is extra new lines to separate blocks of code.  This allows you to easily see what pieces of code go together.  For example, note how I separate the return from the file handling code.

You have comments explaining what the file format should be, but you don't explain what the command line arguments should be.  A user would have to read the code to figure it out.

Your function does two distinct things.  First, it reads the command line arguments.  Second, it opens a file and processes it based on the command line arguments.  It would be better if you could separate that into two functions.


Javascript PriorityQueue based on object property

You're off to a great start. +1 for providing comments.

Here are some tips:

1) Define variables before modifying them.

So the constants MAX_HEAP and MIN_HEAP should be defined after PriorityQueue.

Old Code:

PriorityQueue.MAX_HEAP = 0;
PriorityQueue.MIN_HEAP = 1;

function PriorityQueue(criteria, heapType) {
    //...
}

New Code:

function PriorityQueue(criteria, heapType) {
    //...
}
PriorityQueue.MAX_HEAP = 0;
PriorityQueue.MIN_HEAP = 1;

Side note: In shiftHighestPriorityElement(), _queue isn't defined. I think it should be queue.

2) Use this to attach attributes to a Constructor.

More info

Example:
Old Code:

//..
function PriorityQueue(criteria, heapType) {
    this.length = 0;
    var queue = [];
    var isMax = false;
    //...

New Code:

//..
function PriorityQueue(criteria, heapType) {
    this.length = 0;
    this.queue = [];
    this.isMax = false;
//...

3) Split up functions longer than 8 - 12 lines of code into smaller functions.

Use the prototype on an object to attach functions to the constructor instead of including all the functionality within.

Old Code:

function PriorityQueue(criteria, heapType) {
    //...
    this.insert = function (value) {
        if (!value.hasOwnProperty(criteria)) {
            throw "Cannot insert " + value + " because it does not have a property by the name of " + criteria + ".";
        }
        queue.push(value);
        length++;
        bubbleUp(length - 1);
    }
    //...
    var swap = function (self, target) {
        var placeHolder = queue[self];
        queue[self] = queue[target];
        queue[target] = placeHolder;
    }
    //...
}

New Code:

function PriorityQueue(criteria, heapType) {
//...
}
PriorityQueue.prototype.insert = function (value) {
    if (!value.hasOwnProperty(this.criteria)) {
        throw "Cannot insert " + value + " because it does not have a property by the name of " + this.criteria + ".";
    }
    this.queue.push(value);
    this.length++;
    this.bubbleUp(this.length - 1);
}
PriorityQueue.prototype.swap = function (self, target) {
    var placeHolder = this.queue[self];
    this.queue[self] = this.queue[target];
    this.queue[target] = placeHolder;
}

4) Sometimes it's better to just return an boolean expression.

Old Code:

if (queue[self][criteria] < queue[target][criteria]) {
    return true;
} else {
    return false;
}

New Code:

return (queue[self][criteria] < queue[target][criteria]);

5) Make sure to create test units.

Try out qunit.js

6) Simplify if and else conditions.

Old Code:

var isMax = false;

//Constructor
if (heapType==PriorityQueue.MAX_HEAP) {
    isMax = true;
} else if (heapType==PriorityQueue.MIN_HEAP) {
    isMax = false;
} else {
    throw heapType + " not supported.";
}

New Code:

this.isMax = !!heapType;
if ( heapType !== 0 || heapType !== 1 ){
    throw heapType + " not supported.";
}

7) Use === instead of == when comparing for value and type of primitive values.

Old code:

} else if (value == 0) {

New Code:

} else if (value === 0) {

Or

} else if (!value) {

Final code:

function PriorityQueue(criteria, heapType) {
    this.criteria = criteria;
    this.length = 0;
    this.queue = [];
    this.isMax = !!heapType;
    if ( heapType !== 0 || heapType !== 1 ){
        throw heapType + " not supported.";
    }
}
PriorityQueue.prototype.insert = function (value) {
    if (!value.hasOwnProperty(this.criteria)) {
        throw "Cannot insert " + value + " because it does not have a property by the name of " + this.criteria + ".";
    }
    this.queue.push(value);
    this.length++;
    this.bubbleUp(this.length - 1);
};
PriorityQueue.prototype.getHighestPriorityElement = function () {
    return this.queue[0];
};
PriorityQueue.prototype.shiftHighestPriorityElement = function () {
    if (length < 0) {
        throw("There are no more elements in your priority queue.");
    }
    var oldRoot = this.queue[0];
    var newRoot = this.queue.pop();
    this.length--;
    this.queue[0] = newRoot;
    this.swapUntilQueueIsCorrect(0);
    return oldRoot;
};
PriorityQueue.prototype.bubbleUp = function (index) {
    if (index === 0) {
        return;
    }
    var parent = this.getParentOf(index);
    if (this.evaluate(index, parent)) {
        this.swap(index, parent);
        this.bubbleUp(parent);
    } else {
        return;
    }
};
PriorityQueue.prototype.swapUntilQueueIsCorrect = function (value) {
    var left = this.getLeftOf(value),
        right = this.getRightOf(value);

    if (this.evaluate(left, value)) {
        this.swap(value, left);
        this.swapUntilQueueIsCorrect(left);
    } else if (this.evaluate(right, value)) {
        this.swap(value, right);
        this.swapUntilQueueIsCorrect(right);
    } else if (value === 0) {
        return;
    } else {
        this.swapUntilQueueIsCorrect(0);
    }
};
PriorityQueue.prototype.swap = function (self, target) {
    var placeHolder = this.queue[self];
    this.queue[self] = this.queue[target];
    this.queue[target] = placeHolder;
};
PriorityQueue.prototype.evaluate = function (self, target) {
    if (this.queue[target] === null || this.queue[self] === null) {
        return false;
    }
    if (this.isMax) {
        return (this.queue[self][this.criteria] > this.queue[target][this.criteria]);
    } else {
        return (this.queue[self][this.criteria] < this.queue[target][this.criteria]);
    }
};
PriorityQueue.prototype.getParentOf = function (index) {
    return Math.floor(index / 2) - 1;
};
PriorityQueue.prototype.getLeftOf = function (index) {
    return index * 2 + 1;
};
PriorityQueue.prototype.getRightOf = function (index) {
    return index * 2 + 2;
};
PriorityQueue.MAX_HEAP = 0;
PriorityQueue.MIN_HEAP = 1;


The books solution, is definitely cleaner, and the biggest difference I can see is the books solution is actually sorting the variables, rather than just changing the display order.

In terms of efficiency, displaying stuff to the console is more efficient than popping up message boxes. There's less conditional logic in the books solution and a lot less code duplication. Other than that, there is very little difference in the sorting operation, the books maybe slightly more efficient due to less conditional checks.

Overall though, in my opinion the book provides the better solution, because it has virtually no duplicated code, conditionals are a single level deep (much easier to read), actually sorts the numbers in memory (if this program were to do more, your variables would already be sorted for you next time you need them, as opposed to having to duplicate the conditional logic, and overall it's much easier to understand what it's doing and what's going on.


Alternative to using strncpy() as 'safe' version of strcpy()

Just a few comments.

The standard type for specifying something like the maximum length of a string is size_t. You should probably use that instead of int.
traversing the remainder of the string on the off chance that somebody might want to know how much was skipped seems like poor design. Unless you know you're going to use that (frequently), I'd advise against it. If somebody wants that information, strlen(s) - size is pretty trivial to type, so it's not like you're saving them something terribly arduous.
I think most people accustomed to C would probably use pointer notation throughout.

char *copystring(char *restrict dest, char const *restrict source, size_t elements) {
    char *d;
    for (d = dest; d + 1 < dest + elements; d++, source++)
        *d = *source;
    *d = '\0';
    return d;
}

This returns a pointer to the end of the new string, which frequently is quite useful. For example, if you're building up a string with data filled in at appropriate points, it's often useful to limit the size of each field you insert to a specific maximum, then get a pointer to where you're going to add the next item (though, in fairness, something like snprintf is often more convenient still).


int[][] maxbenefit = new int[weights.length + 1][capacity + 1];

    for (int i = 0; i <= weights.length; i++)
        maxbenefit[i][0] = 0;
    for (int i = 0; i <= capacity; i++)
        maxbenefit[0][i] = 0;

There is no need to initialize part of the array as 0, because the entire array starts off as 0.

public static void printMatrix(int[][] matrix, int R, int C) {
    for (int i = 0; i <= R; i++) {
        for (int j = 0; j <= C; j++) {

            System.out.print(matrix[i][j] + " | ");

        }

        System.out.println();
    }

}

In here, you should check if R and C don't exceed matrix.length and matrix[i].length respectively. That way you can either limit the printing, or you could throw an error with explanation, rather than running into ArrayIndexOutOfBoundsException.

In the same way, you should check the size of int[] benefits in getMaxBenefit, because if the weights and the benefits are not the same size then you'll throw an error at some point, and failing fast is better.


Although arguably a Pandora's box of other complications, have you considered ditching the Interop libraries and driving this through Ace/Jet drivers via OleDB?  Too often do I see well-intentioned applications fall over because Excel gets upgraded.  Best-case scenario you'll have to manage multiple releases, whereas oftentimes you're stuck redeveloping because of core changes that break existing methods.

Even when I need specific functions available only to the Interop libraries, I try to avoid using an actual reference in my project.  You can dynamically marshal your Excel.Application object if you're building this in .NET 4.0, and it gives you some flexibility depending on what you're trying to achieve.

If you're just interested about data transfer, I'd consider making a move to OleDB if you're comfortable with SQL-based database querying.

I think by omitting your specific methods of how the data gets into the sheet, you're leaving out one of the most important parts of the application in terms of performance.  Are you dumping the data cell by cell?  I'm assuming coming from SQL the data will be in DataSet/DataTable format, so you could dump to an array, and then point to an address in the sheet.

I do like that you've avoided the dreaded double-dot, and are taking the proper Marshalling release methods to make sure Excel goes away when it's supposed to.

/$.02

-- Locke


I don't know if it's a paste-issue, but you should intent your code ;)

You are building the file-path twice. You should move that line:

$mod = 'modules/'.$module.'.tpl';

To the begining of the function (and give it a better name):

public function LoadModule($module,$position)
{

    $absTemplatePath = 'modules/'.$module.'.tpl';
    if(file_exists($absTemplatePath ))
    {

That Line:

LOGIT('$module - module not found.');

should be (else $module wouldn't get replaced):

LOGIT("$module - module not found");

If the template file does not include php-code you should use file_get_contents instead of ob_start, include, ob_get_clean (performance-wise). If you do have php-code in your templates, you might have a look at zend-framework's Zend_View.


Function to spell numbers below 1,000,000,000

def main():
    value = int(input("\nPlease enter a positive integer < 1000000000 : "))
    if value < 100:
        print(processDigit(value))
    elif value > 100:
        print(intName(value))

You extracted logic which should have been encapsulated inside your function into the main function. That should never happen. If intName can't handle values between 1 and 99 itself, it's not living up to its name.

def intName(number):
    part = number
    nameMillion = ""
    nameThousand = ""
    nameHundred = ""

    if part >= 1000000:
        divide = part // 1000000
        part = part % 1000000
        divide1 = divide // 100
        part1 = divide % 100
        nameMillion = digitName(divide1) + " hundred" + processDigit(part1) + " million "

    if part >= 1000:
        divide = part // 1000
        part = part % 1000
        divide1 = divide // 100
        part1 = divide % 100
        nameThousand = digitName(divide1) + " hundred" + processDigit(part1) + " thousand "

    if part >= 100:
        divide = part // 100
        part = part % 100
        nameHundred = digitName(divide) + " hundred" + processDigit(part)

        return nameMillion + nameThousand + nameHundred

This function is simply wrong, for multiple reasons. Let's step through them one by one:

The return statement is sometimes unreachable

Check your indentation. Currently the return statement is only reachable if number % 1000 >= 100.

Numbers >=1,000 and <100,000 do exist

Your forgot to handle the case when the number doesn't contain the term "hundred". The same issue exists with numbers >= 1,000,000 and <100,000,000.

Writing the same code 3x in a row, with the same mistakes

You are using different constants, but the logic is mostly identical. The copy & paste is pretty obvious. And it had exactly the effect you would expect: You copied the mistakes as well.

This would have been easily solved by extracting the common parts of the logic properly.

0 is a number

While you don't say "zero hundred" or "zero thousand", "zero" alone is a valid number and should be supported properly.

Structuring the code properly

nameMillion = digitName(divide1) + " hundred" + processDigit(part1) + " million "

Why did you bother writing this explicitly for every potence of 1,000?

Have another look at how the numbers in the english language are constructed, and try to find ALL patterns.

If you that, you realize that for every number, every potence of 1,000 is formed identically:

[([digit "hundred" ]decimal) "suffix"]

The only exception to that is the part below 1,000 which has no suffix. However, a missing suffix can simply be approximated by an empty suffix instead.

So the logic approach is to write yourself a helper function which correctly formats every number from 0 to 999, because that is the range you need commonly.

Your next realization should be that it is easier to start constructing a number from the LSB, than from the MSB, since you then only ever need one set of constant numbers to extract the relevant part of the number.

Once you have that function, intName() can be written much clearer:

def intName(number):
    output = "";
    suffixes = ["", "thousand", "million", "billion"]

    if number == 0
        return "zero"

    while number > 0:
        number, part = divmod(number, 1000);
        if part > 0
            output = intThousandName(part) + " " + suffixes[0] + " " + output
        suffixes.pop(0)

    return output.strip()

The strip() at the end removes the trailing white space, resulting from the empty suffix, respectively the concatenation of the first valid suffix with the empty string.


There is a nice trick to get the eigenvalues and eigenvectors of the covariance matrix without ever forming the matrix itself. This can be done using the singular value  decomposition (SVD), as described in this post from Stats.SE. Not only is this more numerically stable, but the results are automatically sorted.

A python version might look like this:

def components(X):
    _, vals, vecs = np.linalg.svd(X - X.mean(axis=0), full_matrices=False)
    return vals**2/(len(X)-1), vecs

A few things to note:

As described in the linked post above, the data matrix is typically defined with dimensions as columns, i.e. the transpose of your X.
The principle values and components are typically sorted from largest to smallest, i.e. the reverse of yours.
The function above does not assume that X has been pre-centered.

So to get results comparable to yours, you would need to do:

vals, vecs = components(X.T)
e_vals, e_vecs = vals[::-1], vecs[::-1]


The reason it seems messy is because you have one function doing multiple things. So what does your function do?

It queries the DOM for elements containing the input.
It calculates the BMI based on that input
It has logic that determines what kind of output to produce
It produces output to the DOM.

There are a few problems with that:

What if you want to run this function in a different DOM? You can't, you're bound to elements with specific IDs.
What if you want just the result? You can't, because your function doesn't return anything but explicitly mutates the DOM.
It's unclear from the signature what your function needs to work (i.e. available DOM with elements with specific IDs). Functions normally declare what they need in the form of parameters.

So how can we do better? We can divide into several independent functions:

function calculateBMI(height, weight) {
  // todo
  // calculate BMI based on height and weight passed in.
  // returns a number (the BMI)
}

function bmiToHealth(bmi) {
  // todo
  // determine what text to display based on the bmi value.
  // returns a string (the text to display)
}

And use it like this:

function calculateBmiFromDOM() {
    let heightInput = document.getElementById('height');
    let weightInput = document.getElementById('weight');
    let output = document.getElementById('output');
    let result = document.getElementById('result');

    let bmi = calculateBMI(heightInput.value, weightInput.value);
    output.textContent = bmi.toPrecision(3); // 25 -> 25.0, 23.752 -> 23.7
    result.textContent = bmiToHealth(bmi);
}
let form = getFormSomehow(); // usually with getElementById or querySelector
// You can pass functions as parameters in JavaScript
form.addEventListener('submit', calculateBmiFromDOM);

And that last snippet the only thing that's specific to your current DOM, so when your DOM changes, you don't need to change all of your code, just the bit that interacts with it.

Additional notes for future snippets (just general things I've noticed):

anything != 'NaN' is pointless, nothing in your logic might return a string with the value of 'NaN'. Even if it were NaN, you can't compare it with ==, you need to use the isNaN() function.
You should always use === or !== when comparing. Using == and != can introduce unexpected behavior due to type conversion.
Functions work best when they accept values as arguments and/or return values as result.


If you want to improve usability, you should introduce some kind of type for your array (typedef the pointer, or introduce some type of struct that will contain useful metadata) and provide the appropriate free function for it. This way, the user doesn't have to free all the elements themselves and can just call my_free(&my_type_ptr) when he's done. Your error_cleanup should just call this function as well.
This bit of code does unnecessary work:

char *storage = malloc(length + 1);
char *translated = translate(i, alphabet, length);

if (!storage || !translated) {
  if (storage) {
    free(storage);
  }

  if (translated) {
    free(translated);
  }

  array[i] = NULL;
  goto error_cleanup;
}

strcpy(storage, translated);
free(translated);
array[i] = storage;

in the form of allocating an extra block of memory and copying things there from an already allocated block of memory. Simplify to:

array[i] = translate(i, alphabet, length);
if (array[i] == NULL) {
    // Error in translating, abort
    goto error_cleanup;
}

  is my goto used well and with good reason?

No. You only have one user of the goto. If you look above at the more concise version of your function, it's completely reasonable just to say "no more goto" and replace it with free_word_array(array); return NULL;. Any time you have a need to clean multiple resources on any failure, goto can be a good choice.
(argc < 2) needs to be (argc < 3). As it is written, running your program with only one extra argument ./main 6 results in Error while enumerating. instead of printing the help message. Remember, the program invocation is the 0th argument but counts in the count as well.
I prefer return from main rather than exit.
translate could use more comments within the algorithm, for quicker reading/understanding. It looks like you're just enumerating all possible words within a given set, and this recovers the word.
Maybe it makes sense not to have an array of arrays, but rather an array of numbers that you then convert to the string representation if the user wants to print it? But then the logical conclusion of that is that you don't really need to allocate memory at all then: you can just as easily return the number of permutations, and work out the appropriate requested permutation when it is requested.
Your code will only work with single-wide characters, and produce gibberish for any alphabet that contains characters that aren't (think UTF-8, for instance, where the character can be wider than a byte, meaning that you'll shuffle the character incorrectly). This might not be in your requirements, but thought I'd mention it since this always plagues non-ASCII character stuff in C.


Instantiating a property when the required attributes have been set

Getters & Setters + Validation

I think it's better to validate the serial and the purchase-id in their setters instead in the GetLicense method that actually could be a readonly-property.

private void GetLicense()
{
    if (!string.IsNullOrEmpty(this.Serial) && !string.IsNullOrEmpty(this.PurchaseId))
    {
        License lice = new License(serial, PurchaseId);
        this.License = lice;
    }
}

After this tiny refactorings the result is:

public class Product
{
    // it's prettier if you group private fields togehter at the top
    private string _purchaseId;
    private string _serial;

    public string Name { get; set; }

    public string PurchaseId
    {
        get { return _purchaseId; }
        set
        {
            if (string.IsNullOrEmpty(value))
                throw new ArgumentNullException(nameof(PurchaseId));
            _purchaseId = value;
        }
    }

    public string Serial
    {
        get { return _serial; }
        set
        {
            if (string.IsNullOrEmpty(value))
                throw new ArgumentNullException(nameof(Serial));
            _serial = value;
        }
    }

    public License License
    {
        get { new License(Serial, PurchaseId); }
    }
}

Magic Strings

  this.Type = "Enterprise";

You should create a const/readonly string for the "Enterprise" and name it for example DefaultLicenseType

Bug

There is a bug. The license constructor expects purchaseId + serial and you create a license with a serial + purchase id

Constructor signature:

public License(string purchaseId, string serial)

License creation:

new License(serial, PurchaseId);


DuplicateDictionary - A dictionary-like class which allows duplicates

Such a data structure already exists, and is called ILookup<TKey, TElement>. It can be created using the ToLookup extension.

  The ToLookup<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>) method returns a Lookup<TKey, TElement>, a one-to-many dictionary that maps keys to collections of values. A Lookup<TKey, TElement> differs from a Dictionary<TKey, TValue>, which performs a one-to-one mapping of keys to single values.

var list = new List<Tuple<string, int>>
{
    Tuple.Create("a", 1),
    Tuple.Create("a", 2),
    Tuple.Create("a", 3),
    Tuple.Create("b", 4),
    Tuple.Create("c", 5)
};

var lookup = list.ToLookup(t => t.Item1, t => t.Item2);

foreach(var kv in lookup)
{
    Console.Write(kv.Key);
    Console.WriteLine(" - " + string.Join(", ", kv));
}

// prints
// a - 1, 2, 3
// b - 4
// c - 5

As Vince pointed out, your DuplicateDictionary will suffer from slow access. Lookup won't.


I'm not much of a jQuery freak, but I still have some points on this code. In your amountValidation function, you have some duplication and overhead:

if(errAmount == true)

can be written:

if(errAmount)

Also you always do the same thing when an error occurs, but that's in each statement:

if(errAmount == true){/* mark the field */};
if(errGVAmount == true){ /* mark the exact same field */};
if(errNeedAmount == true { /* and yet the same thing again */ };

you can shorten this to:

if(errAmount || errGVAmount || errNeedAmount){ /*mark field*/ };

Your variable names could use some change too:

errAmount on the first look is like the geeneral error overall, not that amount is null / empty.
You could use errAmountNull instead.

errNeedAmount sounds like you have no amount given yet, which would be errAmount.
I would use errAmountTooSmall instead

Nobody knows, what the GV in errGVAmount stands for.
From the requirements I would call it: errAmountUnallowedValue


Standard disclaimer: in a production setting it is overwhelmingly better to use somebody else's crypto.

I don't have the expertise to certify "Yes, this is secure" (and as I'm some randomer online, you should assume that even if I was actually a world expert!) There are, however, a few things that strike me as red flags.

byte[] ivSeed = Guid.NewGuid().ToByteArray();

In crypto, if you need a random number, you basically always need a cryptographically secure random number. NewGuid() is not cryptographically secure.

var messageLength = BitConverter.GetBytes(messageLengthAs32Bits);

Block ciphers like AES do not claim to obscure the approximate message length, so this is not strictly a vulnerability. Nevertheless if you are vulnerable to any attacks based on the length, then passing the precise length in plaintext makes those attacks a whole bunch quicker and easier to execute.

byte[] Key = rfc.GetBytes(16);
byte[] IV = rfc.GetBytes(16);

The derivation of your key should not be tied to the derivation of your IV.


Return IEnumerable from a private method; use Dictionary or anon. type?

I think the cleanest way to optimize it and to use only one loop is to first get the values with a select, create key/value pairs there and then filter by value:

private static IEnumerable<KeyValuePair<string, string>> GetPropertyValues(MyClass myClass) {
   return
        PropertyDictionary
        .Select(kvp =>
            new KeyValuePair<string, string>
            (
                kvp.Key,
                (string)kvp.Value.GetValue(myClass, null)
            )
        )
        .Where(kvp => !string.IsNullOrEmpty(kvp.Value));
}


Cancelling Local WebClient ASync Operation

I am not able to comment on your post due to a lack of reputation, but when I did something similar to this, I used a CancellationToken. It's been around for quite some time now (.NET 4.0), and is generally accepted in most .NET Async APIs. It should achieve what you're trying to do. The documentation for the concept is located here.

You don't have to put a WebClient in your class (as a field) if you don't want to. Most of the interactions I've seen with web servers (in C#) behave very similar to the Entity Framework in that you generally send a request, which yields some form of IEnumerable that you have to deal with. So, you could wire up a service util for handling the common bits for a web client, and generate a unique one per request. I did something similar to that, and it worked well, but you need to be cautious of shared state in that scenario (construction really needs to be construction - not use of a singleton - if you're generating a unique client every time).

I hope this helps!


How do you describe this function / math problem?

The input is a list of tests with the same duration. For example, \$input=[2,2,2,2]\$. Given the indexes from 0 to 3, we can see it in a graph:

So we can define the input as a (discrete) function \$f(x)=2\$, or in general \$f(x) = seconds/tests\$. Where \$0<=x<=tests,x∈Z\$.
The function \$durationSpread\$ can be described as \$durationSpread = g(x) * f(x)\$. Where \$g(x)\$ is a function that depends on \$pct\$ and \$tests\$. In the following I am going to refer it as \$g(pct,tests)\$.
Function analysis
For pct=0 the input remains the same: \$g(pct,tests) * input = g(0,4) * [2,2,2,2] = [2, 2, 2, 2]\$. Meaning that all elements of the input are multiplied by 1. So \$g\$ should look like this:

For pct=-1 the result "should be": \$g(-1,4) * [2,2,2,2] = [4.0, 2.67, 1.33, 0.0]\$. The first element of of the input is multiplied by 2, the last one by 0, and the elements in between by a descending factor.
I said "should be" because your code outputs \$[4.0,3.0,1.0,0.0]\$, which is not possible if we consider a constant factor (the gap betweenn 4.0 and 3.0 is 1, but between 3.0 and 1.0 is 2).
So \$g\$ should look like this:

For pct=1 the result is: \$g(1,4) * [2,2,2,2] = [0.0, 1.33, 2.67, 4.0]\$. In this case, the first element is multiplied by 0 and the last one by 2. So the function \$g\$ is:

How to find \$g\$? From the three examples, we know that \$g\$ is a linear function. A linear function can be represented as y = mx + b. How to find m and b? They can be found given two points.
Let's choose the first point (x0,y0) in the origin. x0 is always 0. While y0 depends on pct. Looking at the examples, we can tell that it's equal to abs(pct - 1). Explanation:

In the first example pct=0 and y0=1. In fact, y0 = abs(0 - 1) = 1
In the second example pct=-1 and y0=2. In fact, y0 = abs(- 1 - 1) = abs(-2) = 2
In the third example pct=1 and y0=0. In fact, y0 = abs(1 - 1) = abs(0) = 0

For the second point (x1,y1), we can choose the center. Where y1 is always 1. While x1 can be found as x1 = (tests-1)/2. (You can double-check in the three examples).
Given two points we can find the slope m as m = (y1 - y0) / (x1 - x0). Once we have m, we calculate the constant b as b = y0 - (m * x0).
Now that we found \$g\$, we can multiply the input by \$g\$.
def duration_spread(tests, seconds, pct):
    x0, y0 = 0, abs(pct - 1)
    x1, y1 = (tests - 1) / 2, 1
    m = (y1 - y0) / (x1 - x0)
    b = y0 - (m * x0)
    unit_time = seconds / tests
    return [unit_time * (m * x + b) for x in range(tests)]

Some tests:
times = duration_spread(4, 8, 1)
print(' '.join(f'{x:.1f}' for x in times))
# output: 0.0 1.3 2.7 4.0

times = duration_spread(5, 10, -1)
print(' '.join(f'{x:.1f}' for x in times))
# output: 4.0 3.0 2.0 1.0 0.0

times = duration_spread(5, 10, .5)
print(' '.join(f'{x:.1f}' for x in times))
# output: 1.0 1.5 2.0 2.5 3.0

Code review
Very short since @Reinderien covered most of the ground.

Input type: tests represents the number of tests, so I am not sure why it's a float. It should be an integer.
Missing return type hint: the return type hint is missing in both functions.


Find the smallest number of perfect squares that sum to a target

Caching

You are using sums as a cache for your dynamic programming.  Python comes with built-in caching (functools.lru_cache), so you don't need to implement your own.  Using it will avoid polluting the global namespace.

Integer Square-Root

With Python3.8 comes a built-in math.isqrt, rendering the idiom int(n**(1/2)) obsolete.

Unnecessary filtering

    squares = [i**2 for i in range(1, isqrt(n) + 1)]
    while len(squares) and squares[-1] > n:
        squares.pop()

Here, you are generating all the squares up to (and including if it is a perfect square) n.  Then, you check if the last item is larger than n.  It is impossible for it to be, so squares.pop() will never be executed, making the entire while loop redundant code which can be deleted.

Unnecessary (and suspicious) minimum

    s = 2**31
    for i in squares:
        s = min(s, numSquares(n - i) + 1)

Here, 2**31 is used as a value larger than any possible value, so you can compute the minimum in the for loop.  But is it really larger than any possible value???  I can think of larger values, but perhaps it comes from the challenge text.

Still, Python provides a better way: the min(...) function and list comprehension:

    s = min(numSquares(n - i) + 1 for i in squares)

This loops through all squares, and evaluates numSquares(n - i) + 1 for each one, and selects the minimum value.  No magic "value larger than any possible value" value is required.

Still, it can be made even more efficient.  If there are 10,000 squares, we add one to each result, and take the minimum.  That's 10,000 plus one operations.  If we compute the minimum value, and add one to that, we've saved 9,999 additions.

    s = min(numSquares(n - i) for i in squares) + 1

Unnecessary list creation

The code would now read:

    squares = [i**2 for i in range(1, isqrt(n) + 1)]
    s = min(numSquares(n - i) for i in squares) + 1

We create a list of squares and then immediately loop through that list exactly once, and never use it again.  Creating the list is an unnecessary step, that consumes memory and wastes time.  Just compute the squares on the fly!

    s = min(numSquares(n - i ** 2) for i in range(1, isqrt(n) + 1)) + 1

PEP-8

Functions and variables should be in snake_case, not mixedCase.  Your function should be named num_squares.

There should be a space around binary operators like ** and /.

Variable names like s are meaningless.  Variable names should be descriptive.  s is the minimum count of the terms summing to n; min_terms would be more descriptive.

Updated Code

from functools import lru_cache
from math import isqrt

@lru_cache(maxsize=None)
def num_squares(n: int) -> int:

    root_n = isqrt(n)
    if root_n ** 2 == n:
        return 1

    return min(num_squares(n - i ** 2) for i in range(1, root_n + 1)) + 1

Further improvements

Consider 10001.  It is not a perfect square.  So you start subtracting squares off it, beginning with \$1^2\$ and discover \$10001 - 1^2 = 100^2\$, for min_terms of 2.  You should stop searching; there will be no better answer.  But instead, you will continue with \$10001 - 2^2\$, and figure out the num_squares() of that, and then try
\$10001 - 3^2\$ and so on.  This is all busy work.

Determining how to prune the search tree left as exercise to student.


JavaScript function for to toggle multiple CSS-classes at once

This code is well-done, clear and rigourous, and it works fine.
But I would not work exactly the same.

Error processing.

I agree with your doubts, like this one:

  I also ask myself if my approach of throwing errors isn't a bit too drastically.

and this one:

  It isn't really necessary to react so hard.

As you already noticed this kind of function, only working on style, has nothing critical about failure.
So IMO it's preferable to silently not work when it's not possible, either because the target element is not found, or the list of classes is empty.

Obviously, at the opposite, it must take care of any "technical" failure which might fire an error message, but this should not lead to something blocking.
The only "not-silent" point I think good to keep is the true-or-undefined return: this allows to know how it turned when one is concerned, while it can be ignored otherwise.

Following this point of view, I suggest to merely ensure each involved data is clean, and work only if so.
As a supplemental benefit, it ends with a reduced code:

first regarding the presence of the two arguments, we can merely assign default values with classes = classes || ''; and selector = selector || '';
then use a unique if to ensure:

they are not of bad type
they are not empty
the selector really targets an element

List of classes argument.

Like you suggested:

  I'm still not sure if I shall stay with the way of assigning the classes. One could also use an array instead of a space-separated string.

I think it can be useful to offer a versatile way, even adding not only an array or a space-separated string but also a comma-separated string (with optional spaces).

This triple capability can be easily achieved by:

if (!Array.isArray(classes)) {
  classes = classes.replace(/(,\s*|\s+)/g, ' ').split(' ');
}

The toggle process itself.

Since it was your starting point, I'm surprised you didn't use the toggleClass() method in the final working part of your code:

element.className.indexOf(classItem) === -1
  ? element.classList.add(classItem)
  : element.classList.remove(classItem);

It can be replaced by:

element.classList.toggleClass(classItem);

Finally here is my proposed version, following all the above remarks:

/**
 * Adds / removes CSS-class(es) from an HTML-element.
 *
 * @param selector: a CSS selector for the involved element (string)
 *
 * @param classes: list of classes to be toggled, either:
 * - (string) comma- or space(s)-separated list of classes
 * - (array) of classes
 *
 * @return:
 * - true if could work
 * - undefined if any error occurred (bad, empty, or unsuccessfull
 *   selector; bad or empty classes)
 */

function toggleClasses(selector, classes) {
  selector = selector || '';
  classes = classes || '';
  if (
    typeof selector == 'string'
  &&
    (typeof classes == 'string' || Array.isArray(classes))
  &&
    classes.length // true if either string or array not empty
  &&
    (selector = document.querySelector(selector))
  ) {
    var classList = selector.classList;
    if (!Array.isArray(classes)) {
      classes = classes.replace(/(,\s*|\s+)/g, ' ').split(' ');
    }
    for (var className of classes) {
      classList.toggle(className);
    }
    return true;
  }
}

document.querySelector('.toggle-classes')
  .addEventListener('click', function() {
    console.log(toggleClasses(
    '.demo', 'shadows font-special red-theme blue-theme misc-foo'
    ));
});
.wrap {
  margin: 20px auto;
  width: 900px;
  background-color: rgba(245, 245, 245, 1.0);
  padding: 20px 30px;
}

.demo {
  width: 150px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  margin: 10px 0;
}

.blue-theme {
  border: 3px solid pink;
  background-color: teal;
  color: white;
  font-weight: 800;
}

.red-theme {
  border: 3px solid teal;
  background-color: pink;
}

.shadows {
  text-shadow: 3px 3px 3px white;
  box-shadow: 3px 3px 3px grey;
}

.font-special {
  color: grey;
  font-weight: bold;
  font-family: georgia;
}

.misc-foo {
  border-radius: 12px;
  transform: skewY(5deg);
}

  <button class="toggle-classes">Toggle classes</button>

Demonstration


.trim_left().trim_right() is just .trim().
You might as well inline str_iter, since you only use it in one place. At least move it closer to the use-point.
Folds aren't the idiomatic loop primitive in Rust. In this case it would be much nicer to just use for.

This improves compiler analysis, and you find out that digit's initial assignment isn't getting read. You don't need digit outside the loop at all, and thus it doesn't even need to be mutable.

You're using too many type annotations. The one as usize after to_digit is enough, and even if you did need to annotate the others you should use let last: usize = 1 or let last = 1usize. Similarly, let the Vec's type parameter be inferred.
Your brace formatting is not Rusty.
Instead of dealing with window, just run two zipped offset parallel iterators. Indices work fine, too, and aren't unidiomatic: clearer, efficient code is always idiomatic.


Lazy Pirate Request Response pattern using zeromq and C#/.NET bindings

It seems zeromq will release sent data itself. With GC supported in C#, this feature is useless. The byteProvider parameter seems inappropriate, so why not just use IEnumerable<byte>?


Polishing partitions - Reimplementing a partitionOn

The code can be written cleaner if one removes the pred from go. go has access to all bindings in its context, including the ones in partitionOn pred list.

A first step to declutter partitionOn is therefore to get rid of duplication and get rid of unnecessary parentheses:

partitionOn :: ([a] -> Bool) -> [a] -> [[a]]
partitionOn pred list = go pred [] list
    where
        go working [] = [working]
        go working l@(x:xs) = if pred working
                then working : go [] l
                else go (working ++ [x]) xs

Note that I've removed go's type signature. This is somewhat controversial, but the general rule-of-thumb is that you want type signatures at the top-level and usually leave the type-signatures at the not-top level, unless GHC gets confused.

The (small) problem with type signatures in where and let is that the type parameter a in parititionOn is not the same as the one in go. -XScopedTypeVariables is necessary for that. So lets get rid of that.

  Would it be cleaner to use the following go?

No. Or rather: it would be slightly cleaner, but pred also needs to work on the reversed list. This is more obvious if we don't use a position-independent predicate:

notInOrder []           = False
notInOrder (x:xs@(y:_)) = x > y || notInOrder xs

Your old version returns [1..10] on partitionOn notInOrder [1..10], but your new one returns [[1],[2],[3],…,[10]], unless you also check pred (reverse working).

Therefore—At least in the sense of asymptotic analysis—both variants will have the same performance.

  Am I missing a special case of groupBy here? It feels like there should be a simple standard function to do this.

The standard functions for splitting lists at some point are span, break, splitAt, take(While), drop(While(End)), group(By), inits and tails. They all are concerned with a single element in their predicate, so they are not candidates for our problem, unless we already have our splits:

splits :: [a] -> [([a],[a])]
splits xs = zip (inits xs) (tails xs)

That function does not exist, though. A perfect building block for partitionOn would have the type signature ([a] -> Bool) -> [a] -> ([a],[a]), but that's missing from the standard library. Others packages provide functions with that signature, but none does provide our needed functionality.

But we can write that function ourself:

breakAcc :: ([a] -> Bool) -> [a] -> ([a],[a])
breakAcc p = go []
  where
    go ys []     = if p ys then (ys,[]) else ([],ys)
    go ys (x:xs) = if p ys then (ys, xs)
                           else go (ys ++ [x]) xs

-- or, using `splits` above:

breakAcc p xs = case find (p . fst) (splits xs) of
                 Just ys -> ys
                 Nothing -> ([], xs)

Note that the first variant still has the somewhat awkward ++ [x] there. A partition that starts from the right wouldn't have that problem, but we're stuck with that.

Now partitionOn is just

-- feel free to use a worker wrapper approach here
partitionOn p xs = case spanAcc p xs of
              ([],bs) -> [bs]
              (as,bs) -> as : partitionOn p bs

Note that this will add the empty list at the end if our partition works for all elements, e.g. partitionOn ((0 <) . sum) [1..4] == [[1],[2],[3],[4],[]]. But that's easy to get rid of.

All at once:

import Data.List (inits, tails, find)

splits :: [a] -> [([a],[a])]
splits xs = zip (inits xs) (tails xs)

breakAcc :: ([a] -> Bool) -> [a] -> ([a],[a])
breakAcc p xs = case find (p . fst) (splits xs) of
                  Just ps -> ps
                  Nothing -> ([],xs)

partitionOn :: ([a] -> Bool) -> [a] -> [[a]]
partitionOn p xs = case breakAcc p xs of
                     ([],bs) -> [bs]
                     (as,bs) -> as : partitionOn p bs

-- for QuickCheck
partitionOnResult_prop :: ([a] -> Bool) -> [[a]] -> Bool
partitionOnResult_prop p xs = all p (init xs)

partitionOn_prop :: ([a] -> Bool) -> [a] -> Bool
partitionOn_prop p xs = partitionOnResult_prop p (partitionOn p xs)

-- quickCheck $ \(Blind p) -> partitionOn_prop p

Now that we have all of this code, let's compare it again with your (almost) original variant:

partitionOn :: ([a] -> Bool) -> [a] -> [[a]]
partitionOn pred list = go pred [] list
    where
        go working [] = [working]
        go working l@(x:xs) = if pred working
                then working : go [] l
                else go (working ++ [x]) xs

If we quint our eyes, both codes look the same (if we use the first breakAcc variant). However, I wouldn't call a list l, since lists are usually identified with a suffix s called e.g. ls. Also, working is somewhat of a misnomer: are we working with that list? Or does that list fulfill some requirement? As we currently accumulate elements in there, the usual acc or accs might be better, but naming is hard and left as an exercise.

Other than that, unless you want to have little, test-able functions, your original variant was therefore fine to begin with, but contained some functions that can be re-used.


Some tips:

Tip 1

@Autowired
AccountRepository accountRepository;

@Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;
...

Setter injection is considered as bad practice prefer constructor injection to gain more control and to avoid NullPointerExceptions.
Why field injection is evil

Tip 2

@Id
private String id = UUID.randomUUID().toString();

Encapsulate id generation into some component class eg. IDGenerator.nextId() where IDGenerator is an interface and you would provide some implementation class for that. You'll have more control in testing.

Tip 3

Optional<Account> optionalAccount = accountRepository.findByUsername(s);

if (!optionalAccount.isPresent()) {
    throw new UsernameNotFoundException("Account named " + s + " not found");
}

return new AccountDetails(optionalAccount.get());

Using Optional like that is considered as bad practice. Something like that would be a lot better:

Account account = accountRepository.findByUsername(s).orElseThrow(UsernameNotFoundException::new)
return new AccountDetails(account)

Tip 4

throw new RuntimeException();

You should throw more specific exceptions.

Tip 5 UPDATE

I think that AccountService.remove(AccountDTO accountDTO) is too complex.
I believe in that case would be better to just write own deletion method in repository:

public void remove(AccountDTO accountDTO) {
    Objects.requireNonNull(accountDTO);
    accountRepository.deleteByUsername(accountDTO.getUsername());
}

Tip 6

AccountService and AccountDetailsService could be as one class, these classes have similar responsibilities.

Tip 7

  Then where should we use loadbyusername method?

Spring security needs class which implements this interface when we use some other user data store than in memory.
When some client app try to login / generate token this method
would be invoked by spring and whether if user exists or not spring
would respond with 400 Bad Request or 200 OK.


The last element...

  It seems like I'm not being as lazy as I should be with regards to my concatenation and use of last.

Yes. Let's have a look at an example and check addRow's behaviour:

       6
     1   4
   3   5   2
 9   1   2   6

addRows [6] [1, 4] = (6 + 1) : addMid [6] [4] ++ [6 + 4]            (1)
                   = 7       : []             ++ [10]
                   = [7, 10]

addRows [7, 10] [3, 5, 2] = (7 + 3) : [5 + max 7 10] ++ [10 + 2]    (2)
                          = [10, 15, 12]

Let's check how often you actually use each number. In (1), you use 6 twice, and both 1 and 4 once. In (2), you use 7 twice, 10 twice, and all of the other numbers once. Hm. Does this hold for a fourth line?

addRows [10, 15, 12] [9, 1, 2, 6]
     = (10 + 9) : addMid [10, 15, 12] [1, 2, 6] ++ [12 + 6]
     = (10 + 9) : 1 + (max 10 15) : 2 + (max 15 12) : [] ++ [12 + 6]

Using a function that "does things right"

This pattern seems to hold. You always use the elements in the first list twice, and the once in the second list only, well, once. This sound like it should be possible to zipWith the first elements with themselves somehow. If we were able to pattern match on the last element, this would be

(x:xs:[y]) -> x : zipWith max (x:xs:[y]) (xs:[y]) ++ [y]

However, the dreaded last element makes this hard. We could write our own zip function:

transformLine :: (Ord a) => [a] -> [a]
transformLine xs@(x:_) = x : go xs
  where
    go [y]           = y
    go (a: ys@(b:_)) = max a b : go ys

It's important that we only use cons to gain a maximum of laziness. This function will transform a line into another that's exactly one number longer:

transformLine [6]   == [6, 6]
transformLine [1,4] == [1, 4, 4]

It is therefore a list that can simply get summed onto the next line:

    [6,  6]   |->   [ 7, 10, 10]    | ->  [10, 15, 15, 12]
 +  [1,  4]   |   + [ 3,  5,  2]    |   + [ 9,  1,  2,  6]
 =  [7, 10] ->|   = [10, 15, 12] -> |   = [19, 16, 17, 18]

That way, addRows is simply

addRows xs ys = zipWith (+) (transformLine xs) ys

Turn your world upside down

However, we can also turn the triangle upside down and start with the longer lines:

 9   1   2   6
   3   5   2
     1   4
       6

Which makes this a lot easier, because we're now reducing the information instead of gaining additional:

     / 9 1 2   (init first line)  \
 max                               \
     \ 1 2 6   (tail first line)    (+)
                                   /
       3 5 2   (second line       /

Or, in actual code:

addRows :: (Num a, Ord a) => [a] -> [a] -> [a]
addRows xs ys = zipWith (+) ys $ zipWith max xs (tail xs)

However, now it's necessary to reverse the triangle beforehand or flip the arguments of addRows:

head . foldr1 addRows . reverse $ tri

head . foldr1 (flip addRows) $ tri

Note that head is fine here, since addRows always decreases the number of elements in the accumulating list, therefore you end up with a singleton. Also note that foldr is usually lazier on lists.

... and the oddities

While the previous section was concerned with laziness and last, this one contains general remarks:

import Control.Monad (liftM)

This isn't necessary, since IO is also an instance of Functor. And since the Applicative-Monad-Proposal every Monad is also an Applicative and therefore a Functor.

parse = map ((read <$>) . words) . lines

The <$> here is quite hard to read, especially since there are two operators next to each other (<$> and (.)). A simple fmap is easier to the eye:

parse = map (fmap read . words) . lines

Alternatively use map, since you're working with lists.

main =
    ...
    return $ maximum ...

main should have the type IO (). If you want to print the number, use print instead of return.

Summary

Other than the few oddities, well done. The last issue isn't that easy to solve unless you write another function or change your point of view. However, if you manage to actually reduce the amount of available information in your fold*, your usually on the right track.


I think the handling of the cache could be improved. You add to the cache in _calc, then check the cache in collatz. Why not just let _calc handle the cache? That way collatz doesn't need to know anything about how _calc is getting its results. I'd change it to something like:

def _calc2(number: int) -> int:
    if number in collatz_cache:  # Let it do the lookup
        return collatz_cache[number]

    if number % 2 == 0:
        next_number = number // 2
    else:
        next_number = number * 3 + 1

    collatz_cache[number] = next_number
    return next_number

def collatz2(number: int) -> List[int]:
    if number < 1:
        raise ValueError(f"Collatz sequence not defined for {type(number).__name__}({number})")

    results = [number]

    new_number = number
    while new_number != 1:
        new_number = _calc2(new_number)
        results.append(new_number)

    return results

I also don't think collatz really needs to do an isinstance check on number. You've said via type-hints that it only accepts integers. If you're going to go down that road, arguably every function should check what it's arguments are. I suppose protecting against a float being passed may be worth it since that will silently mess with the results, but you can only hand-hold the user so much.

I'll note though that your manual memoization isn't necessary. functools has a decorator for this:

from functools import lru_cache

@lru_cache(maxsize=int(1e6))  # This could probably be smaller
def _calc3(number: int) -> int:
    if number % 2 == 0:
        next_number = number // 2
    else:
        next_number = number * 3 + 1

    return next_number

Using a dirty timeit timing using seeded random numbers, I found that all three versions perform nearly identically for me:

from timeit import timeit
from random import randint, seed

timeit(lambda: collatz(randint(5, 100)),
       setup=lambda: seed(12345),
       number=int(1e6))

# All take between 7 seconds for me

I used random numbers so the cache is actually getting fully tested instead of just returning the same numbers over and over. The random numbers are seeded, so the results should be reliable.

I'll note, you could also write your own bare-bones memoize decorator as well:

def memoize(f):
    cache = {}

    def wrapper(*args):
        if args in cache:
            return cache[args]

        else:
            result = f(*args)
            cache[args] = result
            return result

    return wrapper

@memoize
def tester(n, m):
    print("Called with", n, m)
    return n + m

>>>> tester(1, 3)
Called with 1 3
4

>>> tester(1, 3)
4

I'll note too though, this could be made into a generator if you wanted to generalize it:

from typing import Generator

def collatz3(number: int) -> Generator[int, None, None]:
    yield number  # To be consistent with the other functions

    new_number = number
    while new_number != 1:
        new_number = _calc3(new_number)
        yield new_number

This may prove to be more memory efficient for longer sequences, depending on how it's used. Now the whole sequence isn't required to be held in memory all at once.


Python class to manage a table in SQLite

I exposed the database connection and database cur as instance variables. Is that a good practice?

Having a cursor defined as an instance variable is a common practice. The problem though here is that you don't have a way to close the cursor and the connection itself in case of an error. In situations like this, having "context manager" capabilities on your class would be quite handy:

def __enter__(self):
    return self

def __exit__(self, ext_type, exc_value, traceback):
    self.cursor.close()
    if isinstance(exc_value, Exception):
        self.connection.rollback()
    else:
        self.connection.commit()
    self.connection.close()

Then, the Database class could be used with with:

with Database() as db:
    db.create_table()


Script for dynamically-loading data onto a restaurant menu for printing

Piece iterates over list, calling same $.ajax(), err or, other functions, etc., for each item within list. Save list items to _list , poll until _list.length === list.length - all list items processed - display "menu ready" to viewer.

JSFiddle

(function menus() {

var list = ["prestarters"
           , "starters"
           , "mains"
           , "sides"
           , "dessert"
           , "dessertwines"
           , "afterdinnerdrinks"
           , "whiskeys"
           , "hotdrinks"
           , "ports"
           , "cognacs"
           , "liqueurs"];

var err = function (jqxhr, textStatus, errorThrown) {
    if (textStatus == 'error') {
        var msg = "Sorry but there was an error: ";
        $(".s")
            .html(msg + textStatus + " " + errorThrown);
    };
};

var _list = [];

$.each(list, function (index, value) {
    $.when(value)
        .then(function (data) {
        // var _ids = "#" + data;
        // var _urls = data + ".php";
        // console.log(_ids, _urls);
        // i.e.g.,
        // `$.get(data + ".php")`
        $.post("/echo/json/", {
            json: JSON.stringify([value])
        }, "json")
            .then(function (response, textStatus, jqxhr) {
            _list.push(response);
            // `html`
            $("<section>", {
                    "id": response[0],
                    "html": response[0] + "<br />"
            }).appendTo("#menu");
        }, err)
            .always(function (response, textStatus, jsxhr) {
                // `always` complete callback,
                // when `list` complete
            if (_list.length === list.length) {
                $("<data>" + _list.length + " menus ready</data>")
                    .css({
                    "position": "absolute",
                    "left": "200px",
                    "top": "32px",
                    "fontSize": "28px",
                    "color": "blue"
                })
                .prependTo("#menu") && $("data").fadeOut(7500, function () {
                    $("#menu data").remove()
                });
                // alert(_list.length + " menus ready")
            };
        })
    })
});
}());


Design - prevent multiple nesting in function

Use optional instead of null. I wrote an article about avoiding nulls if you are interested.
Use early returns to avoid nesting

If !reader return [status: '50', message: 'READER NOT FOUND']

If !userSettings return...
Rest of the logic

I prefer to avoid nulls,so I would choose to call save with failOnError=true and it will throw exception instead of returning null when save fails.
I assume  you want any exception to return [ status: '60', message: 'error'], if you use save with failOnError=true then the error is handled in one place only.
add validation for params.isAccessIn. If by mistake it is nor true or false, it is better to throw error than do something the client didn't intend to.
Maybe you should be more flexible with params.isAccessIn and compare strings without case sensitivity.


IEEE754 conformance
Compilers aren't required to support IEEE754 decimals. Most implementations do, but regardless, it's better to check for maximum portability. If you're using C99 or later, the macro __STDC_IEC_559__ is defined whenever IEEE754 is supported.

sizeof(int)
Similarly, int isn't guaranteed to be 32 bits. The compiler only guarantees a minimum size of 16 bits. You can use the fixed width integer types defined in stdint.h i.e. uint32_t or int32_t.

Use size_t instead of int
The proper type for sizeof expression is size_t. As a general use, any variable representing size or index should be size_t.

Since you're not using s outside of the binary function, you can just allocate a fixed an array of size 33 on the stack instead of on the heap using malloc.
static const size_t num_bits = 33;
char s[num_bits];

*(s + index) is just fancy way to write s[index]. The latter is much cleaner, IMO and much more easier to understand for someone who isn't familiar with pointer arithmetic.


Interop between C++ and C# via C++/CLI with callbacks

I'm not sure about the callbacks but you are using the destructor/finalizer in a way that might cause problems.

   ~WrapperClass()
    {
        this->!WrapperClass();
    };

    !WrapperClass()
    {
        if (m_native != nullptr)
            delete m_native;
    };

If you are doing this then the descructor should call GC.SuppressFinalize(this); because the finalizer has already been called.

Then in your finalizer you should set the m_native = nullptr; because if the GC calls it again later it will crash as the object has been deleted but it's still pointing to it.

    !WrapperClass()
    {
        if (m_native != nullptr)
        {
            delete m_native;
            m_native = nullptr;
        }
    }

As to the m_native I'd call it _nativePtr.


If you add a total count field to each node, you can find the k-th element efficiently (in logarithmic time) by writing a method like this (untested):

node *kth(int k)
{
    assert(k >= 0 && k < total);

    if (left != NULL) {
        if (k < left->total)
            return left->kth(k);
        k -= left->total;
    }

    if (k == 0)
        return this;

    assert(right != NULL);
    return right->kth(k - 1);
}

Otherwise, the recursive algorithm you used for findKthInorder is the most elegant way I can think of to do this.  I would clean it up a bit, though:

static const Node *kth_(const Node *node, int &k)
{
    if (node == NULL)
        return NULL;

    const Node *tmp = kth_(node->left, k);
    if (tmp != NULL)
        return tmp;

    if (k-- == 0)
        return node;

    return kth_(node->right, k);
}

int kth(int k) const
{
    assert(k >= 0);

    const Node *node = kth_(this, k);
    if (node == NULL) {
        std::cerr << "kth: k is too large\n";
        exit(1);
    }

    return node->elem;
}

Returning a node pointer instead of an element from the helper function has two advantages:

We can use NULL to indicate failure.
We get to drop an argument from the helper function.
In the future, it will be easier to write a function to update the kth element.

In your findKthInOrder helper function, the k argument is never actually used, and can be dropped as well.

A couple cleanups on the side:

I renamed the class node to Node to avoid having to say mynode all over the place.  I suppose this is just a matter of taste, seeing how the STL uses lowercase type names.
I switched to zero-based indexing.  Again, this is a matter of taste, but zero-based indexing is far more common in C++, and is easier to work with in many cases.


Context managers that also deal with sys.stdin and sys.stdout

All the files you're dealing with are already context managers, including sys.stdin and sys.stdout. Delegating to them instead of reinventing the wheel, your infile class becomes a trivial function:

def infile(filename=None):
    if filename is None:
        return sys.stdin
    return open(filename)

outfile isn't quite as easy as that, but we can still simplify it a little. First, the inplace flag completely changes the behaviour of the function (causes it to choose between mostly disjoint codepaths), and would usually be specified as a literal in the source. It makes more sense to have it as a separate function instead. If you do need to decide between them based on user input, you can always write a short wrapper function.

I'll reuse the name outfile for the clobbering version, and use atomic_update for the non-clobbering version. The clobbering version is then really just as simple as infile:

def outfile(filename=None):
    if filename is None:
        return sys.stdout
    return open(filename, 'w')

The updating version really does need to do some extra stuff after it the files get closed. So it does need to be it's own context manager. But instead of writing it as a class, it's a little easier to use the stdlib contextlib to write it as a coroutine:

from contextlib import contextmanager

@contextmanager
def atomic_update(filename):
    if filename is None:
        f = sys.stdout
    else:
        f = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
        tmppath = f.name

    with f:
        yield f

    if filename is not None:
        shutil.copy(tmppath, filename)
        os.remove(tmppath)

nb. It would be nice if we just return sys.stdout like in the other cases, but the contextmanger decorator considers it an error if the generator doesn't yield exactly once.

As it is, this is a little bit cumbersome to use effectively - you need to open the file for input separately (the tempfile is returned empty), and then it's probably a good idea to be careful to close them in the right order. It also loses, eg, file permissions, which isn't ideal. You might want to copy the original file (and metadata) into the temp file, and then shutil.move it back when you're done.


Better to use string concatenation using std::string::operator+() or std::string::reserve() and std::string::append()?

This question is a bit too general. And I believe you are nitpicking but not for the reason you mentioned.

In the code it first reads all 1000+ lines and stores them into a deque. Each line is a potential allocation and deque also allocates linearly in the number of objects (one allocation for each 4k bytes and each strings takes 32 bytes... surely these numbers depend on platform and implementation and it works differently for large objects). Wouldn't that be a much much bigger source of memory fragmentation than just resizing 10 times one poor big string? IIRC string's capacity is in increased via the same policy as vectors, i.e., exponentially - thus it is just a few resizes.

I find the issue of storing the string as separate entities to be a much bigger problem than the big string. To deal with it, one needs to read each line and process it immediately (put it into the batchline and hopefully getline will reuse reserved data). At least I hope its enough. In this case one cannot figure out the final size of the string batch without reading the file twice... and nobody wants that. So you can either increase its size by appending or reserve at the start its maximal size and add elements till it hits the capacity and then forward it. Ofc, there is a small nuance of dealing with extra large strings bigger than the reserved size - but it is never too hard to fix. Just make sure you deal with it.

Disclaimer: I don't fully understand what brings more problems to memory fragmentation - it might be that deleting those strings at the end fixes most problems but if it so then why worry about the batch_string?


Generate the Norwegian equivalent to social security numbers - follow-up

Here are some suggestions which may help you improve your code.

Don't abuse using namespace std

Putting using namespace std within your program is generally a bad habit that you'd do well to avoid.

Use the appropriate #includes

The code uses the strlen() function a number of places but does not #include <cstring> which is where that library function is defined.

Eliminate unused variables

This code declares main with arguments argc and argv in the usual way, but neither argc nor argv are actually used.  This could be addressed by either declaring int main() or by modifying the code to actually use the variables.  There is a third way, which is to declare it as int main(int, char *[]) but this is not recommended because it's a bit confusing to read.

Separate I/O from object creation

The Date class should not do I/O directly to std::cout and std::cin.  Better design would be to create a custom inserter and custom extractor for the class to allow but not to force I/O operations for the creation of an object.  For example, your Date class might have the following two definitions:

std::ostream &operator<<(std::operator &out, const Date &d);
std::istream &operator>>(std::operator &in, Date &d);

The same is true of the KontrollSiffer class.

Perform better error checking for user input

As it is currently written, one can type in "Norway" as the Date and the code proceeds to proces that input as though it were a valid date, producing invalid results.  Better would be to include more checking beyond just whether the string is 6 characters long.

Prefer std::string to raw char *

The Date class uses a raw char * but would probably be better served by using std::string in this context.

Use aggregation rather than inheritance for composition

The inheritance mechanism is generally suited for "is-a" relationships.  For example, if one had a Birthday class, it might reasonably be derived from a Date base class, since a Birthday is a Date.  However, an IndividSiffer is not really a Date, but is rather constructed from one, so a better design might either have a Date as a private instance variable with the IndividSiffer class or to simply accept a const Date & variable as an argument to an IndividSiffer constructor.

Don't keep variables you don't need

The ans variable is only actually used within the askForDate() routine, so there's no reason to keep it as part of the Date class.  Better would be to declare it as a local variable within the askForDate() function.

Prefer to avoid using new and delete directly

The ans variable within the Date::askForDate() function is small enough to easily fit on the stack, so rather than using new to allocate it, better would be to declare it locally within the askForDate function as:

char ans[DATE_LENGTH];

That way, it is automatically created with the correct length and then discarded when the function is complete.

Think carefully about static variables

The code for IndividSiffer::individSiffer() uses a static variable individ which is a problem.  When you create two IndividSiffer instances in the same program, only the first one will have the variable initialized.  That is because a static variable only gets initialized once before the program is run.  This very greatly limits the use of these classes.

Consider using a standard container

The effect of the KontrollSiffer class is to create and print 500 individual numbers.  Rather than simply print and discard them, it might be more sensible for general use to create a collection of them, perhaps in a std::vector<IndividSiffer> for example.

Omit return 0

If your program completes successfully, the return 0 at the end of main() will be generated automatically, so it's not needed in C++ programs.


Dont call private methods in constructor, put the code into the constructor directly (well unless you have reason to call the same piece of code from elsewhere too, not your case tho).

Don't put your db credentials into the class's constants. This way you are unable to use the class to connect to any other database. Well you can change their values, but that means change the code, or you can extend the class and override the constants. But that's also not very convenient.

You might want to prefer PDO instead of the mysqli extension. The PDO contains mysql adapter in it (maybe you need pdo_mysql extension i think). But you will have the freedom to change the underlying database transparently anytime (well unless you are using some specific sql dialect features).

PDO basically offers the same as your class does, except it has no hardcoded credentials, which, as I already mentioned, is bad.

So learn to use PDO and you may find out that you need no such wrapper at all, you just need a place where you pass the right credentials to its contructor. This place could be described as database connection factory.