Let's look at the inline assembly code that you have:

You were correct to use the __volatile__ specifier here. That's a common mistake when writing inline asm, so that's a good start. The CPUID instruction has very important side-effects, and you don't want the compiler deciding to elide it in the name of "optimization".
(Note: I may be wrong here, and __volatile__ may not actually be necessary for CPUID. The official documentation, as I read it, is rather unclear, and I confess to not fully understanding the nuances. See also discussion in comments below.)
You don't need a semicolon after the cpuid instruction in the inline assembly block. For only a single instruction, no terminator is needed. If you have multiple instructions, standard practice is simply to separate them with \n\t so that they will be nicely formatted in the compiler's intermediate assembly output. A semicolon won't affect the correctness of the code, of course, but they might confuse a human reader of the code who isn't expecting to see one there. They also just clutter up the compiler's intermediate asm output, should you ever need to analyze it.
This is purely stylistic, but I like to align the colons in the inline asm syntax in columns with the opening and closing parentheses. The way you have it now is perfectly readable, though. This starts to matter more when you have multiple instructions in a single asm block.
You also expressed concern in the question about whether you should initialize the values of the registers to 0. In fact, you seem to be slightly confused about exactly how to call CPUID. The authoritative reference is always the Intel manuals, but transcriptions have been made and placed online by multiple folks. Searching Google for the instruction name + x86 makes them very easy to find. Here is the documentation for CPUID. It tells you exactly how it needs to be called.

The summary is, EAX needs to be set to the "function"/"level", which indicates the type of information to retrieve. In your case, to get the feature bits, EAX should contain 1. The other registers do not need to be pre-initialized; they will be clobbered and filled by the CPU during the execution of CPUID. The code you have is therefore correct as-written; there are no hidden "gotchas" to be aware of (at least, as long as you are using CPUID as shown here; it is a very "overloaded" instruction!).
Finally, I know this is probably just demo code (are you expected to post real code here?), but you really should wrap ugliness like this up in a function. Not only because it looks cleaner, but it also helps to consolidate the scope when the need arises to maintain it. Here's how I'd write it (using my preferred naming conventions; use whatever matches your project):

void InvokeCPUID(unsigned int  function,
                 unsigned int  subfunction,
                 unsigned int* pEAX,
                 unsigned int* pEBX,
                 unsigned int* pECX,
                 unsigned int* pEDX)
{
    assert(pEAX != NULL);
    assert(pEBX != NULL);
    assert(pECX != NULL);
    assert(pEDX != NULL);

    __asm__ __volatile__("cpuid"
                        : "=a" (*pEAX),
                          "=b" (*pEBX),
                          "=c" (*pECX),
                          "=d" (*pEDX)
                        :  "a" (function),
                           "c" (subfunction)
                        );
}

_Bool SupportsRDRAND()
{
    const unsigned int flag_RDRAND = (1 << 30);

    unsigned int eax, ebx, ecx, edx;
    InvokeCPUID(1, 0, &eax, &ebx, &ecx, &edx);

    return ((ecx & flag_RDRAND) == flag_RDRAND);
}

The object code emitted by GCC and Clang for SupportsRDRAND (with the call to CPUID inlined) is beautifully simple:

SupportsRDRAND:
    push    ebx        ; preserve caller-save EBX (required by calling convention)
    mov     eax, 1     ; set EAX to request function 1
    xor     ecx, ecx   ; set ECX to request subfunction 0
    cpuid
    shr     ecx, 30    ; the result we want is in ECX...
    and     ecx, 1     ; ...test for the flag of interest...
    mov     eax, ecx   ; ...and put the result in EAX so it can be returned
    pop     ebx        ; restore previously-saved value of EBX
    ret

That said…it is my recommendation that you not use inline assembly at all! I know its raw power is quite seductive, and sometimes you truly have no choice, but you really should try to avoid inline assembly if at all possible. Architectural portability obviously isn't a compelling argument here, but the fact that inline assembly disrupts the optimizer is still important, and even more important is that it vastly increases the development time and maintenance costs. You really do need to be an expert to get the inline assembly code right. And even if you are such an expert (and we still get it wrong regularly), the maintenance programmer who comes along later is invariably not.

Intrinsics are virtually always a better choice, unless you can really demonstrably outsmart the compiler—and even then, only if the code is a real performance bottleneck to justify the maintenance cost. In this case, it is absolutely not necessary. There are intrinsics/built-ins for the CPUID instruction, so you don't need to resort to inline assembly.

Based on the inline assembly syntax used here, you're obviously targeting a Gnu-style compiler. GCC and Clang both support the __get_cpuid built-in, but you'll need to include the <cpuid.h> header to use it. (If you were using MSVC, it has an equivalent __cpuid built-in, in <intrin.h>, that you could use.) Here's how I'd write the code:

#include <cpuid.h>   // for __get_cpuid intrinsic

_Bool SupportsRDRAND()
{
    const unsigned int flag_RDRAND = (1 << 30);

    unsigned int eax, ebx, ecx, edx;
    __get_cpuid(1, &eax, &ebx, &ecx, &edx);

    return ((ecx & flag_RDRAND) == flag_RDRAND);
}

Clang does an outstanding job with this code, producing object code virtually identical to that shown above. On the other hand, seemingly intent on making a liar out of me regarding the virtues of intrinsics, GCC makes an absolute mess of it. The reason for the "mess" is that it is calling CPUID twice: the first time with EAX set to 0 in order to obtain the highest function/level that the CPU supports, and then the second time with EAX set to the requested function/level. It appears to be doing this out of an abundance of caution, and perhaps based on a literal reading of the Intel documentation, which does recommend this. However, as far as I'm concerned, it is completely unnecessary. All CPUs that support the CPUID instruction support at least function/level 1, so the compiler should be able to detect that this is what you've requested and elide the first verificatory call to CPUID. GCC is clearly not making any attempt whatsoever to optimize the translation of the __get_cpuid intrinsic, since even calling it with the function/level set to 0 results in two invocations of CPUID, this time clearly redundant. While this isn't a bug per se, it is a pretty significant missed optimization opportunity.

The good news, though, is that a call to CPUID is never on the critical path for an application, so even the slowest calling code in the world cannot be a bottleneck. This is probably the counter-argument to be made for GCC's failure to optimize __get_cpuid, and means it is not worth losing sleep over. If for some reason you did find yourself losing sleep over this, you could always resort to using inline assembly, as discussed above. Or, you could use the internal __cpuid macro (which is used internally by the __get_cpuid intrinsic):

#include <cpuid.h>     // for __cpuid

_Bool SupportsRDRAND()
{
    const unsigned int flag_RDRAND = (1 << 30);

    unsigned int eax, ebx, ecx, edx;
    __cpuid(1, eax, ebx, ecx, edx);

    return ((ecx & flag_RDRAND) == flag_RDRAND);
}

This brings the object code emitted by GCC into line with my expectations, like that shown above. (Which makes sense, considering the definition of the macro is essentially identical to our inline asm above!) Although I can't find evidence from the Gnu folks that this is documented and intended for public consumption, it does work on GCC, Clang, and ICC. (This is also the name of the corresponding intrinsic for MSVC, although it is called a bit differently.)

Other Notes:

The above discussion of code quality reminds me of an important point that needs to be pointed out explicitly: when using CPUID, you should call it at application initialization to obtain the desired information, and then immediately cache those results away in a global variable. Whenever you want to make dynamic-dispatching decisions during the course of your application's execution, check the global flag—don't re-call CPUID each time! There is no need to pay the speed penalty (even with the most optimal calling code generation, CPUID itself is an extremely slow instruction), because the CPU is not going to change during your application's lifetime.
Notice that I have written my bit-testing code slightly differently than yours. You are just ANDing the mask with the bits, and then testing if the result is non-zero:

if (ecx & flag_RDRAND) { ... }

By contrast, I prefer to explicitly test that the result is equal to the mask:

((ecx & flag_RDRAND) == flag_RDRAND) { ... }

In the majority of cases, the results will be identical, but I prefer this for readability and generality. In the case that you have a multi-bit mask, comparing against zero may lead to an incorrect result, as it will evaluate to non-zero if either of the flags are set. Also, in the event that you ever have a mask of 0 (which you shouldn't, of course), writing the comparison the way I've done will ensure that you get the expected result.

The way I look at it is, writing code is difficult enough already, so the fewer things you have to remember and think about, the better. If you can write bit-testing code that is always correct without ever having to think about it, then I believe that's what you should do.
If possible, prefer not using macros to define constants! I realize there are cases in C where you actually do need to use a #define (or possibly an enum), and a static const variable simply won't work since it's not a true constant (e.g., when declaring the size of a memory array in a structure), but I believe you should prefer const objects whenever possible. These are more debugger-friendly, avoid namespace pollution, respect scoping rules, and are type-safe. Any decent optimizing compiler should fold constants, so the resulting binary will be equivalent. If you're on an embedded system, the rules may be different, but this code is clearly x86-specific!
Dair already noted your use of printf as opposed to puts. I guess he's probably right; I can't argue with the statement that simpler is usually better than more complicated. But this is obviously just demo code, not a demonstration of what you're actually going to be doing with these results. Furthermore, which function you use for console output is just not something that matters in real-world code. Both functions are so slow from an optimization perspective that the potentially-minor speed improvement of puts over printf is unimportant. The bottleneck there is not the speed of the output, but the speed at which a human operator can perceive the stimuli. Besides, a sufficiently smart compiler may optimize printf into puts when possible.

Next Steps:

Finally, harking back to the discussion at the top of why you should always prefer intrinsics to inline assembly, when you get ready to invoke RDRAND on the processors that you determine have support for it, make sure that you use an intrinsic to do so.

The following are the intrinsics for RDRAND, parameterized on the size (in bits) of the random integer to be generated:

int _rdrand16_step(unsigned short*)
int _rdrand32_step(unsigned int*)
int _rdrand64_step(unsigned long long*)

These write the generated random value into to the specified pointer, and return an int indicating success (1) or failure (0). To use them, you must include the <x86intrin.h> header (or, specifically, <immintrin.h>).

Usage is drop-dead simple. If you wanted to retain the ability to check for success, you could do something like:

#include <x86intrin.h>   // for _rdrand32_step intrinsic

_Bool GetRandomViaRDRAND(unsigned int* pResult)
{
    // This function should *only* be called if the underlying processor supports
    // the RDRAND instruction. This is the caller's responsibility to verify,
    // e.g., using the CPUID instruction. For performance reasons,
    // we don't want to verify this each time a random number is desired,
    // but to ensure correctness, we will validate it in debugging builds.
    assert(SupportsRDRAND());

    return (_rdrand32_step(pResult) != 0);
}

Or, if you want to play it dangerously and ignore the hardware's success flag, you could do the following:

unsigned int GetRandomViaRDRAND()
{
    // This function should *only* be called if the underlying processor supports
    // the RDRAND instruction. This is the caller's responsibility to verify,
    // e.g., using the CPUID instruction. For performance reasons,
    // we don't want to verify this each time a random number is desired,
    // but to ensure correctness, we will validate it in debugging builds.
    assert(SupportsRDRAND());

    unsigned int value;
    int result;
    result = _rdrand32_step(&value);
    assert(result != 0);
    return value;
}

This not only simplifies the interface by which the function is called, but also results in slightly more efficient object code. Because you're using an intrinsic, the compiler can tell whether or not you're actually using its return value. If you do, it has to store the carry flag (CF is set by the CPU after executing RDRAND) in such a way that you can test it (compilers use a conditional move instruction for this). If you don't use the return value, it can elide this code altogether, executing only an RDRAND instruction.

If you did need to fall back to inline assembly for RDRAND, hopefully you know how to do it correctly now. Notice that we need to use the cc clobber, since the instruction clobbers the flags:

unsigned int GetRandomViaRDRAND()
{
    unsigned int value;
    __asm__("rdrand  %[value]"
           : [value] "=r" (value)
           :       /* no inputs */
           : "cc"  /* clobbers flags (condition codes) */
           );
    return value;
}


General comments:

Your push method takes time proportional to the length of the list. Usually I would expect this method to take constant time. How can you change your data structure to achieve this?

Your push method could also check (in constant time) that the sorted order is preserved, and throw an exception if the client tries to push an illegal int.

Probably your class ought to be called SortedList, since this is the object you’re implementing. Then your sortTwoLists() (which could be called mergeTwoLists()) would be an instance method taking a SortedList object as a parameter. Note that both SortedLists involved are changed by this method.

printList() would probably be better as an instance method (in which case, it needn’t take any parameters).

Question 1:
Here’s one possible approach. You could build an auxiliary MergingNode class, with instance variables:

Node mergedNode; // a node in the merged list
Node thisNode; // current node in the first list you’re merging
Node thatNode; // current node in the second list you’re merging

This class could have methods getMergedNode(), which just returns mergedNode, and nextMergeStep(), which replaces mergedNode by the next node in the merged list and updates either thisNode or thatNode, depending on which list we took a node from. Note that nextMergeStep() modifies the original SortedLists.

Then, Step 1 can be replaced by

SortedList merged = new SortedList();
MergingNode mergingNode = new MergingNode(null, headA, headB);
mergingNode.nextMergeStep();
merged.head = mergingNode.getMergedNode();

Step 2 can be replaced by

Node curNode = merged.head;
while (curNode != null) {
  mergingNode.nextMergeStep();
  Node nextNode = mergingNode.getMergedNode();
  curNode.next = nextNode;
  curNode = nextNode;
}

This way the nextMergeStep() method does all the work of your if statements.

Question 2:
To clean up your main method, you could, for example, write a constructor for SortedList that takes an array of integers as a parameter, and constructs the SortedList containing those integers (meanwhile checking that the array was sorted).


Making equal-sized tabs to fill the full width of a box

Use the length as an index for an array containing classes :

$(document).ready(function() {
    var classes = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
    $('ul.tabs-list').each(function () {
        $(this).addClass(classes[$(this).children().length]);
    });
});


Handling periods ('.') in CSV column names with Pandas

Did a little digging and found that you can use df._columnid when pandas df.columns runs into an issue with a name (in this example dealing with a ".")

I am sure you already know that you could just do df['birth.place'], since it's inside a string container, however it becomes tricky for row.birth.placeas you mentioned. For that you can do the following:

for row in df.itertuples():
   print(row._2)

The _2 corresponds to the column id that pandas had issues parsing. It renamed it with an underscore and enumerated id in the column's list. Note that this renaming process only occurs when pandas ran into an issue grabbing the actual column name (i.e. row.name is still row.name, and you cannot use row._1 in-place of it). Hope that helps! Happy pythoning!


One guiding principle in software development is Don't Repeat Yourself (DRY). Your code for player 1 and 2 are almost identical, so you should extract them into a login function:

import crypt

class AuthenticationError(Exception):
    pass

def encrypt(word, salt):
    # use some one-way hashing function here
    return crypt.crypt(word, salt)

def login(users, max_tries=3):
    for i in range(max_tries):
        username = input("Please enter your username ")
        password = input("Please enter your password ")
        if username in users and encrypt(password, username) == users[username]:
            print("You are logged in as", username)
            return username
        else:
            print(f"Login failed. You have {max_tries - i - 1} tries left.")
    raise AuthenticationError(f"You have been locked out please restart to try again.")

This uses a hashing function, like @ChadG suggested in their answer, with a salt to prevent rainbow table attacks.

By raising an Exception (here a custom one, to give it a nice name), the execution of the program is automatically halted, so no need to explicitly do sys.exit.

This code assumes that you have read the users file before into a dictionary (only need to do it once!), something like this:

import re

def get_users(file_name):
    line_fmt = re.compile(r'username: (.*) password: (.*)')
    with open(file_name) as f:
        return dict(line_fmt.match(line.strip()).groups() for line in f)

Or, this slightly expanded version which ensures that the entries not conforming to the format are skipped (including any trailing newline):

def get_users(file_name):
    line_fmt = re.compile(r'username: (.*) password: (.*)')
    users = {}
    with open(file_name) as f:
        for line in f:
            try:
                name, password = line_fmt.match(line.strip()).groups()
                users[name] = password
            except AttributeError:
                print("Malformed line:", line)
        return users

Use it like this:

if __name__ == "__main__":
    registered_users = get_users("accountfile.txt")

    print("Could player 1 enter their username and password")
    player1 = login(registered_users)

    print("Could player 2 enter their username and password")
    player2 = login(registered_users)

    # start dice game

This uses a if __name__ == "__main__": guard to allow importing from this script from another script.


Staircase problem solved using recursion

The staircase problem actually just generates the Fibonnacci sequence.

Whilst the recursive solution is nice, without memoization you're much better off just using a loop:

def count_stairways(n):

   a, b = 0, 1
   for _ in range(n):
       a, b = b, a+b

   return b

A nice alternative if you want multiple values out is to create a generator:

def count_stairways():

    a, b = 0, 1
    while True:
        a, b = b, a+b
        yield b

If you just want a particular value (possibly for a large n), the fibonnacci sequence actually has a closed form

 def count_stairways(n):

     phi = (1 + math.sqrt(5)) / 2

     return int((pow(phi, n+1) - pow(1-phi, n+1))/math.sqrt(5))


Fist of all I will recommend you to use Constructor based dependency injection. Then I can not see the relation between the Question, QuestionAnswer, and QuestionRightAnswer entities... currently you are selecting all the right answers from the DB which you should NOT do! You have to get all the correct answers for this question only. Use the question.id from QuestionAnswer just to match the QuestionRightAnswer.questionId FK. Also you do take care of the MULTI_CHOICE questions only, but why?

Consider an implementation such as:

@Service
public class StudentServiceImpl implements StudentService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    QuestionRepository questionRepository;
    UserRepository userRepository;
    Transformer transformer;

    @Autowired
    public NotificationService(QuestionRepository questionRepository,
                               UserRepository userRepository,
                               Transformer transformer) {
        this.questionRepository = questionRepository;
        this.userRepository = userRepository;
        this.transformer = transformer;
    }

    @Override
    @Transactional
    public void correctAnswer(List<StudentAnswersDTO> questionAnswers) {
        logger.info("****** start correct answers ********");
        Long grade = questionAnswers
            .stream()
            .filter(questionAnswer -> questionAnswer.getType().toLowerCase().equals(AppConstants.MULTI_CHOICE))
            .filter(questionAnswer -> questionRepository
                .getRightAnswersByQuestionId(questionAnswer.getId())
                .stream()
                .anyMatch(rightAnswer -> questionAnswer.getAnswerId().equals(rightAnswer.getAnswerId())))
            .count();

        User currentStudent = userRepository.findByMobileNumber(SecurityHelper.getCurrentUser());
        ((Student) currentStudent).setGrade(grade);
        ((Student) currentStudent).setStudentAnswers(transformer.transform(questionAnswers, AnswerSelected.class));
    }
}


Tweets per second calculator (Talent Buddy)

Naming

Your FindMaxLastK method doesn't describe it's intention very well, what is tps and k when viewed at a glance?. What you have is a windowing function finding the max within that window. Name your function after that:

static int MaxInWindow(int[] values, int start, int trailingWindowSize)

The conditional expression in your max function could be clearer if you used Math.Max(int, int)

My implementation would look like:

public static int MaxInWindow(int[] values, int start, int trailingWindowSize)
{
    //TODO Validate arguments
    var lowerBound = Math.Max(start - trailingWindowSize, -1);
    var max = values[start];
    for (int index = start - 1; index > lowerBound; index--)
    {
        max = Math.Max(max, values[index]);
    }
    return max;
}

Performance

Your solution is O(m * n) where m is the number of seconds and n is the window size. I just saw the answer in a related question and the optimal solution is O(m).

The solution uses a LinkedList to keep track of the max in the window. Here is my implementation in C#:

public static IEnumerable<T> MaxInSlidingWindow<T>(T[] values, int windowSize)
{
    var comparer = Comparer<T>.Default;
    var window = new LinkedList<Tuple<T, int>>();// Max at position and position

    var length = values.Length;
    for (var index = 0; index < length; index++)
    {
        var value = values[index];
        while (window.Count != 0 && comparer.Compare(window.Last.Value.Item1, value) < 0)
        {
            window.RemoveLast();
        }

        window.AddLast(Tuple.Create(value, index));

        while (window.First.Value.Item2 <= index - windowSize)
        {
            window.RemoveFirst();
        }

        yield return window.First.Value.Item1;
    }
}


Here are some things I see that might help you improve your code:

Use more whitespace

Lines like this one:

char*lFillEnd=((char*)pToFill)+pToFillSize;

make my eyes bleed.

char *lFillEnd = ( (char*)pToFill ) + pToFillSize;

That version is much easier for humans to parse because of the judicious use of whitespace.

Use better names

The code has an odd characteristic in that every variable names begins with either p or l rendering the names unprounceable and impeding readability.  I can only guess that these might have been intended to signify parameter and local but those distinctions are quite obvious to anyone who knows C and not helpful.  Also memcopyfill isn't a terrible name, but perhaps patternfill would be more descriptive?  I'd suggest using memcpy inspired names that are terse but easier to read for the parameters:  dst, dstsize, src and srcsize.

Combine conditions for early bailout

It's good to have the early bailout in the case of NULL pointers or zero-length but it makes less sense for those to be two separate if statements.  Because of short-circuit evaluations, the resulting code will be just as efficient if you write just a single if statement and it is, I think, a little easier to see what is going on in the code.

Think carefully about size comparisons

The code currently has a line:

if(pToFillSize<pFillWithSize){

But shouldn't that comparison be <=?

Consider returning an error code

In the case of an early bailout, it might be handy to return an error code indicating that something was wrong.  This might also be used in the case that the buffers overlap, violating your stated calling conditions.

Don't use const inappropriately

Normally I find myself advocating for more use of const in code I review, but in this case, I see two instances where it might be better omitted.  Specifically, having the size parameters declared as merely size_t rather than const size_t makes sense and mirrors the declaration of the library routine memcpy.  Also, we are clearly going to alter the memory pointed to by pToFill so it's inappropriate to declare it const.

Remove the local variables

Most of the local variables are actually not needed in this code.  Don't forget that your parameters are actually local copies that can be used instead:

Put it all together

Here's one alternative that incorporates all of these changes:

bool patternfill(char *dst, size_t dstsize, const char *src, size_t srcsize)
{
    if (dst == NULL || dstsize == 0 || src == NULL || srcsize == 0) {
        return false;  //Can do nothing...
    }
    size_t remaining = dstsize;
    if (remaining <= srcsize) {
        memcpy(dst, src, remaining);
        return true;
    }
    // make one full copy
    memcpy(dst, src, srcsize);
    dst += srcsize;
    remaining -= srcsize;
    // now copy from destination buffer, doubling size each iteration
    for (src = dst; remaining > srcsize; srcsize *= 2) {
        memcpy(dst, src, srcsize);
        dst += srcsize;
        remaining -= srcsize;
    }
    // copy any remainder
    memcpy(dst, src, remaining);
    return true;
}

Perform tests

I wrote some simple test code to exercise the two versions of this function (with some minor changes to the original to have the same signature).  Here is the code.  First, a simple verification function to check that the pattern was successfully copied:

bool verifyfill(const char *buff, size_t buffsize,
        const char *pattern, size_t patternsize)
{
    if (buff == NULL || pattern == NULL || buffsize == 0 || patternsize == 0)
        return true;
    const char *pattend = (char *)pattern+patternsize;
    for (const char *p = pattern; buffsize && *buff == *p; buff++, --buffsize)
        if (++p == pattend)
            p = pattern;
    return buffsize == 0;
}

Then a bit more test harness to collect and compare the two functions:

typedef bool (*TestFunc)(char *, size_t, const char *, size_t);

bool checkpatternfill(TestFunc test, char *buffer, size_t buffsize,
        const char *pattern, size_t patternsize)
{
    memset(buffer, 'x', buffsize);
    test(buffer, buffsize, pattern, patternsize);
    return (verifyfill(buffer, buffsize, pattern, patternsize));

}

struct {
    TestFunc fn;
    const char *name;
} tests[] = {
    { memcopyfill, "original" },
    { patternfill, "improved" }
};

Finally, a main routine to check both accuracy and performance:

int main()
{
    const size_t buffsize = 100;
    const char pattern[]="Pattern";
    const size_t patternsize = strlen(pattern);
    const int testCount = sizeof(tests)/sizeof(tests[0]);
    char *buffer = malloc(buffsize);
    if (buffer == NULL) {
        perror("Can' allocate buffer");
        return 1;
    }

    // basic functionality tests
    for (int i=0; i < testCount; ++i) {
        if (checkpatternfill(tests[i].fn, buffer, buffsize, pattern, patternsize))
        {
            printf("%s Test passed\n", tests[i].name);
        } else {
            printf("%s Test failed!\n", tests[i].name);
            char *buffend = buffer+buffsize;
            for (char *p = buffer; p < buffend; ++p)
                putc(*p, stderr);
        }
    }

    // speed tests
    for (int i=0; i < testCount; ++i) {
        clock_t start = clock(), diff;
        for (int j=10000000; j; --j) {
            tests[i].fn(buffer, buffsize, pattern, patternsize);
        }
        diff = clock() - start;
        printf("%s took %f seconds\n", tests[i].name, 1.0 * diff / CLOCKS_PER_SEC);
    }
    free(buffer);
}

Test results:

On my 64-bit Linux box using gcc with -O2 optimization, I get this result:

 original Test passed
 improved Test passed
 original took 0.338862 seconds
 improved took 0.270134 seconds


Factory for object init and configuration

I find the right word in you question - 'extract'.

Code style

Logic section

Use blank lines to separate your code into logical sections

Instead of:

DateField dateField = new DateField();
dateField.setCaption(caption);
dateField.setDateFormat(UilibI18N.dateFormat.getText());
dateField.setResolution(Resolution.DAY);
bind(dateField, propertyId);

You can use:

// creation logic part
DateField dateField = new DateField();

// setting the field's properties logic part
dateField.setCaption(caption);
dateField.setDateFormat(UilibI18N.dateFormat.getText());
dateField.setResolution(Resolution.DAY);

// bind operation logic part
bind(dateField, propertyId);

Design issue

I read your code very carefully and I've found that you use 2 variables in all your 3 if/else conditions.

They are caption and propertyID.

Assume that these 2 properties will be an input of some method which we'll call (I don't know the context, that's why I'll use the random name) makeOperationWithField

public void makeOperationWithField(int propertyID, String caption) {
 // some code
}

I'll move deeply and remove this big if/else if statements.

Replace conditional with polymorphism.

Lets do it step by step.

Step1

Create an abstract class that will create objects depending on field's type.

abstract class FieldConfigurationType {
  static final int TEXTFIELD = FieldConfiguration.FIELD_TYPE.TEXTFIELD;
  static final int SEARCHFIELD = FieldConfiguration.FIELD_TYPE.SEARCHFIELD;
  static final int DATEFIELD = FieldConfiguration.FIELD_TYPE.DATEFIELD;

  abstract void makeOperationWithField(int propertyID, String caption);

  public static FieldConfigurationType newType(int code) {
    switch (code) {
      case TEXTFIELD:
        return new TextFieldConfiguration();
      case SEARCHFIELD:
        return new SearchFieldConfiguration();
      case DATEFIELD:
        return new DateFieldConfiguration();
      default:
        throw new IllegalArgumentException("Incorrect Field Type");
    }
  }
}

Now, we can use the simple construction:

FieldConfigurationType fieldType = FieldConfigurationType.newType(type);
fieldType.makeOperationWithField(propertyID, caption);

Step 2

Add separate implementation for each field type.

public class TextFieldConfiguration extends FieldConfigurationType {
  @Override public void makeOperationWithField(int propertyID, String caption) {
    TextField textField = new TextField(caption);
    textField.setNullRepresentation("");

    bind(textField, propertyId);

    field = textField;

    if (field.getValue() == null && isNestedProperty) {
      ObjectProperty property = new ObjectProperty("", String.class);
        textField.setPropertyDataSource(property);
    }
  }
}

public class SearchFieldConfiguration extends FieldConfigurationType {
  @Override public void makeOperationWithField(int propertyID, String caption) {
    SearchBox searchField = new SearchBox(caption);
    bind(searchField, propertyId);

    field = searchField;
  }
}

public class DateFieldConfiguration extends FieldConfigurationType {
  @Override public void makeOperationWithField(int propertyID, String caption) {
    DateField dateField = new DateField();

    dateField.setCaption(caption);
    dateField.setDateFormat(UilibI18N.dateFormat.getText());
    dateField.setResolution(Resolution.DAY);

    bind(dateField, propertyId);
  }
}

If you need to add a new field type, all you need to do is just add new subclass without rewriting the existing code. Open/Closed Principle


Setting variables inside if / else-if statment blocks

I don't know what the purpose of declaring your variable within your if statement is supposed to be here. For readability, I would declare those variables at the beginning of your function, like so:

function test() {
    var x = 3,
        msg,
        state;
    if (x > 5) {
        msg = "m", state = "d";
    } else if (x < 5) {
        msg = "a", state = "d";
    } else {
        msg = "e", state = "n";
    }
    $('#id1').removeClass().addClass(state);
    $('#id2').html("Some text " + msg + " and more text.");
    $('#id3').attr('title', "Different text " + msg + " still different text.");
}

That being said, I don't know a reason why you couldn't do so; it most depends on readability and the best practices you are following.


Can casting to fragment be more efficient than using a variable?

You could make it more dynamic. Because this method adds the Fragment only to the R.id.fragment_secondpane layout. If this is all what you desire, it's ok. Otherwise add a parameter for the layout. This way you can use your method to add a Fragment to different layouts.

Because every type of Fragment like ListFragment, DialogFragment or even a SherlockFragment is using Fragment as super class, you can use Fragment as the parameter type. There's no need to use Object. Note that you should avoid to mix the Fragment types of different librarys.

With methods like this you can avoid extra code in this situation, replacing different Fragments of a specific layout.

The processing will be the same. The creation of the necessary objects have to be done. There will be no difference if this happens in e.g. onCreate or the method you wrote. The only thing you could avoid is to hold an extra reference of the FragmentManager.

To sum all up you would have something like this:

private void changeFrag(int layout, Fragment newFrag){

    getSupportFragmentManager() // gets the FragmentManager of the Activity, no need to hold a reference
         .beginTransaction()
         .replace(layout, newFrag) // use the layout and the fragment, no need for a cast
         .commit();

}

Note that this method will work and is straightforward. If you have an approach with adding some Fragments to the backstack and some not or using different kind of animations, your method will be more complex and lacks performance. That's why I would not use this in every situation.


A couple of comments first

It would be better to let your divide method should return an int, not do the output to System.out itself. Do the output in main like this:

public static void main(String[] args) {
    System.out.println(divide(-4,-10));
}

The variables N and D are short and don't follow the Java naming conventions. Parameter names should start with a lowercase letter and use camelCase. I would recommend calling them numerator and denominator.

If denominator == 0 is a quite exceptional case, I would recommend throwing an ArithmeticException stating that it was caused by division by zero.

You treat more special cases than you need to. I don't think you need to handle either numerator == denominator or numerator == 0 as a special case. It should be possible to handle that using the normal logic for division.

If you were doing divisions by a power of 2 (2, 4, 8, 16, etc.) you could use right shift numerator >> 1, numerator >> 2 etc. However, your code should support more than just those cases which makes things more difficult.

In the end, you are trying to re-implement division by using repetitive subtraction. It will be slow, no matter what you do. If you want to be possibly somewhat faster for bigger numbers, or want to try another approach (I can't promise you it will be faster, but I believe that for big enough numbers it will be significantly faster), you could try to implement division by using one of the good old "pen and paper" ways. Think about the division 303364 / 596. Try to solve that by hand! and think about what it is that you are doing. (Hint: Also think about how you do multiplications by hand, how would you solve 583 * 42 ?)

However, in reality though, the fastest solution is to use the / operator in Java, but that wouldn't be a challenge now, would it? So I guess that's out of the question :)


"fibonnaci" is a misspelling.

There really isn't any need for jQuery here.

As you have already observed, there is also no need to keep the entire array, unless you wanted to modify the code to reuse the memoized results for multiple calculations.

If you want the fastest way to calculate a specific Fibonacci number, even when the number is large, then go for the closed-form formula instead:

$$
F_n = \frac{\phi^n - \psi^n}{\sqrt{5}}
$$
… where
\$\phi = \dfrac{1 + \sqrt{5}}{2}\$ and \$\psi = \dfrac{1 - \sqrt{5}}{2}\$.


overall this code looks nice and tidy, and it passes pylint with minimal errors which is a good start!

Some observations:

If you're returning in an if block you don't need to use elif and/or else since on match the code will never continue.  I'd probably use or instead of 3 elif statements to avoid having the `return "won" repeated. And maybe carry the result in a variable - this allows you to set a default and avoid one test. So something like:

def check_victory(computer_choice, user_choice):
    result = "lost"
    if user_choice == computer_choice:
        result = "tie"
    if computer_choice == "rock" and user_choice == "paper" or \
       computer_choice == "paper" and user_choice == "scissors" or \
       computer_choice == "scissors" and user_choice == "rock":
        result = "won"
    return result

Another thing might be to replace some of the descriptive comments with docstrings - less important in a small program, but a useful habit to get into for more complex projects later on.

Finally since you're using f-strings for the first print, you could use them for both?

print(f"Computer choose: {computer_choice}")
print(f"You {check_victory(computer_choice, user_choice)}\n\n")

Only other things are 'features' like documenting the choices available, providing 'shortcuts' like r/p/s etc - but those are 'optional extras' and nothing to do with the code quality!


Can someone tell me if this is clean code...

The code is somewhat easy to read (e.g. it appears to somewhat align with the recommendations of PSR-12. It is also great that parameters are bound to the queries so SQL injection should be less likely to occur.

...or if it's too much?

The mixing of PHP within HTML is not great. It is recommended to have the PHP fetch data and then within the HTML just output any data that might have been retrieved.
There are quite a few duplicate lines in these three blocks:

if (isset($_POST['beginner'])) {
    # code...
    $get_exercises = $con->prepare("SELECT exercise_name, difficulty FROM exercises WHERE difficulty = ?");
    $get_exercises->bind_param("s", $_POST['beginner']);
    $get_exercises->execute();
    $get_exercises->store_result();
    $num_of_rows = $get_exercises->num_rows;
    $get_exercises->bind_result($exercise_selected, $difficulty);
}

if (isset($_POST['intermediate'])) {
    # code...
    $get_exercises = $con->prepare("SELECT exercise_name, difficulty FROM exercises WHERE difficulty = ?");
    $get_exercises->bind_param("s", $_POST['intermediate']);
    $get_exercises->execute();
    $get_exercises->store_result();
    $num_of_rows = $get_exercises->num_rows;
    $get_exercises->bind_result($exercise_selected, $difficulty);
}

if (isset($_POST['advanced'])) {
    # code...
    $get_exercises = $con->prepare("SELECT exercise_name, difficulty FROM exercises WHERE difficulty = ?");
    $get_exercises->bind_param("s", $_POST['advanced']);
    $get_exercises->execute();
    $get_exercises->store_result();
    $num_of_rows = $get_exercises->num_rows;
    $get_exercises->bind_result($exercise_selected, $difficulty);
}

It appears that only two of each eight lines in each block changes - i.e. the if condition and the second parameter passed to $get_exercises->bind_param().
A commonly accepted principle is the Don't Repeat Yourself. principle. The common lines could be abstracted to a function, or even a simple check for common values:
Instead of setting the name attribute uniquely on each button

<button id="beginner" name="beginner" value="beginner">Beginner</button>

Set the name on all three the same - e.g. name=“difficulty”. That can make the query logic much simpler:
//initialize to avoid undefined variables if POST not set
$exercise_selected = $difficulty = null;
if (isset($_POST['difficulty']) {
    $get_exercises = $con->prepare("SELECT exercise_name, difficulty FROM exercises WHERE difficulty = ?");
    $get_exercises->bind_param("s", $_POST['difficulty']);
    $get_exercises->execute();
    $get_exercises->store_result();
    $num_of_rows = $get_exercises->num_rows;
    $get_exercises->bind_result($exercise_selected, $difficulty);
}


C function to find and delete a node from a singly linked list

The neatest way to deal with this is to use what I was taught as the "2 pointer trick" (thank you Charles Lindsay all those years ago):

Instead of holding a pointer to the record you hold a pointer to the pointer that points to it - that is you use a double indirection. This enables you to both modify the pointer to the record and to modify the record without keeping track of the previous node.

One of the nice things about this approach is that you don't need to special case dealing with the first node.

An untested sketch using this idea for delete_item (in C++) looks like:

void delete_item(node** head, int i) {
  for (node** current = head; *current; current = &(*current)->next) {
    if ((*current)->x == i) {
      node* next = (*current)->next;
      delete *current;
      *current = next;
      break;
    }
  }
}

This loop will break after the first entry it finds, but if you remove the "break" then it will remove all entries that match.


Implementing Sieve of Eratosthenes faster

Four* letters to rule them all

The Sieve of Eratosthenes is an algorithm which heavily relies on loops. Unfortunately, Python's convenient scripty nature comes at a cost: it's not terribly fast when it comes to loops, so it's best to avoid them.

However, this is not always possible, or one, like me in this case, is not so much into algorithms to transform them into another form. Enter numba. numba is a just-in-time compiler for Python code. The just-in-time compiler can transform plain Python code into "native" code for your system. So what are those magical four letters I was talking about? It's @jit.

This simple decorator and no further code changes brought the time for n = 100 000 000 from 36s down to about 3s on my machine. The larger test case did not work out to well with my 16GB RAM and some other things to do apart from Code Review.

from numba import jit

@jit
def eratos_sieve(n:"find prime below this"=100000000):
    # ... the rest of your code here

You can also have a look at this generator based implementation of the algorithm presented on Stack Overflow. The implementation can benefit from just-in-time compilation as well. A quick test using the SO approach and @jit for the previous n brought the execution time down to just below 2s on the same machine as before.

What numba cannot fix for you

There are a few aspects with respect to style and idiomatic language features (often called pythonic code) that you have to/can improve yourself.

While

number =10000000
def eratos_sieve(n:"find prime below this"=None):
    if not(n):
        n = number
    ...

might be working and syntactically valid, I find it very, very uncommon and would not recommend it. A more "pythonic" way to express this would be

def eratos_sieve(n: int = 100000000):
    """Find all primes below a given whole number n"""
    ...

This makes use of Python 3's type hinting and the recommended way to write function documentation using docstrings.

The way you construct your candidate list using numbers = [x for x in range(0, n+1)] is also a little bit complicated, and may be simplified to numbers = list(range(n+1)). 0 is the implicit starting value for range(...) and since range(...) already returns a generator you can simply pass it to a list constructor and work with it.

You should also have a look at the official Style Guide for Python Code (PEP8) and follow it's recommendations regarding whitespace within expressions and statements.

If you intend to supply your testing code together with your function in a single script, wrap it in the well known if __name__ == "__main__": construct to ensure it is only run if your code is used as a script.

* Well not strictly speaking, but it's close.


Why do you make this call Async.StartAsTask instead of just return the Async<T> to let the client handle that as needed?

  let rec StartReading (client:TcpClient) =

I would call it reader and then give it the signature of:

let rec reader frameNo (client:TcpClient) =

in order to get rid of reffor frameNumber.

You can then initially call it:

reader 0 client |> Async.StartAsTask

and recursively:

return! reader (frameNo + 1) client


Need a feedback on my Javascript code and app implementation idea

From a quick glance there are a couple of points where your making simple mistakes.

// Document.write is bad
document.write('<script language="javascript" type="text/javascript" >');

// use css definitions instead
counter_div.setAttribute('style', 'width: 310px; height: 50px; font-family:lucida,tahoma,helvetica,arial,sans-serif; display: block; overflow:hide;');

// dont set inner html. This is bad. use DOM manipulation instead
title_span.innerHTML = meter_title;

// uses eval here. pass a function rather then a string
setInterval("increment()", interval);

// forgetting to declare addCommas with `var`. This is implecetly global.
addCommas = function(nStr) {

I shall have a look at how to redesign this.

Why do you need to append the div after the script tag. It's bad by design to use the script tag in the DOM for positioning.

it would be better to create a <div> to fill with the timer/counter.

Refactored partly here. This includes fixing the issues above plus making the dom manipulation a bit nicer.

I'm not too certain how to do refactoring on your timer code.


Pandas dataframe custom forward fillna optimisation

a few ways to make it more pythonic

'private' variables

variable within a function are limited to the scope of that function, so prepending them with a _ is unnecessary

lists

sync_with could also be another Container, like a tuple or so. Only when it is a str you need to convert it.

also be aware of what can go wrong with mutable default arguments. They are instantiated at the moment of function definition. In this case they are not appended to in the function or returned, so it should not pose any problems, but I try to avoid them anyway

fixed_cols can then be assembled like this:

fixed_cols = ['agent', 'date'] + list(sync_with)

Then only if sync_with is an generator, something can go wrong, so I would do something like this:

def synchronize(df, sync_with=None):
    if sync_with is None:
        sync_with = []
    elif isinstance(sync_with, str):
        sync_with = [sync_with, ]
    else:
        sync_with = list(sync_with)

performance

Making a copy initially is unnecessary, unless you will perform operations inplace on the df
You can use DataFrame.groupby.transform, and then select the rows which had any non-null value in the original df

You would get something like this:

def synchronize3(df,sync_with=[]):
    if isinstance(sync_with, str):
        sync_with = [sync_with, ]
    else:
        sync_with = list(sync_with)
    result = df.groupby('agent').transform(lambda x: x.fillna(method='ffill'))
    if sync_with:
        result = result.loc[pd.notnull(df[sync_with]).any(axis=1), :]
    result = result.assign(agent=df['agent']).reindex(columns=df.columns)
    return result

Results:

%timeit synchronize(foo)

9.48 ms ± 527 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit synchronize(foo,'_c')

29 ms ± 817 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit synchronize(foo,['_a','_b'])

27.8 ms ± 608 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

assert synchronize(foo).equals(synchronize3(foo))
%timeit synchronize3(foo)

5.71 ms ± 935 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

  _a  _b  _c  agent   date
0 1.0 11.0    111.0   1   2010-01-01
1 1.0 22.0    111.0   1   2011-01-01
2 1.0 22.0    333.0   1   2012-01-01
3 4.0 22.0    333.0   1   2013-01-01
4 5.0 55.0    NaN     2   2010-01-01
5 5.0 55.0    666.0   2   2013-01-01
6 7.0 77.0    777.0   2   2015-01-01
7 8.0 77.0    777.0   2   2016-01-01

assert synchronize(foo,'_c').equals(synchronize3(foo,'_c'))
%timeit synchronize3(foo,'_c')

6.41 ms ± 131 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

  _a  _b  _c  agent   date
0 1.0 11.0    111.0   1   2010-01-01
2 1.0 22.0    333.0   1   2012-01-01
5 5.0 55.0    666.0   2   2013-01-01
6 7.0 77.0    777.0   2   2015-01-01

assert synchronize(foo,['_a','_b']).equals(synchronize3(foo,['_a','_b']))
%timeit synchronize3(foo,['_a','_b'])

7.33 ms ± 1.16 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

_a    _b  _c  agent   date
0 1.0 11.0    111.0   1   2010-01-01
1 1.0 22.0    111.0   1   2011-01-01
3 4.0 22.0    333.0   1   2013-01-01
4 5.0 55.0    NaN     2   2010-01-01
6 7.0 77.0    777.0   2   2015-01-01
7 8.0 77.0    777.0   2   2016-01-01

bugfixes

the version of your algorithm I used was this:

def synchronize(df,sync_with=[]):
    _df = df.copy()

    if not isinstance(sync_with,list):
        sync_with = [sync_with]

    _fixed_cols = ['date','agent']
    _fixed_cols.extend(sync_with)
    _colset = [c for c in _df.columns if c not in _fixed_cols]

    for ag in _df.agent.unique():
        _df.loc[_df.agent==ag,_colset] = _df.loc[_df.agent==ag,_colset].fillna(method='ffill')
        if sync_with:
            _df.loc[_df.agent==ag,:] = _df.loc[_df.agent==ag,:].dropna(how='all', subset=sync_with)
            _df.loc[_df.agent==ag,:] = _df.loc[_df.agent==ag,:].fillna(method='ffill')
    if sync_with:
        _df = _df.dropna(how='all', subset=sync_with)
    return _df.astype({'agent': 'int64'})  # else the `dtype` is different from the one in my method, throwing of the assertions


Seconds -> Days, Hours, Minutes, and Seconds

Your code is lacking in the regards that you do floating arithmetic when you don't need to, and this potentially introduces smaller errors as you multiply back the different intervals.

With that being said your code looks clean enough, well spaced and good variable names. Only thing missing as such would be a docstring to document the functions return value as the name is somewhat ambiguous.

To avoid the floating arithmetic, and ease the calculation I would flip the order of doing divmod operations, and then we end up with the following code:

def convert_to_d_h_m_s(seconds):
    """Return the tuple of days, hours, minutes and seconds."""

    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    days, hours = divmod(hours, 24)

    return days, hours, minutes, seconds

if __name__ == '__main__':

    for seconds in [ 11, 61, 3601, 3668, 86400, 86401, 90061, 1043573894573948573 ]:
        print("{0} seconds: {1[0]} days, {1[1]} hours, {1[2]} minutes, {1[3]} seconds".format(
              seconds, convert_to_d_h_m_s(seconds)))

Notice how this also uses the if __name__ == '__main__': idiom to pack the test code used. This would allow for the convert function to be imported from another script if imported. The output of this code is:

11 seconds: 0 days, 0 hours, 0 minutes, 11 seconds
61 seconds: 0 days, 0 hours, 1 minutes, 1 seconds
3601 seconds: 0 days, 1 hours, 0 minutes, 1 seconds
3668 seconds: 0 days, 1 hours, 1 minutes, 8 seconds
86400 seconds: 1 days, 0 hours, 0 minutes, 0 seconds
86401 seconds: 1 days, 0 hours, 0 minutes, 1 seconds
90061 seconds: 1 days, 1 hours, 1 minutes, 1 seconds
1043573894573948573 seconds: 12078401557568 days, 20 hours, 22 minutes, 53 seconds


Having 700 functions, they all fit into your memory. No need to write files and use str2func. I would use anonymous functions instead.

Modified preprocessing.

% This part of the code is calculated once, it is not the issue
dvs = 5;
X=sym('X',[dvs,1]);
num = dvs - 1; % number of constraints

% multiple functions
for k = 1:num
    f1(X(k+1),X(k)) = (X(k+1)^3 - X(k)^2*k^2);
    c(k) = f1;
end

gradc = jacobian(c,X).'; % .' performs transpose

parfor k = 1:num
    hessc{k} = matlabFunction(jacobian(gradc(:,k),X),'vars',X);
end

And the simplified code using function handles:

%% Now we use the functions to run an "optimization." Just for an example the "optimization" is just a for loop

fprintf('This is test A, where the functions are evaluated in series!\n');
tic
for q = 1:10

    x_dv = rand(dvs,1);   % these are the design variables
    lambda = rand(num,1); % these are the lagrange multipliers

    x_dv_cell = num2cell(x_dv); % for passing large design variables

    for k = 1:num
        H_temp(:,:,k) = lambda(k)*hessc{k}(x_dv_cell{:});
    end

    H = sum(H_temp,3);

end
fprintf('The time for test A was:\n')
toc

On my system the code runs roughly 4 times faster.


Neatly printing integers interspersed with spaces

Usability

do you really need the groupLength? I'm not aware of any number writing scheme where it is fixed, but not 3[*].
on the other hand, the separator is different in a lot of countries. You can see an example for thousands separators here (or on wikipedia). For example, Canada uses , Italy uses ., the US uses ,, and Switzerland uses '. It might be nice to add that as a parameter instead of hardcoding . You can still use  as a default.
your code doesn't deal that well with negative numbers. -123 becomes - 123, and -123456 becomes - 123 456. I would not expect a space after the -.

[*] In India it seems to be written eg as 15,00,000, which doesn't use 3, but which also isn't a fixed length.

Misc

if you start your loop at 1 and prepend sb.append(charArray[0]);, you can save the i != 0 check you perform each time.


Not a question that fits CR well. This is clearly short, untested sample code. You need $("#counter"), not $(".counter").

var counter = $("#counter")
counter.html( parseInt(counter.html()) + 1 )

1

If you truly wish to increase the content of a field that you access by id you could try this:

document.getElementById('counter').textContent++;

1

This works as of IE9.. Personally I would always make sure that there is a number in textContent since otherwise the value will become NaN which looks like amateur hour.


A free-standing weak_ptr equivalent to handle lifetime of non-shared callback objects

I never saw a similar pattern so it was really interesting to understand your code !

First, about the name weak_ref, it implies that it has the syntax of a reference, but it is not the case (for instance, operator-> is for pointers). I personnaly named it something like ptr_to_instance.

Then, it seems the weak_ref should not be used on its own, without calling enable_weak_ref::get_weak_ref(). So I will make the weak_ref constructor private, making enable_weak_ref a friend. I will put the weak_ref class inside enable_weak_ref :

template<typename CRTP>
class enable_weak_ref {
  public:
    class weak_ref { /**/ };
    /**/
};

So instead of weak_ref<T> we have enable_weak_ref<T>::weak_ref. I think it makes more understandable the use of these classes.

Also, because weak_ref should not modify the pointer in weak_data_, I would use std::shared_ptr<T* const> so it is clear that this pointer is for read-only use.

If you do not want to use std::shared_ptr, you should create a int* (counting references), a CRTP** (which will hold this or nullptr) in enable_weak_ref, and weak_ref should have a int* const and a CRTP const* const (const specifier shows that weak_ref is linked to only one enable_weak_ref and can not be changed).


Addressing your specific questions

  Is this a good and correct way to use WeakReferences, or is there a simpler way? I don't want the Value to prevent its listeners from getting cleaned up, or to manually break links when a listener is no longer needed by the UI/calculations/whatever.

See "Pros and Cons of Listeners as WeakReferences" on StackOverflow.  BegemoT's answer explains how using weak references changes the semantics. To prevent anyone from being surprised when using an anonymous class listener (which are common in UI frameworks like SWT), I recommend clearly documenting this semantic on the addListener method. Also, in my experience, weak references are not as well known by many developers which further reiterates the need for documentation.

There's other fascinating corners to explore in weak references including WeakHashMap, which uses a ReferenceQueue to cleanup, as discussed another SO question with some facinating links.  If you dive into WeakHashMap (perhaps wrapped as a Set using Collections.newSetFromMap) at some point, as noted, Guava (Google's common java library) makes a case for using their MapMaker instead.

Because of their relative obscurity and behavior depending on when the GC will run, I personally shy away from weak references and use them sparingly.

  Use the interface List<...> or the actual implementation type ArrayList<...> when declaring the member mListeners?

See "Type List vs type ArrayList in Java" on StackOverflow.  Declaring to the interface (List<...>) is to be preferred.

  Initialize mListeners with an empty list at the member declaration, or in the constructor?

See "Should I initialize variable within constructor or outside constructor" on StackOverflow.  Where you can, I recommend initializing at declaration for clarity.

Additional Thoughts

Java already has an implementation for the Observer pattern in java.util.Observable.  This has found to be wanting in that you have to extend Observable.  As suggested in "Alternative to Java's Observable class?", Guava's EventBus is a good alternative.  I've used it before and recommend it for its ease of use and aide in decoupling code.
Declare fields as final where you can. Use final fields where you can to help prevent potential issues in mutability.  Qualify mListeners as final.
I was surprised to see the fields at the bottom of the class.  For customary readability, fields are typically declared prior to the constructors.


Your solution is actually quite decent, and the code style is good, etc. There are a couple of style changes I would recommend:

In a for loop, the variable i typically indicates an int, and people tend to use c to indicate a char. So, I would write for (char c = 'a'; c <= 'z'; c++) {...
your isPanagram method should be public.

Now, about the algorithm, your code will scan the result as many as 26 times. In reality, this will happen fast, and there's no pressing need to change that, but it could be faster, but would require a little work to get it right.

If you reverse the logic, and just iterate through each characters in the String once, then you can reference it back to an index for the characters.... It would go something like:

boolean[] seen = new boolean[26]; // or a constant for the number of characters.
int stillNeed = seen.length;
for (int i = 0; i < inputString.length(); i++) {
    char c = Character.toLowerCase(inputString.charAt(i));
    if (c >= 'a' && c <= 'z') {
        c = c - 'a';
        if (!seen[c]) {
            seen[c] = true;
            stillNeed--;
            if (stillNeed == 0) {
                return true;
            }
        }
    }
}
return false;

Now, for long strings, the above will be more efficient than your solution. It goes through each character in the string just once, but it has to create a list of what's been seen, or not. If it is a new character, it has to count it as seen.

Your mileage may vary.


Angular Models as Property or Injectable?

Because Javascript allows you to easily create objects without an explicit class, I usually find it unnecessary to define a class that doesn't have any functions.  That is, there's no benefit to using new Person(x,y) over {firstName: x, lastName: y}.  In fact, I would back up a step and have that kind of data in my model instead of separate arrays of first and last names:

$scope.pageData = [{firstName: 'John', lastName: 'Smith'} /* etc */];


Iterate through a list of data and add it to nested models

Some quick remarks.

Don't pointlessly abbreviate: fContent isn't a clear name, for instance.

i, j and k are okay names for variables in a for-loop, but here they really should have meaningful names.

Avoid adding words like "list" to names of collections. Especially when Documentlist isn't a collection, but the oddly named Documents. A class with a plural name? Which is then initialized by setting the badly named property Attdocument?

I'm assuming that you cannot change the property name f_name?

Are you certain that .Contains("Maindocument") will always work? Or should it be case insensitive?

In several places you seem to use string concatenation to create directory paths. Avoid this and instead use Path.Combine().

When you construct the MainDocumentModel, try to keep it succinct. (I have omitted Message = "" since IMHO it seems superfluous: why not simply leave it null?) Same for AttDocumentModel in the else, BTW.
  var mainDocumentModel = new MainDocumentModel
  {
      Status = true,
      MainDoc = new List<FileContent>{ fContent }
  };

I have trouble figuring out what if (!(fileNameBefore.Split(' ')[0] == file.f_name.Split(' ')[0])) is supposed to mean. As a matter of fact, that whole if...else seems to reference some kind of logic that really should be documented there with comments. It doesn't help that we don't have access to the code for GenerateOrderNumberForRis.

There are two places where you do documentOrderNumber + ".pdf".

Maindocument, Attdocument, ... are compound words and thus should be PascalCase.


Now that you've allowed the users to add custom providers, how about hiding the providerMethods object itself, and only providing a function which allows them to add to it. This would allow you to also validate if the users' want to override behaviour for predefined providers.
You have a process.exit(1) inside the call to usage(). Butm when used from cli, you catch all exceptions, then call the usage function, and against have another process.exit(1).
The call to usage should not be exiting from the program entirely. It is already handled in case of errors. You can then have a --help commandline parameter, which spits out the usage string (without raising an error for the shell).

Most of your if- conditions use the negated equality check, which is somewhat harder to follow for a developer (at least in my experience). When checking for args.length, you have double negation checks. It took me almost a minute to figure out what it is supposed to do. How about applying de Morgan's laws:
if (!(args.length === 3 || args.length === 4))

Or, maybe simply adding a comment?
Also consider:
console.log((result.length === 1) ? result[0] : result)


Class for finding the median of a two-dimensional space

I guess your Point is not a java.awt.Point since that holds x and y as int and you're using double.

Why not getting rid of your Point class by making the "Finder" class itself a MedianPoint?

import java.awt.geom.Point2D;

public class MedianPoint extends Point2D.Double {

  public MedianPoint(JavaRDD<Point> points) {
    super(
      /* your x calculation */,
      /* your y calculation */
      );
  }

  private static Point2D.Double greaterByXOf(Point2D.Double p1, Point2D.Double p2) {
    // ...
  }

  private static Point2D.Double greaterByYOf(Point2D.Double p1, Point2D.Double p2) {
    // ...
  }

} // MedianPoint


"Log in", extract number from a map, increment it, and log out

I would inline, eta-reduce and use more library functions to make the code short enough that adding another command is trivial. Perhaps give the fields names so adding another can't mess up numbering, and you need less comments because the code describes itself.

Edit: I'll use non, making the map not add a value for new users until they want to change it. This way we don't need to initialize with db . at user %= (<|> Just 0) on logging in, and we can get rid of the Just returned by the "get" action without needing to promise we already initialized. (Which we don't necessarily have, as the initial ""!)

{#- LANGUAGE TemplateHaskell, LambdaCase -#}
import Control.Lens -- batteries included
import Control.Monad.Trans.Maybe
import Control.Applicative -- (<$>), (<*>), empty, (<|>)
import qualified Data.Map as M -- Data.Map's name collisions with prelude are customarily handled by qualification

data AppState = AppState
  { _appStateUsername :: String
  , _appStateDb :: M.Map String Int
  }

makeFields ''AppState

-- Here's one we can actually outline, because it's used more than once, and it allows us to pull out the liftIO, and it shows us that we forgot the hFlush and the trailing ' ' one of the times.
prompt :: MonadIO m => String -> m String
prompt s = liftIO $ do
  putStr $ s ++ ": "
  hFlush stdout
  getLine

main = runMaybeT $ (`execStateT` AppState "" M.empty) $ forever $ do
  prompt "next action" >>= \case
    "inc" -> do
      user <- use username
      db . at user . non 0 += 1
    "login" -> do
      user <- prompt "enter username"
      username .= user
    "get" -> do
      n <- M.findWithDefault 0 <$> use username <*> use db
      liftIO $ putStrLn $ "current num: " ++ show n -- Note that this includes the Maybe, even though at this point we're always just, unless we're still the initial "".
    "logout" -> do
      username .= "" -- Note that this makes for shenanigans if someone logs in as "".
    "stop" -> empty -- MaybeT helps us out with the control flow to get rid of the special case and recursion.
    _ -> liftIO $ putStrLn $ "usage: ehhh just look at the code mmkay"


Don't use this, it's a redundant duplicate

for i in range(0, len(second_booth_voters)):
    item = second_booth_voters[i]

Instead use Python's for value in iterable syntax that lets you directly get the value of each list item for each iteration.

for item in second_booth_voters:

Also you should include a docstring.


Country data archiving script using Google Spreadsheet

You have a lot of repeated code when creating the data array. Note that the names of each cell value are ultimately irrelevant. That part could also be expressed as:

var columns = ["A" // office
              ,"B" // title
              ,"C" // imdbId
              ,"D" // channel
              ,"E" // type
              ,"F" // added
              ,"G" // deadline
              ,"H" // airing
              ,"I" // link
              ,"J" // picture
              ,"K" // comment
              ,"L" // portId
              ,"M" // status
              ];
var data = columns.map(function (col) {
  return source_sheet.getRange(col + i).getValue();
});

Less redundant code, same level of documentation.

Code like

if (...) {
  ...;
  i++;
} else {
  i++;
}

is usually better written as:

if (...) {
  ...;
}
i++;

However, we now have

var i = 2;
while (i <= lastRow) {
  ...;
  i++;
}

which is a more complicated formulation of

for (var i = 2; i <= lastRow; i++) {
  ...;
}

Similarly,

rowsToBeDeleted.reverse();
for (var j = 0; j < rowsToBeDeleted.length; j++)
{
    source_sheet.deleteRow(rowsToBeDeleted[j]);
}

is the same as:

for (var i = rowsToBeDeleted.length - 1; i >= 0; i--) {
  source_sheet.deleteRow(rowsToBeDeleted[i]);
}

If I see that correctly, your two function only differ in the strings croatian_backup vs. serbian_backup and CRO vs. SER. Instead of copy-pasting that code, take those strings from the function parameters. Now we have a general archive function:

function archive(outputSheet, languageCode) { ... }

If you need two seperate funtions that don't take any arguments, we can use the currying technique (also known as partial application) to pre-fill the arguments:

function CroatianArchive() {
  return archive("croatian_backup", "CRO");
}

Some of your names use underscores, other capitalization to separate words:

source_range
lastRow

You should settle for one style – Javascript tends to prefer capitalization rather than underscores.


Let's start simple. First of all, your code seems fine. However, as you've noticed yourself, there's an abundance of returns. Several of them don't seem necessary, so let us inspect some patterns:

((merge (return a') (return ys)) >>= \z -> return (y : z))

The pattern x >>= \z -> return (f z) is the same as fmap f x. That already reduces the number of returns by two:

type ArrayWithLogging a = WriterT [String] Identity [a]

merge :: (Show a, Ord a) => ArrayWithLogging a -> ArrayWithLogging a -> ArrayWithLogging a
merge al bl = do
    a <- al
    b <- bl
    case (a, b) of
        ([], b') -> tell ["Returning " ++ show b'] >> return b'
        (a', []) -> tell ["Returning " ++ show a'] >> return a'
        (a'@(x:xs), b'@(y:ys)) -> if (x <= y)
                                    then tell ["Min " ++ show x ++ " merging " ++ show xs ++ " with " ++ show b]
                                        >> fmap (x:) (merge (return xs) (return b'))
                                    else tell ["Min " ++ show y ++ " merging " ++ show a ++ " with " ++ show ys]
                                        >> fmap (y:) (merge (return a') (return ys))

Now, for the next step, let's get rid of the WriterT monad in the first two arguments. There's no reason for that, and it further removes the return:

merge :: (Show a, Ord a) => [a] -> [a] -> ArrayWithLogging a
merge a b = do
    case (a, b) of
        ([], b') -> tell ["Returning " ++ show b'] >> return b'
        (a', []) -> tell ["Returning " ++ show a'] >> return a'
        (a'@(x:xs), b'@(y:ys)) -> if (x <= y)
                                    then tell ["Min " ++ show x ++ " merging " ++ show xs ++ " with " ++ show b]
                                        >> fmap (x:) (merge xs b')
                                    else tell ["Min " ++ show y ++ " merging " ++ show a ++ " with " ++ show ys]
                                        >> fmap (y:) (merge a' ys)

We can still get the old variant by using the following merge':

merge' a1 b1 =
  a <- a1
  b <- b1
  merge a b

Now that we've reduced function pretty far (but didn't lose any functionality!), we can go ahead and change some indentation to make our intend more clear. Furthermore, let us also introduce a small helper called message:

merge :: (Show a, Ord a) => [a] -> [a] -> ArrayWithLogging a
merge a b = do
    case (a, b) of
        ([], b') -> tell ["Returning " ++ show b'] >> return b'
        (a', []) -> tell ["Returning " ++ show a'] >> return a'
        (a'@(x:xs), b'@(y:ys)) ->
            if (x <= y)
                then message x xs b  >> fmap (x:) (merge xs b')
                else message y a  ys >> fmap (y:) (merge a' ys)
  where
   message e ls rs = tell ["Min " ++ show e ++ " merging " ++ show ls ++ " with " ++ show rs]

OK, let's reiterate our steps:

We changed x >>= \z -> (f z) to fmap f x
We changed the arguments into their non-monad variant
We introduced another function to keep the old behaviour (if necessary)
We changed the indentation to make sure that it looks nicer.
We introduced a small helper to make sure that we don't repeat ourselves.

And those are all the non-opinionated (well, except the last one) changes I'd recommend to you. In my personal opinion, the function gets even a little bit nicer if we use pattern matching on the arguments:

type ArrayWithLogging a = WriterT [String] Identity [a]

merge :: (Show a, Ord a) => [a] -> [a] -> ArrayWithLogging a
merge a        []     = tell ["Returning " ++ show a] >> return a
merge []       b      = tell ["Returning " ++ show b] >> return b
merge a@(x:xs) b@(y:ys)
  | x <= y    = message x xs b  >> fmap (x:) (merge xs b)
  | otherwise = message y a  ys >> fmap (y:) (merge a ys)
  where
    message e ls rs = tell ["Min " ++ show e ++ " merging " ++ show ls ++ " with " ++ show rs]

merge' :: (Show a, Ord a) => ArrayWithLogging a-> ArrayWithLogging a-> ArrayWithLogging a
merge' a b = do
   a1 <- a
   b1 <- b
   merge a1 b1


nTier architecture for an MVC application

An accepted design pattern for separation of concerns is the Repository design pattern.  There is a pretty good description of using this design pattern in MVC here. Your example is close to this pattern in your BLL layer, although your simple example does not have any business logic and just encapsulates the DAL.  If you need to access multiple Repositories for your view it is recommended to use a Service Layer that coordinates transactions between multiple Repositories.  There is a good description of this pattern here.

Your View Model should be totally separated from the BLL and not query it directly. I assume you are querying the results in the View since you are returning an IQueryable object.  The controller for the MVC should take any query parameters from the View, pass them to the Model (Repository or Service Layer) and get back an object graph that represents the View Model, which in turn is passed to the View.  The View Model usually does not clone the objects that are manipulated in the Repository.  For example you would not need to pass things like foreign keys used for navigation in the DAL to the View Model.  Only pass to the View Model what it needs to get its job done, which is to allow the View to render a user interface.  This usually requires a lot of data mapping from one object to another. Although it is a hassle upfront you will appreciate it going forward because you will have a code base that is not fragile to changes in either your model or view.  A good tool to help with the data mapping is AutoMapper.
For a great example on how to create a robust modern website using MVC take a look at Microsoft's Silk Project.


Check for errors in stat, setuid, fork, and execvp, to name a few.  If the exec fails in the child you should call exit.
Do you really want the p in execvp?  This is not guaranteed to be the same as the argv[1] you just stat-ed.  If argv[1] is ls your stat will look for a file at ./ls and it will likely find the program in /bin.  I would use execve and either do that PATH lookup yourself or simply omit that part and require the user to specify a full path for something in PATH (eg. /bin/ls instead of just ls).
The stat + observe state + exec thing is a race condition.  Another process can change the attributes on the file in that timing window.  This may or may not be important to you.  Given that this is a security-ish program I would say it may very well be.
Instead of returning 0, you might want to return the child process's exit code (which you can get with waitpid.)  You might also want to return nonzero when the functions I mention in #1 fail.  This way a shell script or something calling you programmatically can determine success or failure.


Finding .txt files that exist in one directory but not the other

That's where generators can be very helpful, for example you could use:

if args:
    folderlist = (f for f in folderlist if f.endswith('.txt') and not os.path.exists(os.path.join(folder2, f))
else:
    folderlist = (f for f in folderlist if f.endswith('.txt'))

for x in folderlist:
    full_path = os.path.join(folder, x)
    the_list.append(full_path)

The checks are now done in the "generator expression"s.

You could simplify this some more because the if x.endswith('.txt') is done in both branches:

folderlist = (f for f in folderlist if f.endswith('.txt'))
if args:
    folderlist = (f for f in folderlist if not os.path.exists(os.path.join(folder2, f))

for x in folderlist:
    full_path = os.path.join(folder, x)
    the_list.append(full_path)


Welcome to Code Review. Your code is understandable, so we can, more or less, figure out what it does, but it is always nice for reviewers to hear you say what you use a piece of code for, what its purpose is, what the code itself specifically does, and to have some usage examples. This also helps you to reflect on the choices you made.

I couldn't get your getClassTotal() and getMethodTotal() to work. They assume that all the files are PHP files, and in my test directory they are not. You should have checked the PHP file extension before tokenizing the file content.

From what I can see this looks like a class that wraps four independent function. That only doesn't justify the existence of this class. Is there nothing common to these functions? I think we can agree that the RecursiveDirectoryIterator and RecursiveIteratorIterator are present in all four, so I made that part of the class.

There are also some simplifications I added in the file and bytes counter.

Using the build-in PHP tokenizer was a good idea, but clearly the way that classes and methods are counted is very similar. So I created a new method which will count either. I don't see the point of checking for a class name, so I left that bit out.

In your code a counter is the second argument to all four method. I fail to see why this is a good thing. I dropped it.

This gives me the following code:

<?php

class DirectoryScanner
{
    private $files;

    public function __construct($path)
    {
        $dirIterator = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
        $this->files = new RecursiveIteratorIterator($dirIterator);
    }

    public function getFileCount()
    {
        return iterator_count($this->files);
    }

    public function getBytesUsed()
    {
        $bytes = 0;
        foreach ($this->files as $file) {
            $bytes += $file->getSize();
        }
        return $bytes;
    }

    private function getPhpTokenCount($token)
    {
        $counter = 0;
        foreach ($this->files as $file) {
            if ($file->getExtension() == 'php') {
                $contents = file_get_contents($file);
                $tokens   = token_get_all($contents);
                $values   = array_count_values(array_column($tokens, 0));
                $counter += isset($values[$token]) ? $values[$token] : 0;
            }
        }
        return $counter;
    }

    public function getPhpClassCount()
    {
        return $this->getPhpTokenCount(T_CLASS);
    }

    public function getPhpFunctionCount()
    {
        return $this->getPhpTokenCount(T_FUNCTION);
    }
}

?>

I left out all the comments to save some space. This code can be tested like this:

$path = $_SERVER['DOCUMENT_ROOT'];
$test = new DirectoryScanner($path);

echo 'getFileCount: ' . $test->getFileCount() . '
';
echo 'getBytesUsed: ' . $test->getBytesUsed() . '
';
echo 'getPhpClassCount: ' . $test->getPhpClassCount() . '
';
echo 'getPhpFunctionCount: ' . $test->getPhpFunctionCount() . '
';

In my code I take advantage of what a class is: An piece of code in which you share fields and methods in a local scope. I made $files and getPhpTokenCount() private intentionally to stress this point.

I think the first two methods have little in common with the last three. So I would split this up in two classes, like so:

class DirectoryScanner
{
    protected $files;

    public function __construct($path)
    {
        $dirIterator = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
        $this->files = new RecursiveIteratorIterator($dirIterator);
    }

    public function getFileCount()
    {
        return iterator_count($this->files);
    }

    public function getBytesUsed()
    {
        $bytes = 0;
        foreach ($this->files as $file) {
            $bytes += $file->getSize();
        }
        return $bytes;
    }
}

class PhpFilesScanner extends DirectoryScanner
{

    public function getPhpTokenCount($token)
    {
        $counter = 0;
        foreach ($this->files as $file) {
            if ($file->getExtension() == 'php') {
                $contents = file_get_contents($file);
                $tokens   = token_get_all($contents);
                $values   = array_count_values(array_column($tokens, 0));
                $counter += isset($values[$token]) ? $values[$token] : 0;
            }
        }
        return $counter;
    }

    public function getPhpClassCount()
    {
        return $this->getPhpTokenCount(T_CLASS);
    }

    public function getPhpFunctionCount()
    {
        return $this->getPhpTokenCount(T_FUNCTION);
    }
}

?>

It just makes more sense this way. Note that PhpFilesScanner does rely on DirectoryScanner for the iterator functionality.

I think, depending on your usage, that result buffering would be a nice addition to these classes. For instance, by once buffering alle the token counts, the PhpFilesScanner class can return multiple requests for counts of certain tokens much quicker. Especially if you expand it to include more types of tokens. Buffering would make the class look something like this:

class PhpFileScanner extends DirectoryScanner
{
    private $tokenCounts = [];

    public function __construct($path)
    {
        parent::__construct($path);
        foreach ($this->files as $file) {
            if ($file->getExtension() == 'php') {
                $contents = file_get_contents($file);
                $tokens   = token_get_all($contents);
                $counts   = array_count_values(array_column($tokens, 0));
                foreach ($counts as $token => $count) {
                    if (!isset($this->tokenCounts[$token])) {
                        $this->tokenCounts[$token] = 0;
                    }
                    $this->tokenCounts[$token] += $count;
                }
            }
        }
    }

    public function getPhpClassCount()
    {
        return $this->tokenCounts[T_CLASS] ?? 0;
    }

    public function getPhpFunctionCount()
    {
        return $this->tokenCounts[T_FUNCTION] ?? 0;
    }
}

The ?? is the new Null coalescing operator of PHP 7.


If done cleverly, you can get away with a single method to get the input of any type:

static T GetInput<T>(string message, Converter<string, T> transform)
{
    Console.WriteLine(message);
    return transform(Console.ReadLine());
}

All you need to do is pass in a transformation function (the Converter<TInput,TOutput> delegate is equivalent to Func<T,TResult>):

int parsedInt = GetInput("Type in a number", int.Parse);
float parsedFloat = GetInput("Type in a float", float.Parse);

And ta-da, you've got your input, parsed as the desired type.

But as you also noted in the second half of your question, it's dangerous to assume that the input will always be valid. There's a universal version of your insist-on-valid-input function too. However, you should avoid using exceptions for normal control flow. Use the xxx.TryParse methods instead.

First, define the following delegate that matches the TryParse method defined in all the primitive types:

delegate bool TryParse<T>(string input, out T output);

Then, you can implement the loop:

static T InsistOnValidInput<T>(string message, string errorMessage, TryParse<T> validator)
{
    Console.WriteLine(message);
    T result;
    while (!validator(Console.ReadLine(), out result))
    {
        Console.WriteLine(errorMessage);
    }
    return result;
}

And call it:

bool parsedBool = InsistOnValidInput<bool>("Type in a bool", "Try again", bool.TryParse);

Unfortunately, C# doesn't infer the type parameter of the output argument, so you need to specify it manually (in this case, <bool>).


That's typically how C enums are written, but it's done differently in C++.  The typedef keyword is no longer needed, and the name is given after the enum keyword.

enum State {
    Idle,
    Start,
    Stop,
    ChangeSpeed
};


Haskell function to format a floating-point number with some precision

Here's another way to write it (without changing too much). The functions toString and padZereos do sensible things on their own, so I kept them in the global namespace. Everything else is local. Having one big where-clause where you define everything local to a function is something you'll see often. Note that due to lazy evaluation you can define a_trimmed and a_padded, even if only one is used, so the other is never calculated. That further cleans up the code.

In a next step, I'd probably get rid of calc entirely, and fold sign handling into its body. Also, normalize looks like it should be calculated with divMod or quotRem.

showEngFloat :: RealFloat a => Int -> a -> [Char]
showEngFloat precision x = result where
  result = if x >= 0 then calc x else '-' : calc (-x)
  normalize :: Int -> (Int,Int)
  normalize dp = loop dp 0 where
    loop dp e
      | dp > 3 = loop (dp - 3) (e+3)
      | dp < 1 = loop (dp + 3) (e-3)
      | otherwise = (dp,e)
  calc n = a ++ "." ++ b ++ "E" ++ c where
    (digits,dotPos0) = floatToDigits 10 n
    ndigits = length digits
    (dotPos1,e) = normalize dotPos0
    a_trimmed = toString (take dotPos1 digits)
    a_padded  = padZeroes (dotPos1 - ndigits) (toString (take ndigits digits))
    a = if ndigits >= dotPos1 then a_trimmed else a_padded
    b = padZeroes (precision - max dotPos1 ndigits) (toString (drop dotPos1 digits))
    c = toString [e]


There are two difficulties here:

The input needs to be sorted in decreasing order by height, but increasing order by count. The code in the post handles this by collating the input by height and then sorting twice: first in reverse order by height, and then for a given height in normal order by count.

This could be simplified by passing a key function to sorted so that it sorts in the required order. In particular, if take the key to be (-height, count) then the list will sort into the required order without any need for collation.

def _queue_key(person):
    height, count = person
    return -height, count

def reconstruct_queue_2(people):
    result = []
    for person in sorted(people, key=_queue_key):
        _, count = person
        result.insert(count, person)
    return result

Inserting an item into the middle a list takes time proportional to the length of the list (see the TimeComplexity page in the Python wiki). This means that the reconstruction algorithm takes time that's quadratic in the length of the queue. It would nice to do better than this.

The data structure that's needed here is some kind of balanced tree. Python doesn't have anything suitable in the standard library, but the sortedcontainers package from the Python Package Index has a SortedListWithKey class that can do what we need.

from sortedcontainers import SortedListWithKey

def reconstruct_queue_3(people):
    result = SortedListWithKey(key=lambda _:0)
    for person in sorted(people, key=_queue_key):
        _, count = person
        result.insert(count, person)
    return result

This is slightly tricksy code because we're not making use of the "sorted" property of the SortedListWithKey class — we use the key= argument to make all the items identical as far as sort order is concerned. We're using the class only to get efficient insertion at an arbitrary index in a list.


Invoking API calls with parameters specified using JSON

Sounds like a simple use case for polymorphism:

interface JsonOperation {
    void run();
}

private void setHttp(JsonObject jo) {
    runAndHandleErrors(() -> {
        // ...
    });
}

private void setSsl(JsonObject jo) {
    runAndHandleErrors(() -> {
        // ...
    });
}

private void runAndHandleErrors(JsonOperation op) {
    try {
        op.run();
    } catch (Exception e) {
        // ...
    } finally {
        // ...
    }
}

Explanation: JsonOperation is an interface with one method so it is considered a functional interface, meaning a lambda can be considered an implementation of it. runAndHandleErrors takes a JsonOperation so whenever we call runAndHandleErrors with a lambda, the compiler infers the lambda to implement JsonOperation.

A lambda, like an anonymous inner class, captures final variables in enclosing blocks. That means that a lambda, like an anonymous inner class, can use these variables and sees the values of the variables that were assigned when the lambda / anonymous inner class was created. A lambda also captures variables that are effectively final, meaning their values are never changed whether or not they are declared as final.

When setHttp(x) is called, the following happens:

x is assigned to jo
an implementation of JsonOperation capturing jo is created (but not run)
runAndHandleErrors is called and the JsonOperation from step 2 is assigned to op
runAndHandleErrors calls op.run(), causing the JsonOperation to run
the JsonOperation runs, doing whatever it wants with jo - it sees the same value of jo as was assigned in step 2

However, since you posted to the Code Review Stack Exchange and not Programmers Stack Exchange, I'll critique your code:

catch Exception and throws Exception are code smells - to the greatest degree possible, catch and declare specific Exception types.
The logic regarding success and errorString is convoluted. You could instead separately throw an appropriate subclass of Exception in the try and catch blocks and get rid of the success and errorString variables. Your code reuse isn't actually helping because you need conditional logic in the finally block to account for both cases. Also, the thrown exception in the catch block should properly wrap the original exception by passing the latter directly into the former's constructor.
Make a helper method for getJsonElementAsString that takes a varargs array of attribute keys and returns a list of attributes. This method would make your code much terser.


The short answer is don't use VBA at all. Use native Excel formulas. We like to code, so it's natural that we all too often reach for the IDE when we should be heading to the formula bar.

Consider sheet Data_new

And sheet Data_old

You can use a VLookup from Data_old to find the corresponding values in DataNew.

=VLOOKUP(Data_new!$A2,Data_new!$A:$B,2,FALSE)

And then wrap the lookup in an IF formula to populate the final result.

=IF(B2 = VLOOKUP(Data_new!$A2,Data_new!$A:$B,2,FALSE),"OK","NOK")

resulting in the new & improved sheet Data_old.


Some random observations:

What does your base class database do? I hope not the stuff it sounds like. Your aim is to separate storage and view logic, not add view logic to your database.
Having both static and non-static functions in a class should make you suspicious (as this is an indicator this class has one then more objective or is inconsistently written).
Some functions do echo, some return and some call other functions. Decide for one way ;).
invoke for parameter to function resolving? Have a look at the much cooler magic function __call.

Some suggestions:

It is probably a good idea to move the single view operations into it's own classes. This becomes more important when you add even more operations.
Unify the way your class is accessed and the return values.
Views don't extend a database.

Easy to implement way:

Let every view operation be it's own class.
Define a common interface for all view operations (e.g. ViewOperation with one required function run()).
Create one main class View that is responsible to resolve view operations to subclasses.

Example implementation:

interface ViewOperation
{
    public function run();
}

public class ControllAdd implements ViewOperation
{
    private $_types = array('pass' => '<xx_p>', 'fail' => '<xx_f>');

    public function run()
    {
        $params = func_get_arg(1);
        if(isset($params) && !empty($params) && array_key_exists($this->_types, $params))
        {
            return $this->_types[$params];
        }
    }
}

public class View
{
    public function __call($name, $arguments)
    {
        // More security required here of course
        require_once './ViewOperartopns/' . $name . '.php';

        $instance = new $name;
        return $instance->run($arguments);
    }
}


Compiler warning on unused exception...need to improve structure?

You can refactor your code the following way:

public int DoSomethingComplicated(ComplicatedObject input)
{
    try
    {
        return input.Analyse();
    }
    catch(CustomExceptionTwo ex2)
    {
         Log(ex2.Message);
         return -1;
    }
}

throw; re-throws the same exception, so there is no point in such catch block.

Alternatively, you can use catch(CustomExceptionOne) syntax.


What doesn't work properly

As pointed by @Roland Illig's answer, your solution produces an error when list contains only 1 item and this item doesn't match el.

It comes from the fact that:

for a 1-item list, LIM is 0
after the while() expression didn't find a match, --LIM gives -1, which evaluates to true
so if (!--LIM) is false and the loop continues infinitely...

This issue can be solved by merely changing this test to if (--LIM <= 0)

Possible improvements

As pointed by @Dair, your names are somewhat cryptic.
For the sake of readability you'd better to change:

el to searchedValue
LIM to tries (also note that using uppercase is supposed to be reserved for constants, while this data is not)
lb to lowerBound
ub to upperBound

Also, following best practices, I recommend to use block marks for if()s.

All that said, here is a suggested improved (and corrected) version:

function search(searchedValue, list) {
    var tries = Math.ceil(Math.log2(list.length)),
        lowerBound = 0,
        upperBound = list.length - 1,
        i;
    while (
        searchedValue !== list[i = ~~((lowerBound + upperBound) / 2)]
    &&
        searchedValue !== list[++i]
    ) {
        if (--tries <= 0) {
            return ("NOT FOUND");
        }
        if (searchedValue > list[i]) {
            lowerBound = i;
        } else {
            upperBound = i;
        }
    }
    return i;
}


Breadth-first search on a tree in Python

get_something is not a good name for the function. Obviously, it specifies your tree by returning the child nodes of an argument node; rename to, say, get_neighbors. Also, your implementation overkills breadth-first search a bit. See what I mean:

def get_neighbors(x):
    if x == 'a':
        return ['b', 'c']
    if x == 'b':
        return ['d', 'e']
    if x == 'c':
        return []
    if x == 'd':
        return ['f']
    if x == 'e':
        return []
    if x == 'f':
        return []

    return [] # Other nodes have no neighbors.

def bfs(start):
    queue = [start]
    visited = set(start)

    while queue:
        node = queue.pop(0)

        for neighbor in get_neighbors(node):
            if neighbor not in visited:
                queue.append(neighbor)
                visited.add(neighbor)

    return visited

print(str(bfs('a')))

Also, note that seen_list should be rather a Python set as operating on it is more efficient than on lists.


Given an array, find all its elements that can become a leader

def modify(segment):
   return [e+1 for e in segment]

This function is used only in one place, and is only one line. That often means it's better to just inline it:

modifiedA[x:K+x] = modify(A[x:K+x])
# Becomes:
modifiedA[x:K+x] = [e+1 for e in A[x:K+x]]

Use meaningful variable names. No matter what your challenge says, K, M and A are not meaningful variable names. It also seems like you're not doing anything with that M, so why do we even pass it to the function?

In your dominant() function, you look like you want to use collections.Counter. For practice with a language it can be good to check how to set it up yourself, but sometimes we have a good solution ready-made and available, and much better tested than any individual developer could ever do.

With Counter, you can make it work like this:

from collections import Counter

def dominant(string):
    count = Counter(string)
    return [key for key, value in count.items() if value == count.most_common(1)[0][1]]

Yeah, it's as simple as that. You could split it out over multiple lines, for clarity:

from collections import Counter

def dominant(string):
    count = Counter(string)
    dom_list = []
    max_occurred = count.most_common(1)[0][1]
    for key, value in count.items():
        if value >= max_occurred:
            dom_list.append(key)
    return dom_list


Two things:

You need to use a lot of consts.

Example:

    void setNext(ListNode &node)

    void setNext(const ListNode &node)

You call to new in some places of your code but never call to delete


Your m digit checking can be simplified and your do while loop can be replaced with the simpler for loop. The constants also seem excessive given that non-zero truthiness is baked into C.
int isPrimeNumber(uint64_t n)
{
    if (n==2 || n==3) return 1;
    if (n%2==0) return 0;

    // Start near line x=y.
    uint64_t x = (n / 2) + 2;
    uint64_t y = n - x;

    uint64_t count = sqrt(n) / 2;
    for (uint64_t i=0;i<count;++i) {
        // Check lattice point visibility...
        if (gcd(x, y) != 1) return 0;

        x++; y--;
    }

    return 1;
}